ConsoleCommand
1 month ago
Dimension
1 month ago
API.php
6 months ago
AggregatedMetric.php
2 years ago
ArchivedMetric.php
1 year ago
Archiver.php
1 month ago
Categories.php
2 years ago
ComponentFactory.php
3 months ago
ComputedMetric.php
1 year ago
ConsoleCommand.php
1 month ago
Controller.php
1 month ago
ControllerAdmin.php
2 weeks ago
Dependency.php
1 month ago
LogTablesProvider.php
2 years ago
Manager.php
1 month ago
Menu.php
1 month ago
MetadataLoader.php
1 month ago
Metric.php
1 month ago
PluginException.php
1 year ago
ProcessedMetric.php
3 months ago
ReleaseChannels.php
3 months ago
Report.php
1 month ago
ReportsProvider.php
2 years ago
RequestProcessors.php
4 months ago
Segment.php
3 months ago
SettingsProvider.php
1 month ago
Tasks.php
1 month ago
ThemeStyles.php
2 weeks ago
ViewDataTable.php
3 months ago
Visualization.php
1 year ago
WidgetsProvider.php
3 months ago
Visualization.php
763 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 | private function postDataTableLoadedFromAPI() |
| 371 | { |
| 372 | $columns = $this->dataTable->getColumns(); |
| 373 | $hasNbVisits = in_array('nb_visits', $columns); |
| 374 | $hasNbUniqVisitors = in_array('nb_uniq_visitors', $columns); |
| 375 | // if any comparison period doesn't support unique visitors, we can't display it for the main table |
| 376 | if ($this->isComparing()) { |
| 377 | $request = $this->getRequestArray(); |
| 378 | if (!empty($request['comparePeriods'])) { |
| 379 | foreach ($request['comparePeriods'] as $comparePeriod) { |
| 380 | if (!SettingsPiwik::isUniqueVisitorsEnabled($comparePeriod)) { |
| 381 | $hasNbUniqVisitors = \false; |
| 382 | break; |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | // default columns_to_display to label, nb_uniq_visitors/nb_visits if those columns exist in the |
| 388 | // dataset. otherwise, default to all columns in dataset. |
| 389 | if (empty($this->config->columns_to_display)) { |
| 390 | $this->config->setDefaultColumnsToDisplay($columns, $hasNbVisits, $hasNbUniqVisitors); |
| 391 | } |
| 392 | if (empty($this->requestConfig->filter_sort_column)) { |
| 393 | $this->requestConfig->setDefaultSort($this->config->columns_to_display, $hasNbUniqVisitors, $columns); |
| 394 | } |
| 395 | // deal w/ table metadata |
| 396 | $metadata = null; |
| 397 | if ($this->dataTable instanceof DataTable) { |
| 398 | $metadata = $this->dataTable->getAllTableMetadata(); |
| 399 | } else { |
| 400 | // if the dataTable is Map |
| 401 | if ($this->dataTable instanceof DataTable\Map) { |
| 402 | // load all the data |
| 403 | $dataTable = $this->dataTable->getDataTables(); |
| 404 | // find the latest key |
| 405 | foreach ($dataTable as $item) { |
| 406 | $itemMetaData = $item->getAllTableMetadata(); |
| 407 | // initial metadata and update metadata if current is more recent |
| 408 | 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]))) { |
| 409 | $metadata = $itemMetaData; |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | // if metadata set display report date |
| 415 | if (!empty($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME])) { |
| 416 | $this->reportLastUpdatedMessage = $this->makePrettyArchivedOnText($metadata[DataTable::ARCHIVED_DATE_METADATA_NAME]); |
| 417 | } |
| 418 | $pivotBy = Common::getRequestVar('pivotBy', \false) ?: $this->requestConfig->pivotBy; |
| 419 | if (empty($pivotBy) && $this->dataTable instanceof DataTable) { |
| 420 | $this->config->disablePivotBySubtableIfTableHasNoSubtables($this->dataTable); |
| 421 | } |
| 422 | } |
| 423 | private function addVisualizationInfoFromMetricMetadata() |
| 424 | { |
| 425 | $dataTable = $this->dataTable instanceof DataTable\Map ? $this->dataTable->getFirstRow() : $this->dataTable; |
| 426 | $metrics = \Piwik\Plugin\Report::getMetricsForTable($dataTable, $this->report); |
| 427 | // TODO: instead of iterating & calling translate everywhere, maybe we can get all translated names in one place. |
| 428 | // may be difficult, though, since translated metrics are specific to the report. |
| 429 | foreach ($metrics as $metric) { |
| 430 | $name = $metric->getName(); |
| 431 | if (empty($this->config->translations[$name])) { |
| 432 | $this->config->translations[$name] = $metric->getTranslatedName(); |
| 433 | } |
| 434 | if (empty($this->config->metrics_documentation[$name])) { |
| 435 | $this->config->metrics_documentation[$name] = $metric->getDocumentation(); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | private function applyFilters() |
| 440 | { |
| 441 | $postProcessor = $this->makeDataTablePostProcessor(); |
| 442 | // must be created after requestConfig is final |
| 443 | $self = $this; |
| 444 | $postProcessor->setCallbackBeforeGenericFilters(function (DataTable\DataTableInterface $dataTable) use($self, $postProcessor) { |
| 445 | $self->setDataTable($dataTable); |
| 446 | // First, filters that delete rows |
| 447 | foreach ($self->config->getPriorityFilters() as $filter) { |
| 448 | $dataTable->filter($filter[0], $filter[1]); |
| 449 | } |
| 450 | $self->beforeGenericFiltersAreAppliedToLoadedDataTable(); |
| 451 | if (!in_array($self->requestConfig->filter_sort_column, $self->config->columns_to_display)) { |
| 452 | $hasNbUniqVisitors = in_array('nb_uniq_visitors', $self->config->columns_to_display); |
| 453 | $columns = $dataTable->getColumns(); |
| 454 | $self->requestConfig->setDefaultSort($self->config->columns_to_display, $hasNbUniqVisitors, $columns); |
| 455 | } |
| 456 | $postProcessor->setRequest($self->buildApiRequestArray()); |
| 457 | }); |
| 458 | $postProcessor->setCallbackAfterGenericFilters(function (DataTable\DataTableInterface $dataTable) use($self) { |
| 459 | $self->setDataTable($dataTable); |
| 460 | $self->afterGenericFiltersAreAppliedToLoadedDataTable(); |
| 461 | // queue other filters so they can be applied later if queued filters are disabled |
| 462 | foreach ($self->config->getPresentationFilters() as $filter) { |
| 463 | $dataTable->queueFilter($filter[0], $filter[1]); |
| 464 | } |
| 465 | if (!empty($this->dataTable)) { |
| 466 | $self->removeEmptyColumnsFromDisplay(); |
| 467 | } |
| 468 | }); |
| 469 | $this->dataTable = $postProcessor->process($this->dataTable); |
| 470 | } |
| 471 | private function removeEmptyColumnsFromDisplay() |
| 472 | { |
| 473 | if ($this->dataTable instanceof DataTable\Map) { |
| 474 | $emptyColumns = $this->dataTable->getMetadataIntersectArray(DataTable::EMPTY_COLUMNS_METADATA_NAME); |
| 475 | } else { |
| 476 | $emptyColumns = $this->dataTable->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME); |
| 477 | } |
| 478 | if (is_array($emptyColumns)) { |
| 479 | foreach ($emptyColumns as $emptyColumn) { |
| 480 | $key = array_search($emptyColumn, $this->config->columns_to_display); |
| 481 | if ($key !== \false) { |
| 482 | unset($this->config->columns_to_display[$key]); |
| 483 | } |
| 484 | } |
| 485 | $this->config->columns_to_display = array_values($this->config->columns_to_display); |
| 486 | } |
| 487 | } |
| 488 | /** |
| 489 | * Returns prettified and translated text that describes when a report was last updated. |
| 490 | * |
| 491 | * @param $dateText |
| 492 | * @return string |
| 493 | * @throws \Exception |
| 494 | */ |
| 495 | private function makePrettyArchivedOnText($dateText) |
| 496 | { |
| 497 | $date = Date::factory($dateText); |
| 498 | $today = mktime(0, 0, 0); |
| 499 | $metricsFormatter = new HtmlFormatter(); |
| 500 | if ($date->getTimestamp() > $today) { |
| 501 | $elapsedSeconds = time() - $date->getTimestamp(); |
| 502 | $timeAgo = $metricsFormatter->getPrettyTimeFromSeconds($elapsedSeconds); |
| 503 | return Piwik::translate('CoreHome_ReportGeneratedXAgo', $timeAgo); |
| 504 | } |
| 505 | $prettyDate = $date->getLocalized(Date::DATE_FORMAT_SHORT); |
| 506 | $timezoneAppend = ' (UTC)'; |
| 507 | return Piwik::translate('CoreHome_ReportGeneratedOn', $prettyDate) . $timezoneAppend; |
| 508 | } |
| 509 | /** |
| 510 | * Returns true if it is likely that the data for this report has been purged and if the |
| 511 | * user should be told about that. |
| 512 | * |
| 513 | * In order for this function to return true, the following must also be true: |
| 514 | * - The data table for this report must either be empty or not have been fetched. |
| 515 | * - The period of this report is not a multiple period. |
| 516 | * - The date of this report must be older than the delete_reports_older_than config option. |
| 517 | * @return bool |
| 518 | */ |
| 519 | private function hasReportBeenPurged() |
| 520 | { |
| 521 | if (!$this->isPluginActivated('PrivacyManager')) { |
| 522 | return \false; |
| 523 | } |
| 524 | return PrivacyManager::hasReportBeenPurged($this->dataTable); |
| 525 | } |
| 526 | /** |
| 527 | * Return true if the config for the plug is disabled |
| 528 | * @return bool |
| 529 | */ |
| 530 | private function hasReportSegmentDisabled() |
| 531 | { |
| 532 | $module = $this->requestConfig->getApiModuleToRequest(); |
| 533 | $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest(); |
| 534 | if (!empty($rawSegment) && Rules::isSegmentPluginArchivingDisabled($module)) { |
| 535 | return \true; |
| 536 | } |
| 537 | return \false; |
| 538 | } |
| 539 | /** |
| 540 | * Returns array of properties that should be visible to client side JavaScript. The data |
| 541 | * will be available in the data-props HTML attribute of the .dataTable div. |
| 542 | * |
| 543 | * @return array Maps property names w/ property values. |
| 544 | */ |
| 545 | private function getClientSidePropertiesToSet() |
| 546 | { |
| 547 | $result = array(); |
| 548 | foreach ($this->config->clientSideProperties as $name) { |
| 549 | if (property_exists($this->requestConfig, $name)) { |
| 550 | $result[$name] = $this->getIntIfValueIsBool($this->requestConfig->{$name}); |
| 551 | } elseif (property_exists($this->config, $name)) { |
| 552 | $result[$name] = $this->getIntIfValueIsBool($this->config->{$name}); |
| 553 | } |
| 554 | } |
| 555 | return $result; |
| 556 | } |
| 557 | private function getIntIfValueIsBool($value) |
| 558 | { |
| 559 | return is_bool($value) ? (int) $value : $value; |
| 560 | } |
| 561 | /** |
| 562 | * This functions reads the customization values for the DataTable and returns an array (name,value) to be printed in Javascript. |
| 563 | * This array defines things such as: |
| 564 | * - name of the module & action to call to request data for this table |
| 565 | * - optional filters information, eg. filter_limit and filter_offset |
| 566 | * - etc. |
| 567 | * |
| 568 | * The values are loaded: |
| 569 | * - from the generic filters that are applied by default @see Piwik\API\DataTableGenericFilter::getGenericFiltersInformation() |
| 570 | * - from the values already available in the GET array |
| 571 | * - from the values set using methods from this class (eg. setSearchPattern(), setLimit(), etc.) |
| 572 | * |
| 573 | * @return array eg. array('show_offset_information' => 0, 'show_... |
| 574 | */ |
| 575 | protected function getClientSideParametersToSet() |
| 576 | { |
| 577 | // build javascript variables to set |
| 578 | $javascriptVariablesToSet = array(); |
| 579 | foreach ($this->config->custom_parameters as $name => $value) { |
| 580 | $javascriptVariablesToSet[$name] = $value; |
| 581 | } |
| 582 | foreach ($_GET as $name => $value) { |
| 583 | try { |
| 584 | $requestValue = Common::getRequestVar($name); |
| 585 | } catch (\Exception $e) { |
| 586 | $requestValue = ''; |
| 587 | } |
| 588 | $javascriptVariablesToSet[$name] = $requestValue; |
| 589 | } |
| 590 | foreach ($this->requestConfig->clientSideParameters as $name) { |
| 591 | if (isset($javascriptVariablesToSet[$name])) { |
| 592 | continue; |
| 593 | } |
| 594 | $valueToConvert = \false; |
| 595 | if (property_exists($this->requestConfig, $name)) { |
| 596 | $valueToConvert = $this->requestConfig->{$name}; |
| 597 | } elseif (property_exists($this->config, $name)) { |
| 598 | $valueToConvert = $this->config->{$name}; |
| 599 | } |
| 600 | if (\false !== $valueToConvert) { |
| 601 | $javascriptVariablesToSet[$name] = $this->getIntIfValueIsBool($valueToConvert); |
| 602 | } |
| 603 | } |
| 604 | $javascriptVariablesToSet['module'] = $this->config->controllerName; |
| 605 | $javascriptVariablesToSet['action'] = $this->config->controllerAction; |
| 606 | if (!isset($javascriptVariablesToSet['viewDataTable'])) { |
| 607 | $javascriptVariablesToSet['viewDataTable'] = static::getViewDataTableId(); |
| 608 | } |
| 609 | if ($this->dataTable && !$this->dataTable instanceof DataTable\Map && empty($javascriptVariablesToSet['totalRows'])) { |
| 610 | $javascriptVariablesToSet['totalRows'] = $this->dataTable->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME) ?: $this->dataTable->getRowsCount(); |
| 611 | } |
| 612 | $deleteFromJavascriptVariables = array('filter_excludelowpop', 'filter_excludelowpop_value'); |
| 613 | foreach ($deleteFromJavascriptVariables as $name) { |
| 614 | if (isset($javascriptVariablesToSet[$name])) { |
| 615 | unset($javascriptVariablesToSet[$name]); |
| 616 | } |
| 617 | } |
| 618 | $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest(); |
| 619 | if (!empty($rawSegment)) { |
| 620 | $javascriptVariablesToSet['segment'] = $rawSegment; |
| 621 | } |
| 622 | if (isset($javascriptVariablesToSet['compareSegments'])) { |
| 623 | $javascriptVariablesToSet['compareSegments'] = Common::unsanitizeInputValues($javascriptVariablesToSet['compareSegments']); |
| 624 | } |
| 625 | return $javascriptVariablesToSet; |
| 626 | } |
| 627 | /** |
| 628 | * Hook that is called before loading report data from the API. |
| 629 | * |
| 630 | * Use this method to change the request parameters that is sent to the API when requesting |
| 631 | * data. |
| 632 | * |
| 633 | * @api |
| 634 | */ |
| 635 | public function beforeLoadDataTable() |
| 636 | { |
| 637 | } |
| 638 | /** |
| 639 | * Hook that is executed before generic filters are applied. |
| 640 | * |
| 641 | * Use this method if you need access to the entire dataset (since generic filters will |
| 642 | * limit and truncate reports). |
| 643 | * |
| 644 | * @api |
| 645 | */ |
| 646 | public function beforeGenericFiltersAreAppliedToLoadedDataTable() |
| 647 | { |
| 648 | } |
| 649 | /** |
| 650 | * Hook that is executed after generic filters are applied. |
| 651 | * |
| 652 | * @api |
| 653 | */ |
| 654 | public function afterGenericFiltersAreAppliedToLoadedDataTable() |
| 655 | { |
| 656 | } |
| 657 | /** |
| 658 | * Hook that is executed after the report data is loaded and after all filters have been applied. |
| 659 | * Use this method to format the report data before the view is rendered. |
| 660 | * |
| 661 | * @api |
| 662 | */ |
| 663 | public function afterAllFiltersAreApplied() |
| 664 | { |
| 665 | } |
| 666 | /** |
| 667 | * Hook that is executed directly before rendering. Use this hook to force display properties to |
| 668 | * be a certain value, despite changes from plugins and query parameters. |
| 669 | * |
| 670 | * @api |
| 671 | */ |
| 672 | public function beforeRender() |
| 673 | { |
| 674 | // eg $this->config->showFooterColumns = true; |
| 675 | } |
| 676 | private function fireBeforeRenderHook() |
| 677 | { |
| 678 | /** |
| 679 | * Posted immediately before rendering the view. Plugins can use this event to perform last minute |
| 680 | * configuration of the view based on it's data or the report being viewed. |
| 681 | * |
| 682 | * @param Visualization $view The instance to configure. |
| 683 | */ |
| 684 | Piwik::postEvent('Visualization.beforeRender', [$this]); |
| 685 | } |
| 686 | private function makeDataTablePostProcessor() |
| 687 | { |
| 688 | $request = $this->buildApiRequestArray(); |
| 689 | $module = $this->requestConfig->getApiModuleToRequest(); |
| 690 | $method = $this->requestConfig->getApiMethodToRequest(); |
| 691 | $processor = new DataTablePostProcessor($module, $method, $request); |
| 692 | $processor->setFormatter($this->metricsFormatter); |
| 693 | return $processor; |
| 694 | } |
| 695 | private function logMessageIfRequestPropertiesHaveChanged(array $requestPropertiesBefore) |
| 696 | { |
| 697 | $requestProperties = $this->requestConfig->getProperties(); |
| 698 | $diff = array_diff_assoc($this->makeSureArrayContainsOnlyStrings($requestProperties), $this->makeSureArrayContainsOnlyStrings($requestPropertiesBefore)); |
| 699 | if (!empty($diff['filter_sort_column'])) { |
| 700 | // this here might be ok as it can be changed after data loaded but before filters applied |
| 701 | unset($diff['filter_sort_column']); |
| 702 | } |
| 703 | if (!empty($diff['filter_sort_order'])) { |
| 704 | // this here might be ok as it can be changed after data loaded but before filters applied |
| 705 | unset($diff['filter_sort_order']); |
| 706 | } |
| 707 | if (empty($diff)) { |
| 708 | return; |
| 709 | } |
| 710 | $details = array('changedProperties' => $diff, 'apiMethod' => $this->requestConfig->apiMethodToRequestDataTable, 'controller' => $this->config->controllerName . '.' . $this->config->controllerAction, 'viewDataTable' => static::getViewDataTableId()); |
| 711 | $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); |
| 712 | Log::warning($message); |
| 713 | } |
| 714 | private function makeSureArrayContainsOnlyStrings($array) |
| 715 | { |
| 716 | $result = array(); |
| 717 | foreach ($array as $key => $value) { |
| 718 | $result[$key] = json_encode($value); |
| 719 | } |
| 720 | return $result; |
| 721 | } |
| 722 | /** |
| 723 | * @internal |
| 724 | * |
| 725 | * @return array |
| 726 | */ |
| 727 | public function buildApiRequestArray() |
| 728 | { |
| 729 | $request = $this->getRequestArray(); |
| 730 | if (\false === $this->config->enable_sort) { |
| 731 | $request['filter_sort_column'] = ''; |
| 732 | $request['filter_sort_order'] = ''; |
| 733 | } |
| 734 | if (!array_key_exists('format_metrics', $request) || $request['format_metrics'] === 'bc') { |
| 735 | $request['format_metrics'] = '1'; |
| 736 | } |
| 737 | if (!$this->requestConfig->disable_queued_filters && array_key_exists('disable_queued_filters', $request)) { |
| 738 | unset($request['disable_queued_filters']); |
| 739 | } |
| 740 | if ($this->isComparing()) { |
| 741 | $request['compare'] = '1'; |
| 742 | } |
| 743 | return $request; |
| 744 | } |
| 745 | /** |
| 746 | * Apply the metrics formatting filter to the dataset |
| 747 | * |
| 748 | * This is a workaround to allow visualizations to access unformatted data via format_metrics=0 and then |
| 749 | * subsequently apply formatting without needed to reload the dataset or reapply other filters. This method may |
| 750 | * be removed in the future. |
| 751 | * |
| 752 | * @param bool $forceFormatting if set to true, all metrics will be formatted and request parameter will be ignored |
| 753 | * |
| 754 | * @internal |
| 755 | */ |
| 756 | protected function applyMetricsFormatting(bool $forceFormatting = \false) |
| 757 | { |
| 758 | $postProcessor = $this->makeDataTablePostProcessor(); |
| 759 | // must be created after requestConfig is final |
| 760 | $this->dataTable = $postProcessor->applyMetricsFormatting($this->dataTable, $forceFormatting); |
| 761 | } |
| 762 | } |
| 763 |