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