PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.3.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.3.0
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / Plugin / Visualization.php
matomo / app / core / Plugin Last commit date
Dimension 5 years ago API.php 5 years ago AggregatedMetric.php 5 years ago ArchivedMetric.php 5 years ago Archiver.php 5 years ago Categories.php 5 years ago ComponentFactory.php 5 years ago ComputedMetric.php 5 years ago ConsoleCommand.php 5 years ago Controller.php 5 years ago ControllerAdmin.php 5 years ago Dependency.php 5 years ago LogTablesProvider.php 5 years ago Manager.php 5 years ago Menu.php 5 years ago MetadataLoader.php 5 years ago Metric.php 5 years ago PluginException.php 5 years ago ProcessedMetric.php 5 years ago ReleaseChannels.php 5 years ago Report.php 5 years ago ReportsProvider.php 5 years ago RequestProcessors.php 5 years ago Segment.php 5 years ago SettingsProvider.php 5 years ago Tasks.php 5 years ago ThemeStyles.php 5 years ago ViewDataTable.php 5 years ago Visualization.php 5 years ago WidgetsProvider.php 5 years ago
Visualization.php
869 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9
10 namespace Piwik\Plugin;
11
12 use Piwik\API\DataTablePostProcessor;
13 use Piwik\API\Proxy;
14 use Piwik\API\Request;
15 use Piwik\API\Request as ApiRequest;
16 use Piwik\API\ResponseBuilder;
17 use Piwik\Common;
18 use Piwik\Container\StaticContainer;
19 use Piwik\DataTable;
20 use Piwik\Date;
21 use Piwik\Http\BadRequestException;
22 use Piwik\Log;
23 use Piwik\Metrics\Formatter\Html as HtmlFormatter;
24 use Piwik\NoAccessException;
25 use Piwik\Option;
26 use Piwik\Period;
27 use Piwik\Piwik;
28 use Piwik\Plugins\API\API as ApiApi;
29 use Piwik\Plugins\API\Filter\DataComparisonFilter;
30 use Piwik\Plugins\Monolog\Processor\ExceptionToTextProcessor;
31 use Piwik\Plugins\PrivacyManager\PrivacyManager;
32 use Piwik\SettingsPiwik;
33 use Piwik\View;
34 use Piwik\ViewDataTable\Manager as ViewDataTableManager;
35 use Piwik\Plugin\Manager as PluginManager;
36 use Psr\Log\LoggerInterface;
37
38 /**
39 * The base class for report visualizations that output HTML and use JavaScript.
40 *
41 * Report visualizations that extend from this class will be displayed like all others in
42 * the Piwik UI. The following extra UI controls will be displayed around the visualization
43 * itself:
44 *
45 * - report documentation,
46 * - a header message (if {@link Piwik\ViewDataTable\Config::$show_header_message} is set),
47 * - a footer message (if {@link Piwik\ViewDataTable\Config::$show_footer_message} is set),
48 * - a list of links to related reports (if {@link Piwik\ViewDataTable\Config::$related_reports} is set),
49 * - a button that allows users to switch visualizations,
50 * - a control that allows users to export report data in different formats,
51 * - a limit control that allows users to change the amount of rows displayed (if
52 * {@link Piwik\ViewDataTable\Config::$show_limit_control} is true),
53 * - and more depending on the visualization.
54 *
55 * ### Rendering Process
56 *
57 * The following process is used to render reports:
58 *
59 * - The report is loaded through Piwik's Reporting API.
60 * - The display and request properties that require report data in order to determine a default
61 * value are defaulted. These properties are:
62 *
63 * - {@link Piwik\ViewDataTable\Config::$columns_to_display}
64 * - {@link Piwik\ViewDataTable\RequestConfig::$filter_sort_column}
65 * - {@link Piwik\ViewDataTable\RequestConfig::$filter_sort_order}
66 *
67 * - Priority filters are applied to the report (see {@link Piwik\ViewDataTable\Config::$filters}).
68 * - The filters that are applied to every report in the Reporting API (called **generic filters**)
69 * are applied. (see {@link Piwik\API\Request})
70 * - The report's queued filters are applied.
71 * - A {@link Piwik\View} instance is created and rendered.
72 *
73 * ### Rendering Hooks
74 *
75 * The Visualization class defines several overridable methods that are called at specific
76 * points during the rendering process. Derived classes can override these methods change
77 * the data that is displayed or set custom properties.
78 *
79 * The overridable methods (called **rendering hooks**) are as follows:
80 *
81 * - **beforeLoadDataTable**: Called at the start of the rendering process before any data
82 * is loaded.
83 * - **beforeGenericFiltersAreAppliedToLoadedDataTable**: Called after data is loaded and after priority
84 * filters are called, but before other filters. This
85 * method should be used if you need the report's
86 * entire dataset.
87 * - **afterGenericFiltersAreAppliedToLoadedDataTable**: Called after generic filters are applied, but before
88 * queued filters are applied.
89 * - **afterAllFiltersAreApplied**: Called after data is loaded and all filters are applied.
90 * - **beforeRender**: Called immediately before a {@link Piwik\View} is created and rendered.
91 * - **isThereDataToDisplay**: Called after a {@link Piwik\View} is created to determine if the report has
92 * data or not. If not, a message is displayed to the user.
93 *
94 * ### The DataTable JavaScript class
95 *
96 * In the UI, visualization behavior is provided by logic in the **DataTable** JavaScript class.
97 * When creating new visualizations, the **DataTable** JavaScript class (or one of its existing
98 * descendants) should be extended.
99 *
100 * To learn more read the [Visualizing Report Data](/guides/visualizing-report-data#creating-new-visualizations)
101 * guide.
102 *
103 * ### Examples
104 *
105 * **Changing the data that is loaded**
106 *
107 * class MyVisualization extends Visualization
108 * {
109 * // load the previous period's data as well as the requested data. this will change
110 * // $this->dataTable from a DataTable instance to a DataTable\Map instance.
111 * public function beforeLoadDataTable()
112 * {
113 * $date = Common::getRequestVar('date');
114 * list($previousDate, $ignore) = Range::getLastDate($date, $period);
115 *
116 * $this->requestConfig->request_parameters_to_modify['date'] = $previousDate . ',' . $date;
117 * }
118 *
119 * // since we load the previous period's data too, we need to override the logic to
120 * // check if there is data or not.
121 * public function isThereDataToDisplay()
122 * {
123 * $tables = $this->dataTable->getDataTables()
124 * $requestedDataTable = end($tables);
125 *
126 * return $requestedDataTable->getRowsCount() != 0;
127 * }
128 * }
129 *
130 * **Force properties to be set to certain values**
131 *
132 * class MyVisualization extends Visualization
133 * {
134 * // ensure that some properties are set to certain values before rendering.
135 * // this will overwrite any changes made by plugins that use this visualization.
136 * public function beforeRender()
137 * {
138 * $this->config->max_graph_elements = false;
139 * $this->config->datatable_js_type = 'MyVisualization';
140 * $this->config->show_flatten_table = false;
141 * $this->config->show_pagination_control = false;
142 * $this->config->show_offset_information = false;
143 * }
144 * }
145 */
146 class Visualization extends ViewDataTable
147 {
148 /**
149 * The Twig template file to use when rendering, eg, `"@MyPlugin/_myVisualization.twig"`.
150 *
151 * Must be defined by classes that extend Visualization.
152 *
153 * @api
154 */
155 const TEMPLATE_FILE = '';
156
157 private $templateVars = array();
158 private $reportLastUpdatedMessage = null;
159 private $metadata = null;
160 protected $metricsFormatter = null;
161
162 /**
163 * @var Report
164 */
165 protected $report;
166
167 final public function __construct($controllerAction, $apiMethodToRequestDataTable, $params = array())
168 {
169 $templateFile = static::TEMPLATE_FILE;
170
171 if (empty($templateFile)) {
172 throw new \Exception('You have not defined a constant named TEMPLATE_FILE in your visualization class.');
173 }
174
175 $this->metricsFormatter = new HtmlFormatter();
176
177 parent::__construct($controllerAction, $apiMethodToRequestDataTable, $params);
178
179 $this->report = ReportsProvider::factory($this->requestConfig->getApiModuleToRequest(), $this->requestConfig->getApiMethodToRequest());
180 }
181
182 public function render()
183 {
184 $this->overrideSomeConfigPropertiesIfNeeded();
185
186 try {
187 $this->beforeLoadDataTable();
188 $this->loadDataTableFromAPI();
189 $this->postDataTableLoadedFromAPI();
190
191 $requestPropertiesAfterLoadDataTable = $this->requestConfig->getProperties();
192
193 $this->applyFilters();
194 $this->addVisualizationInfoFromMetricMetadata();
195 $this->afterAllFiltersAreApplied();
196
197 $this->beforeRender();
198 $this->fireBeforeRenderHook();
199
200 $this->logMessageIfRequestPropertiesHaveChanged($requestPropertiesAfterLoadDataTable);
201 } catch (NoAccessException $e) {
202 throw $e;
203 } catch (\Exception $e) {
204 StaticContainer::get(LoggerInterface::class)->error('Failed to get data from API: {exception}', [
205 'exception' => $e,
206 'ignoreInScreenWriter' => true,
207 ]);
208
209 $message = ExceptionToTextProcessor::getMessageAndWholeBacktrace($e);
210
211 $loadingError = array('message' => $message);
212 }
213
214 $view = new View("@CoreHome/_dataTable");
215 $view->assign($this->templateVars);
216
217 if (!empty($loadingError)) {
218 $view->error = $loadingError;
219 }
220
221 $view->visualization = $this;
222 $view->visualizationTemplate = static::TEMPLATE_FILE;
223 $view->visualizationCssClass = $this->getDefaultDataTableCssClass();
224 $view->reportMetdadata = $this->getReportMetadata();
225
226 if (null === $this->dataTable) {
227 $view->dataTable = null;
228 } else {
229 $view->dataTableHasNoData = !$this->isThereDataToDisplay();
230 $view->dataTable = $this->dataTable;
231
232 // if it's likely that the report data for this data table has been purged,
233 // set whether we should display a message to that effect.
234 $view->showReportDataWasPurgedMessage = $this->hasReportBeenPurged();
235 $view->deleteReportsOlderThan = Option::get('delete_reports_older_than');
236 }
237
238 $view->idSubtable = $this->requestConfig->idSubtable;
239 $clientSideParameters = $this->getClientSideParametersToSet();
240 if (isset($clientSideParameters['showtitle'])) {
241 unset($clientSideParameters['showtitle']);
242 }
243 $view->clientSideParameters = $clientSideParameters;
244 $view->clientSideProperties = $this->getClientSidePropertiesToSet();
245 $view->properties = array_merge($this->requestConfig->getProperties(), $this->config->getProperties());
246 $view->reportLastUpdatedMessage = $this->reportLastUpdatedMessage;
247 $view->footerIcons = $this->config->footer_icons;
248 $view->isWidget = Common::getRequestVar('widget', 0, 'int');
249 $view->notifications = [];
250 $view->isComparing = $this->isComparing();
251
252 if (!$this->supportsComparison()
253 && DataComparisonFilter::isCompareParamsPresent()
254 && empty($view->dataTableHasNoData)
255 ) {
256 if (empty($view->properties['show_footer_message'])) {
257 $view->properties['show_footer_message'] = '';
258 }
259 $view->properties['show_footer_message'] .= '<br/>' . Piwik::translate('General_VisualizationDoesNotSupportComparison');
260 }
261
262 if (empty($this->dataTable) || !$this->hasAnyData($this->dataTable)) {
263 /**
264 * @ignore
265 */
266 Piwik::postEvent('Visualization.onNoData', [$view]);
267 }
268
269 return $view->render();
270 }
271
272 protected function checkRequestIsNotForMultiplePeriods()
273 {
274 $date = $this->requestConfig->getRequestParam('date');
275 $period = $this->requestConfig->getRequestParam('period');
276 if (Period::isMultiplePeriod($date, $period)) {
277 throw new BadRequestException("The '" . static::ID . "' visualization does not support multiple periods.");
278 }
279 }
280
281 protected function checkRequestIsOnlyForMultiplePeriods()
282 {
283 try {
284 $this->checkRequestIsNotForMultiplePeriods();
285 } catch (BadRequestException $ex) {
286 return; // ignore
287 }
288
289 throw new BadRequestException("The '" . static::ID . "' visualization does not support single periods.");
290 }
291
292 private function hasAnyData(DataTable\DataTableInterface $dataTable)
293 {
294 $hasData = false;
295 $dataTable->filter(function (DataTable $table) use (&$hasData) {
296 if ($hasData || $table->getRowsCount() == 0) {
297 return;
298 }
299
300 foreach ($table->getRows() as $row) {
301 foreach ($row->getColumns() as $column => $value) {
302 if ($value != 0 && $value !== '0%') {
303 $hasData = true;
304 return;
305 }
306 }
307 }
308 });
309 return $hasData;
310 }
311
312 /**
313 * @internal
314 */
315 protected function loadDataTableFromAPI()
316 {
317 if (!is_null($this->dataTable)) {
318 // data table is already there
319 // this happens when setDataTable has been used
320 return $this->dataTable;
321 }
322
323 // we build the request (URL) to call the API
324 $request = $this->buildApiRequestArray();
325
326 $module = $this->requestConfig->getApiModuleToRequest();
327 $method = $this->requestConfig->getApiMethodToRequest();
328
329 list($module, $method) = Request::getRenamedModuleAndAction($module, $method);
330
331 PluginManager::getInstance()->checkIsPluginActivated($module);
332
333 $proxyRequestParams = $request;
334 if ($this->isComparing()) {
335 $proxyRequestParams = array_merge($proxyRequestParams, [
336 'disable_root_datatable_post_processor' => 1,
337 ]);
338 }
339
340 $class = ApiRequest::getClassNameAPI($module);
341 $dataTable = Proxy::getInstance()->call($class, $method, $proxyRequestParams);
342
343 $response = new ResponseBuilder($format = 'original', $request);
344 $response->disableSendHeader();
345 $response->disableDataTablePostProcessor();
346
347 $this->dataTable = $response->getResponse($dataTable, $module, $method);
348 }
349
350 private function getReportMetadata()
351 {
352 $request = $this->request->getRequestArray() + $_GET + $_POST;
353
354 $idSite = Common::getRequestVar('idSite', null, 'int', $request);
355 $module = $this->requestConfig->getApiModuleToRequest();
356 $action = $this->requestConfig->getApiMethodToRequest();
357
358 $apiParameters = array();
359 $entityNames = StaticContainer::get('entities.idNames');
360 foreach ($entityNames as $entityName) {
361 $idEntity = Common::getRequestVar($entityName, 0, 'int');
362 if ($idEntity > 0) {
363 $apiParameters[$entityName] = $idEntity;
364 }
365 }
366
367 $metadata = ApiApi::getInstance()->getMetadata($idSite, $module, $action, $apiParameters);
368
369 if (!empty($metadata)) {
370 return array_shift($metadata);
371 }
372
373 return false;
374 }
375
376 private function overrideSomeConfigPropertiesIfNeeded()
377 {
378 if (empty($this->config->footer_icons)) {
379 $this->config->footer_icons = ViewDataTableManager::configureFooterIcons($this);
380 }
381
382 if (!$this->isPluginActivated('Goals')) {
383 $this->config->show_goals = false;
384 }
385 }
386
387 private function isPluginActivated($pluginName)
388 {
389 return PluginManager::getInstance()->isPluginActivated($pluginName);
390 }
391
392 /**
393 * Assigns a template variable making it available in the Twig template specified by
394 * {@link TEMPLATE_FILE}.
395 *
396 * @param array|string $vars One or more variable names to set.
397 * @param mixed $value The value to set each variable to.
398 * @api
399 */
400 public function assignTemplateVar($vars, $value = null)
401 {
402 if (is_string($vars)) {
403 $this->templateVars[$vars] = $value;
404 } elseif (is_array($vars)) {
405 foreach ($vars as $key => $value) {
406 $this->templateVars[$key] = $value;
407 }
408 }
409 }
410
411 /**
412 * Returns `true` if there is data to display, `false` if otherwise.
413 *
414 * Derived classes should override this method if they change the amount of data that is loaded.
415 *
416 * @api
417 */
418 protected function isThereDataToDisplay()
419 {
420 return !empty($this->dataTable) && 0 < $this->dataTable->getRowsCount();
421 }
422
423 /**
424 * Hook called after the dataTable has been loaded from the API
425 * Can be used to add, delete or modify the data freshly loaded
426 *
427 * @return bool
428 */
429 private function postDataTableLoadedFromAPI()
430 {
431 $columns = $this->dataTable->getColumns();
432 $hasNbVisits = in_array('nb_visits', $columns);
433 $hasNbUniqVisitors = in_array('nb_uniq_visitors', $columns);
434
435 // if any comparison period doesn't support unique visitors, we can't display it for the main table
436 if ($this->isComparing()) {
437 $request = $this->getRequestArray();
438 if (!empty($request['comparePeriods'])) {
439 foreach ($request['comparePeriods'] as $comparePeriod) {
440 if (!SettingsPiwik::isUniqueVisitorsEnabled($comparePeriod)) {
441 $hasNbUniqVisitors = false;
442 break;
443 }
444 }
445 }
446 }
447
448 // default columns_to_display to label, nb_uniq_visitors/nb_visits if those columns exist in the
449 // dataset. otherwise, default to all columns in dataset.
450 if (empty($this->config->columns_to_display)) {
451 $this->config->setDefaultColumnsToDisplay($columns, $hasNbVisits, $hasNbUniqVisitors);
452 }
453
454 if (empty($this->requestConfig->filter_sort_column)) {
455 $this->requestConfig->setDefaultSort($this->config->columns_to_display, $hasNbUniqVisitors, $columns);
456 }
457
458 // deal w/ table metadata
459 if ($this->dataTable instanceof DataTable) {
460 $this->metadata = $this->dataTable->getAllTableMetadata();
461
462 if (isset($this->metadata[DataTable::ARCHIVED_DATE_METADATA_NAME])) {
463 $this->reportLastUpdatedMessage = $this->makePrettyArchivedOnText();
464 }
465 }
466
467 $pivotBy = Common::getRequestVar('pivotBy', false) ?: $this->requestConfig->pivotBy;
468 if (empty($pivotBy)
469 && $this->dataTable instanceof DataTable
470 ) {
471 $this->config->disablePivotBySubtableIfTableHasNoSubtables($this->dataTable);
472 }
473 }
474
475 private function addVisualizationInfoFromMetricMetadata()
476 {
477 $dataTable = $this->dataTable instanceof DataTable\Map ? $this->dataTable->getFirstRow() : $this->dataTable;
478
479 $metrics = Report::getMetricsForTable($dataTable, $this->report);
480
481 // TODO: instead of iterating & calling translate everywhere, maybe we can get all translated names in one place.
482 // may be difficult, though, since translated metrics are specific to the report.
483 foreach ($metrics as $metric) {
484 $name = $metric->getName();
485
486 if (empty($this->config->translations[$name])) {
487 $this->config->translations[$name] = $metric->getTranslatedName();
488 }
489
490 if (empty($this->config->metrics_documentation[$name])) {
491 $this->config->metrics_documentation[$name] = $metric->getDocumentation();
492 }
493 }
494 }
495
496 private function applyFilters()
497 {
498 $postProcessor = $this->makeDataTablePostProcessor(); // must be created after requestConfig is final
499 $self = $this;
500
501 $postProcessor->setCallbackBeforeGenericFilters(function (DataTable\DataTableInterface $dataTable) use ($self, $postProcessor) {
502
503 $self->setDataTable($dataTable);
504
505 // First, filters that delete rows
506 foreach ($self->config->getPriorityFilters() as $filter) {
507 $dataTable->filter($filter[0], $filter[1]);
508 }
509
510 $self->beforeGenericFiltersAreAppliedToLoadedDataTable();
511
512 if (!in_array($self->requestConfig->filter_sort_column, $self->config->columns_to_display)) {
513 $hasNbUniqVisitors = in_array('nb_uniq_visitors', $self->config->columns_to_display);
514 $columns = $dataTable->getColumns();
515 $self->requestConfig->setDefaultSort($self->config->columns_to_display, $hasNbUniqVisitors, $columns);
516 }
517
518 $postProcessor->setRequest($self->buildApiRequestArray());
519 });
520
521 $postProcessor->setCallbackAfterGenericFilters(function (DataTable\DataTableInterface $dataTable) use ($self) {
522
523 $self->setDataTable($dataTable);
524 $self->afterGenericFiltersAreAppliedToLoadedDataTable();
525
526 // queue other filters so they can be applied later if queued filters are disabled
527 foreach ($self->config->getPresentationFilters() as $filter) {
528 $dataTable->queueFilter($filter[0], $filter[1]);
529 }
530
531 if (!empty($this->dataTable)) {
532 $self->removeEmptyColumnsFromDisplay();
533 }
534 });
535
536 $this->dataTable = $postProcessor->process($this->dataTable);
537 }
538
539 private function removeEmptyColumnsFromDisplay()
540 {
541 if ($this->dataTable instanceof DataTable\Map) {
542 $emptyColumns = $this->dataTable->getMetadataIntersectArray(DataTable::EMPTY_COLUMNS_METADATA_NAME);
543 } else {
544 $emptyColumns = $this->dataTable->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME);
545 }
546
547 if (is_array($emptyColumns)) {
548 foreach ($emptyColumns as $emptyColumn) {
549 $key = array_search($emptyColumn, $this->config->columns_to_display);
550 if ($key !== false) {
551 unset($this->config->columns_to_display[$key]);
552 }
553 }
554
555 $this->config->columns_to_display = array_values($this->config->columns_to_display);
556 }
557 }
558
559 /**
560 * Returns prettified and translated text that describes when a report was last updated.
561 *
562 * @return string
563 */
564 private function makePrettyArchivedOnText()
565 {
566 $dateText = $this->metadata[DataTable::ARCHIVED_DATE_METADATA_NAME];
567 $date = Date::factory($dateText);
568 $today = mktime(0, 0, 0);
569 $metricsFormatter = new HtmlFormatter();
570
571 if ($date->getTimestamp() > $today) {
572 $elapsedSeconds = time() - $date->getTimestamp();
573 $timeAgo = $metricsFormatter->getPrettyTimeFromSeconds($elapsedSeconds);
574
575 return Piwik::translate('CoreHome_ReportGeneratedXAgo', $timeAgo);
576 }
577
578 $prettyDate = $date->getLocalized(Date::DATE_FORMAT_SHORT);
579
580 $timezoneAppend = ' (UTC)';
581 return Piwik::translate('CoreHome_ReportGeneratedOn', $prettyDate) . $timezoneAppend;
582 }
583
584 /**
585 * Returns true if it is likely that the data for this report has been purged and if the
586 * user should be told about that.
587 *
588 * In order for this function to return true, the following must also be true:
589 * - The data table for this report must either be empty or not have been fetched.
590 * - The period of this report is not a multiple period.
591 * - The date of this report must be older than the delete_reports_older_than config option.
592 * @return bool
593 */
594 private function hasReportBeenPurged()
595 {
596 if (!$this->isPluginActivated('PrivacyManager')) {
597 return false;
598 }
599
600 return PrivacyManager::hasReportBeenPurged($this->dataTable);
601 }
602
603 /**
604 * Returns array of properties that should be visible to client side JavaScript. The data
605 * will be available in the data-props HTML attribute of the .dataTable div.
606 *
607 * @return array Maps property names w/ property values.
608 */
609 private function getClientSidePropertiesToSet()
610 {
611 $result = array();
612
613 foreach ($this->config->clientSideProperties as $name) {
614 if (property_exists($this->requestConfig, $name)) {
615 $result[$name] = $this->getIntIfValueIsBool($this->requestConfig->$name);
616 } elseif (property_exists($this->config, $name)) {
617 $result[$name] = $this->getIntIfValueIsBool($this->config->$name);
618 }
619 }
620
621 return $result;
622 }
623
624 private function getIntIfValueIsBool($value)
625 {
626 return is_bool($value) ? (int)$value : $value;
627 }
628
629 /**
630 * This functions reads the customization values for the DataTable and returns an array (name,value) to be printed in Javascript.
631 * This array defines things such as:
632 * - name of the module & action to call to request data for this table
633 * - optional filters information, eg. filter_limit and filter_offset
634 * - etc.
635 *
636 * The values are loaded:
637 * - from the generic filters that are applied by default @see Piwik\API\DataTableGenericFilter::getGenericFiltersInformation()
638 * - from the values already available in the GET array
639 * - from the values set using methods from this class (eg. setSearchPattern(), setLimit(), etc.)
640 *
641 * @return array eg. array('show_offset_information' => 0, 'show_...
642 */
643 protected function getClientSideParametersToSet()
644 {
645 // build javascript variables to set
646 $javascriptVariablesToSet = array();
647
648 foreach ($this->config->custom_parameters as $name => $value) {
649 $javascriptVariablesToSet[$name] = $value;
650 }
651
652 foreach ($_GET as $name => $value) {
653 try {
654 $requestValue = Common::getRequestVar($name);
655 } catch (\Exception $e) {
656 $requestValue = '';
657 }
658 $javascriptVariablesToSet[$name] = $requestValue;
659 }
660
661 foreach ($this->requestConfig->clientSideParameters as $name) {
662 if (isset($javascriptVariablesToSet[$name])) {
663 continue;
664 }
665
666 $valueToConvert = false;
667
668 if (property_exists($this->requestConfig, $name)) {
669 $valueToConvert = $this->requestConfig->$name;
670 } elseif (property_exists($this->config, $name)) {
671 $valueToConvert = $this->config->$name;
672 }
673
674 if (false !== $valueToConvert) {
675 $javascriptVariablesToSet[$name] = $this->getIntIfValueIsBool($valueToConvert);
676 }
677 }
678
679 $javascriptVariablesToSet['module'] = $this->config->controllerName;
680 $javascriptVariablesToSet['action'] = $this->config->controllerAction;
681 if (!isset($javascriptVariablesToSet['viewDataTable'])) {
682 $javascriptVariablesToSet['viewDataTable'] = static::getViewDataTableId();
683 }
684
685 if ($this->dataTable &&
686 // Set doesn't have the method
687 !($this->dataTable instanceof DataTable\Map)
688 && empty($javascriptVariablesToSet['totalRows'])
689 ) {
690 $javascriptVariablesToSet['totalRows'] =
691 $this->dataTable->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME) ?: $this->dataTable->getRowsCount();
692 }
693
694 $deleteFromJavascriptVariables = array(
695 'filter_excludelowpop',
696 'filter_excludelowpop_value',
697 );
698
699 foreach ($deleteFromJavascriptVariables as $name) {
700 if (isset($javascriptVariablesToSet[$name])) {
701 unset($javascriptVariablesToSet[$name]);
702 }
703 }
704
705 $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest();
706 if (!empty($rawSegment)) {
707 $javascriptVariablesToSet['segment'] = $rawSegment;
708 }
709
710 if (isset($javascriptVariablesToSet['compareSegments'])) {
711 $javascriptVariablesToSet['compareSegments'] = Common::unsanitizeInputValues($javascriptVariablesToSet['compareSegments']);
712 }
713
714 return $javascriptVariablesToSet;
715 }
716
717 /**
718 * Hook that is called before loading report data from the API.
719 *
720 * Use this method to change the request parameters that is sent to the API when requesting
721 * data.
722 *
723 * @api
724 */
725 public function beforeLoadDataTable()
726 {
727 }
728
729 /**
730 * Hook that is executed before generic filters are applied.
731 *
732 * Use this method if you need access to the entire dataset (since generic filters will
733 * limit and truncate reports).
734 *
735 * @api
736 */
737 public function beforeGenericFiltersAreAppliedToLoadedDataTable()
738 {
739 }
740
741 /**
742 * Hook that is executed after generic filters are applied.
743 *
744 * @api
745 */
746 public function afterGenericFiltersAreAppliedToLoadedDataTable()
747 {
748 }
749
750 /**
751 * Hook that is executed after the report data is loaded and after all filters have been applied.
752 * Use this method to format the report data before the view is rendered.
753 *
754 * @api
755 */
756 public function afterAllFiltersAreApplied()
757 {
758 }
759
760 /**
761 * Hook that is executed directly before rendering. Use this hook to force display properties to
762 * be a certain value, despite changes from plugins and query parameters.
763 *
764 * @api
765 */
766 public function beforeRender()
767 {
768 // eg $this->config->showFooterColumns = true;
769 }
770
771 private function fireBeforeRenderHook()
772 {
773 /**
774 * Posted immediately before rendering the view. Plugins can use this event to perform last minute
775 * configuration of the view based on it's data or the report being viewed.
776 *
777 * @param Visualization $view The instance to configure.
778 */
779 Piwik::postEvent('Visualization.beforeRender', [$this]);
780 }
781
782 private function makeDataTablePostProcessor()
783 {
784 $request = $this->buildApiRequestArray();
785 $module = $this->requestConfig->getApiModuleToRequest();
786 $method = $this->requestConfig->getApiMethodToRequest();
787
788 $processor = new DataTablePostProcessor($module, $method, $request);
789 $processor->setFormatter($this->metricsFormatter);
790
791 return $processor;
792 }
793
794 private function logMessageIfRequestPropertiesHaveChanged(array $requestPropertiesBefore)
795 {
796 $requestProperties = $this->requestConfig->getProperties();
797
798 $diff = array_diff_assoc($this->makeSureArrayContainsOnlyStrings($requestProperties),
799 $this->makeSureArrayContainsOnlyStrings($requestPropertiesBefore));
800
801 if (!empty($diff['filter_sort_column'])) {
802 // this here might be ok as it can be changed after data loaded but before filters applied
803 unset($diff['filter_sort_column']);
804 }
805 if (!empty($diff['filter_sort_order'])) {
806 // this here might be ok as it can be changed after data loaded but before filters applied
807 unset($diff['filter_sort_order']);
808 }
809
810 if (empty($diff)) {
811 return;
812 }
813
814 $details = array(
815 'changedProperties' => $diff,
816 'apiMethod' => $this->requestConfig->apiMethodToRequestDataTable,
817 'controller' => $this->config->controllerName . '.' . $this->config->controllerAction,
818 'viewDataTable' => static::getViewDataTableId()
819 );
820
821 $message = 'Some ViewDataTable::requestConfig properties have changed after requesting the data table. '
822 . 'That means the changed values had probably no effect. For instance in beforeRender() hook. '
823 . 'Probably a bug? Details:'
824 . print_r($details, 1);
825
826 Log::warning($message);
827 }
828
829 private function makeSureArrayContainsOnlyStrings($array)
830 {
831 $result = array();
832
833 foreach ($array as $key => $value) {
834 $result[$key] = json_encode($value);
835 }
836
837 return $result;
838 }
839
840 /**
841 * @internal
842 *
843 * @return array
844 */
845 public function buildApiRequestArray()
846 {
847 $request = $this->getRequestArray();
848
849 if (false === $this->config->enable_sort) {
850 $request['filter_sort_column'] = '';
851 $request['filter_sort_order'] = '';
852 }
853
854 if (!array_key_exists('format_metrics', $request) || $request['format_metrics'] === 'bc') {
855 $request['format_metrics'] = '1';
856 }
857
858 if (!$this->requestConfig->disable_queued_filters && array_key_exists('disable_queued_filters', $request)) {
859 unset($request['disable_queued_filters']);
860 }
861
862 if ($this->isComparing()) {
863 $request['compare'] = '1';
864 }
865
866 return $request;
867 }
868 }
869