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