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