PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.13.3
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.13.3
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 4 years ago Archiver.php 3 years ago Categories.php 5 years ago ComponentFactory.php 5 years ago ComputedMetric.php 4 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 5 years ago PluginException.php 5 years ago ProcessedMetric.php 5 years ago ReleaseChannels.php 5 years ago Report.php 3 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 3 years ago WidgetsProvider.php 5 years ago
Visualization.php
908 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
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 protected function loadDataTableFromAPI()
315 {
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 $metadata = null;
460 if ($this->dataTable instanceof DataTable) {
461 $metadata = $this->dataTable->getAllTableMetadata();
462 } else {
463 // if the dataTable is Map
464 if ($this->dataTable instanceof DataTable\Map) {
465 // load all the data
466 $dataTable = $this->dataTable->getDataTables();
467 // find the latest key
468 foreach ($dataTable as $item) {
469 $itemMetaData = $item->getAllTableMetadata();
470 // initial metadata and update metadata if current is more recent
471 if (!empty($itemMetaData[DataTable::ARCHIVED_DATE_METADATA_NAME])
472 && (
473 empty($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME])
474 || strtotime($itemMetaData[DataTable::ARCHIVED_DATE_METADATA_NAME]) > strtotime($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME])
475 )
476 ) {
477 $metadata = $itemMetaData;
478 }
479 }
480 }
481 }
482
483 // if metadata set display report date
484 if (!empty($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME])) {
485 $this->reportLastUpdatedMessage = $this->makePrettyArchivedOnText($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME]);
486 }
487
488 $pivotBy = Common::getRequestVar('pivotBy', false) ?: $this->requestConfig->pivotBy;
489 if (empty($pivotBy)
490 && $this->dataTable instanceof DataTable
491 ) {
492 $this->config->disablePivotBySubtableIfTableHasNoSubtables($this->dataTable);
493 }
494 }
495
496 private function addVisualizationInfoFromMetricMetadata()
497 {
498 $dataTable = $this->dataTable instanceof DataTable\Map ? $this->dataTable->getFirstRow() : $this->dataTable;
499
500 $metrics = Report::getMetricsForTable($dataTable, $this->report);
501
502 // TODO: instead of iterating & calling translate everywhere, maybe we can get all translated names in one place.
503 // may be difficult, though, since translated metrics are specific to the report.
504 foreach ($metrics as $metric) {
505 $name = $metric->getName();
506
507 if (empty($this->config->translations[$name])) {
508 $this->config->translations[$name] = $metric->getTranslatedName();
509 }
510
511 if (empty($this->config->metrics_documentation[$name])) {
512 $this->config->metrics_documentation[$name] = $metric->getDocumentation();
513 }
514 }
515 }
516
517 private function applyFilters()
518 {
519 $postProcessor = $this->makeDataTablePostProcessor(); // must be created after requestConfig is final
520 $self = $this;
521
522 $postProcessor->setCallbackBeforeGenericFilters(function (DataTable\DataTableInterface $dataTable) use ($self, $postProcessor) {
523
524 $self->setDataTable($dataTable);
525
526 // First, filters that delete rows
527 foreach ($self->config->getPriorityFilters() as $filter) {
528 $dataTable->filter($filter[0], $filter[1]);
529 }
530
531 $self->beforeGenericFiltersAreAppliedToLoadedDataTable();
532
533 if (!in_array($self->requestConfig->filter_sort_column, $self->config->columns_to_display)) {
534 $hasNbUniqVisitors = in_array('nb_uniq_visitors', $self->config->columns_to_display);
535 $columns = $dataTable->getColumns();
536 $self->requestConfig->setDefaultSort($self->config->columns_to_display, $hasNbUniqVisitors, $columns);
537 }
538
539 $postProcessor->setRequest($self->buildApiRequestArray());
540 });
541
542 $postProcessor->setCallbackAfterGenericFilters(function (DataTable\DataTableInterface $dataTable) use ($self) {
543
544 $self->setDataTable($dataTable);
545 $self->afterGenericFiltersAreAppliedToLoadedDataTable();
546
547 // queue other filters so they can be applied later if queued filters are disabled
548 foreach ($self->config->getPresentationFilters() as $filter) {
549 $dataTable->queueFilter($filter[0], $filter[1]);
550 }
551
552 if (!empty($this->dataTable)) {
553 $self->removeEmptyColumnsFromDisplay();
554 }
555 });
556
557 $this->dataTable = $postProcessor->process($this->dataTable);
558 }
559
560 private function removeEmptyColumnsFromDisplay()
561 {
562 if ($this->dataTable instanceof DataTable\Map) {
563 $emptyColumns = $this->dataTable->getMetadataIntersectArray(DataTable::EMPTY_COLUMNS_METADATA_NAME);
564 } else {
565 $emptyColumns = $this->dataTable->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME);
566 }
567
568 if (is_array($emptyColumns)) {
569 foreach ($emptyColumns as $emptyColumn) {
570 $key = array_search($emptyColumn, $this->config->columns_to_display);
571 if ($key !== false) {
572 unset($this->config->columns_to_display[$key]);
573 }
574 }
575
576 $this->config->columns_to_display = array_values($this->config->columns_to_display);
577 }
578 }
579
580
581 /**
582 * Returns prettified and translated text that describes when a report was last updated.
583 *
584 * @param $dateText
585 * @return string
586 * @throws \Exception
587 */
588 private function makePrettyArchivedOnText($dateText)
589 {
590 $date = Date::factory($dateText);
591 $today = mktime(0, 0, 0);
592 $metricsFormatter = new HtmlFormatter();
593
594 if ($date->getTimestamp() > $today) {
595 $elapsedSeconds = time() - $date->getTimestamp();
596 $timeAgo = $metricsFormatter->getPrettyTimeFromSeconds($elapsedSeconds);
597
598 return Piwik::translate('CoreHome_ReportGeneratedXAgo', $timeAgo);
599 }
600
601 $prettyDate = $date->getLocalized(Date::DATE_FORMAT_SHORT);
602
603 $timezoneAppend = ' (UTC)';
604 return Piwik::translate('CoreHome_ReportGeneratedOn', $prettyDate) . $timezoneAppend;
605 }
606
607 /**
608 * Returns true if it is likely that the data for this report has been purged and if the
609 * user should be told about that.
610 *
611 * In order for this function to return true, the following must also be true:
612 * - The data table for this report must either be empty or not have been fetched.
613 * - The period of this report is not a multiple period.
614 * - The date of this report must be older than the delete_reports_older_than config option.
615 * @return bool
616 */
617 private function hasReportBeenPurged()
618 {
619 if (!$this->isPluginActivated('PrivacyManager')) {
620 return false;
621 }
622
623 return PrivacyManager::hasReportBeenPurged($this->dataTable);
624 }
625
626 /**
627 * Return true if the config for the plug is disabled
628 * @return bool
629 */
630
631 private function hasReportSegmentDisabled()
632 {
633 $module = $this->requestConfig->getApiModuleToRequest();
634 $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest();
635
636 if (!empty($rawSegment) && Rules::isSegmentPluginArchivingDisabled($module)) {
637 return true;
638 }
639 return false;
640 }
641
642 /**
643 * Returns array of properties that should be visible to client side JavaScript. The data
644 * will be available in the data-props HTML attribute of the .dataTable div.
645 *
646 * @return array Maps property names w/ property values.
647 */
648 private function getClientSidePropertiesToSet()
649 {
650 $result = array();
651
652 foreach ($this->config->clientSideProperties as $name) {
653 if (property_exists($this->requestConfig, $name)) {
654 $result[$name] = $this->getIntIfValueIsBool($this->requestConfig->$name);
655 } elseif (property_exists($this->config, $name)) {
656 $result[$name] = $this->getIntIfValueIsBool($this->config->$name);
657 }
658 }
659
660 return $result;
661 }
662
663 private function getIntIfValueIsBool($value)
664 {
665 return is_bool($value) ? (int)$value : $value;
666 }
667
668 /**
669 * This functions reads the customization values for the DataTable and returns an array (name,value) to be printed in Javascript.
670 * This array defines things such as:
671 * - name of the module & action to call to request data for this table
672 * - optional filters information, eg. filter_limit and filter_offset
673 * - etc.
674 *
675 * The values are loaded:
676 * - from the generic filters that are applied by default @see Piwik\API\DataTableGenericFilter::getGenericFiltersInformation()
677 * - from the values already available in the GET array
678 * - from the values set using methods from this class (eg. setSearchPattern(), setLimit(), etc.)
679 *
680 * @return array eg. array('show_offset_information' => 0, 'show_...
681 */
682 protected function getClientSideParametersToSet()
683 {
684 // build javascript variables to set
685 $javascriptVariablesToSet = array();
686
687 foreach ($this->config->custom_parameters as $name => $value) {
688 $javascriptVariablesToSet[$name] = $value;
689 }
690
691 foreach ($_GET as $name => $value) {
692 try {
693 $requestValue = Common::getRequestVar($name);
694 } catch (\Exception $e) {
695 $requestValue = '';
696 }
697 $javascriptVariablesToSet[$name] = $requestValue;
698 }
699
700 foreach ($this->requestConfig->clientSideParameters as $name) {
701 if (isset($javascriptVariablesToSet[$name])) {
702 continue;
703 }
704
705 $valueToConvert = false;
706
707 if (property_exists($this->requestConfig, $name)) {
708 $valueToConvert = $this->requestConfig->$name;
709 } elseif (property_exists($this->config, $name)) {
710 $valueToConvert = $this->config->$name;
711 }
712
713 if (false !== $valueToConvert) {
714 $javascriptVariablesToSet[$name] = $this->getIntIfValueIsBool($valueToConvert);
715 }
716 }
717
718 $javascriptVariablesToSet['module'] = $this->config->controllerName;
719 $javascriptVariablesToSet['action'] = $this->config->controllerAction;
720 if (!isset($javascriptVariablesToSet['viewDataTable'])) {
721 $javascriptVariablesToSet['viewDataTable'] = static::getViewDataTableId();
722 }
723
724 if ($this->dataTable &&
725 // Set doesn't have the method
726 !($this->dataTable instanceof DataTable\Map)
727 && empty($javascriptVariablesToSet['totalRows'])
728 ) {
729 $javascriptVariablesToSet['totalRows'] =
730 $this->dataTable->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME) ?: $this->dataTable->getRowsCount();
731 }
732
733 $deleteFromJavascriptVariables = array(
734 'filter_excludelowpop',
735 'filter_excludelowpop_value',
736 );
737
738 foreach ($deleteFromJavascriptVariables as $name) {
739 if (isset($javascriptVariablesToSet[$name])) {
740 unset($javascriptVariablesToSet[$name]);
741 }
742 }
743
744 $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest();
745 if (!empty($rawSegment)) {
746 $javascriptVariablesToSet['segment'] = $rawSegment;
747 }
748
749 if (isset($javascriptVariablesToSet['compareSegments'])) {
750 $javascriptVariablesToSet['compareSegments'] = Common::unsanitizeInputValues($javascriptVariablesToSet['compareSegments']);
751 }
752
753 return $javascriptVariablesToSet;
754 }
755
756 /**
757 * Hook that is called before loading report data from the API.
758 *
759 * Use this method to change the request parameters that is sent to the API when requesting
760 * data.
761 *
762 * @api
763 */
764 public function beforeLoadDataTable()
765 {
766 }
767
768 /**
769 * Hook that is executed before generic filters are applied.
770 *
771 * Use this method if you need access to the entire dataset (since generic filters will
772 * limit and truncate reports).
773 *
774 * @api
775 */
776 public function beforeGenericFiltersAreAppliedToLoadedDataTable()
777 {
778 }
779
780 /**
781 * Hook that is executed after generic filters are applied.
782 *
783 * @api
784 */
785 public function afterGenericFiltersAreAppliedToLoadedDataTable()
786 {
787 }
788
789 /**
790 * Hook that is executed after the report data is loaded and after all filters have been applied.
791 * Use this method to format the report data before the view is rendered.
792 *
793 * @api
794 */
795 public function afterAllFiltersAreApplied()
796 {
797 }
798
799 /**
800 * Hook that is executed directly before rendering. Use this hook to force display properties to
801 * be a certain value, despite changes from plugins and query parameters.
802 *
803 * @api
804 */
805 public function beforeRender()
806 {
807 // eg $this->config->showFooterColumns = true;
808 }
809
810 private function fireBeforeRenderHook()
811 {
812 /**
813 * Posted immediately before rendering the view. Plugins can use this event to perform last minute
814 * configuration of the view based on it's data or the report being viewed.
815 *
816 * @param Visualization $view The instance to configure.
817 */
818 Piwik::postEvent('Visualization.beforeRender', [$this]);
819 }
820
821 private function makeDataTablePostProcessor()
822 {
823 $request = $this->buildApiRequestArray();
824 $module = $this->requestConfig->getApiModuleToRequest();
825 $method = $this->requestConfig->getApiMethodToRequest();
826
827 $processor = new DataTablePostProcessor($module, $method, $request);
828 $processor->setFormatter($this->metricsFormatter);
829
830 return $processor;
831 }
832
833 private function logMessageIfRequestPropertiesHaveChanged(array $requestPropertiesBefore)
834 {
835 $requestProperties = $this->requestConfig->getProperties();
836
837 $diff = array_diff_assoc($this->makeSureArrayContainsOnlyStrings($requestProperties),
838 $this->makeSureArrayContainsOnlyStrings($requestPropertiesBefore));
839
840 if (!empty($diff['filter_sort_column'])) {
841 // this here might be ok as it can be changed after data loaded but before filters applied
842 unset($diff['filter_sort_column']);
843 }
844 if (!empty($diff['filter_sort_order'])) {
845 // this here might be ok as it can be changed after data loaded but before filters applied
846 unset($diff['filter_sort_order']);
847 }
848
849 if (empty($diff)) {
850 return;
851 }
852
853 $details = array(
854 'changedProperties' => $diff,
855 'apiMethod' => $this->requestConfig->apiMethodToRequestDataTable,
856 'controller' => $this->config->controllerName . '.' . $this->config->controllerAction,
857 'viewDataTable' => static::getViewDataTableId()
858 );
859
860 $message = 'Some ViewDataTable::requestConfig properties have changed after requesting the data table. '
861 . 'That means the changed values had probably no effect. For instance in beforeRender() hook. '
862 . 'Probably a bug? Details:'
863 . print_r($details, 1);
864
865 Log::warning($message);
866 }
867
868 private function makeSureArrayContainsOnlyStrings($array)
869 {
870 $result = array();
871
872 foreach ($array as $key => $value) {
873 $result[$key] = json_encode($value);
874 }
875
876 return $result;
877 }
878
879 /**
880 * @internal
881 *
882 * @return array
883 */
884 public function buildApiRequestArray()
885 {
886 $request = $this->getRequestArray();
887
888 if (false === $this->config->enable_sort) {
889 $request['filter_sort_column'] = '';
890 $request['filter_sort_order'] = '';
891 }
892
893 if (!array_key_exists('format_metrics', $request) || $request['format_metrics'] === 'bc') {
894 $request['format_metrics'] = '1';
895 }
896
897 if (!$this->requestConfig->disable_queued_filters && array_key_exists('disable_queued_filters', $request)) {
898 unset($request['disable_queued_filters']);
899 }
900
901 if ($this->isComparing()) {
902 $request['compare'] = '1';
903 }
904
905 return $request;
906 }
907 }
908