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