diff --git a/core/API/DataTableManipulator.php b/core/API/DataTableManipulator.php index b56cb144969..adcb2eaeedb 100644 --- a/core/API/DataTableManipulator.php +++ b/core/API/DataTableManipulator.php @@ -171,7 +171,8 @@ protected function getApiMethodForSubtable($request) if (empty($meta)) { throw new Exception(sprintf( "The DataTable cannot be manipulated: Metadata for report %s.%s could not be found. You can define the metadata in a hook, see example at: %s", - $this->apiModule, $this->apiMethod, + $this->apiModule, + $this->apiMethod, Url::addCampaignParametersToMatomoLink('https://developer.matomo.org/api-reference/events#apigetreportmetadata') )); } diff --git a/core/API/DataTablePostProcessor.php b/core/API/DataTablePostProcessor.php index 65407229942..1c4484466be 100644 --- a/core/API/DataTablePostProcessor.php +++ b/core/API/DataTablePostProcessor.php @@ -249,7 +249,11 @@ public function applyProcessedMetricsGenericFilters($dataTable) $addNormalProcessedMetrics = null; try { $addNormalProcessedMetrics = Common::getRequestVar( - 'filter_add_columns_when_show_all_columns', null, 'integer', $this->request); + 'filter_add_columns_when_show_all_columns', + null, + 'integer', + $this->request + ); } catch (Exception $ex) { // ignore } @@ -261,7 +265,11 @@ public function applyProcessedMetricsGenericFilters($dataTable) $addGoalProcessedMetrics = null; try { $addGoalProcessedMetrics = Common::getRequestVar( - 'filter_update_columns_when_show_all_goals', false, 'string', $this->request); + 'filter_update_columns_when_show_all_goals', + false, + 'string', + $this->request + ); if ((int) $addGoalProcessedMetrics === 0 && $addGoalProcessedMetrics !== '0' && $addGoalProcessedMetrics != Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER diff --git a/core/API/Request.php b/core/API/Request.php index f12eb738931..6dbd1a226c7 100644 --- a/core/API/Request.php +++ b/core/API/Request.php @@ -474,8 +474,10 @@ public static function checkTokenAuthIsNotLimited($module, $action) } if (Access::getInstance()->hasSuperUserAccess()) { - $ex = new \Piwik\Exception\Exception(Piwik::translate('Widgetize_TooHighAccessLevel', - ['', ''])); + $ex = new \Piwik\Exception\Exception(Piwik::translate( + 'Widgetize_TooHighAccessLevel', + ['', ''] + )); $ex->setIsHtmlMessage(); throw $ex; } @@ -491,9 +493,11 @@ public static function checkTokenAuthIsNotLimited($module, $action) // // NOTE: this does not apply if the [General] enable_framed_allow_write_admin_token_auth INI // option is set. - $ex = new \Piwik\Exception\Exception(Piwik::translate('Widgetize_ViewAccessRequired', + $ex = new \Piwik\Exception\Exception(Piwik::translate( + 'Widgetize_ViewAccessRequired', ['https://matomo.org/faq/troubleshooting/faq_147/'])); + '" rel="noreferrer noopener">https://matomo.org/faq/troubleshooting/faq_147/'] + )); $ex->setIsHtmlMessage(); throw $ex; } diff --git a/core/Access.php b/core/Access.php index 918b123b39d..5e69c56d060 100644 --- a/core/Access.php +++ b/core/Access.php @@ -363,10 +363,11 @@ public function getSitesIdWithAtLeastViewAccess() $this->loadSitesIfNeeded(); return array_unique(array_merge( - $this->idsitesByAccess['view'], - $this->idsitesByAccess['write'], - $this->idsitesByAccess['admin'], - $this->idsitesByAccess['superuser'])); + $this->idsitesByAccess['view'], + $this->idsitesByAccess['write'], + $this->idsitesByAccess['admin'], + $this->idsitesByAccess['superuser'] + )); } /** @@ -381,9 +382,10 @@ public function getSitesIdWithAtLeastWriteAccess() $this->loadSitesIfNeeded(); return array_unique(array_merge( - $this->idsitesByAccess['write'], - $this->idsitesByAccess['admin'], - $this->idsitesByAccess['superuser'])); + $this->idsitesByAccess['write'], + $this->idsitesByAccess['admin'], + $this->idsitesByAccess['superuser'] + )); } /** @@ -397,8 +399,9 @@ public function getSitesIdWithAdminAccess() $this->loadSitesIfNeeded(); return array_unique(array_merge( - $this->idsitesByAccess['admin'], - $this->idsitesByAccess['superuser'])); + $this->idsitesByAccess['admin'], + $this->idsitesByAccess['superuser'] + )); } /** diff --git a/core/Application/Kernel/EnvironmentValidator.php b/core/Application/Kernel/EnvironmentValidator.php index d2f4db51e1d..19bee5aad20 100644 --- a/core/Application/Kernel/EnvironmentValidator.php +++ b/core/Application/Kernel/EnvironmentValidator.php @@ -120,9 +120,13 @@ private function getMessageWhenFileExistsButNotReadable($path) $format = "\n ยป %s \n"; } - return sprintf($format, - $this->translator->translate('General_ExceptionConfigurationFilePleaseCheckReadableByUser', - array($path, Filechecks::getUser()))); + return sprintf( + $format, + $this->translator->translate( + 'General_ExceptionConfigurationFilePleaseCheckReadableByUser', + array($path, Filechecks::getUser()) + ) + ); } /** @@ -137,8 +141,10 @@ private function getSpecificMessageWhetherFileExistsOrNot($path) $message .= $this->getMessageWhenFileExistsButNotReadable($path); } } else { - $message = $this->translator->translate('General_ExceptionConfigurationFileExistsButNotReadable', - array($path)); + $message = $this->translator->translate( + 'General_ExceptionConfigurationFileExistsButNotReadable', + array($path) + ); $message .= $this->getMessageWhenFileExistsButNotReadable($path); } diff --git a/core/Archive/ArchiveInvalidator.php b/core/Archive/ArchiveInvalidator.php index a25dc4ad30b..4f6292ebbe8 100644 --- a/core/Archive/ArchiveInvalidator.php +++ b/core/Archive/ArchiveInvalidator.php @@ -524,8 +524,15 @@ public function reArchiveReport($idSites, string $plugin = null, string $report ) { foreach ($idSites as $idSite) { foreach (Rules::getSegmentsToProcess([$idSite]) as $segment) { - $this->markArchivesAsInvalidated($idSites, $dates, 'day', new Segment($segment, [$idSite]), - $cascadeDown = false, $forceInvalidateRanges = false, $name); + $this->markArchivesAsInvalidated( + $idSites, + $dates, + 'day', + new Segment($segment, [$idSite]), + $cascadeDown = false, + $forceInvalidateRanges = false, + $name + ); } } } diff --git a/core/Archive/ArchivePurger.php b/core/Archive/ArchivePurger.php index de67f2740dc..1eb6544fb23 100644 --- a/core/Archive/ArchivePurger.php +++ b/core/Archive/ArchivePurger.php @@ -204,7 +204,9 @@ protected function getDeletedSegmentArchiveIds(Date $date, array $deletedSegment { $archiveTable = ArchiveTableCreator::getNumericTable($date); return $this->model->getArchiveIdsForSegments( - $archiveTable, $deletedSegments, $this->getOldestTemporaryArchiveToKeepThreshold() + $archiveTable, + $deletedSegments, + $this->getOldestTemporaryArchiveToKeepThreshold() ); } @@ -236,7 +238,11 @@ public function purgeArchivesWithPeriodRange(Date $date) $blobTable = ArchiveTableCreator::getBlobTable($date); $deletedCount = $this->model->deleteArchivesWithPeriod( - $numericTable, $blobTable, Piwik::$idPeriods['range'], $this->purgeCustomRangesOlderThan); + $numericTable, + $blobTable, + Piwik::$idPeriods['range'], + $this->purgeCustomRangesOlderThan + ); $level = $deletedCount == 0 ? 'debug' : 'info'; $this->logger->$level("Purged {count} range archive rows from {numericTable} & {blobTable}.", array( diff --git a/core/Archive/DataCollection.php b/core/Archive/DataCollection.php index 1ed30f380a8..2ebb3a537a2 100644 --- a/core/Archive/DataCollection.php +++ b/core/Archive/DataCollection.php @@ -237,7 +237,13 @@ public function getIndexedArray($resultIndices) public function getDataTable($resultIndices) { $dataTableFactory = new DataTableFactory( - $this->dataNames, $this->dataType, $this->sitesId, $this->periods, $this->segment, $this->defaultRow); + $this->dataNames, + $this->dataType, + $this->sitesId, + $this->periods, + $this->segment, + $this->defaultRow + ); $index = $this->getIndexedArray($resultIndices); @@ -254,7 +260,13 @@ public function getDataTable($resultIndices) public function getMergedDataTable($resultIndices) { $dataTableFactory = new DataTableFactory( - $this->dataNames, $this->dataType, $this->sitesId, $this->periods, $this->segment, $this->defaultRow); + $this->dataNames, + $this->dataType, + $this->sitesId, + $this->periods, + $this->segment, + $this->defaultRow + ); $index = $this->getIndexedArray($resultIndices); @@ -286,7 +298,13 @@ public function getExpandedDataTable($resultIndices, $idSubTable = null, $depth $this->checkExpandedMethodPrerequisites(); $dataTableFactory = new DataTableFactory( - $this->dataNames, 'blob', $this->sitesId, $this->periods, $this->segment, $this->defaultRow); + $this->dataNames, + 'blob', + $this->sitesId, + $this->periods, + $this->segment, + $this->defaultRow + ); $dataTableFactory->expandDataTable($depth, $addMetadataSubTableId); $dataTableFactory->useSubtable($idSubTable); diff --git a/core/ArchiveProcessor/ArchivingStatus.php b/core/ArchiveProcessor/ArchivingStatus.php index 3f90b2b6d83..10f32edd5f5 100644 --- a/core/ArchiveProcessor/ArchivingStatus.php +++ b/core/ArchiveProcessor/ArchivingStatus.php @@ -102,10 +102,19 @@ public function getSitesCurrentlyArchiving() */ private function makeArchivingLock(Parameters $params) { - $doneFlag = Rules::getDoneStringFlagFor([$params->getSite()->getId()], $params->getSegment(), - $params->getPeriod()->getLabel(), $params->getRequestedPlugin()); - return $this->makeArchivingLockFromDoneFlag($params->getSite()->getId(), $params->getSite()->getId(), $params->getPeriod()->getDateStart()->toString(), - $params->getPeriod()->getDateEnd()->toString(), $doneFlag); + $doneFlag = Rules::getDoneStringFlagFor( + [$params->getSite()->getId()], + $params->getSegment(), + $params->getPeriod()->getLabel(), + $params->getRequestedPlugin() + ); + return $this->makeArchivingLockFromDoneFlag( + $params->getSite()->getId(), + $params->getSite()->getId(), + $params->getPeriod()->getDateStart()->toString(), + $params->getPeriod()->getDateEnd()->toString(), + $doneFlag + ); } private function makeArchivingLockFromDoneFlag($idSite, $date1, $date2, $period, $doneFlag) diff --git a/core/ArchiveProcessor/Loader.php b/core/ArchiveProcessor/Loader.php index 0fd5071c3bf..3097acc0484 100644 --- a/core/ArchiveProcessor/Loader.php +++ b/core/ArchiveProcessor/Loader.php @@ -203,8 +203,12 @@ protected function insertArchiveData($visits, $visitsConverted, $existingArchive */ private function makeArchivingLockId() { - $doneFlag = Rules::getDoneStringFlagFor([$this->params->getSite()->getId()], $this->params->getSegment(), - $this->params->getPeriod()->getLabel(), $this->params->getRequestedPlugin()); + $doneFlag = Rules::getDoneStringFlagFor( + [$this->params->getSite()->getId()], + $this->params->getSegment(), + $this->params->getPeriod()->getLabel(), + $this->params->getRequestedPlugin() + ); return $this->params->getPeriod()->getDateStart()->toString() . $this->params->getPeriod()->getDateEnd()->toString() . '.' . $doneFlag; } @@ -605,7 +609,11 @@ private function shouldForceInvalidatedArchive($value, $tsArchived) // if coming from a browser request, and period does contain today, check the ttl for the period (done just below this) $minDatetimeArchiveProcessedUTC = Rules::getMinTimeProcessedForInProgressArchive( - $params->getDateStart(), $params->getPeriod(), $params->getSegment(), $params->getSite()); + $params->getDateStart(), + $params->getPeriod(), + $params->getSegment(), + $params->getSite() + ); $minDatetimeArchiveProcessedUTC = Date::factory($minDatetimeArchiveProcessedUTC); if ($minDatetimeArchiveProcessedUTC && Date::factory($tsArchived)->isEarlier($minDatetimeArchiveProcessedUTC) diff --git a/core/ArchiveProcessor/PluginsArchiver.php b/core/ArchiveProcessor/PluginsArchiver.php index 0e0cd1911bf..793ecc267c7 100644 --- a/core/ArchiveProcessor/PluginsArchiver.php +++ b/core/ArchiveProcessor/PluginsArchiver.php @@ -127,8 +127,12 @@ public function callAggregateCoreMetrics() */ public function callAggregateAllPlugins($visits, $visitsConverted, $forceArchivingWithoutVisits = false) { - Log::debug("PluginsArchiver::%s: Initializing archiving process for all plugins [visits = %s, visits converted = %s]", - __FUNCTION__, $visits, $visitsConverted); + Log::debug( + "PluginsArchiver::%s: Initializing archiving process for all plugins [visits = %s, visits converted = %s]", + __FUNCTION__, + $visits, + $visitsConverted + ); /** @var Logger $performanceLogger */ $performanceLogger = StaticContainer::get(Logger::class); @@ -189,7 +193,8 @@ public function callAggregateAllPlugins($visits, $visitsConverted, $forceArchivi $performanceLogger->logMeasurement('plugin', $pluginName, $this->params, $timer); - Log::debug("PluginsArchiver::%s: %s while archiving %s reports for plugin '%s' %s.", + Log::debug( + "PluginsArchiver::%s: %s while archiving %s reports for plugin '%s' %s.", __FUNCTION__, $timer->getMemoryLeak(), $this->params->getPeriod()->getLabel(), @@ -284,10 +289,12 @@ protected function shouldProcessReportsForPlugin($pluginName) return false; } - if (Rules::shouldProcessReportsAllPlugins( - array($this->params->getSite()->getId()), - $this->params->getSegment(), - $this->params->getPeriod()->getLabel()) + if ( + Rules::shouldProcessReportsAllPlugins( + [$this->params->getSite()->getId()], + $this->params->getSegment(), + $this->params->getPeriod()->getLabel() + ) ) { return true; } diff --git a/core/ArchiveProcessor/Rules.php b/core/ArchiveProcessor/Rules.php index cbd3ea9cd7f..cdb091f556a 100644 --- a/core/ArchiveProcessor/Rules.php +++ b/core/ArchiveProcessor/Rules.php @@ -151,8 +151,10 @@ public static function getMinTimeProcessedForInProgressArchive( // This week, this month, this year: // accept any archive that was processed today after 00:00:01 this morning $timezone = $site->getTimezone(); - $minimumArchiveTime = Date::factory(Date::factory('now', - $timezone)->getDateStartUTC())->setTimezone($timezone)->getTimestamp(); + $minimumArchiveTime = Date::factory(Date::factory( + 'now', + $timezone + )->getDateStartUTC())->setTimezone($timezone)->getTimestamp(); } } return $minimumArchiveTime; diff --git a/core/Changes/Model.php b/core/Changes/Model.php index 63b79b0af85..0486e9338f8 100644 --- a/core/Changes/Model.php +++ b/core/Changes/Model.php @@ -102,7 +102,8 @@ public function addChange(string $pluginName, array $change): void if(!isset($change['version']) || !isset($change['title']) || !isset($change['description'])) { StaticContainer::get(LoggerInterface::class)->warning( "Change item for plugin {plugin} missing version, title or description fields - ignored", - ['plugin' => $pluginName]); + ['plugin' => $pluginName] + ); return; } diff --git a/core/CliMulti.php b/core/CliMulti.php index 2b8547528c7..455600db824 100644 --- a/core/CliMulti.php +++ b/core/CliMulti.php @@ -207,8 +207,16 @@ private function buildCommand($hostname, $query, $outputFileIfAsync, $doEsacpeAr $query = escapeshellarg($query); } - return sprintf('%s %s %s/console climulti:request -q --matomo-domain=%s %s %s %s', - $bin, $this->phpCliOptions, PIWIK_INCLUDE_PATH, $hostname, $superuserCommand, $query, $append); + return sprintf( + '%s %s %s/console climulti:request -q --matomo-domain=%s %s %s %s', + $bin, + $this->phpCliOptions, + PIWIK_INCLUDE_PATH, + $hostname, + $superuserCommand, + $query, + $append + ); } private function getResponse() diff --git a/core/Concurrency/LockBackend/MySqlLockBackend.php b/core/Concurrency/LockBackend/MySqlLockBackend.php index dd648a109b4..f47be08093a 100644 --- a/core/Concurrency/LockBackend/MySqlLockBackend.php +++ b/core/Concurrency/LockBackend/MySqlLockBackend.php @@ -58,9 +58,11 @@ public function setIfNotExists($key, $value, $ttlInSeconds) Db::query($sql, array($key)); } - $query = sprintf('INSERT INTO %s (`key`, `value`, `expiry_time`) + $query = sprintf( + 'INSERT INTO %s (`key`, `value`, `expiry_time`) VALUES (?,?,(UNIX_TIMESTAMP() + ?))', - $tablePrefixed); + $tablePrefixed + ); // we make sure to update the row if the key is expired and consider it as "deleted" try { diff --git a/core/Console.php b/core/Console.php index e8897a0bc52..2e5a3de4a2d 100644 --- a/core/Console.php +++ b/core/Console.php @@ -38,7 +38,8 @@ public function __construct(Environment $environment = null) $this->environment = $environment; - $option = new InputOption('matomo-domain', + $option = new InputOption( + 'matomo-domain', null, InputOption::VALUE_OPTIONAL, 'Matomo URL (protocol and domain) eg. "http://matomo.example.org"' @@ -46,7 +47,8 @@ public function __construct(Environment $environment = null) $this->getDefinition()->addOption($option); - $option = new InputOption('xhprof', + $option = new InputOption( + 'xhprof', null, InputOption::VALUE_NONE, 'Enable profiling with XHProf' @@ -54,8 +56,12 @@ public function __construct(Environment $environment = null) $this->getDefinition()->addOption($option); - $option = new InputOption('ignore-warn', null, InputOption::VALUE_NONE, - 'Return 0 exit code even if there are warning logs or error logs detected in the command output.'); + $option = new InputOption( + 'ignore-warn', + null, + InputOption::VALUE_NONE, + 'Return 0 exit code even if there are warning logs or error logs detected in the command output.' + ); $this->getDefinition()->addOption($option); } diff --git a/core/CronArchive.php b/core/CronArchive.php index d171e36d5d0..89171649b08 100644 --- a/core/CronArchive.php +++ b/core/CronArchive.php @@ -370,8 +370,17 @@ public function run() $countOfProcesses = $this->getMaxConcurrentApiRequests(); - $queueConsumer = new QueueConsumer($this->logger, $this->websiteIdArchiveList, $countOfProcesses, $pid, - $this->model, $this->segmentArchiving, $this, $this->cliMultiRequestParser, $this->archiveFilter); + $queueConsumer = new QueueConsumer( + $this->logger, + $this->websiteIdArchiveList, + $countOfProcesses, + $pid, + $this->model, + $this->segmentArchiving, + $this, + $this->cliMultiRequestParser, + $this->archiveFilter + ); $queueConsumer->setMaxSitesToProcess($this->maxSitesToProcess); @@ -518,8 +527,14 @@ private function launchArchivingFor($archives, QueueConsumer $queueConsumer) $visitsForPeriod = $this->getVisitsFromApiResponse($stats); - $this->logArchiveJobFinished($url, $timers[$index], $visitsForPeriod, - $archivesBeingQueried[$index]['plugin'], $archivesBeingQueried[$index]['report'], !$checkInvalid); + $this->logArchiveJobFinished( + $url, + $timers[$index], + $visitsForPeriod, + $archivesBeingQueried[$index]['plugin'], + $archivesBeingQueried[$index]['report'], + !$checkInvalid + ); $this->deleteInvalidatedArchives($archivesBeingQueried[$index]); @@ -559,8 +574,10 @@ private function generateUrlToArchiveFromArchiveInfo($archive) $url = $this->makeRequestUrl($url); if (!empty($segment)) { - $shouldSkipToday = $this->archiveFilter->isSkipSegmentsForToday() && !$this->wasSegmentChangedRecently($segment, - $this->segmentArchiving->getAllSegments()); + $shouldSkipToday = $this->archiveFilter->isSkipSegmentsForToday() && !$this->wasSegmentChangedRecently( + $segment, + $this->segmentArchiving->getAllSegments() + ); if ($shouldSkipToday) { $url .= '&skipArchiveSegmentToday=1'; @@ -938,8 +955,14 @@ private function invalidateWithSegments($idSites, $date, $period, $_forceInvalid if ($this->canWeSkipInvalidatingBecauseThereIsAUsablePeriod($params, $doNotIncludeTtlInExistingArchiveCheck)) { $this->logger->debug(' Found usable archive for {archive}, skipping invalidation.', ['archive' => $params]); } else { - $this->getApiToInvalidateArchivedReport()->invalidateArchivedReports($idSite, $date, $period, $segment = false, $cascadeDown = false, - $_forceInvalidateNonexistent); + $this->getApiToInvalidateArchivedReport()->invalidateArchivedReports( + $idSite, + $date, + $period, + $segment = false, + $cascadeDown = false, + $_forceInvalidateNonexistent + ); } foreach ($this->segmentArchiving->getAllSegmentsToArchive($idSite) as $segmentDefinition) { @@ -978,8 +1001,14 @@ private function invalidateWithSegments($idSites, $date, $period, $_forceInvalid } } - $this->getApiToInvalidateArchivedReport()->invalidateArchivedReports($idSite, $date, $period, $segmentDefinition, - $cascadeDown = false, $_forceInvalidateNonexistent); + $this->getApiToInvalidateArchivedReport()->invalidateArchivedReports( + $idSite, + $date, + $period, + $segmentDefinition, + $cascadeDown = false, + $_forceInvalidateNonexistent + ); } } } diff --git a/core/CronArchive/Performance/Logger.php b/core/CronArchive/Performance/Logger.php index e7374a3dd97..3dc89c10d62 100644 --- a/core/CronArchive/Performance/Logger.php +++ b/core/CronArchive/Performance/Logger.php @@ -49,10 +49,17 @@ public function logMeasurement($category, $name, ArchiveProcessor\Parameters $ac return; } - $measurement = new Measurement($category, $name, $activeArchivingParams->getSite()->getId(), - $activeArchivingParams->getPeriod()->getRangeString(), $activeArchivingParams->getPeriod()->getLabel(), - $activeArchivingParams->getSegment()->getString(), $timer->getTime(), $timer->getMemoryLeakValue(), - $timer->getPeakMemoryValue()); + $measurement = new Measurement( + $category, + $name, + $activeArchivingParams->getSite()->getId(), + $activeArchivingParams->getPeriod()->getRangeString(), + $activeArchivingParams->getPeriod()->getLabel(), + $activeArchivingParams->getSegment()->getString(), + $timer->getTime(), + $timer->getMemoryLeakValue(), + $timer->getPeakMemoryValue() + ); $params = array_merge($_GET); unset($params['pid']); diff --git a/core/CronArchive/QueueConsumer.php b/core/CronArchive/QueueConsumer.php index b0593cd25b5..d56bd310c77 100644 --- a/core/CronArchive/QueueConsumer.php +++ b/core/CronArchive/QueueConsumer.php @@ -589,7 +589,8 @@ private function getNextIdSiteToArchive() private function getInvalidationDescription(array $invalidatedArchive) { - return sprintf("[idinvalidation = %s, idsite = %s, period = %s(%s - %s), name = %s, segment = %s]", + return sprintf( + "[idinvalidation = %s, idsite = %s, period = %s(%s - %s), name = %s, segment = %s]", $invalidatedArchive['idinvalidation'], $invalidatedArchive['idsite'], $this->periodIdsToLabels[$invalidatedArchive['period']], diff --git a/core/CronArchive/SegmentArchiving.php b/core/CronArchive/SegmentArchiving.php index 87b210cdf59..26b81beb582 100644 --- a/core/CronArchive/SegmentArchiving.php +++ b/core/CronArchive/SegmentArchiving.php @@ -124,8 +124,10 @@ public function getReArchiveSegmentStartDate($segmentInfo) if (empty($segmentLastEditedTime)) { return null; } - $this->logger->debug("process_new_segments_from set to segment_last_edit_time, segment last edit time is {time}", - array('time' => $segmentLastEditedTime)); + $this->logger->debug( + "process_new_segments_from set to segment_last_edit_time, segment last edit time is {time}", + array('time' => $segmentLastEditedTime) + ); return $segmentLastEditedTime; } else if (preg_match("/^editLast([0-9]+)$/", $this->processNewSegmentsFrom, $matches)) { diff --git a/core/DataAccess/ArchiveSelector.php b/core/DataAccess/ArchiveSelector.php index 4184954912e..93248723a9d 100644 --- a/core/DataAccess/ArchiveSelector.php +++ b/core/DataAccess/ArchiveSelector.php @@ -523,7 +523,10 @@ public static function querySingleBlob(array $archiveIds, string $recordName) $chunk = new Chunk(); [$getValuesSql, $bind] = self::getSqlTemplateToFetchArchiveData( - [$recordName], Archive::ID_SUBTABLE_LOAD_ALL_SUBTABLES, true); + [$recordName], + Archive::ID_SUBTABLE_LOAD_ALL_SUBTABLES, + true + ); $archiveIdsPerMonth = self::getArchiveIdsByYearMonth($archiveIds); diff --git a/core/DataAccess/ArchiveWriter.php b/core/DataAccess/ArchiveWriter.php index 49f878d43f6..92c0233f87a 100644 --- a/core/DataAccess/ArchiveWriter.php +++ b/core/DataAccess/ArchiveWriter.php @@ -374,8 +374,10 @@ private function checkDoneValueIsOnlyPartialForPluginArchives($doneValue) // if the done flag is not like done%.PluginName, then it shouldn't be a partial archive. // log a warning. if ($doneValue == self::DONE_PARTIAL && strpos($this->doneFlag, '.') == false) { - $ex = new \Exception(sprintf("Trying to create a partial archive w/ an all plugins done flag (done flag = %s). This should not happen.", - $this->doneFlag)); + $ex = new \Exception(sprintf( + "Trying to create a partial archive w/ an all plugins done flag (done flag = %s). This should not happen.", + $this->doneFlag + )); StaticContainer::get(LoggerInterface::class)->warning('{exception}', [ 'exception' => $ex, ]); diff --git a/core/DataAccess/ArchivingDbAdapter.php b/core/DataAccess/ArchivingDbAdapter.php index 5190564b9d8..f49adcca4a7 100644 --- a/core/DataAccess/ArchivingDbAdapter.php +++ b/core/DataAccess/ArchivingDbAdapter.php @@ -122,8 +122,10 @@ private function callFunction($function, ...$args) $this->isErrNo($e, \Piwik\Updater\Migration\Db::ERROR_CODE_MAX_EXECUTION_TIME_EXCEEDED_SORT_ABORTED) ) { - $this->logger->warning('Archiver query exceeded maximum execution time: {details}', - ['details' => json_encode($args, true)]); + $this->logger->warning( + 'Archiver query exceeded maximum execution time: {details}', + ['details' => json_encode($args, true)] + ); } throw $e; } diff --git a/core/DataAccess/LogAggregator.php b/core/DataAccess/LogAggregator.php index 81125af2928..12fb0697f5c 100644 --- a/core/DataAccess/LogAggregator.php +++ b/core/DataAccess/LogAggregator.php @@ -599,8 +599,16 @@ public function queryVisitsByDimension( $timeLimit = -1, $rankingQueryGenerate = false ) { - $query = $this->getQueryByDimensionSql($dimensions, $where, $additionalSelects, $metrics, $rankingQuery, $orderBy, - $timeLimit, $rankingQueryGenerate); + $query = $this->getQueryByDimensionSql( + $dimensions, + $where, + $additionalSelects, + $metrics, + $rankingQuery, + $orderBy, + $timeLimit, + $rankingQueryGenerate + ); // Ranking queries will return the data directly if ($rankingQuery && !$rankingQueryGenerate) { @@ -1244,10 +1252,13 @@ public function queryConversionsByPageView(string $linkField, int $idGoal) ]; $where = $this->getWhereStatement('log_conversion', 'server_time'); - $where .= sprintf('AND log_conversion.idgoal = %d + $where .= sprintf( + 'AND log_conversion.idgoal = %d AND logva.server_time <= log_conversion.server_time AND lac.type = %s', - (int) $idGoal, ($linkField == 'idaction_url' ? Action::TYPE_PAGE_URL : Action::TYPE_PAGE_TITLE)); + (int) $idGoal, + ($linkField == 'idaction_url' ? Action::TYPE_PAGE_URL : Action::TYPE_PAGE_TITLE) + ); $groupBy = 'log_conversion.idvisit, lac.idaction'; @@ -1268,8 +1279,8 @@ public function queryConversionsByEntryPageView(string $linkField, int $rankingQ $tableName = self::LOG_CONVERSION_TABLE; $select = implode( - ', ', - [ + ', ', + [ 'log_conversion.idgoal AS idgoal', sprintf('log_visit.%s AS idaction', $linkField), 'log_action.type', @@ -1283,7 +1294,7 @@ public function queryConversionsByEntryPageView(string $linkField, int $rankingQ sprintf('SUM(log_conversion.items) AS `%d`', Metrics::INDEX_GOAL_ECOMMERCE_ITEMS), sprintf('COUNT(*) AS `%d`', Metrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY) ] - ); + ); $from = [ $tableName, diff --git a/core/DataAccess/LogQueryBuilder/JoinGenerator.php b/core/DataAccess/LogQueryBuilder/JoinGenerator.php index 0d24d881162..69fcdebb54e 100644 --- a/core/DataAccess/LogQueryBuilder/JoinGenerator.php +++ b/core/DataAccess/LogQueryBuilder/JoinGenerator.php @@ -236,10 +236,20 @@ public function findJoinCriteriasForTables(LogTable $logTable, $availableLogTabl foreach ($availableLogTables as $availableLogTable) { if ($logTable->getColumnToJoinOnIdVisit() && $availableLogTable->getColumnToJoinOnIdVisit()) { - $join = sprintf("%s.%s = %s.%s", $table, $logTable->getColumnToJoinOnIdVisit(), - $availableLogTable->getName(), $availableLogTable->getColumnToJoinOnIdVisit()); - $alternativeJoin = sprintf("%s.%s = %s.%s", $availableLogTable->getName(), $availableLogTable->getColumnToJoinOnIdVisit(), - $table, $logTable->getColumnToJoinOnIdVisit()); + $join = sprintf( + "%s.%s = %s.%s", + $table, + $logTable->getColumnToJoinOnIdVisit(), + $availableLogTable->getName(), + $availableLogTable->getColumnToJoinOnIdVisit() + ); + $alternativeJoin = sprintf( + "%s.%s = %s.%s", + $availableLogTable->getName(), + $availableLogTable->getColumnToJoinOnIdVisit(), + $table, + $logTable->getColumnToJoinOnIdVisit() + ); if ($availableLogTable->shouldJoinWithSubSelect()) { $this->joinWithSubSelect = true; @@ -310,11 +320,21 @@ protected function generateNonVisitJoins($tableName, $tableNameToJoin, $index) $logTable = $this->tables->getLogTable($tableName); $logTableToJoin = $this->tables->getLogTable($tableNameToJoin); - $nonVisitJoin = sprintf("%s.%s = %s.%s", $logTableToJoin->getName(), $logTableToJoin->getColumnToJoinOnIdAction(), - $tableName, $logTable->getColumnToJoinOnIdAction()); - - $altNonVisitJoin = sprintf("%s.%s = %s.%s", $tableName, $logTable->getColumnToJoinOnIdAction(), - $logTableToJoin->getName(), $logTableToJoin->getColumnToJoinOnIdAction()); + $nonVisitJoin = sprintf( + "%s.%s = %s.%s", + $logTableToJoin->getName(), + $logTableToJoin->getColumnToJoinOnIdAction(), + $tableName, + $logTable->getColumnToJoinOnIdAction() + ); + + $altNonVisitJoin = sprintf( + "%s.%s = %s.%s", + $tableName, + $logTable->getColumnToJoinOnIdAction(), + $logTableToJoin->getName(), + $logTableToJoin->getColumnToJoinOnIdAction() + ); if ($index > 0 && $this->tables->hasAddedTableManually($tableName) diff --git a/core/DataAccess/Model.php b/core/DataAccess/Model.php index e859e2599f5..f9be680b0f8 100644 --- a/core/DataAccess/Model.php +++ b/core/DataAccess/Model.php @@ -531,7 +531,8 @@ public function allocateNewArchiveId($numericTable) public function updateArchiveStatus($numericTable, $archiveId, $doneFlag, $value) { - Db::query("UPDATE $numericTable SET `value` = ? WHERE idarchive = ? and `name` = ?", + Db::query( + "UPDATE $numericTable SET `value` = ? WHERE idarchive = ? and `name` = ?", array($value, $archiveId, $doneFlag) ); } diff --git a/core/DataTable.php b/core/DataTable.php index 05d2ca2686b..fac883bbdaf 100644 --- a/core/DataTable.php +++ b/core/DataTable.php @@ -835,7 +835,10 @@ public function addRow(Row $row) $this->addSummaryRow(new Row(array(Row::COLUMNS => $columns))); } else { $this->summaryRow->sumRow( - $row, $enableCopyMetadata = false, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME)); + $row, + $enableCopyMetadata = false, + $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME) + ); } return $this->summaryRow; } @@ -1353,7 +1356,8 @@ public function getSerialized( } if (!is_null($maximumRowsInDataTable)) { - $this->filter('Truncate', + $this->filter( + 'Truncate', array($maximumRowsInDataTable - 1, DataTable::LABEL_SUMMARY_ROW, $columnToSortByBeforeTruncation, @@ -1984,7 +1988,8 @@ protected function aggregateRowWithLabel(Row $row, $columnAggregationOps) { $labelToLookFor = $row->getColumn('label'); if ($labelToLookFor === false) { - $message = sprintf("Label column not found in the table to add in addDataTable(). Row: %s", + $message = sprintf( + "Label column not found in the table to add in addDataTable(). Row: %s", var_export($row->getColumns(), 1) ); throw new Exception($message); diff --git a/core/DataTable/Filter/CalculateEvolutionFilter.php b/core/DataTable/Filter/CalculateEvolutionFilter.php index 5906e1bb8fd..ea0e9f763c2 100644 --- a/core/DataTable/Filter/CalculateEvolutionFilter.php +++ b/core/DataTable/Filter/CalculateEvolutionFilter.php @@ -57,7 +57,13 @@ class CalculateEvolutionFilter extends ColumnCallbackAddColumnPercentage public function __construct($table, $pastDataTable, $columnToAdd, $columnToRead, $quotientPrecision = 0) { parent::__construct( - $table, $columnToAdd, $columnToRead, $columnToRead, $quotientPrecision, $shouldSkipRows = true); + $table, + $columnToAdd, + $columnToRead, + $columnToRead, + $quotientPrecision, + $shouldSkipRows = true + ); $this->pastDataTable = $pastDataTable; diff --git a/core/DataTable/Filter/PivotByDimension.php b/core/DataTable/Filter/PivotByDimension.php index 125c248abbe..a79cdc258ec 100644 --- a/core/DataTable/Filter/PivotByDimension.php +++ b/core/DataTable/Filter/PivotByDimension.php @@ -160,9 +160,16 @@ public function __construct( ) { parent::__construct($table); - Log::debug("PivotByDimension::%s: creating with [report = %s, pivotByDimension = %s, pivotColumn = %s, " - . "pivotByColumnLimit = %s, isFetchingBySegmentEnabled = %s]", __FUNCTION__, $report, $pivotByDimension, - $pivotColumn, $pivotByColumnLimit, $isFetchingBySegmentEnabled); + Log::debug( + "PivotByDimension::%s: creating with [report = %s, pivotByDimension = %s, pivotColumn = %s, " + . "pivotByColumnLimit = %s, isFetchingBySegmentEnabled = %s]", + __FUNCTION__, + $report, + $pivotByDimension, + $pivotColumn, + $pivotByColumnLimit, + $isFetchingBySegmentEnabled + ); $this->pivotByColumnLimit = $pivotByColumnLimit ?: self::getDefaultColumnLimit(); $this->isFetchingBySegmentEnabled = $isFetchingBySegmentEnabled; diff --git a/core/DataTable/Row.php b/core/DataTable/Row.php index b85e9afbed1..bb8dc8e4cab 100644 --- a/core/DataTable/Row.php +++ b/core/DataTable/Row.php @@ -584,9 +584,11 @@ public function sumRowMetadata($rowToSum, $aggregationOperations = array()) } // We shall update metadata, and keep the metadata with the _most visits or pageviews_, rather than first or last seen - $visits = max($rowToSum->getColumn(Metrics::INDEX_PAGE_NB_HITS) || $rowToSum->getColumn(Metrics::INDEX_NB_VISITS), + $visits = max( + $rowToSum->getColumn(Metrics::INDEX_PAGE_NB_HITS) || $rowToSum->getColumn(Metrics::INDEX_NB_VISITS), // Old format pre-1.2, @see also method doSumVisitsMetrics() - $rowToSum->getColumn('nb_actions') || $rowToSum->getColumn('nb_visits')); + $rowToSum->getColumn('nb_actions') || $rowToSum->getColumn('nb_visits') + ); if (($visits && $visits > $this->maxVisitsSummed) || empty($this->metadata) ) { @@ -663,8 +665,13 @@ protected function sumRowArray($thisColumnValue, $columnToSumValue, $columnName $label = $this->getColumn('label'); $thisColumnDescription = $this->getColumnValueDescriptionForError($thisColumnValue); $columnToSumValueDescription = $this->getColumnValueDescriptionForError($columnToSumValue); - throw new \Exception(sprintf('Trying to sum unsupported operands for column %s in row with label = %s: %s + %s', - $columnName, $label, $thisColumnDescription, $columnToSumValueDescription)); + throw new \Exception(sprintf( + 'Trying to sum unsupported operands for column %s in row with label = %s: %s + %s', + $columnName, + $label, + $thisColumnDescription, + $columnToSumValueDescription + )); } return $thisColumnValue + $columnToSumValue; diff --git a/core/Db/Schema/Mysql.php b/core/Db/Schema/Mysql.php index 7762c2a03f5..eb6352231f6 100644 --- a/core/Db/Schema/Mysql.php +++ b/core/Db/Schema/Mysql.php @@ -539,12 +539,14 @@ public function createTable($nameWithoutPrefix, $createDefinition) $dbSettings = new Db\Settings(); $charset = $dbSettings->getUsedCharset(); - $statement = sprintf("CREATE TABLE IF NOT EXISTS `%s` ( %s ) ENGINE=%s DEFAULT CHARSET=%s %s;", - Common::prefixTable($nameWithoutPrefix), - $createDefinition, - $this->getTableEngine(), - $charset, - $dbSettings->getRowFormat()); + $statement = sprintf( + "CREATE TABLE IF NOT EXISTS `%s` ( %s ) ENGINE=%s DEFAULT CHARSET=%s %s;", + Common::prefixTable($nameWithoutPrefix), + $createDefinition, + $this->getTableEngine(), + $charset, + $dbSettings->getRowFormat() + ); try { Db::exec($statement); diff --git a/core/Http.php b/core/Http.php index 0f52b763b7c..bc1729a5d85 100644 --- a/core/Http.php +++ b/core/Http.php @@ -103,9 +103,26 @@ public static function sendHttpRequest( $file = self::ensureDestinationDirectoryExists($destinationPath); $acceptLanguage = $acceptLanguage ? 'Accept-Language: ' . $acceptLanguage : ''; - return self::sendHttpRequestBy(self::getTransportMethod(), $aUrl, $timeout, $userAgent, $destinationPath, $file, - $followDepth, $acceptLanguage, $acceptInvalidSslCertificate = false, $byteRange, $getExtendedInfo, $httpMethod, - $httpUsername, $httpPassword, null, [], null, $checkHostIsAllowed); + return self::sendHttpRequestBy( + self::getTransportMethod(), + $aUrl, + $timeout, + $userAgent, + $destinationPath, + $file, + $followDepth, + $acceptLanguage, + $acceptInvalidSslCertificate = false, + $byteRange, + $getExtendedInfo, + $httpMethod, + $httpUsername, + $httpPassword, + null, + [], + null, + $checkHostIsAllowed + ); } public static function ensureDestinationDirectoryExists($destinationPath) @@ -882,7 +899,8 @@ public static function downloadChunk($url, $outputPath, $isContinuation) ) { throw new Exception( Piwik::translate('General_DownloadFail_FileExists', "'" . $outputPath . "'") - . ' ' . Piwik::translate('General_DownloadPleaseRemoveExisting')); + . ' ' . Piwik::translate('General_DownloadPleaseRemoveExisting') + ); } // if we're starting a download, get the expected file size & save as an option @@ -924,7 +942,8 @@ public static function downloadChunk($url, $outputPath, $isContinuation) if ($existingSize >= $expectedFileSize) { throw new Exception( Piwik::translate('General_DownloadFail_FileExistsContinue', "'" . $outputPath . "'") - . ' ' . Piwik::translate('General_DownloadPleaseRemoveExisting')); + . ' ' . Piwik::translate('General_DownloadPleaseRemoveExisting') + ); } // download a chunk of the file @@ -944,8 +963,13 @@ public static function downloadChunk($url, $outputPath, $isContinuation) || $result['status'] > 299 ) { $result['data'] = self::truncateStr($result['data'], 1024); - Log::info("Failed to download range '%s-%s' of file from url '%s'. Got result: %s", - $byteRange[0], $byteRange[1], $url, print_r($result, true)); + Log::info( + "Failed to download range '%s-%s' of file from url '%s'. Got result: %s", + $byteRange[0], + $byteRange[1], + $url, + print_r($result, true) + ); throw new Exception(Piwik::translate('General_DownloadFail_HttpRequestFail')); } diff --git a/core/Menu/MenuAbstract.php b/core/Menu/MenuAbstract.php index d97225dbbb0..347d5876e3f 100644 --- a/core/Menu/MenuAbstract.php +++ b/core/Menu/MenuAbstract.php @@ -219,8 +219,18 @@ private function buildMenuItem( private function buildMenu() { foreach ($this->menuEntries as $menuEntry) { - $this->buildMenuItem($menuEntry[0], $menuEntry[1], $menuEntry[2], $menuEntry[3], $menuEntry[4], - $menuEntry[5], $menuEntry[6], $menuEntry[7], $menuEntry[8], $menuEntry[9]); + $this->buildMenuItem( + $menuEntry[0], + $menuEntry[1], + $menuEntry[2], + $menuEntry[3], + $menuEntry[4], + $menuEntry[5], + $menuEntry[6], + $menuEntry[7], + $menuEntry[8], + $menuEntry[9] + ); } } @@ -388,7 +398,8 @@ protected function menuCompare($itemOne, $itemTwo) if ($itemOne['_order'] == $itemTwo['_order']) { return strcmp( $itemOne['_name'] ?? '', - $itemTwo['_name'] ?? ''); + $itemTwo['_name'] ?? '' + ); } return ($itemOne['_order'] < $itemTwo['_order']) ? -1 : 1; diff --git a/core/Nonce.php b/core/Nonce.php index 5a248639ac5..d1d13dd9b76 100644 --- a/core/Nonce.php +++ b/core/Nonce.php @@ -101,7 +101,8 @@ public static function verifyNonceWithErrorMessage($id, $cnonce, $allowedReferre // The Session cookie is set to a secure cookie, when SSL is mis-configured, it can cause the PHP session cookie ID to change on each page view. // Indicate to user how to solve this particular use case by forcing secure connections. if (Url::isSecureConnectionAssumedByPiwikButNotForcedYet()) { - $additionalErrors = '

' . Piwik::translate('Login_InvalidNonceSSLMisconfigured', + $additionalErrors = '

' . Piwik::translate( + 'Login_InvalidNonceSSLMisconfigured', array( '', '', @@ -109,7 +110,7 @@ public static function verifyNonceWithErrorMessage($id, $cnonce, $allowedReferre '
force_ssl=1
', '
[General]
', ) - ); + ); } // validate token diff --git a/core/Period/Year.php b/core/Period/Year.php index 13c70baac31..0d81c5e0c3b 100644 --- a/core/Period/Year.php +++ b/core/Period/Year.php @@ -66,8 +66,8 @@ protected function generate() $year = $this->date->toString("Y"); for ($i = 1; $i <= 12; $i++) { $this->addSubperiod(new Month( - Date::factory("$year-$i-01") - )); + Date::factory("$year-$i-01") + )); } } diff --git a/core/Piwik.php b/core/Piwik.php index 0cf7d2b5be6..5402a22cfcd 100644 --- a/core/Piwik.php +++ b/core/Piwik.php @@ -135,8 +135,13 @@ public static function getQuotientSafe($dividend, $divisor, $precision = 0) $dividend = 0; } if (!is_numeric($dividend) || !is_numeric($divisor)) { - throw new \Exception(sprintf('Trying to round unsupported operands for dividend %s (%s) and divisor %s (%s)', - $dividend, gettype($dividend), $divisor, gettype($divisor))); + throw new \Exception(sprintf( + 'Trying to round unsupported operands for dividend %s (%s) and divisor %s (%s)', + $dividend, + gettype($dividend), + $divisor, + gettype($divisor) + )); } return round($dividend / $divisor, $precision); } @@ -365,7 +370,8 @@ public static function requestTemporarySystemAuthToken($reason, $validForHours) 'System generated ' . $reason, Date::now()->getDatetime(), $expireDate, - true); + true + ); return $token[$reason]; } @@ -722,9 +728,9 @@ public static function getArrayFromApiParameter($columns, $unique = true) public static function redirectToModule($newModule, $newAction = '', $parameters = array()) { $newUrl = 'index.php' . Url::getCurrentQueryStringWithParametersModified( - array('module' => $newModule, 'action' => $newAction) + array('module' => $newModule, 'action' => $newAction) + $parameters - ); + ); Url::redirectToUrl($newUrl); } diff --git a/core/Plugin.php b/core/Plugin.php index 7106803dc97..edc81936391 100644 --- a/core/Plugin.php +++ b/core/Plugin.php @@ -388,8 +388,13 @@ public function findComponent($componentName, $expectedSubclass) } if (!empty($expectedSubclass) && !is_subclass_of($classname, $expectedSubclass)) { - Log::warning(sprintf('Cannot use component %s for plugin %s, class %s does not extend %s', - $componentName, $this->pluginName, $classname, $expectedSubclass)); + Log::warning(sprintf( + 'Cannot use component %s for plugin %s, class %s does not extend %s', + $componentName, + $this->pluginName, + $classname, + $expectedSubclass + )); return null; } diff --git a/core/Plugin/ComponentFactory.php b/core/Plugin/ComponentFactory.php index d79a2f2959e..7654dbdcd0d 100644 --- a/core/Plugin/ComponentFactory.php +++ b/core/Plugin/ComponentFactory.php @@ -37,8 +37,12 @@ class ComponentFactory public static function factory($pluginName, $componentClassSimpleName, $componentTypeClass) { if (empty($pluginName) || empty($componentClassSimpleName)) { - Log::debug("ComponentFactory::%s: empty plugin name or component simple name requested (%s, %s)", - __FUNCTION__, $pluginName, $componentClassSimpleName); + Log::debug( + "ComponentFactory::%s: empty plugin name or component simple name requested (%s, %s)", + __FUNCTION__, + $pluginName, + $componentClassSimpleName + ); return null; } @@ -58,8 +62,13 @@ public static function factory($pluginName, $componentClassSimpleName, $componen } } - Log::debug("ComponentFactory::%s: Could not find requested component (args = ['%s', '%s', '%s']).", - __FUNCTION__, $pluginName, $componentClassSimpleName, $componentTypeClass); + Log::debug( + "ComponentFactory::%s: Could not find requested component (args = ['%s', '%s', '%s']).", + __FUNCTION__, + $pluginName, + $componentClassSimpleName, + $componentTypeClass + ); return null; } @@ -99,8 +108,13 @@ public static function getComponentIf($componentTypeClass, $pluginName, $predica } } - Log::debug("ComponentFactory::%s: Could not find component that satisfies predicate (args = ['%s', '%s', '%s']).", - __FUNCTION__, $componentTypeClass, $pluginName, get_class($predicate)); + Log::debug( + "ComponentFactory::%s: Could not find component that satisfies predicate (args = ['%s', '%s', '%s']).", + __FUNCTION__, + $componentTypeClass, + $pluginName, + get_class($predicate) + ); return null; } @@ -115,8 +129,11 @@ private static function getActivatedPlugin($function, $pluginName) $pluginManager = PluginManager::getInstance(); try { if (!$pluginManager->isPluginActivated($pluginName)) { - Log::debug("ComponentFactory::%s: component for deactivated plugin ('%s') requested.", - $function, $pluginName); + Log::debug( + "ComponentFactory::%s: component for deactivated plugin ('%s') requested.", + $function, + $pluginName + ); return null; } diff --git a/core/Plugin/Controller.php b/core/Plugin/Controller.php index ad183e790e1..97a86522e41 100644 --- a/core/Plugin/Controller.php +++ b/core/Plugin/Controller.php @@ -405,7 +405,11 @@ protected function renderReport($apiAction, $controllerAction = false) protected function getLastUnitGraph($currentModuleName, $currentControllerAction, $apiMethod) { $view = ViewDataTableFactory::build( - Evolution::ID, $apiMethod, $currentModuleName . '.' . $currentControllerAction, $forceDefault = true); + Evolution::ID, + $apiMethod, + $currentModuleName . '.' . $currentControllerAction, + $forceDefault = true + ); $view->config->show_goals = false; return $view; } diff --git a/core/Plugin/Dimension/DimensionMetadataProvider.php b/core/Plugin/Dimension/DimensionMetadataProvider.php index 6484e323f9c..d767fcecec3 100644 --- a/core/Plugin/Dimension/DimensionMetadataProvider.php +++ b/core/Plugin/Dimension/DimensionMetadataProvider.php @@ -64,7 +64,8 @@ public function getActionReferenceColumnsByTable() $dimensionIdActionColumns = $this->getVisitActionTableActionReferences(); $result['log_link_visit_action'] = array_unique( - array_merge($result['log_link_visit_action'], $dimensionIdActionColumns)); + array_merge($result['log_link_visit_action'], $dimensionIdActionColumns) + ); foreach ($this->actionReferenceColumnsOverride as $table => $columns) { if (empty($result[$table])) { diff --git a/core/Plugin/ViewDataTable.php b/core/Plugin/ViewDataTable.php index 529b19d2ead..5f61c484eaa 100644 --- a/core/Plugin/ViewDataTable.php +++ b/core/Plugin/ViewDataTable.php @@ -219,8 +219,10 @@ public function __construct($controllerAction, $apiMethodToRequestDataTable, $ov $relatedReportName = $relatedReport->getName(); - $this->config->addRelatedReport($relatedReport->getModule() . '.' . $relatedReport->getAction(), - $relatedReportName); + $this->config->addRelatedReport( + $relatedReport->getModule() . '.' . $relatedReport->getAction(), + $relatedReportName + ); } } diff --git a/core/Plugin/Visualization.php b/core/Plugin/Visualization.php index 034fe63f2ae..2f454760f6e 100644 --- a/core/Plugin/Visualization.php +++ b/core/Plugin/Visualization.php @@ -838,8 +838,10 @@ private function logMessageIfRequestPropertiesHaveChanged(array $requestProperti { $requestProperties = $this->requestConfig->getProperties(); - $diff = array_diff_assoc($this->makeSureArrayContainsOnlyStrings($requestProperties), - $this->makeSureArrayContainsOnlyStrings($requestPropertiesBefore)); + $diff = array_diff_assoc( + $this->makeSureArrayContainsOnlyStrings($requestProperties), + $this->makeSureArrayContainsOnlyStrings($requestPropertiesBefore) + ); if (!empty($diff['filter_sort_column'])) { // this here might be ok as it can be changed after data loaded but before filters applied diff --git a/core/ProfessionalServices/Advertising.php b/core/ProfessionalServices/Advertising.php index ad16a15ec67..29a0665c702 100644 --- a/core/ProfessionalServices/Advertising.php +++ b/core/ProfessionalServices/Advertising.php @@ -56,7 +56,8 @@ public function areAdsForProfessionalServicesEnabled() */ public function getPromoUrlForProfessionalServices($campaignMedium, $campaignContent = '') { - return Url::addCampaignParametersToMatomoLink('https://matomo.org/support-plans/', + return Url::addCampaignParametersToMatomoLink( + 'https://matomo.org/support-plans/', self::CAMPAIGN_NAME_PROFESSIONAL_SERVICES, null, $campaignMedium diff --git a/core/ReportRenderer/Html.php b/core/ReportRenderer/Html.php index 71b77c00dcc..79c28175eda 100644 --- a/core/ReportRenderer/Html.php +++ b/core/ReportRenderer/Html.php @@ -83,8 +83,15 @@ private function epilogue() public function renderFrontPage($reportTitle, $prettyDate, $description, $reportMetadata, $segment) { - $frontPageView = new View\HtmlReportEmailHeaderView($reportTitle, $prettyDate, $description, $reportMetadata, - $segment, $this->idSite, $this->report['period']); + $frontPageView = new View\HtmlReportEmailHeaderView( + $reportTitle, + $prettyDate, + $description, + $reportMetadata, + $segment, + $this->idSite, + $this->report['period'] + ); $this->rendering .= $frontPageView->render(); } diff --git a/core/Scheduler/Schedule/Daily.php b/core/Scheduler/Schedule/Daily.php index 8c402300885..7e1ac006a04 100644 --- a/core/Scheduler/Schedule/Daily.php +++ b/core/Scheduler/Schedule/Daily.php @@ -28,7 +28,8 @@ public function getRescheduledTime() $currentTime = $this->getTime(); // Add one day - $rescheduledTime = mktime(date('H', $currentTime), + $rescheduledTime = mktime( + date('H', $currentTime), date('i', $currentTime), date('s', $currentTime), date('n', $currentTime), diff --git a/core/Scheduler/Schedule/Hourly.php b/core/Scheduler/Schedule/Hourly.php index 69f48891482..ac1815eaf92 100644 --- a/core/Scheduler/Schedule/Hourly.php +++ b/core/Scheduler/Schedule/Hourly.php @@ -27,7 +27,8 @@ public function getRescheduledTime() $currentTime = $this->getTime(); // Adds one hour and reset the number of minutes - $rescheduledTime = mktime(date('H', $currentTime) + 1, + $rescheduledTime = mktime( + date('H', $currentTime) + 1, 0, date('s', $currentTime), date('n', $currentTime), diff --git a/core/Scheduler/Schedule/Monthly.php b/core/Scheduler/Schedule/Monthly.php index fb5e7dabb0e..46d6a866698 100644 --- a/core/Scheduler/Schedule/Monthly.php +++ b/core/Scheduler/Schedule/Monthly.php @@ -64,7 +64,8 @@ public function getRescheduledTime() $currentTime = $this->getTime(); // Adds one month - $rescheduledTime = mktime(date('H', $currentTime), + $rescheduledTime = mktime( + date('H', $currentTime), date('i', $currentTime), date('s', $currentTime), date('n', $currentTime) + 1, diff --git a/core/Scheduler/Schedule/Schedule.php b/core/Scheduler/Schedule/Schedule.php index e7b40321218..552d9926c1b 100644 --- a/core/Scheduler/Schedule/Schedule.php +++ b/core/Scheduler/Schedule/Schedule.php @@ -164,7 +164,8 @@ protected function adjustHour($rescheduledTime) { if ($this->hour !== null) { // Reset the number of minutes and set the scheduled hour to the one specified with setHour() - $rescheduledTime = mktime($this->hour, + $rescheduledTime = mktime( + $this->hour, 0, date('s', $rescheduledTime), date('n', $rescheduledTime), diff --git a/core/Scheduler/Schedule/Weekly.php b/core/Scheduler/Schedule/Weekly.php index 95c4f6cd6fc..b847036de5a 100644 --- a/core/Scheduler/Schedule/Weekly.php +++ b/core/Scheduler/Schedule/Weekly.php @@ -38,7 +38,8 @@ public function getRescheduledTime() } // Adds correct number of days - $rescheduledTime = mktime(date('H', $currentTime), + $rescheduledTime = mktime( + date('H', $currentTime), date('i', $currentTime), date('s', $currentTime), date('n', $currentTime), diff --git a/core/Scheduler/Scheduler.php b/core/Scheduler/Scheduler.php index 2a265fc7e6d..0c34910cdec 100644 --- a/core/Scheduler/Scheduler.php +++ b/core/Scheduler/Scheduler.php @@ -161,16 +161,20 @@ public function run() // Task has already been retried three times, give up $this->timetable->clearRetryCount($task->getName()); - $this->logger->warning("Scheduler: '{task}' has already been retried three times, giving up", - ['task' => $task->getName()]); + $this->logger->warning( + "Scheduler: '{task}' has already been retried three times, giving up", + ['task' => $task->getName()] + ); } else { $readFromOption = true; $rescheduledDate = $this->timetable->rescheduleTaskAndRunInOneHour($task); $this->timetable->incrementRetryCount($task->getName()); - $this->logger->info("Scheduler: '{task}' retry scheduled for {date}", - ['task' => $task->getName(), 'date' => $rescheduledDate]); + $this->logger->info( + "Scheduler: '{task}' retry scheduled for {date}", + ['task' => $task->getName(), 'date' => $rescheduledDate] + ); } $this->scheduleRetry = false; } else { @@ -308,8 +312,10 @@ private function executeTask($task) call_user_func($callable, $task->getMethodParameter()); $message = $timer->__toString(); } catch (\Exception $e) { - $this->logger->error("Scheduler: Error {errorMessage} for task '{task}'", - ['errorMessage' => $e->getMessage(), 'task' => $task->getName()]); + $this->logger->error( + "Scheduler: Error {errorMessage} for task '{task}'", + ['errorMessage' => $e->getMessage(), 'task' => $task->getName()] + ); $message = 'ERROR: ' . $e->getMessage(); // If the task has indicated that retrying on exception is safe then flag for rescheduling diff --git a/core/Segment.php b/core/Segment.php index 28c88e70285..b6c1c5ac279 100644 --- a/core/Segment.php +++ b/core/Segment.php @@ -592,8 +592,16 @@ public function getSelectQuery($select, $from, $where = false, $bind = array(), if ($forceGroupBy && $groupBy) { $this->segmentQueryBuilder->forceInnerGroupBySubselect(LogQueryBuilder::FORCE_INNER_GROUP_BY_NO_SUBSELECT); } - $result = $this->segmentQueryBuilder->getSelectQueryString($segmentExpression, $select, $from, $where, $bind, - $groupBy, $orderBy, $limitAndOffset); + $result = $this->segmentQueryBuilder->getSelectQueryString( + $segmentExpression, + $select, + $from, + $where, + $bind, + $groupBy, + $orderBy, + $limitAndOffset + ); } catch (Exception $e) { if ($forceGroupBy && $groupBy) { $this->segmentQueryBuilder->forceInnerGroupBySubselect(''); diff --git a/core/Session.php b/core/Session.php index 78f773cfba1..ae374ce2157 100644 --- a/core/Session.php +++ b/core/Session.php @@ -127,7 +127,8 @@ public static function start($options = false) $pathToSessions = Filechecks::getErrorMessageMissingPermissions(self::getSessionsDirectory()); } - $message = sprintf("Error: %s %s\n
Debug: the original error was \n%s
", + $message = sprintf( + "Error: %s %s\n
Debug: the original error was \n%s
", Piwik::translate('General_ExceptionUnableToStartSession'), $pathToSessions, $e->getMessage() diff --git a/core/Session/SessionAuth.php b/core/Session/SessionAuth.php index 2051eeb4d1f..43695d919f6 100644 --- a/core/Session/SessionAuth.php +++ b/core/Session/SessionAuth.php @@ -238,7 +238,8 @@ private function checkIfSessionFailedToRead() { if (Session\SaveHandler\DbTable::$wasSessionToLargeToRead) { StaticContainer::get(LoggerInterface::class)->warning( - "Too much data stored in the session so it could not be read properly. If you were logged out, this is why."); + "Too much data stored in the session so it could not be read properly. If you were logged out, this is why." + ); } } } diff --git a/core/Settings/Setting.php b/core/Settings/Setting.php index 02fa8759715..42aa094676f 100644 --- a/core/Settings/Setting.php +++ b/core/Settings/Setting.php @@ -255,8 +255,10 @@ private function validateValue($value) } // TODO move error message creation to a subclass, eg in MeasurableSettings we do not want to mention plugin name - $errorMsg = Piwik::translate('CoreAdminHome_PluginSettingsValueNotAllowed', - array(strip_tags($config->title), $this->pluginName)); + $errorMsg = Piwik::translate( + 'CoreAdminHome_PluginSettingsValueNotAllowed', + array(strip_tags($config->title), $this->pluginName) + ); if (is_array($value) && $this->type === FieldConfig::TYPE_ARRAY) { foreach ($value as $val) { @@ -272,15 +274,19 @@ private function validateValue($value) } elseif ($this->type === FieldConfig::TYPE_INT || $this->type === FieldConfig::TYPE_FLOAT) { if (!is_numeric($value)) { - $errorMsg = Piwik::translate('CoreAdminHome_PluginSettingsValueNotAllowed', - array(strip_tags($config->title), $this->pluginName)); + $errorMsg = Piwik::translate( + 'CoreAdminHome_PluginSettingsValueNotAllowed', + array(strip_tags($config->title), $this->pluginName) + ); throw new \Exception($errorMsg); } } elseif ($this->type === FieldConfig::TYPE_BOOL) { if (!in_array($value, array(true, false, '0', '1', 0, 1), true)) { - $errorMsg = Piwik::translate('CoreAdminHome_PluginSettingsValueNotAllowed', - array(strip_tags($config->title), $this->pluginName)); + $errorMsg = Piwik::translate( + 'CoreAdminHome_PluginSettingsValueNotAllowed', + array(strip_tags($config->title), $this->pluginName) + ); throw new \Exception($errorMsg); } } diff --git a/core/SettingsPiwik.php b/core/SettingsPiwik.php index 4a2862c7be7..ae839bcecf1 100644 --- a/core/SettingsPiwik.php +++ b/core/SettingsPiwik.php @@ -166,8 +166,10 @@ public static function getKnownSegmentsToArchiveForSite($idSite): array */ public static function getWebsitesCountToDisplay(): int { - $count = max(Config::getInstance()->General['site_selector_max_sites'], - Config::getInstance()->General['autocomplete_min_sites']); + $count = max( + Config::getInstance()->General['site_selector_max_sites'], + Config::getInstance()->General['autocomplete_min_sites'] + ); return (int)$count; } @@ -369,15 +371,16 @@ public static function checkPiwikServerWorking(string $piwikServerUrl, bool $acc { // Now testing if the webserver is running try { - $fetched = Http::sendHttpRequestBy('curl', - $piwikServerUrl, - $timeout = 45, - $userAgent = null, - $destinationPath = null, - $file = null, - $followDepth = 0, - $acceptLanguage = false, - $acceptInvalidSSLCertificates + $fetched = Http::sendHttpRequestBy( + 'curl', + $piwikServerUrl, + $timeout = 45, + $userAgent = null, + $destinationPath = null, + $file = null, + $followDepth = 0, + $acceptLanguage = false, + $acceptInvalidSSLCertificates ); } catch (Exception $e) { $fetched = "ERROR fetching: " . $e->getMessage(); diff --git a/core/SiteContentDetector.php b/core/SiteContentDetector.php index 7c563c0cf7c..68af539d074 100644 --- a/core/SiteContentDetector.php +++ b/core/SiteContentDetector.php @@ -372,8 +372,19 @@ private function requestSiteResponse(string $url, int $timeOut): array $siteData = []; try { - $siteData = Http::sendHttpRequestBy(Http::getTransportMethod(), $url, $timeOut, null, null, - null, 0, false, true, false, true); + $siteData = Http::sendHttpRequestBy( + Http::getTransportMethod(), + $url, + $timeOut, + null, + null, + null, + 0, + false, + true, + false, + true + ); } catch (\Exception $e) { } diff --git a/core/Tracker/GoalManager.php b/core/Tracker/GoalManager.php index c2c307c237e..f7785fd1187 100644 --- a/core/Tracker/GoalManager.php +++ b/core/Tracker/GoalManager.php @@ -389,7 +389,10 @@ protected function recordEcommerceGoal(VisitProperties $visitProperties, Request if ($isThereExistingCartInVisit) { $recorded = $this->getModel()->updateConversion( - $visitProperties->getProperty('idvisit'), self::IDGOAL_CART, $conversion); + $visitProperties->getProperty('idvisit'), + self::IDGOAL_CART, + $conversion + ); } else { $recorded = $this->insertNewConversion($conversion, $visitProperties->getProperties(), $request, $action); } @@ -457,7 +460,8 @@ protected function recordEcommerceItems($goal, $items) //Item in the cart in the DB, but not anymore in the cart if (!isset($itemInCartBySku[$itemInDb[0]])) { - $itemToUpdate = array_merge($itemInDb, + $itemToUpdate = array_merge( + $itemInDb, array('deleted' => 1, 'idorder_original_value' => $itemInDbOriginal['idorder_original_value'] ) diff --git a/core/Tracker/Model.php b/core/Tracker/Model.php index 153237b7e7b..1f80029e904 100644 --- a/core/Tracker/Model.php +++ b/core/Tracker/Model.php @@ -568,8 +568,8 @@ private function findVisitorByVisitorId($idVisitor, $select, $from, $where, $bin $cache = Cache::getCacheGeneral(); // use INDEX index_idsite_idvisitor_time (idsite, idvisitor, visit_last_action_time) if available - if (array_key_exists(self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME, - $cache) && true === $cache[self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME]) { + if (array_key_exists(self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME, $cache) + && true === $cache[self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME]) { $from .= ' FORCE INDEX (index_idsite_idvisitor_time) '; } diff --git a/core/Tracker/Request.php b/core/Tracker/Request.php index 49f747c9860..439e91c3be3 100644 --- a/core/Tracker/Request.php +++ b/core/Tracker/Request.php @@ -92,8 +92,10 @@ public function __construct($params, $tokenAuth = false) // check for 4byte utf8 characters in all tracking params and replace them with ๏ฟฝ if not support by database $this->params = $this->replaceUnsupportedUtf8Chars($this->params); - $this->customTimestampDoesNotRequireTokenauthWhenNewerThan = (int) TrackerConfig::getConfigValue('tracking_requests_require_authentication_when_custom_timestamp_newer_than', - $this->getIdSiteIfExists()); + $this->customTimestampDoesNotRequireTokenauthWhenNewerThan = (int) TrackerConfig::getConfigValue( + 'tracking_requests_require_authentication_when_custom_timestamp_newer_than', + $this->getIdSiteIfExists() + ); } protected function replaceUnsupportedUtf8Chars($value, $key = false) @@ -693,7 +695,8 @@ protected function makeThirdPartyCookieUID() $cookie = new Cookie( $this->getCookieName(), $this->getCookieExpire(), - $this->getCookiePath()); + $this->getCookiePath() + ); $domain = $this->getCookieDomain(); if (!empty($domain)) { diff --git a/core/Tracker/Settings.php b/core/Tracker/Settings.php index ec46e0cc869..96e640164fe 100644 --- a/core/Tracker/Settings.php +++ b/core/Tracker/Settings.php @@ -110,7 +110,8 @@ public function getConfigId(Request $request, $ipAddress) $plugin_Cookie, $ipAddress, $browserLang, - $fingerprintSalt); + $fingerprintSalt + ); } /** diff --git a/core/Tracker/TrackerCodeGenerator.php b/core/Tracker/TrackerCodeGenerator.php index 845b7faa932..4a02ddf81ec 100644 --- a/core/Tracker/TrackerCodeGenerator.php +++ b/core/Tracker/TrackerCodeGenerator.php @@ -182,9 +182,16 @@ public function generate( $codeImpl['protocol'] = 'https://'; } - $parameters = compact('mergeSubdomains', 'groupPageTitlesByDomain', 'mergeAliasUrls', 'visitorCustomVariables', - 'pageCustomVariables', 'customCampaignNameQueryParam', 'customCampaignKeywordParam', - 'doNotTrack'); + $parameters = compact( + 'mergeSubdomains', + 'groupPageTitlesByDomain', + 'mergeAliasUrls', + 'visitorCustomVariables', + 'pageCustomVariables', + 'customCampaignNameQueryParam', + 'customCampaignKeywordParam', + 'doNotTrack' + ); /** * Triggered when generating JavaScript tracking code server side. Plugins can use diff --git a/core/Tracker/Visit.php b/core/Tracker/Visit.php index 0e329058110..15fa3a5fae1 100644 --- a/core/Tracker/Visit.php +++ b/core/Tracker/Visit.php @@ -445,7 +445,8 @@ protected function updateExistingVisit($valuesToUpdate) throw new VisitorNotFoundInDb( "The visitor with idvisitor=" . bin2hex($this->visitProperties->getProperty('idvisitor')) . " and idvisit=" . @$this->visitProperties->getProperty('idvisit') - . " wasn't found in the DB, we fallback to a new visitor"); + . " wasn't found in the DB, we fallback to a new visitor" + ); } } @@ -557,8 +558,10 @@ protected function getAllVisitDimensions() $dimensionNames[] = $dimension->getColumnName(); } - Common::printDebug("Following dimensions have been collected from plugins: " . implode(", ", - $dimensionNames)); + Common::printDebug("Following dimensions have been collected from plugins: " . implode( + ", ", + $dimensionNames + )); } return self::$dimensions; diff --git a/core/Translation/Weblate/API.php b/core/Translation/Weblate/API.php index dad14ee6aca..2a0e9da167a 100644 --- a/core/Translation/Weblate/API.php +++ b/core/Translation/Weblate/API.php @@ -130,9 +130,24 @@ protected function getApiResults($apiPath, $raw = false) { $apiUrl = $this->apiUrl . $apiPath; - $response = Http::sendHttpRequestBy(Http::getTransportMethod(), $apiUrl, 60, null, null, null, 5, false, - false, false, true, 'GET', null, null, null, - ['Authorization: Token ' . $this->apiToken]); + $response = Http::sendHttpRequestBy( + Http::getTransportMethod(), + $apiUrl, + 60, + null, + null, + null, + 5, + false, + false, + false, + true, + 'GET', + null, + null, + null, + ['Authorization: Token ' . $this->apiToken] + ); $httpStatus = $response['status']; $response = $response['data']; diff --git a/core/Twig.php b/core/Twig.php index 9f2561ef83e..8f61ff7dc6c 100644 --- a/core/Twig.php +++ b/core/Twig.php @@ -108,7 +108,8 @@ public function __construct() // Create new Twig Environment and set cache dir $cache = StaticContainer::get('twig.cache'); - $this->twig = new Environment($chainLoader, + $this->twig = new Environment( + $chainLoader, array( 'debug' => true, // to use {{ dump(var) }} in twig templates 'strict_variables' => true, // throw an exception if variables are invalid diff --git a/core/Updater.php b/core/Updater.php index 28ca96f1ac0..39991bdc6ef 100644 --- a/core/Updater.php +++ b/core/Updater.php @@ -590,8 +590,12 @@ public function executeMigration($file, Migration $migration) $migration->exec(); } catch (\Exception $e) { if (!$migration->shouldIgnoreError($e)) { - $message = sprintf("%s:\nError trying to execute the migration '%s'.\nThe error was: %s", - $file, $migration->__toString(), $e->getMessage()); + $message = sprintf( + "%s:\nError trying to execute the migration '%s'.\nThe error was: %s", + $file, + $migration->__toString(), + $e->getMessage() + ); throw new UpdaterErrorException($message); } } diff --git a/core/Updater/Migration/Db/CreateTable.php b/core/Updater/Migration/Db/CreateTable.php index 70f6f3bddbf..29afa9f102d 100644 --- a/core/Updater/Migration/Db/CreateTable.php +++ b/core/Updater/Migration/Db/CreateTable.php @@ -35,8 +35,14 @@ public function __construct(Db\Settings $dbSettings, $table, $columnNames, $prim } - $sql = rtrim(sprintf('CREATE TABLE `%s` (%s) ENGINE=%s DEFAULT CHARSET=%s %s', - $table, implode(', ', $columns), $dbSettings->getEngine(), $dbSettings->getUsedCharset(), $dbSettings->getRowFormat())); + $sql = rtrim(sprintf( + 'CREATE TABLE `%s` (%s) ENGINE=%s DEFAULT CHARSET=%s %s', + $table, + implode(', ', $columns), + $dbSettings->getEngine(), + $dbSettings->getUsedCharset(), + $dbSettings->getRowFormat() + )); parent::__construct($sql, static::ERROR_CODE_TABLE_EXISTS); } diff --git a/core/Updates/0.9.1.php b/core/Updates/0.9.1.php index 024706b1a83..6b231ed783f 100644 --- a/core/Updates/0.9.1.php +++ b/core/Updates/0.9.1.php @@ -50,11 +50,13 @@ public function getMigrations(Updater $updater) return array( $this->migration->db->sql( 'UPDATE ' . Common::prefixTable('site') . ' - SET timezone = "UTC" WHERE timezone IN (' . $timezoneList . ')'), + SET timezone = "UTC" WHERE timezone IN (' . $timezoneList . ')' + ), $this->migration->db->sql( 'UPDATE `' . Common::prefixTable('option') . '` - SET option_value = "UTC" WHERE option_name = "SitesManager_DefaultTimezone" AND option_value IN (' . $timezoneList . ')'), + SET option_value = "UTC" WHERE option_name = "SitesManager_DefaultTimezone" AND option_value IN (' . $timezoneList . ')' + ), ); } diff --git a/core/Updates/1.2.3.php b/core/Updates/1.2.3.php index 6ed5359bbbe..bde19f52347 100644 --- a/core/Updates/1.2.3.php +++ b/core/Updates/1.2.3.php @@ -40,7 +40,7 @@ public function getMigrations(Updater $updater) // Various performance improvements schema updates $this->migration->db->sql( - 'ALTER TABLE `' . Common::prefixTable('log_visit') . '` + 'ALTER TABLE `' . Common::prefixTable('log_visit') . '` DROP INDEX index_idsite_datetime_config, DROP INDEX index_idsite_idvisit, ADD INDEX index_idsite_config_datetime (idsite, config_id, visit_last_action_time), diff --git a/core/Updates/1.2.5-rc1.php b/core/Updates/1.2.5-rc1.php index c1c1e679cbd..c5b9fab1614 100644 --- a/core/Updates/1.2.5-rc1.php +++ b/core/Updates/1.2.5-rc1.php @@ -36,7 +36,9 @@ public function getMigrations(Updater $updater) 'ALTER TABLE `' . Common::prefixTable('log_conversion') . '` ADD buster int unsigned NOT NULL AFTER revenue, DROP PRIMARY KEY, - ADD PRIMARY KEY (idvisit, idgoal, buster)', Updater\Migration\Db::ERROR_CODE_DUPLICATE_COLUMN), + ADD PRIMARY KEY (idvisit, idgoal, buster)', + Updater\Migration\Db::ERROR_CODE_DUPLICATE_COLUMN + ), ); } diff --git a/core/Updates/1.8.4-b1.php b/core/Updates/1.8.4-b1.php index 52a7503d940..d3ca6fa29ed 100644 --- a/core/Updates/1.8.4-b1.php +++ b/core/Updates/1.8.4-b1.php @@ -47,7 +47,7 @@ public function getMigrations(Updater $updater) // remove protocol and www and store information in url_prefix $this->migration->db->sql( - " UPDATE `$action` + " UPDATE `$action` SET url_prefix = IF ( LEFT(name, 11) = 'http://www.', 1, IF ( @@ -71,7 +71,8 @@ public function getMigrations(Updater $updater) WHERE type = 1 AND url_prefix IS NULL; - "), + " + ), $this->migration->db->dropTable('log_action_duplicates'), $this->migration->db->createTable('log_action_duplicates', array( 'before' => 'int(10) unsigned NOT NULL', @@ -82,7 +83,7 @@ public function getMigrations(Updater $updater) // grouping by name only would be case-insensitive, so we GROUP BY name,hash // ON (action.type = 1 AND canonical.hash = action.hash) will use index (type, hash) $this->migration->db->sql( - " INSERT INTO `$duplicates` ( + " INSERT INTO `$duplicates` ( SELECT action.idaction AS `before`, canonical.idaction AS `after` @@ -107,11 +108,12 @@ public function getMigrations(Updater $updater) AND canonical.name = action.name AND canonical.idaction != action.idaction ); - "), + " + ), // replace idaction in log_link_visit_action $this->migration->db->sql( - " UPDATE + " UPDATE `$visitAction` AS link LEFT JOIN `$duplicates` AS duplicates_idaction_url @@ -120,9 +122,10 @@ public function getMigrations(Updater $updater) link.idaction_url = duplicates_idaction_url.after WHERE duplicates_idaction_url.after IS NOT NULL; - "), + " + ), $this->migration->db->sql( - " UPDATE + " UPDATE `$visitAction` AS link LEFT JOIN `$duplicates` AS duplicates_idaction_url_ref @@ -131,11 +134,12 @@ public function getMigrations(Updater $updater) link.idaction_url_ref = duplicates_idaction_url_ref.after WHERE duplicates_idaction_url_ref.after IS NOT NULL; - "), + " + ), // replace idaction in log_conversion $this->migration->db->sql( - " UPDATE + " UPDATE `$conversion` AS conversion LEFT JOIN `$duplicates` AS duplicates @@ -144,11 +148,12 @@ public function getMigrations(Updater $updater) conversion.idaction_url = duplicates.after WHERE duplicates.after IS NOT NULL; - "), + " + ), // replace idaction in log_visit $this->migration->db->sql( - " UPDATE + " UPDATE `$visit` AS visit LEFT JOIN `$duplicates` AS duplicates_entry @@ -157,9 +162,10 @@ public function getMigrations(Updater $updater) visit.visit_entry_idaction_url = duplicates_entry.after WHERE duplicates_entry.after IS NOT NULL; - "), + " + ), $this->migration->db->sql( - " UPDATE + " UPDATE `$visit` AS visit LEFT JOIN `$duplicates` AS duplicates_exit @@ -168,18 +174,20 @@ public function getMigrations(Updater $updater) visit.visit_exit_idaction_url = duplicates_exit.after WHERE duplicates_exit.after IS NOT NULL; - "), + " + ), // remove duplicates from log_action $this->migration->db->sql( - " DELETE action FROM + " DELETE action FROM `$action` AS action LEFT JOIN `$duplicates` AS duplicates ON action.idaction = duplicates.before WHERE duplicates.after IS NOT NULL; - "), + " + ), // remove the duplicates table $this->migration->db->dropTable('log_action_duplicates') diff --git a/core/Updates/2.1.1-b11.php b/core/Updates/2.1.1-b11.php index aaadc499d44..3ee09b506d3 100644 --- a/core/Updates/2.1.1-b11.php +++ b/core/Updates/2.1.1-b11.php @@ -61,7 +61,9 @@ public function doUpdate(Updater $updater) $sql = "SELECT idarchive, idsite, period, date1, date2 FROM $table WHERE name = ? GROUP BY idarchive"; $visitSummaryReturningSegmentDone = Rules::getDoneFlagArchiveContainsOnePlugin( - new Segment(VisitFrequencyApi::RETURNING_VISITOR_SEGMENT, $idSites = array()), 'VisitsSummary'); + new Segment(VisitFrequencyApi::RETURNING_VISITOR_SEGMENT, $idSites = array()), + 'VisitsSummary' + ); $idArchivesWithVisitReturningSegment = Db::fetchAll($sql, array($visitSummaryReturningSegmentDone)); // collect info for new visitssummary archives have to be created to match archives w/ *._returning diff --git a/core/Updates/3.0.0-b1.php b/core/Updates/3.0.0-b1.php index 02ae9653106..0f1b44ffdec 100644 --- a/core/Updates/3.0.0-b1.php +++ b/core/Updates/3.0.0-b1.php @@ -177,8 +177,10 @@ private function getSiteSettingsMigrations($queries) )); $table = Common::prefixTable($table); - $queries[] = $this->migration->db->sql("ALTER TABLE `$table` ADD INDEX(idsite, plugin_name);", - Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS); + $queries[] = $this->migration->db->sql( + "ALTER TABLE `$table` ADD INDEX(idsite, plugin_name);", + Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS + ); return $queries; } diff --git a/core/Updates/3.13.1-b2.php b/core/Updates/3.13.1-b2.php index e2bc0517af2..d51333ca8ce 100644 --- a/core/Updates/3.13.1-b2.php +++ b/core/Updates/3.13.1-b2.php @@ -37,10 +37,14 @@ public function getMigrations(Updater $updater) { $geoIpLiteUrl = 'https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz'; $optionTable = Common::prefixTable('option'); - $migration1 = $this->migration->db->boundSql("UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", - [GeoIp2::getDbIpLiteUrl(), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, $geoIpLiteUrl]); - $migration2 = $this->migration->db->boundSql("UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", - [GeoIp2::getDbIpLiteUrl('country'), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, self::GEO_LITE_COUNTRY_URL]); + $migration1 = $this->migration->db->boundSql( + "UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", + [GeoIp2::getDbIpLiteUrl(), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, $geoIpLiteUrl] + ); + $migration2 = $this->migration->db->boundSql( + "UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", + [GeoIp2::getDbIpLiteUrl('country'), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, self::GEO_LITE_COUNTRY_URL] + ); return [$migration1, $migration2]; } diff --git a/core/Updates/3.6.0-b2.php b/core/Updates/3.6.0-b2.php index e385db072a2..3aa384b8baf 100644 --- a/core/Updates/3.6.0-b2.php +++ b/core/Updates/3.6.0-b2.php @@ -69,8 +69,11 @@ public function getMigrations(Updater $updater) } // changes for session auth - $migrations[] = $this->migration->db->addColumn('user', 'ts_password_modified', - 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'); + $migrations[] = $this->migration->db->addColumn( + 'user', + 'ts_password_modified', + 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP' + ); return $migrations; } diff --git a/core/Updates/3.8.0-b4.php b/core/Updates/3.8.0-b4.php index dca57352071..5c021f382e8 100644 --- a/core/Updates/3.8.0-b4.php +++ b/core/Updates/3.8.0-b4.php @@ -27,12 +27,14 @@ public function __construct(MigrationFactory $factory) public function getMigrations(Updater $updater) { - $trackingFailureTable = $this->migration->db->createTable('tracking_failure', + $trackingFailureTable = $this->migration->db->createTable( + 'tracking_failure', array('idsite' => 'BIGINT(20) UNSIGNED NOT NULL', 'idfailure' => 'SMALLINT UNSIGNED NOT NULL', 'date_first_occurred' => 'DATETIME NOT NULL', 'request_url' => 'MEDIUMTEXT NOT NULL'), - array('idsite', 'idfailure')); + array('idsite', 'idfailure') + ); $columns = array( 'id_brute_force_log' => 'bigint(11) NOT NULL AUTO_INCREMENT', diff --git a/core/Updates/4.0.0-rc4.php b/core/Updates/4.0.0-rc4.php index ee0bd4e4c7b..f4a2c25cb4b 100644 --- a/core/Updates/4.0.0-rc4.php +++ b/core/Updates/4.0.0-rc4.php @@ -51,7 +51,9 @@ public function getMigrations(Updater $updater) if (DbHelper::tableExists($blobTable) && DbHelper::tableExists($numericTable)) { $migrations[] = $this->migration->db->sql( - "DELETE FROM `$blobTable` WHERE idarchive NOT IN (SELECT idarchive FROM `$numericTable`)", []); + "DELETE FROM `$blobTable` WHERE idarchive NOT IN (SELECT idarchive FROM `$numericTable`)", + [] + ); } } } diff --git a/core/Updates/4.7.0-b2.php b/core/Updates/4.7.0-b2.php index 6442acd1cf6..538d5e38329 100644 --- a/core/Updates/4.7.0-b2.php +++ b/core/Updates/4.7.0-b2.php @@ -42,8 +42,11 @@ public function getMigrations(Updater $updater) $migrations = []; // add column to track the last change a user viewed the changes list - $migrations[] = $this->migration->db->addColumn('user', 'idchange_last_viewed', - 'INTEGER UNSIGNED NULL'); + $migrations[] = $this->migration->db->addColumn( + 'user', + 'idchange_last_viewed', + 'INTEGER UNSIGNED NULL' + ); $migrations[] = $this->migration->db->createTable('changes', array( 'idchange' => 'INT(11) NOT NULL AUTO_INCREMENT', diff --git a/core/Updates/5.0.0-b1.php b/core/Updates/5.0.0-b1.php index debbb22aee2..83e6fe8007f 100644 --- a/core/Updates/5.0.0-b1.php +++ b/core/Updates/5.0.0-b1.php @@ -96,7 +96,8 @@ private function appendLogVisitTableMigrations($migrations) // already existing index has the correct fields. Try renaming, but ignore syntax error thrown if rename command does not exist $migrations[] = $this->migration->db->sql( "ALTER TABLE `{$this->tableName}` RENAME INDEX `{$this->indexName}` TO `{$this->newIndexName}`", - [DbAlias::ERROR_CODE_SYNTAX_ERROR]); + [DbAlias::ERROR_CODE_SYNTAX_ERROR] + ); } // create the new index if it does not yet exist and drop the old one diff --git a/core/UrlHelper.php b/core/UrlHelper.php index 0e1fdfbab8f..4f80b0b0306 100644 --- a/core/UrlHelper.php +++ b/core/UrlHelper.php @@ -127,7 +127,8 @@ public static function getLossyUrl($url) '.{}$4', '$1{}.', ), - $url); + $url + ); } /** diff --git a/phpcs.xml b/phpcs.xml index 445b4192760..cb4bd667b1f 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -39,10 +39,6 @@ - - - - diff --git a/plugins/API/API.php b/plugins/API/API.php index 0a21c060503..b8699440b67 100644 --- a/plugins/API/API.php +++ b/plugins/API/API.php @@ -304,8 +304,23 @@ public function getProcessedReport( ) { Piwik::checkUserHasViewAccess($idSite); - $processed = $this->processedReport->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment, - $apiParameters, $idGoal, $language, $showTimer, $hideMetricsDoc, $idSubtable, $showRawMetrics, $format_metrics, $idDimension); + $processed = $this->processedReport->getProcessedReport( + $idSite, + $period, + $date, + $apiModule, + $apiAction, + $segment, + $apiParameters, + $idGoal, + $language, + $showTimer, + $hideMetricsDoc, + $idSubtable, + $showRawMetrics, + $format_metrics, + $idDimension + ); return $processed; } @@ -464,8 +479,22 @@ public function getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, } $rowEvolution = new RowEvolution(); - return $rowEvolution->getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label, $segment, $column, - $language, $apiParameters, $legendAppendMetric, $labelUseAbsoluteUrl, $labelSeries, $showGoalMetricsForGoal); + return $rowEvolution->getRowEvolution( + $idSite, + $period, + $date, + $apiModule, + $apiAction, + $label, + $segment, + $column, + $language, + $apiParameters, + $legendAppendMetric, + $labelUseAbsoluteUrl, + $labelSeries, + $showGoalMetricsForGoal + ); } /** @@ -592,7 +621,8 @@ public function getSuggestedValuesForSegment($segmentName, $idSite) if (isset($segment['suggestedValuesCallback'])) { $suggestedValuesCallbackRequiresTable = $this->doesSuggestedValuesCallbackNeedData( - $segment['suggestedValuesCallback']); + $segment['suggestedValuesCallback'] + ); if (!$suggestedValuesCallbackRequiresTable) { return call_user_func($segment['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn); diff --git a/plugins/API/Filter/DataComparisonFilter.php b/plugins/API/Filter/DataComparisonFilter.php index e0bcca7d78d..3d8a8a56063 100644 --- a/plugins/API/Filter/DataComparisonFilter.php +++ b/plugins/API/Filter/DataComparisonFilter.php @@ -401,7 +401,9 @@ private function getMetadataFromModifiedParams($modifiedParams) $metadata['comparePeriodPretty'] = ucfirst($prettyPeriod); $metadata['compareSeriesPretty'] = self::getComparisonSeriesLabelSuffixFromParts( - $metadata['comparePeriodPretty'], $metadata['compareSegmentPretty']); + $metadata['comparePeriodPretty'], + $metadata['compareSegmentPretty'] + ); return $metadata; } diff --git a/plugins/API/Filter/DataComparisonFilter/ComparisonRowGenerator.php b/plugins/API/Filter/DataComparisonFilter/ComparisonRowGenerator.php index fb81154509d..881bbeedf87 100644 --- a/plugins/API/Filter/DataComparisonFilter/ComparisonRowGenerator.php +++ b/plugins/API/Filter/DataComparisonFilter/ComparisonRowGenerator.php @@ -136,8 +136,10 @@ private function compareRow(DataTable $table, $compareMetadata, DataTable\Row $r $comparisonDataTable = $row->getComparisons(); if (empty($comparisonDataTable)) { $comparisonDataTable = new DataTable(); - $comparisonDataTable->setMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME, - $table->getMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME)); + $comparisonDataTable->setMetadata( + DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME, + $table->getMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME) + ); $row->setComparisons($comparisonDataTable); } diff --git a/plugins/API/Glossary.php b/plugins/API/Glossary.php index 2c6d71ab856..d612ae3ca4d 100644 --- a/plugins/API/Glossary.php +++ b/plugins/API/Glossary.php @@ -85,10 +85,12 @@ public function metricsGlossary($idSite) $metricKey = $metricName; if (isset($metrics[$metricKey]) && $metrics[$metricKey]['documentation'] !== $metricDocumentation) { - throw new \Exception(sprintf("Metric %s has two different documentations: \n(1) %s \n(2) %s", - $metricKey, - $metrics[$metricKey]['documentation'], - $metricDocumentation)); + throw new \Exception(sprintf( + "Metric %s has two different documentations: \n(1) %s \n(2) %s", + $metricKey, + $metrics[$metricKey]['documentation'], + $metricDocumentation + )); } } else { diff --git a/plugins/API/Menu.php b/plugins/API/Menu.php index b2ec5b1ead7..7167f803e2f 100644 --- a/plugins/API/Menu.php +++ b/plugins/API/Menu.php @@ -27,14 +27,16 @@ public function configureTopMenu(MenuTop $menu) public function configureAdminMenu(MenuAdmin $menu) { - $menu->addPlatformItem('General_API', + $menu->addPlatformItem( + 'General_API', $this->urlForAction('listAllAPI', array('segment' => false)), 7, Piwik::translate('API_TopLinkTooltip') ); if(Piwik::isUserIsAnonymous()) { - $menu->addPlatformItem('API_Glossary', + $menu->addPlatformItem( + 'API_Glossary', $this->urlForAction('glossary', array('segment' => false)), 50 ); diff --git a/plugins/API/ProcessedReport.php b/plugins/API/ProcessedReport.php index f2525d0575b..910bc4bf136 100644 --- a/plugins/API/ProcessedReport.php +++ b/plugins/API/ProcessedReport.php @@ -366,8 +366,17 @@ public function getProcessedReport( } // Is this report found in the Metadata available reports? - $reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, - $period, $date, $hideMetricsDoc, $showSubtableReports = true); + $reportMetadata = $this->getMetadata( + $idSite, + $apiModule, + $apiAction, + $apiParameters, + $language, + $period, + $date, + $hideMetricsDoc, + $showSubtableReports = true + ); if (empty($reportMetadata)) { throw new Exception("Requested report $apiModule.$apiAction for Website id=$idSite not found in the list of available reports. \n"); } diff --git a/plugins/API/RowEvolution.php b/plugins/API/RowEvolution.php index 497f7a1a8bd..05a47a5b383 100644 --- a/plugins/API/RowEvolution.php +++ b/plugins/API/RowEvolution.php @@ -426,8 +426,17 @@ private function loadRowEvolutionDataFromAPI($metadata, $idSite, $period, $date, */ private function getRowEvolutionMetaData($idSite, $period, $date, $apiModule, $apiAction, $language, $apiParameters) { - $reportMetadata = API::getInstance()->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, - $period, $date, $hideMetricsDoc = false, $showSubtableReports = true); + $reportMetadata = API::getInstance()->getMetadata( + $idSite, + $apiModule, + $apiAction, + $apiParameters, + $language, + $period, + $date, + $hideMetricsDoc = false, + $showSubtableReports = true + ); if (empty($reportMetadata)) { throw new Exception("Requested report $apiModule.$apiAction for Website id=$idSite " @@ -558,7 +567,11 @@ private function getMultiRowEvolution( if ($labelRow) { $actualLabels[$labelIdx] = $this->getRowUrlForEvolutionLabel( - $labelRow, $apiModule, $apiAction, $labelUseAbsoluteUrl); + $labelRow, + $apiModule, + $apiAction, + $labelUseAbsoluteUrl + ); $prettyLabel = $labelRow->getColumn('label_html'); if ($prettyLabel !== false) { diff --git a/plugins/Actions/ArchivingHelper.php b/plugins/Actions/ArchivingHelper.php index 26b53c1c672..9f2d7146065 100644 --- a/plugins/Actions/ArchivingHelper.php +++ b/plugins/Actions/ArchivingHelper.php @@ -289,7 +289,8 @@ private static function updateActionsTableRowWithGoals(array $row, bool $isPages $row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY_RATE] = Piwik::getQuotientSafe( $conversions, $nbEntrances, - GoalManager::REVENUE_PRECISION + 1); + GoalManager::REVENUE_PRECISION + 1 + ); } // Calculate revenue per entry @@ -297,7 +298,8 @@ private static function updateActionsTableRowWithGoals(array $row, bool $isPages $row[PiwikMetrics::INDEX_GOAL_REVENUE_PER_ENTRY] = (float) Piwik::getQuotientSafe( $row[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY], $nbEntrances, - GoalManager::REVENUE_PRECISION + 1); + GoalManager::REVENUE_PRECISION + 1 + ); $row[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY] = (float) $row[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY]; } @@ -544,7 +546,10 @@ public static function getActionRow($actionName, $actionType, $urlPrefix, $actio // go to the level of the subcategory $actionExplodedNames = self::getActionExplodedNames($actionName, $actionType, $urlPrefix); list($row, $level) = $currentTable->walkPath( - $actionExplodedNames, self::getDefaultRowColumns(), self::$maximumRowsInSubDataTable); + $actionExplodedNames, + self::getDefaultRowColumns(), + self::$maximumRowsInSubDataTable + ); return $row; } diff --git a/plugins/Actions/RecordBuilders/ActionReports.php b/plugins/Actions/RecordBuilders/ActionReports.php index 86692077ca1..a7ca7887fad 100644 --- a/plugins/Actions/RecordBuilders/ActionReports.php +++ b/plugins/Actions/RecordBuilders/ActionReports.php @@ -77,8 +77,13 @@ protected function aggregate(ArchiveProcessor $archiveProcessor): array $tablesByType = $this->makeReportTables(); - $this->archiveDayActions($archiveProcessor, $rankingQueryLimit, $tablesByType, - array_diff(array_keys($tablesByType), [Action::TYPE_SITE_SEARCH]), true); + $this->archiveDayActions( + $archiveProcessor, + $rankingQueryLimit, + $tablesByType, + array_diff(array_keys($tablesByType), [Action::TYPE_SITE_SEARCH]), + true + ); if ($archiveProcessor->getParams()->getSite()->isSiteSearchEnabled()) { $rankingQueryLimitSiteSearch = max($rankingQueryLimit, ArchivingHelper::$maximumRowsInDataTableSiteSearch); @@ -297,11 +302,29 @@ protected function archiveDayEntryActions(LogAggregator $logAggregator, array $a $groupBy = "log_visit.%s"; - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, $orderBy, - "visit_entry_idaction_url", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "visit_entry_idaction_url", + $rankingQuery + ); - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, $orderBy, - "visit_entry_idaction_name", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "visit_entry_idaction_name", + $rankingQuery + ); } /** @@ -341,11 +364,29 @@ protected function archiveDayExitActions(LogAggregator $logAggregator, array $ac $groupBy = "log_visit.%s"; - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, - $orderBy, "visit_exit_idaction_url", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "visit_exit_idaction_url", + $rankingQuery + ); - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, - $orderBy, "visit_exit_idaction_name", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "visit_exit_idaction_name", + $rankingQuery + ); return array($rankingQuery, $extraSelects, $from, $orderBy, $select, $where, $groupBy); } @@ -387,11 +428,29 @@ protected function archiveDayActionsTime(LogAggregator $logAggregator, array $ac $groupBy = "log_link_visit_action.%s"; - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, - $orderBy, "idaction_url_ref", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "idaction_url_ref", + $rankingQuery + ); - $this->archiveDayQueryProcess($logAggregator, $actionsTablesByType, $select, $from, $where, $groupBy, - $orderBy, "idaction_name_ref", $rankingQuery); + $this->archiveDayQueryProcess( + $logAggregator, + $actionsTablesByType, + $select, + $from, + $where, + $groupBy, + $orderBy, + "idaction_name_ref", + $rankingQuery + ); } protected function archiveDayQueryProcess( diff --git a/plugins/Actions/Tracker/ActionsRequestProcessor.php b/plugins/Actions/Tracker/ActionsRequestProcessor.php index 1c3c2804c7b..a001da2ec98 100644 --- a/plugins/Actions/Tracker/ActionsRequestProcessor.php +++ b/plugins/Actions/Tracker/ActionsRequestProcessor.php @@ -55,10 +55,16 @@ public function processRequestParams(VisitProperties $visitProperties, Request $ // save the exit actions of the last action in this visit as the referrer actions for the action being tracked. // when the visit is updated, these columns will be changed, so we have to do this before recordLogs - $request->setMetadata('Actions', 'idReferrerActionUrl', - $visitProperties->getProperty('visit_exit_idaction_url')); - $request->setMetadata('Actions', 'idReferrerActionName', - $visitProperties->getProperty('visit_exit_idaction_name')); + $request->setMetadata( + 'Actions', + 'idReferrerActionUrl', + $visitProperties->getProperty('visit_exit_idaction_url') + ); + $request->setMetadata( + 'Actions', + 'idReferrerActionName', + $visitProperties->getProperty('visit_exit_idaction_name') + ); } public function afterRequestProcessed(VisitProperties $visitProperties, Request $request) diff --git a/plugins/Actions/VisitorDetails.php b/plugins/Actions/VisitorDetails.php index 21195d35a34..dae2cfd0bdc 100644 --- a/plugins/Actions/VisitorDetails.php +++ b/plugins/Actions/VisitorDetails.php @@ -273,8 +273,10 @@ public function extendActionDetails(&$action, $nextAction, $visitorDetails) } // Convert datetimes to the site timezone - $dateTimeVisit = Date::factory($action['serverTimePretty'], - Site::getTimezoneFor($visitorDetails['idSite'])); + $dateTimeVisit = Date::factory( + $action['serverTimePretty'], + Site::getTimezoneFor($visitorDetails['idSite']) + ); $action['serverTimePretty'] = $dateTimeVisit->getLocalized(Date::DATETIME_FORMAT_SHORT); $action['timestamp'] = $dateTimeVisit->getTimestamp(); diff --git a/plugins/Annotations/API.php b/plugins/Annotations/API.php index bb2bd2924bb..33dc2d87414 100644 --- a/plugins/Annotations/API.php +++ b/plugins/Annotations/API.php @@ -252,7 +252,10 @@ public function getAnnotationCountForDates($idSite, $date, $period, $lastN = fal && $result[$idSite][$strDate]['count'] == 1 ) { $annotationsForSite = $annotations->search( - $date, Date::factory($nextDate->getTimestamp() - 1), $idSite); + $date, + Date::factory($nextDate->getTimestamp() - 1), + $idSite + ); $annotation = reset($annotationsForSite[$idSite]); $result[$idSite][$strDate]['note'] = $annotation['note']; diff --git a/plugins/Annotations/Controller.php b/plugins/Annotations/Controller.php index 0d0aaf3162a..2c7387bf757 100644 --- a/plugins/Annotations/Controller.php +++ b/plugins/Annotations/Controller.php @@ -61,7 +61,9 @@ public function getAnnotationManager($fetch = false, $date = false, $period = fa $view = new View('@Annotations/getAnnotationManager'); $allAnnotations = Request::processRequest( - 'Annotations.getAll', array('date' => $date, 'period' => $period, 'lastN' => $lastN)); + 'Annotations.getAll', + array('date' => $date, 'period' => $period, 'lastN' => $lastN) + ); $view->annotations = empty($allAnnotations[$this->idSite]) ? array() : $allAnnotations[$this->idSite]; $view->period = $period; @@ -210,7 +212,9 @@ public function getEvolutionIcons() { // get annotation the count $annotationCounts = Request::processRequest( - "Annotations.getAnnotationCountForDates", array('getAnnotationText' => 1)); + "Annotations.getAnnotationCountForDates", + array('getAnnotationText' => 1) + ); // create & render the view $view = new View('@Annotations/getEvolutionIcons'); diff --git a/plugins/Annotations/tests/System/AnnotationsTest.php b/plugins/Annotations/tests/System/AnnotationsTest.php index ec09ed23eda..89dba7fae94 100644 --- a/plugins/Annotations/tests/System/AnnotationsTest.php +++ b/plugins/Annotations/tests/System/AnnotationsTest.php @@ -189,7 +189,12 @@ public function testGetInvalidNoteIdFail() public function testSaveSuccess() { API::getInstance()->save( - self::$fixture->idSite1, 0, $date = '2011-04-01', $note = 'new note text', $starred = 1); + self::$fixture->idSite1, + 0, + $date = '2011-04-01', + $note = 'new note text', + $starred = 1 + ); $expectedAnnotation = array( 'date' => '2011-04-01', diff --git a/plugins/CoreAdminHome/API.php b/plugins/CoreAdminHome/API.php index 4a23807a8ec..cb5c907fe0a 100644 --- a/plugins/CoreAdminHome/API.php +++ b/plugins/CoreAdminHome/API.php @@ -397,8 +397,16 @@ public function getOptOutJSEmbedCode( string $language ): string { - return $this->optOutManager->getOptOutJSEmbedCode($matomoUrl, $language, $backgroundColor, $fontColor, $fontSize, - $fontFamily, $applyStyling, $showIntro); + return $this->optOutManager->getOptOutJSEmbedCode( + $matomoUrl, + $language, + $backgroundColor, + $fontColor, + $fontSize, + $fontFamily, + $applyStyling, + $showIntro + ); } /** diff --git a/plugins/CoreAdminHome/Commands/DeleteLogsData.php b/plugins/CoreAdminHome/Commands/DeleteLogsData.php index da127b90753..5bb45c25b42 100644 --- a/plugins/CoreAdminHome/Commands/DeleteLogsData.php +++ b/plugins/CoreAdminHome/Commands/DeleteLogsData.php @@ -54,12 +54,18 @@ protected function configure() $this->setName('core:delete-logs-data'); $this->setDescription('Delete data from the user log tables: ' . implode(', ', self::$logTables) . '.'); $this->addRequiredValueOption('dates', null, 'Delete log data with a date within this date range. Eg, 2012-01-01,2013-01-01'); - $this->addOptionalValueOption('idsite', null, - 'Delete log data belonging to the site with this ID. Comma separated list of website id. Eg, 1, 2, 3, etc. By default log data from all sites is purged.'); + $this->addOptionalValueOption( + 'idsite', + null, + 'Delete log data belonging to the site with this ID. Comma separated list of website id. Eg, 1, 2, 3, etc. By default log data from all sites is purged.' + ); $this->addRequiredValueOption('limit', null, "The number of rows to delete at a time. The larger the number, " . "the more time is spent deleting logs, and the less progress will be printed to the screen.", 1000); - $this->addNoValueOption('optimize-tables', null, - "If supplied, the command will optimize log tables after deleting logs. Note: this can take a very long time."); + $this->addNoValueOption( + 'optimize-tables', + null, + "If supplied, the command will optimize log tables after deleting logs. Note: this can take a very long time." + ); } protected function doExecute(): int @@ -72,8 +78,8 @@ protected function doExecute(): int $step = $this->getRowIterationStep(); $output->writeln(sprintf( - "Preparing to delete all visits belonging to %s between $from and $to.", - $idSite ? "website $idSite" : "ALL websites" + "Preparing to delete all visits belonging to %s between $from and $to.", + $idSite ? "website $idSite" : "ALL websites" )); $confirm = $this->askForDeleteConfirmation(); diff --git a/plugins/CoreAdminHome/Commands/InvalidateReportData.php b/plugins/CoreAdminHome/Commands/InvalidateReportData.php index e145a22d426..67302a3ee29 100644 --- a/plugins/CoreAdminHome/Commands/InvalidateReportData.php +++ b/plugins/CoreAdminHome/Commands/InvalidateReportData.php @@ -38,32 +38,54 @@ protected function configure() { $this->setName('core:invalidate-report-data'); $this->setDescription('Invalidate archived report data by date range, site and period.'); - $this->addRequiredValueOption('dates', null, - 'List of dates or date ranges to invalidate report data for, eg, 2015-01-03 or 2015-01-05,2015-02-12.', null, true); - $this->addRequiredValueOption('sites', null, + $this->addRequiredValueOption( + 'dates', + null, + 'List of dates or date ranges to invalidate report data for, eg, 2015-01-03 or 2015-01-05,2015-02-12.', + null, + true + ); + $this->addRequiredValueOption( + 'sites', + null, 'List of site IDs to invalidate report data for, eg, "1,2,3,4" or "all" for all sites.', - self::ALL_OPTION_VALUE); - $this->addRequiredValueOption('periods', null, + self::ALL_OPTION_VALUE + ); + $this->addRequiredValueOption( + 'periods', + null, 'List of period types to invalidate report data for. Can be one or more of the following values: day, ' . 'week, month, year or "all" for all of them.', - self::ALL_OPTION_VALUE); - $this->addRequiredValueOption('segment', null, + self::ALL_OPTION_VALUE + ); + $this->addRequiredValueOption( + 'segment', + null, 'List of segments to invalidate report data for. This can be the segment string itself, the segment name from the UI or the ID of the segment.' - . ' If specifying the segment definition, make sure it is encoded properly (it should be the same as the segment parameter in the URL.', null, true); - $this->addNoValueOption('cascade', null, + . ' If specifying the segment definition, make sure it is encoded properly (it should be the same as the segment parameter in the URL.', + null, + true + ); + $this->addNoValueOption( + 'cascade', + null, 'If supplied, invalidation will cascade, invalidating child period types even if they aren\'t specified in' . ' --periods. For example, if --periods=week, --cascade will cause the days within those weeks to be ' . 'invalidated as well. If --periods=month, then weeks and days will be invalidated. Note: if a period ' . 'falls partly outside of a date range, then --cascade will also invalidate data for child periods ' . 'outside the date range. For example, if --dates=2015-09-14,2015-09-15 & --periods=week, --cascade will' - . ' also invalidate all days within 2015-09-13,2015-09-19, even those outside the date range.'); + . ' also invalidate all days within 2015-09-13,2015-09-19, even those outside the date range.' + ); $this->addNoValueOption('dry-run', null, 'For tests. Runs the command w/o actually ' . 'invalidating anything.'); $this->addRequiredValueOption('plugin', null, 'To invalidate data for a specific plugin only.'); - $this->addNoValueOption('ignore-log-deletion-limit', null, + $this->addNoValueOption( + 'ignore-log-deletion-limit', + null, 'Ignore the log purging limit when invalidating archives. If a date is older than the log purging threshold (which means ' . 'there should be no log data for it), we normally skip invalidating it in order to prevent losing any report data. In some cases, ' - . 'however it is useful, if, for example, your site was imported from Google, and there is never any log data.'); + . 'however it is useful, if, for example, your site was imported from Google, and there is never any log data.' + ); $this->setHelp('Invalidate archived report data by date range, site and period. Invalidated archive data will ' . 'be re-archived during the next core:archive run. If your log data has changed for some reason, this ' . 'command can be used to make sure reports are generated using the new, changed log data.'); @@ -109,8 +131,16 @@ protected function doExecute(): int } $logger->info($message); } else { - $invalidationResult = $invalidator->markArchivesAsInvalidated($sites, $dates, $periodType, $segment, $cascade, - false, $plugin, $ignoreLogDeletionLimit); + $invalidationResult = $invalidator->markArchivesAsInvalidated( + $sites, + $dates, + $periodType, + $segment, + $cascade, + false, + $plugin, + $ignoreLogDeletionLimit + ); if ($output->getVerbosity() > $output::VERBOSITY_NORMAL) { foreach ($invalidationResult->makeOutputLogs() as $outputLog) { diff --git a/plugins/CoreAdminHome/Commands/OptimizeArchiveTables.php b/plugins/CoreAdminHome/Commands/OptimizeArchiveTables.php index b951728b18c..44c71838816 100644 --- a/plugins/CoreAdminHome/Commands/OptimizeArchiveTables.php +++ b/plugins/CoreAdminHome/Commands/OptimizeArchiveTables.php @@ -26,9 +26,13 @@ protected function configure() { $this->setName('database:optimize-archive-tables'); $this->setDescription("Runs an OPTIMIZE TABLE query on the specified archive tables."); - $this->addRequiredArgument("dates", + $this->addRequiredArgument( + "dates", "The months of the archive tables to optimize. Use '" . self::ALL_TABLES_STRING . "' for all dates or '" . - self::CURRENT_MONTH_STRING . "' to optimize the current month only.", null, true); + self::CURRENT_MONTH_STRING . "' to optimize the current month only.", + null, + true + ); $this->addNoValueOption('dry-run', null, 'For testing purposes.'); $this->setHelp("This command can be used to ease or automate maintenance. Instead of manually running " . "OPTIMIZE TABLE queries, the command can be used.\n\nYou should run the command if you find your " diff --git a/plugins/CoreAdminHome/Menu.php b/plugins/CoreAdminHome/Menu.php index 9232e59fbce..3f7887fb081 100644 --- a/plugins/CoreAdminHome/Menu.php +++ b/plugins/CoreAdminHome/Menu.php @@ -28,21 +28,27 @@ public function configureAdminMenu(MenuAdmin $menu) $menu->addDevelopmentItem('', [], 40); if (Piwik::hasUserSuperUserAccess()) { - $menu->addSystemItem('General_GeneralSettings', + $menu->addSystemItem( + 'General_GeneralSettings', $this->urlForAction('generalSettings'), - $order = 5); + $order = 5 + ); } if (!Piwik::isUserIsAnonymous()) { - $menu->addMeasurableItem('CoreAdminHome_TrackingCode', + $menu->addMeasurableItem( + 'CoreAdminHome_TrackingCode', $this->urlForAction('trackingCodeGenerator'), - $order = 12); + $order = 12 + ); } if (Piwik::isUserHasSomeAdminAccess()) { - $menu->addDiagnosticItem('CoreAdminHome_TrackingFailures', + $menu->addDiagnosticItem( + 'CoreAdminHome_TrackingFailures', $this->urlForAction('trackingFailures'), - $order = 2); + $order = 2 + ); } } @@ -64,11 +70,19 @@ public function configureTopMenu(MenuTop $menu) $icon = ($newChangesStatus === ChangesModel::NEW_CHANGES_EXIST ? 'icon-notifications_on' : 'icon-reporting-actions'); $menu->registerMenuIcon('CoreAdminHome_WhatIsNew', $icon); - $menu->addItem('CoreAdminHome_WhatIsNew', null, 'javascript:', 990, + $menu->addItem( + 'CoreAdminHome_WhatIsNew', + null, + 'javascript:', + 990, Piwik::translate('CoreAdminHome_WhatIsNewTooltip'), - $icon, "Piwik_Popover.createPopupAndLoadUrl('module=CoreAdminHome&action=whatIsNew', '" . + $icon, + "Piwik_Popover.createPopupAndLoadUrl('module=CoreAdminHome&action=whatIsNew', '" . addslashes(Piwik::translate('CoreAdminHome_WhatIsNewTooltip')) . "','what-is-new-popup')", - null, null, $userChanges->getNewChangesCount()); + null, + null, + $userChanges->getNewChangesCount() + ); } } } diff --git a/plugins/CoreAdminHome/OptOutManager.php b/plugins/CoreAdminHome/OptOutManager.php index aad15280d83..25ccbd334ba 100644 --- a/plugins/CoreAdminHome/OptOutManager.php +++ b/plugins/CoreAdminHome/OptOutManager.php @@ -259,9 +259,15 @@ public function getOptOutSelfContainedEmbedCode( window.MatomoConsent = { }; HTML; - return str_replace('window.MatomoConsent = { };', $this->getOptOutCommonJS(), - str_replace('style=""', ($applyStyling ? 'style="' . $styleSheet . '"' : ''), - str_replace("var settings = {};", $settingsString, $code))); + return str_replace( + 'window.MatomoConsent = { };', + $this->getOptOutCommonJS(), + str_replace( + 'style=""', + ($applyStyling ? 'style="' . $styleSheet . '"' : ''), + str_replace("var settings = {};", $settingsString, $code) + ) + ); } /** @@ -297,8 +303,10 @@ public function getOptOutJS(): string // If the language parameter is 'auto' then use the browser language if ($language === 'auto') { - $language = Common::extractLanguageAndRegionCodeFromBrowserLanguage(Common::getBrowserLanguage(), - APILanguagesManager::getInstance()->getAvailableLanguages()); + $language = Common::extractLanguageAndRegionCodeFromBrowserLanguage( + Common::getBrowserLanguage(), + APILanguagesManager::getInstance()->getAvailableLanguages() + ); } $settings = [ @@ -385,9 +393,15 @@ function showOptOutDirect() { window.MatomoConsent = { }; JS; - return str_replace('window.MatomoConsent = { };', $this->getOptOutCommonJS(), - str_replace('stylecss', $styleSheet, - str_replace("var settings = {};", $settingsString, $code))); + return str_replace( + 'window.MatomoConsent = { };', + $this->getOptOutCommonJS(), + str_replace( + 'stylecss', + $styleSheet, + str_replace("var settings = {};", $settingsString, $code) + ) + ); } /** diff --git a/plugins/CoreConsole/Commands/CoreArchiver.php b/plugins/CoreConsole/Commands/CoreArchiver.php index 558403c207f..911dc0de6d7 100644 --- a/plugins/CoreConsole/Commands/CoreArchiver.php +++ b/plugins/CoreConsole/Commands/CoreArchiver.php @@ -89,41 +89,88 @@ public static function configureArchiveCommand(ConsoleCommand $command) but it is recommended to run it via command line/CLI instead. * If you have any suggestion about this script, please let the team know at feedback@matomo.org * Enjoy!"); - $command->addRequiredValueOption('url', null, + $command->addRequiredValueOption( + 'url', + null, "Forces the value of this option to be used as the URL to Piwik. \nIf your system does not support" . " archiving with CLI processes, you may need to set this in order for the archiving HTTP requests to use" - . " the desired URLs."); - $command->addOptionalValueOption('skip-idsites', null, - 'If specified, archiving will be skipped for these websites (in case these website ids would have been archived).'); - $command->addNoValueOption('skip-all-segments', null, - 'If specified, all segments will be skipped during archiving.'); - $command->addOptionalValueOption('force-idsites', null, - 'If specified, archiving will be processed only for these Sites Ids (comma separated)'); - $command->addNoValueOption('skip-segments-today', null, - 'If specified, segments will be only archived for yesterday, but not today. If the segment was created or changed recently, then it will still be archived for today and the setting will be ignored for this segment.'); - $command->addOptionalValueOption('force-periods', null, - "If specified, archiving will be processed only for these Periods (comma separated eg. day,week,month,year,range)"); - $command->addOptionalValueOption('force-date-last-n', null, - "Deprecated. Please use the \"process_new_segments_from\" INI configuration option instead."); - $command->addOptionalValueOption('force-date-range', null, - "If specified, archiving will be processed only for periods included in this date range. Format: YYYY-MM-DD,YYYY-MM-DD"); - $command->addRequiredValueOption('force-idsegments', null, + . " the desired URLs." + ); + $command->addOptionalValueOption( + 'skip-idsites', + null, + 'If specified, archiving will be skipped for these websites (in case these website ids would have been archived).' + ); + $command->addNoValueOption( + 'skip-all-segments', + null, + 'If specified, all segments will be skipped during archiving.' + ); + $command->addOptionalValueOption( + 'force-idsites', + null, + 'If specified, archiving will be processed only for these Sites Ids (comma separated)' + ); + $command->addNoValueOption( + 'skip-segments-today', + null, + 'If specified, segments will be only archived for yesterday, but not today. If the segment was created or changed recently, then it will still be archived for today and the setting will be ignored for this segment.' + ); + $command->addOptionalValueOption( + 'force-periods', + null, + "If specified, archiving will be processed only for these Periods (comma separated eg. day,week,month,year,range)" + ); + $command->addOptionalValueOption( + 'force-date-last-n', + null, + "Deprecated. Please use the \"process_new_segments_from\" INI configuration option instead." + ); + $command->addOptionalValueOption( + 'force-date-range', + null, + "If specified, archiving will be processed only for periods included in this date range. Format: YYYY-MM-DD,YYYY-MM-DD" + ); + $command->addRequiredValueOption( + 'force-idsegments', + null, 'If specified, only these segments will be processed (if the segment should be applied to a site in the first place).' . "\nSpecify stored segment IDs, not the segments themselves, eg, 1,2,3. " - . "\nNote: if identical segments exist w/ different IDs, they will both be skipped, even if you only supply one ID."); - $command->addOptionalValueOption('concurrent-requests-per-website', null, - "When processing a website and its segments, number of requests to process in parallel", CronArchive::MAX_CONCURRENT_API_REQUESTS); - $command->addOptionalValueOption('concurrent-archivers', null, - "The number of max archivers to run in parallel. Depending on how you start the archiver as a cronjob, you may need to double the amount of archivers allowed if the same process appears twice in the `ps ex` output.", 3); - $command->addRequiredValueOption('max-websites-to-process', null, - "Maximum number of websites to process during a single execution of the archiver. Can be used to limit the process lifetime e.g. to avoid increasing memory usage."); - $command->addRequiredValueOption('max-archives-to-process', null, - "Maximum number of archives to process during a single execution of the archiver. Can be used to limit the process lifetime e.g. to avoid increasing memory usage."); - $command->addNoValueOption('disable-scheduled-tasks', null, - "Skips executing Scheduled tasks (sending scheduled reports, db optimization, etc.)."); - $command->addNoValueOption('accept-invalid-ssl-certificate', null, + . "\nNote: if identical segments exist w/ different IDs, they will both be skipped, even if you only supply one ID." + ); + $command->addOptionalValueOption( + 'concurrent-requests-per-website', + null, + "When processing a website and its segments, number of requests to process in parallel", + CronArchive::MAX_CONCURRENT_API_REQUESTS + ); + $command->addOptionalValueOption( + 'concurrent-archivers', + null, + "The number of max archivers to run in parallel. Depending on how you start the archiver as a cronjob, you may need to double the amount of archivers allowed if the same process appears twice in the `ps ex` output.", + 3 + ); + $command->addRequiredValueOption( + 'max-websites-to-process', + null, + "Maximum number of websites to process during a single execution of the archiver. Can be used to limit the process lifetime e.g. to avoid increasing memory usage." + ); + $command->addRequiredValueOption( + 'max-archives-to-process', + null, + "Maximum number of archives to process during a single execution of the archiver. Can be used to limit the process lifetime e.g. to avoid increasing memory usage." + ); + $command->addNoValueOption( + 'disable-scheduled-tasks', + null, + "Skips executing Scheduled tasks (sending scheduled reports, db optimization, etc.)." + ); + $command->addNoValueOption( + 'accept-invalid-ssl-certificate', + null, "It is _NOT_ recommended to use this argument. Instead, you should use a valid SSL certificate!\nIt can be " - . "useful if you specified --url=https://... or if you are using Piwik with force_ssl=1"); + . "useful if you specified --url=https://... or if you are using Piwik with force_ssl=1" + ); $command->addOptionalValueOption('php-cli-options', null, 'Forwards the PHP configuration options to the PHP CLI command. For example "-d memory_limit=8G". Note: These options are only applied if the archiver actually uses CLI and not HTTP.', $default = ''); $command->addNoValueOption('force-all-websites', null, 'Force archiving all websites.'); $command->addOptionalValueOption('force-report', null, 'If specified, only processes invalidations for a specific report in a specific plugin. Value must be in the format of "MyPlugin.myReport".'); diff --git a/plugins/CoreConsole/Commands/DevelopmentSyncProcessedSystemTests.php b/plugins/CoreConsole/Commands/DevelopmentSyncProcessedSystemTests.php index 457c1a927e5..465257cd8ed 100644 --- a/plugins/CoreConsole/Commands/DevelopmentSyncProcessedSystemTests.php +++ b/plugins/CoreConsole/Commands/DevelopmentSyncProcessedSystemTests.php @@ -76,7 +76,9 @@ protected function updateCoreFiles() $filename = sprintf('system.%s.tar.bz2', $buildNumber); $urlBase = sprintf('https://builds-artifacts.matomo.org/%s/%s', $repository, $filename); - $tests = Http::sendHttpRequest($urlBase, $timeout = 120, + $tests = Http::sendHttpRequest( + $urlBase, + $timeout = 120, $userAgent = null, $destinationPath = null, $followDepth = 0, @@ -85,7 +87,8 @@ protected function updateCoreFiles() $getExtendedInfo = false, $httpMethod = 'GET', $httpUser, - $httpPassword); + $httpPassword + ); $tarFile = $tmpDir . $filename; file_put_contents($tarFile, $tests); diff --git a/plugins/CoreConsole/Commands/GeneratePluginBase.php b/plugins/CoreConsole/Commands/GeneratePluginBase.php index e3665fbee76..2ec3a495e12 100644 --- a/plugins/CoreConsole/Commands/GeneratePluginBase.php +++ b/plugins/CoreConsole/Commands/GeneratePluginBase.php @@ -303,8 +303,8 @@ protected function copyTemplateToPlugin($templateFolder, $pluginName, array $rep $replace['PLUGINNAME'] = $pluginName; $files = array_merge( - Filesystem::globr($templateFolder, '*'), - // Also copy files starting with . such as .gitignore + Filesystem::globr($templateFolder, '*'), + // Also copy files starting with . such as .gitignore Filesystem::globr($templateFolder, '.*') ); diff --git a/plugins/CoreConsole/Commands/GenerateReport.php b/plugins/CoreConsole/Commands/GenerateReport.php index 30d4b2aff70..acf3c8fb2c5 100644 --- a/plugins/CoreConsole/Commands/GenerateReport.php +++ b/plugins/CoreConsole/Commands/GenerateReport.php @@ -124,8 +124,10 @@ protected function getReportName() $reportName = $input->getOption('reportname'); if (empty($reportName)) { - $reportName = $this->askAndValidate('Enter the name of your report, for instance "Browser Families": ', - $validate); + $reportName = $this->askAndValidate( + 'Enter the name of your report, for instance "Browser Families": ', + $validate + ); } else { $validate($reportName); } @@ -153,8 +155,10 @@ protected function getDocumentation() $documentation = $input->getOption('documentation'); if (empty($documentation)) { - $documentation = $this->askAndValidate('Enter a documentation that describes the data of your report (you can leave it empty and define it later): ', - $validate); + $documentation = $this->askAndValidate( + 'Enter a documentation that describes the data of your report (you can leave it empty and define it later): ', + $validate + ); } else { $validate($documentation); } @@ -199,10 +203,12 @@ protected function getCategory($pluginName) $categories = array_values(array_unique($categories)); if (empty($category)) { - $category = $this->askAndValidate('Enter the report category, for instance "Visitor" (you can reuse any existing category or define a new one): ', - $validate, - false, - $categories); + $category = $this->askAndValidate( + 'Enter the report category, for instance "Visitor" (you can reuse any existing category or define a new one): ', + $validate, + false, + $categories + ); } else { $validate($category); } @@ -270,10 +276,12 @@ protected function getDimension($pluginName) $actualDimension = $input->getOption('dimension'); if (null === $actualDimension) { - $actualDimension = $this->askAndValidate('Enter the report dimension, for instance "Browser" (you can leave it either empty or use an existing one): ', - $validate, - null, - $dimensionNames); + $actualDimension = $this->askAndValidate( + 'Enter the report dimension, for instance "Browser" (you can leave it either empty or use an existing one): ', + $validate, + null, + $dimensionNames + ); } else { $validate($actualDimension); } diff --git a/plugins/CoreConsole/tests/System/ArchiveCronTest.php b/plugins/CoreConsole/tests/System/ArchiveCronTest.php index 850e253f9e2..fb024c7ae23 100644 --- a/plugins/CoreConsole/tests/System/ArchiveCronTest.php +++ b/plugins/CoreConsole/tests/System/ArchiveCronTest.php @@ -220,7 +220,14 @@ public function testArchivePhpCron() // invalidate exampleplugin only archives in past $invalidator = StaticContainer::get(ArchiveInvalidator::class); $invalidator->markArchivesAsInvalidated( - [1], ['2007-04-05'], 'day', new Segment('', [1]), false, false, 'ExamplePlugin'); + [1], + ['2007-04-05'], + 'day', + new Segment('', [1]), + false, + false, + 'ExamplePlugin' + ); // track a visit in 2007-04-05 so it will archive (don't want to force archiving because then this test will take another 15 mins) $tracker = Fixture::getTracker(1, '2007-04-05'); @@ -347,7 +354,8 @@ public function testArchivePhpCronArchivesFullRanges() $this->assertEquals($expectedInvalidations, $invalidationEntries); - $this->runApiTests(array( + $this->runApiTests( + array( 'VisitsSummary.get', 'Actions.get', 'DevicesDetection.getType'), array('idSite' => '1', 'date' => '2012-08-09,2012-08-13', @@ -380,7 +388,8 @@ public function testRangeBrowserArchivingWorksWhenInvalidatedByVisit() $model->deleteArchiveIds($table, $blobTable, $idArchives); // process archives once - $this->runApiTests(array( + $this->runApiTests( + array( 'VisitsSummary.get', 'Actions.get', 'DevicesDetection.getType'), array('idSite' => '1', 'date' => '2012-08-09,2012-08-13', @@ -405,7 +414,8 @@ public function testRangeBrowserArchivingWorksWhenInvalidatedByVisit() $this->assertNotEmpty($rangeArchivesInvalid); // cron archive not run, but ranges should still be rearchived - $this->runApiTests(array( + $this->runApiTests( + array( 'VisitsSummary.get', 'Actions.get', 'DevicesDetection.getType'), array('idSite' => '1', 'date' => '2012-08-09,2012-08-13', diff --git a/plugins/CoreHome/Controller.php b/plugins/CoreHome/Controller.php index 590dc3bf736..fb77e9dc4c7 100644 --- a/plugins/CoreHome/Controller.php +++ b/plugins/CoreHome/Controller.php @@ -196,7 +196,9 @@ protected function setDateTodayIfWebsiteCreatedToday() $todayLocalTimezone = Date::factory('now', $this->site->getTimezone())->toString('Y-m-d'); if ($creationDateLocalTimezone == $todayLocalTimezone) { - Piwik::redirectToModule('CoreHome', 'index', + Piwik::redirectToModule( + 'CoreHome', + 'index', array('date' => 'today', 'idSite' => $this->idSite, 'period' => Common::getRequestVar('period')) diff --git a/plugins/CoreHome/DataTableRowAction/RowEvolution.php b/plugins/CoreHome/DataTableRowAction/RowEvolution.php index df2416c0ddc..f42fe55590c 100644 --- a/plugins/CoreHome/DataTableRowAction/RowEvolution.php +++ b/plugins/CoreHome/DataTableRowAction/RowEvolution.php @@ -115,8 +115,10 @@ public function __construct($idSite, $date, $graphType = 'graphEvolution') if ($this->period != 'range') { // handle day, week, month and year: display last X periods //handle cache if exist - $cache = ViewDataTableManager::getViewDataTableParameters(Piwik::getCurrentUserLogin(), - 'CoreHome.getRowEvolutionGraph'); + $cache = ViewDataTableManager::getViewDataTableParameters( + Piwik::getCurrentUserLogin(), + 'CoreHome.getRowEvolutionGraph' + ); $lastDay = (isset($cache['evolution_' . $this->period . '_last_n']) ? $cache['evolution_' . $this->period . '_last_n'] : null); $end = $date->toString(); [$this->date, $lastN] = EvolutionViz::getDateRangeAndLastN($this->period, $end, $lastDay); @@ -253,8 +255,12 @@ protected function extractEvolutionReport($report) public function getRowEvolutionGraph($graphType = false, $metrics = false) { // set up the view data table - $view = Factory::build($graphType ? : $this->graphType, $this->apiMethod, - $controllerAction = 'CoreHome.getRowEvolutionGraph', $forceDefault = true); + $view = Factory::build( + $graphType ? : $this->graphType, + $this->apiMethod, + $controllerAction = 'CoreHome.getRowEvolutionGraph', + $forceDefault = true + ); $view->setDataTable($this->dataTable); if (!empty($this->graphMetrics)) { // In row Evolution popover, this is empty diff --git a/plugins/CoreHome/tests/Integration/Column/VisitLastActionTimeTest.php b/plugins/CoreHome/tests/Integration/Column/VisitLastActionTimeTest.php index f0fc25024c0..95ea3810f49 100644 --- a/plugins/CoreHome/tests/Integration/Column/VisitLastActionTimeTest.php +++ b/plugins/CoreHome/tests/Integration/Column/VisitLastActionTimeTest.php @@ -58,9 +58,16 @@ public function test_convertHourToHourInSiteTimezone_UTC() public function test_convertHourToHourInSiteTimezone_WithTimezone() { - $idSite = Fixture::createWebsite('2020-01-02 03:04:05', $ecommerce = 1, 'Site', $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = 'Asia/Jakarta'); + $idSite = Fixture::createWebsite( + '2020-01-02 03:04:05', + $ecommerce = 1, + 'Site', + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = 'Asia/Jakarta' + ); $hourConverted = VisitLastActionTime::convertHourToHourInSiteTimezone(5, $idSite); $this->assertEquals(12, $hourConverted); } @@ -69,9 +76,16 @@ public function test_convertHourToHourInSiteTimezone_WithTimezoneAndCustomDate() { $_GET['period'] = 'day'; $_GET['date'] = '2020-01-02 03:04:05'; - $idSite = Fixture::createWebsite('2020-01-02 03:04:05', $ecommerce = 1, 'Site', $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = 'Asia/Jakarta'); + $idSite = Fixture::createWebsite( + '2020-01-02 03:04:05', + $ecommerce = 1, + 'Site', + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = 'Asia/Jakarta' + ); $hourConverted = VisitLastActionTime::convertHourToHourInSiteTimezone(5, $idSite); unset($_GET['period'], $_GET['date']); $this->assertEquals(12, $hourConverted); diff --git a/plugins/CoreHome/tests/Integration/Tracker/VisitRequestProcessorTest.php b/plugins/CoreHome/tests/Integration/Tracker/VisitRequestProcessorTest.php index 52265a49e44..47314e03896 100644 --- a/plugins/CoreHome/tests/Integration/Tracker/VisitRequestProcessorTest.php +++ b/plugins/CoreHome/tests/Integration/Tracker/VisitRequestProcessorTest.php @@ -32,8 +32,11 @@ public function test_isVisitNew_ReturnsTrue_IfTrackerAlwaysNewVisitorIsSet() /** @var VisitRequestProcessor $visit */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-02 08:08:34', $thisActionTime = '2012-01-02 08:12:45', $isVisitorKnown = true, - [ 'trackerAlwaysNewVisitor' => true ]); + $lastActionTime = '2012-01-02 08:08:34', + $thisActionTime = '2012-01-02 08:12:45', + $isVisitorKnown = true, + [ 'trackerAlwaysNewVisitor' => true ] + ); $result = $visit->isVisitNew($visitProperties, $request, null); @@ -46,8 +49,12 @@ public function test_isVisitNew_ReturnsTrue_IfNewVisitQueryParamIsSet() /** @var VisitRequestProcessor $visit */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-02 08:08:34', $thisActionTime = '2012-01-02 08:12:45', $isVisitorKnown = true, [], - ['new_visit' => '1']); + $lastActionTime = '2012-01-02 08:08:34', + $thisActionTime = '2012-01-02 08:12:45', + $isVisitorKnown = true, + [], + ['new_visit' => '1'] + ); $result = $visit->isVisitNew($visitProperties, $request, null); @@ -60,7 +67,10 @@ public function test_isVisitNew_ReturnsFalse_IfLastActionTimestampIsWithinVisitT /** @var VisitRequestProcessor $visit */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-02 08:08:34', $thisActionTime = '2012-01-02 08:12:45', $isVisitorKnown = true); + $lastActionTime = '2012-01-02 08:08:34', + $thisActionTime = '2012-01-02 08:12:45', + $isVisitorKnown = true + ); $result = $visit->isVisitNew($visitProperties, $request, null); @@ -74,13 +84,19 @@ public function test_isVisitNew_ReturnsTrue_IfLastActionTimestampWasYesterday() // test same day /** @var VisitRequestProcessor $visit */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-01 23:59:58', $thisActionTime = '2012-01-01 23:59:59', $isVisitorKnown = true); + $lastActionTime = '2012-01-01 23:59:58', + $thisActionTime = '2012-01-01 23:59:59', + $isVisitorKnown = true + ); $result = $visit->isVisitNew($visitProperties, $request, null); $this->assertFalse($result); // test different day list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-01 23:59:58', $thisActionTime = '2012-01-02 00:00:01', $isVisitorKnown = true); + $lastActionTime = '2012-01-01 23:59:58', + $thisActionTime = '2012-01-02 00:00:01', + $isVisitorKnown = true + ); $result = $visit->isVisitNew($visitProperties, $request, null); $this->assertTrue($result); } @@ -129,7 +145,10 @@ public function test_isVisitNew_ReturnsFalse_WhenUserIdChanges() /** @var VisitRequestProcessor $visit */ /** @var Request $request */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-02 08:08:34', $thisActionTime = '2012-01-02 08:12:45', $isVisitorKnown = true); + $lastActionTime = '2012-01-02 08:08:34', + $thisActionTime = '2012-01-02 08:12:45', + $isVisitorKnown = true + ); $visitProperties->setProperty('user_id', 'foo_different'); $request->setParam('uid', 'foo'); @@ -149,7 +168,10 @@ public function test_isVisitNew_ReturnsTrue_WhenUserChanges_AndUserIdNotOverwrit /** @var VisitProperties $visitProperties */ /** @var Request $request */ list($visit, $visitProperties, $request) = $this->makeVisitorAndAction( - $lastActionTime = '2012-01-02 08:08:34', $thisActionTime = '2012-01-02 08:12:45', $isVisitorKnown = true); + $lastActionTime = '2012-01-02 08:08:34', + $thisActionTime = '2012-01-02 08:12:45', + $isVisitorKnown = true + ); $visitProperties->setProperty('user_id', 'foo_different'); $request->setParam('uid', 'foo'); @@ -167,8 +189,11 @@ private function makeVisitorAndAction( $idsite = API::getInstance()->addSite("name", "http://piwik.net/"); /** @var Request $request */ - list($visit, $request) = $this->prepareVisitWithRequest(array_merge(['idsite' => $idsite], $extraRequestParams), - $currentActionTime, $processorParams); + list($visit, $request) = $this->prepareVisitWithRequest( + array_merge(['idsite' => $idsite], $extraRequestParams), + $currentActionTime, + $processorParams + ); $visitProperties = new VisitProperties(); $visitProperties->setProperty('visit_last_action_time', Date::factory($lastActionTimestamp)->getTimestamp()); diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php index 0291d745d92..c71d98e416b 100644 --- a/plugins/CorePluginsAdmin/Controller.php +++ b/plugins/CorePluginsAdmin/Controller.php @@ -115,10 +115,12 @@ public function uploadPlugin() Nonce::discardNonce(MarketplaceController::INSTALL_NONCE); - if (!$this->passwordVerify->isPasswordCorrect( - Piwik::getCurrentUserLogin(), - \Piwik\Request::fromRequest()->getStringParameter('confirmPassword') - )) { + if ( + !$this->passwordVerify->isPasswordCorrect( + Piwik::getCurrentUserLogin(), + \Piwik\Request::fromRequest()->getStringParameter('confirmPassword') + ) + ) { throw new \Exception($this->translator->translate('Login_LoginPasswordNotCorrect')); } @@ -309,13 +311,17 @@ protected function getPluginsInfo($themesOnly = false) if ($this->pluginManager->isPluginInFilesystem($pluginName)) { $description = '' - . $this->translator->translate('CorePluginsAdmin_PluginNotCompatibleWith', - array($pluginName, self::getPiwikVersion())) + . $this->translator->translate( + 'CorePluginsAdmin_PluginNotCompatibleWith', + array($pluginName, self::getPiwikVersion()) + ) . '
' . $suffix; } else { - $description = $this->translator->translate('CorePluginsAdmin_PluginNotFound', - array($pluginName)) + $description = $this->translator->translate( + 'CorePluginsAdmin_PluginNotFound', + array($pluginName) + ) . "\n" . $this->translator->translate('CorePluginsAdmin_PluginNotFoundAlternative'); } @@ -452,9 +458,11 @@ public function activate($redirectAfter = true) $message = $this->translator->translate('CorePluginsAdmin_SuccessfullyActicated', array($pluginName)); if ($this->settingsProvider->getSystemSettings($pluginName)) { - $target = sprintf('', + $target = sprintf( + '', Url::getCurrentQueryStringWithParametersModified(array('module' => 'CoreAdminHome', 'action' => 'generalSettings')), - $pluginName); + $pluginName + ); $message .= ' ' . $this->translator->translate('CorePluginsAdmin_ChangeSettingsPossible', array($target, '')); } @@ -531,8 +539,10 @@ public function uninstall($redirectAfter = true) $messagePermissions = Filechecks::getErrorMessageMissingPermissions($path); - $messageIntro = $this->translator->translate("Warning: \"%s\" could not be uninstalled. Piwik did not have enough permission to delete the files in $path. ", - $pluginName); + $messageIntro = $this->translator->translate( + "Warning: \"%s\" could not be uninstalled. Piwik did not have enough permission to delete the files in $path. ", + $pluginName + ); $exitMessage = $messageIntro . "

" . $messagePermissions; $exitMessage .= "
Or manually delete this directory (using FTP or SSH access)"; diff --git a/plugins/CoreUpdater/SystemSettings.php b/plugins/CoreUpdater/SystemSettings.php index e437cd36d90..05bfcca5354 100644 --- a/plugins/CoreUpdater/SystemSettings.php +++ b/plugins/CoreUpdater/SystemSettings.php @@ -98,9 +98,11 @@ private function createReleaseChannel() $field->inlineHelp = Piwik::translate('CoreAdminHome_DevelopmentProcess') . '
' - . Piwik::translate('CoreAdminHome_StableReleases', - ["", - ""]) + . Piwik::translate( + 'CoreAdminHome_StableReleases', + ["", + ""] + ) . '
' . Piwik::translate('CoreAdminHome_LtsReleases'); }); diff --git a/plugins/CoreUpdater/Updater.php b/plugins/CoreUpdater/Updater.php index ccc9b284177..dbd41143b32 100644 --- a/plugins/CoreUpdater/Updater.php +++ b/plugins/CoreUpdater/Updater.php @@ -397,8 +397,10 @@ private function checkFolderPermissions($source, $target) } if (!empty($wrongPermissionDir)) { - throw new Exception($this->translator->translate('CoreUpdater_ExceptionDirWrongPermission', - implode(', ', $wrongPermissionDir))); + throw new Exception($this->translator->translate( + 'CoreUpdater_ExceptionDirWrongPermission', + implode(', ', $wrongPermissionDir) + )); } } } diff --git a/plugins/CoreVisualizations/Visualizations/HtmlTable/AllColumns.php b/plugins/CoreVisualizations/Visualizations/HtmlTable/AllColumns.php index e4af4b3ab7b..448d68ecc8c 100644 --- a/plugins/CoreVisualizations/Visualizations/HtmlTable/AllColumns.php +++ b/plugins/CoreVisualizations/Visualizations/HtmlTable/AllColumns.php @@ -50,7 +50,8 @@ public function beforeGenericFiltersAreAppliedToLoadedDataTable() } $columnsToDisplay = array_merge( - $columnsToDisplay, array('nb_actions', 'nb_actions_per_visit', 'avg_time_on_site', 'bounce_rate') + $columnsToDisplay, + array('nb_actions', 'nb_actions_per_visit', 'avg_time_on_site', 'bounce_rate') ); // only display conversion rate for the plugins that do not provide "per goal" metrics diff --git a/plugins/CoreVue/Commands/Build.php b/plugins/CoreVue/Commands/Build.php index d582ff82680..ed97ffe4bf1 100644 --- a/plugins/CoreVue/Commands/Build.php +++ b/plugins/CoreVue/Commands/Build.php @@ -268,18 +268,25 @@ private function checkNodeJsVersion(): void $npmVersion = ltrim(trim(`npm -v`), 'v'); if (version_compare($nodeVersion, self::RECOMMENDED_NODE_VERSION, '<')) { - $output->writeln(sprintf("The recommended node version for working with Vue is version %s or " + $output->writeln(sprintf( + "The recommended node version for working with Vue is version %s or " . "greater and it looks like you're using %s. Building Vue files may not work with an older version, so " . "we recommend upgrading. nvm can be used to easily install new node versions.", - self::RECOMMENDED_NODE_VERSION, $nodeVersion)); + self::RECOMMENDED_NODE_VERSION, + $nodeVersion + )); } if (version_compare($npmVersion, self::RECOMMENDED_NPM_VERSION, '<')) { - $output->writeln(sprintf("The recommended npm version for working with Vue is version %s " + $output->writeln(sprintf( + "The recommended npm version for working with Vue is version %s " . "or greater and it looks like you're using %s. Using an older version may result in improper " . "dependencies being used, so we recommend upgrading. You can upgrade to the latest version with the " . "command %s", - self::RECOMMENDED_NPM_VERSION, $npmVersion, 'npm install -g npm@latest')); + self::RECOMMENDED_NPM_VERSION, + $npmVersion, + 'npm install -g npm@latest' + )); } } diff --git a/plugins/CustomDimensions/Dao/Configuration.php b/plugins/CustomDimensions/Dao/Configuration.php index 9284c847857..ebdd6b7a0aa 100644 --- a/plugins/CustomDimensions/Dao/Configuration.php +++ b/plugins/CustomDimensions/Dao/Configuration.php @@ -57,7 +57,8 @@ public function configureExistingDimension($idCustomDimension, $idSite, $name, $ $active = $active ? '1' : '0'; $caseSensitive = $caseSensitive ? '1' : '0'; - $this->getDb()->update($this->tableNamePrefixed, + $this->getDb()->update( + $this->tableNamePrefixed, array( 'name' => $name, 'active' => $active, diff --git a/plugins/CustomDimensions/RecordBuilders/CustomDimension.php b/plugins/CustomDimensions/RecordBuilders/CustomDimension.php index e09dbdfdb3c..190b9c11c27 100644 --- a/plugins/CustomDimensions/RecordBuilders/CustomDimension.php +++ b/plugins/CustomDimensions/RecordBuilders/CustomDimension.php @@ -95,8 +95,16 @@ private function aggregateFromVisits( $rankingQuery = new RankingQuery($this->rankingQueryLimit); $rankingQuery->addLabelColumn($dimensions[0]); - $query = $logAggregator->queryVisitsByDimension($dimensions, $where, [], false, $rankingQuery, false, -1, - $rankingQueryGenerate = true); + $query = $logAggregator->queryVisitsByDimension( + $dimensions, + $where, + [], + false, + $rankingQuery, + false, + -1, + $rankingQueryGenerate = true + ); } else { $query = $logAggregator->queryVisitsByDimension($dimensions, $where); } diff --git a/plugins/DBStats/Menu.php b/plugins/DBStats/Menu.php index b529caa59b1..025f72658a9 100644 --- a/plugins/DBStats/Menu.php +++ b/plugins/DBStats/Menu.php @@ -18,9 +18,11 @@ class Menu extends \Piwik\Plugin\Menu public function configureAdminMenu(MenuAdmin $menu) { if (Piwik::hasUserSuperUserAccess()) { - $menu->addDiagnosticItem('DBStats_DatabaseUsage', - $this->urlForAction('index'), - $order = 6); + $menu->addDiagnosticItem( + 'DBStats_DatabaseUsage', + $this->urlForAction('index'), + $order = 6 + ); } } } diff --git a/plugins/DBStats/MySQLMetadataProvider.php b/plugins/DBStats/MySQLMetadataProvider.php index a5fcdaab05c..eb439f0ee10 100644 --- a/plugins/DBStats/MySQLMetadataProvider.php +++ b/plugins/DBStats/MySQLMetadataProvider.php @@ -166,8 +166,12 @@ public function getRowCountsAndSizeByBlobName($forceCache = false) $extraSelects = array("SUM(OCTET_LENGTH(value)) AS 'blob_size'", "SUM(LENGTH(name)) AS 'name_size'"); $extraCols = array('blob_size', 'name_size'); return $this->getRowCountsByArchiveName( - $this->getAllBlobArchiveStatus(), 'getEstimatedBlobArchiveRowSize', $forceCache, $extraSelects, - $extraCols); + $this->getAllBlobArchiveStatus(), + 'getEstimatedBlobArchiveRowSize', + $forceCache, + $extraSelects, + $extraCols + ); } /** @@ -183,7 +187,10 @@ public function getRowCountsAndSizeByBlobName($forceCache = false) public function getRowCountsAndSizeByMetricName($forceCache = false) { return $this->getRowCountsByArchiveName( - $this->getAllNumericArchiveStatus(), 'getEstimatedRowsSize', $forceCache); + $this->getAllNumericArchiveStatus(), + 'getEstimatedRowsSize', + $forceCache + ); } /** @@ -226,8 +233,10 @@ private function getRowCountsByArchiveName( // add estimated_size column $getEstimatedSize = array($this, $getRowSizeMethod); - $table->filter('ColumnCallbackAddColumn', - array($cols, 'estimated_size', $getEstimatedSize, array($status))); + $table->filter( + 'ColumnCallbackAddColumn', + array($cols, 'estimated_size', $getEstimatedSize, array($status)) + ); $dataTable->addDataTable($table); } diff --git a/plugins/DBStats/Reports/GetIndividualMetricsSummary.php b/plugins/DBStats/Reports/GetIndividualMetricsSummary.php index a6c35d6e43b..0853b4d4f00 100644 --- a/plugins/DBStats/Reports/GetIndividualMetricsSummary.php +++ b/plugins/DBStats/Reports/GetIndividualMetricsSummary.php @@ -27,8 +27,12 @@ protected function init() public function configureView(ViewDataTable $view) { $this->addBaseDisplayProperties($view); - $this->addPresentationFilters($view, $addTotalSizeColumn = false, $addPercentColumn = false, - $sizeColumns = array('estimated_size')); + $this->addPresentationFilters( + $view, + $addTotalSizeColumn = false, + $addPercentColumn = false, + $sizeColumns = array('estimated_size') + ); $view->requestConfig->filter_sort_order = 'asc'; $view->config->addTranslation('label', Piwik::translate('General_Metric')); diff --git a/plugins/DBStats/Reports/GetIndividualReportsSummary.php b/plugins/DBStats/Reports/GetIndividualReportsSummary.php index 7d9d6dec630..e631eda737e 100644 --- a/plugins/DBStats/Reports/GetIndividualReportsSummary.php +++ b/plugins/DBStats/Reports/GetIndividualReportsSummary.php @@ -28,8 +28,12 @@ protected function init() public function configureView(ViewDataTable $view) { $this->addBaseDisplayProperties($view); - $this->addPresentationFilters($view, $addTotalSizeColumn = false, $addPercentColumn = false, - $sizeColumns = array('estimated_size')); + $this->addPresentationFilters( + $view, + $addTotalSizeColumn = false, + $addPercentColumn = false, + $sizeColumns = array('estimated_size') + ); $view->requestConfig->filter_sort_order = 'asc'; $view->config->addTranslation('label', Piwik::translate('General_Report')); diff --git a/plugins/Dashboard/Dashboard.php b/plugins/Dashboard/Dashboard.php index 12687796f4f..34259699247 100644 --- a/plugins/Dashboard/Dashboard.php +++ b/plugins/Dashboard/Dashboard.php @@ -80,7 +80,8 @@ public function addWidgetConfigs(&$widgets) private function getDashboards() { - return Request::processRequest('Dashboard.getDashboards', + return Request::processRequest( + 'Dashboard.getDashboards', ['filter_limit' => '-1', 'filter_offset' => 0], [] ); diff --git a/plugins/Dashboard/Model.php b/plugins/Dashboard/Model.php index 363052f3dd3..31feeb609bb 100644 --- a/plugins/Dashboard/Model.php +++ b/plugins/Dashboard/Model.php @@ -33,8 +33,10 @@ public function __construct() */ public function getLayoutForUser($login, $idDashboard) { - $query = sprintf('SELECT layout FROM %s WHERE login = ? AND iddashboard = ?', - $this->table); + $query = sprintf( + 'SELECT layout FROM %s WHERE login = ? AND iddashboard = ?', + $this->table + ); $bind = array($login, $idDashboard); $layouts = Db::fetchAll($query, $bind); @@ -98,8 +100,10 @@ public function createNewDashboardForUser($login, $name, $layout) public function createOrUpdateDashboard($login, $idDashboard, $layout) { $bind = array($login, $idDashboard, $layout, $layout); - $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', - $this->table); + $query = sprintf( + 'INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', + $this->table + ); Db::query($query, $bind); } @@ -125,8 +129,10 @@ private function getNextIdDashboard($login) public function updateLayoutForUser($login, $idDashboard, $layout) { $bind = array($login, $idDashboard, $layout, $layout); - $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', - $this->table); + $query = sprintf( + 'INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', + $this->table + ); Db::query($query, $bind); } diff --git a/plugins/DevicesDetection/Columns/Os.php b/plugins/DevicesDetection/Columns/Os.php index 2380ecc0a73..d06b55df3be 100644 --- a/plugins/DevicesDetection/Columns/Os.php +++ b/plugins/DevicesDetection/Columns/Os.php @@ -54,8 +54,12 @@ public function configureSegments(SegmentsList $segmentsList, DimensionSegmentFa return $result; }); $segment->setSuggestedValuesCallback(function ($idSite, $maxValuesToReturn, $table) { - return $this->sortStaticListByUsage(OperatingSystem::getAvailableOperatingSystems(), $table, - 'operatingSystemCode', $maxValuesToReturn); + return $this->sortStaticListByUsage( + OperatingSystem::getAvailableOperatingSystems(), + $table, + 'operatingSystemCode', + $maxValuesToReturn + ); }); $segmentsList->addSegment($dimensionSegmentFactory->createSegment($segment)); } diff --git a/plugins/DevicesDetection/Menu.php b/plugins/DevicesDetection/Menu.php index a7b3055b249..fd1c58245c4 100644 --- a/plugins/DevicesDetection/Menu.php +++ b/plugins/DevicesDetection/Menu.php @@ -18,9 +18,11 @@ class Menu extends \Piwik\Plugin\Menu public function configureAdminMenu(MenuAdmin $menu) { if (Piwik::isUserHasSomeAdminAccess()) { - $menu->addDiagnosticItem('DevicesDetection_DeviceDetection', - $this->urlForAction('detection'), - $order = 40); + $menu->addDiagnosticItem( + 'DevicesDetection_DeviceDetection', + $this->urlForAction('detection'), + $order = 40 + ); } } } diff --git a/plugins/DevicesDetection/functions.php b/plugins/DevicesDetection/functions.php index 0eb37969981..23a32606e23 100644 --- a/plugins/DevicesDetection/functions.php +++ b/plugins/DevicesDetection/functions.php @@ -331,9 +331,9 @@ function _mapLegacyOsShortCodes($shortCode): string //'VMS' => '', // OpenVMS => ?? ]; return ($shortCode && array_key_exists( - $shortCode, - $legacyShortCodes - )) ? $legacyShortCodes[$shortCode] : (string)$shortCode; + $shortCode, + $legacyShortCodes + )) ? $legacyShortCodes[$shortCode] : (string)$shortCode; } /** diff --git a/plugins/DevicesDetection/tests/Fixtures/MultiDeviceGoalConversions.php b/plugins/DevicesDetection/tests/Fixtures/MultiDeviceGoalConversions.php index d1b679b4a5d..e3be660ad8b 100644 --- a/plugins/DevicesDetection/tests/Fixtures/MultiDeviceGoalConversions.php +++ b/plugins/DevicesDetection/tests/Fixtures/MultiDeviceGoalConversions.php @@ -41,8 +41,14 @@ private function setUpWebsitesAndGoals() if (!self::goalExists($idSite = 1, $idGoal = 1)) { API::getInstance()->addGoal( - $this->idSite, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, - $revenue = 10, $allowMultipleConversions = 1 + $this->idSite, + 'Goal 1 - Thank you', + 'title', + 'Thank you', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = 1 ); } } diff --git a/plugins/Diagnostics/Commands/ArchivingConfig.php b/plugins/Diagnostics/Commands/ArchivingConfig.php index ae6e4000a00..dc43c25529f 100644 --- a/plugins/Diagnostics/Commands/ArchivingConfig.php +++ b/plugins/Diagnostics/Commands/ArchivingConfig.php @@ -21,8 +21,11 @@ class ArchivingConfig extends ConsoleCommand protected function configure() { $this->setName('diagnostics:archiving-config'); - $this->addNoValueOption('json', null, - "If supplied, the command will return data in json format"); + $this->addNoValueOption( + 'json', + null, + "If supplied, the command will return data in json format" + ); $this->setDescription('Show configuration settings that can affect archiving performance'); } diff --git a/plugins/Diagnostics/Commands/ArchivingInstanceStatistics.php b/plugins/Diagnostics/Commands/ArchivingInstanceStatistics.php index 848a1e42267..5e47cfc5bd9 100644 --- a/plugins/Diagnostics/Commands/ArchivingInstanceStatistics.php +++ b/plugins/Diagnostics/Commands/ArchivingInstanceStatistics.php @@ -21,8 +21,11 @@ class ArchivingInstanceStatistics extends ConsoleCommand protected function configure() { $this->setName('diagnostics:archiving-instance-statistics'); - $this->addNoValueOption('json', null, - "If supplied, the command will return data in json format"); + $this->addNoValueOption( + 'json', + null, + "If supplied, the command will return data in json format" + ); $this->setDescription('Show data statistics which can affect archiving performance'); } @@ -59,14 +62,16 @@ public function getArchivingInstanceStatistics(): array [ Date::now()->setDay(1)->subMonth(1)->setTime('00:00:00')->toString('Y-m-d H:i:s'), Date::now()->setDay(1)->subDay(1)->setTime('23:59:59')->toString('Y-m-d H:i:s') - ]) + ] + ) ]; $stats[] = ['Last 12 Month Hits', (int) Db::fetchOne( "SELECT COUNT(*) FROM " . Common::prefixTable("log_link_visit_action") . " WHERE server_time >= ? AND server_time <= ?", [ Date::now()->setDay(1)->subMonth(12)->setTime('00:00:00')->toString('Y-m-d H:i:s'), Date::now()->setDay(1)->subDay(1)->setTime('23:59:59')->toString('Y-m-d H:i:s') - ]) + ] + ) ]; return $stats; } diff --git a/plugins/Diagnostics/Commands/ArchivingMetrics.php b/plugins/Diagnostics/Commands/ArchivingMetrics.php index d11024807f4..2d848c5e685 100644 --- a/plugins/Diagnostics/Commands/ArchivingMetrics.php +++ b/plugins/Diagnostics/Commands/ArchivingMetrics.php @@ -21,8 +21,11 @@ class ArchivingMetrics extends ConsoleCommand protected function configure() { $this->setName('diagnostics:archiving-metrics'); - $this->addNoValueOption('json', null, - "If supplied, the command will return data in json format"); + $this->addNoValueOption( + 'json', + null, + "If supplied, the command will return data in json format" + ); $this->setDescription('Show metrics describing the current archiving status'); } diff --git a/plugins/Diagnostics/Commands/ArchivingQueue.php b/plugins/Diagnostics/Commands/ArchivingQueue.php index 732ed4f79f8..d3169fe2381 100644 --- a/plugins/Diagnostics/Commands/ArchivingQueue.php +++ b/plugins/Diagnostics/Commands/ArchivingQueue.php @@ -19,8 +19,11 @@ class ArchivingQueue extends ConsoleCommand protected function configure() { $this->setName('diagnostics:archiving-queue'); - $this->addNoValueOption('json', null, - "If supplied, the command will return table data in json format"); + $this->addNoValueOption( + 'json', + null, + "If supplied, the command will return table data in json format" + ); $this->setDescription('Show the current state of the archive invalidations queue as a table'); } diff --git a/plugins/Diagnostics/Commands/ArchivingStatus.php b/plugins/Diagnostics/Commands/ArchivingStatus.php index f21758301b2..e8f2263b184 100644 --- a/plugins/Diagnostics/Commands/ArchivingStatus.php +++ b/plugins/Diagnostics/Commands/ArchivingStatus.php @@ -22,10 +22,16 @@ class ArchivingStatus extends ConsoleCommand protected function configure() { $this->setName('diagnostics:archiving-status'); - $this->addNoValueOption('with-stats', null, - "If supplied, the command will include instance statistics such as monthly hits and site count"); - $this->addOptionalValueOption('email', null, - "If supplied, the command will email the output to the supplied email address"); + $this->addNoValueOption( + 'with-stats', + null, + "If supplied, the command will include instance statistics such as monthly hits and site count" + ); + $this->addOptionalValueOption( + 'email', + null, + "If supplied, the command will email the output to the supplied email address" + ); $this->setDescription(''); } diff --git a/plugins/Diagnostics/Diagnostic/CronArchivingCheck.php b/plugins/Diagnostics/Diagnostic/CronArchivingCheck.php index 36add393ae2..2a04ea6ceb3 100644 --- a/plugins/Diagnostics/Diagnostic/CronArchivingCheck.php +++ b/plugins/Diagnostics/Diagnostic/CronArchivingCheck.php @@ -75,8 +75,10 @@ public function execute() $comment .= $this->translator->translate('Installation_NotSupported') . ' ' . $this->translator->translate('Goals_Optional') . ' (' . $this->translator->translate('General_Reasons') . ': ' . $reasonText . ')' - . $this->translator->translate('General_LearnMore', - [' ', '']); + . $this->translator->translate( + 'General_LearnMore', + [' ', ''] + ); $status = DiagnosticResult::STATUS_INFORMATIONAL; } diff --git a/plugins/Diagnostics/Diagnostic/CronArchivingLastRunCheck.php b/plugins/Diagnostics/Diagnostic/CronArchivingLastRunCheck.php index 6999de817f5..a633bdce054 100644 --- a/plugins/Diagnostics/Diagnostic/CronArchivingLastRunCheck.php +++ b/plugins/Diagnostics/Diagnostic/CronArchivingLastRunCheck.php @@ -57,8 +57,10 @@ public function execute() $lastRunTime = (int)Option::get(CronArchive::OPTION_ARCHIVING_FINISHED_TS); if (empty($lastRunTime)) { $comment = $this->translator->translate('Diagnostics_CronArchivingHasNotRun') - . '

' . $this->translator->translate('Diagnostics_CronArchivingRunDetails', - [$coreArchiveShort, $mailto, $commandToRerun, '', '']); + . '

' . $this->translator->translate( + 'Diagnostics_CronArchivingRunDetails', + [$coreArchiveShort, $mailto, $commandToRerun, '', ''] + ); return [DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_ERROR, $comment)]; } diff --git a/plugins/Diagnostics/Diagnostic/DatabaseAbilitiesCheck.php b/plugins/Diagnostics/Diagnostic/DatabaseAbilitiesCheck.php index f683c04c8f9..d47dfa3a3ff 100644 --- a/plugins/Diagnostics/Diagnostic/DatabaseAbilitiesCheck.php +++ b/plugins/Diagnostics/Diagnostic/DatabaseAbilitiesCheck.php @@ -62,7 +62,8 @@ protected function checkUtf8mb4Charset() if (DbHelper::getDefaultCharset() === 'utf8mb4') { return new DiagnosticResultItem( - DiagnosticResult::STATUS_WARNING, 'UTF8mb4 charset

' . + DiagnosticResult::STATUS_WARNING, + 'UTF8mb4 charset

' . $this->translator->translate('Diagnostics_DatabaseUtf8mb4CharsetAvailableButNotUsed', '' . PIWIK_INCLUDE_PATH . '/console core:convert-to-utf8mb4') . '

' . $this->translator->translate('Diagnostics_DatabaseUtf8Requirement', ['๏ฟฝ', @@ -72,7 +73,8 @@ protected function checkUtf8mb4Charset() } return new DiagnosticResultItem( - DiagnosticResult::STATUS_WARNING, 'UTF8mb4 charset

' . + DiagnosticResult::STATUS_WARNING, + 'UTF8mb4 charset

' . $this->translator->translate('Diagnostics_DatabaseUtf8mb4CharsetRecommended') . '

' . $this->translator->translate('Diagnostics_DatabaseUtf8Requirement', ['๏ฟฝ', diff --git a/plugins/Diagnostics/Diagnostic/DbMaxPacket.php b/plugins/Diagnostics/Diagnostic/DbMaxPacket.php index 6fe71aaf197..cc0ca14da89 100644 --- a/plugins/Diagnostics/Diagnostic/DbMaxPacket.php +++ b/plugins/Diagnostics/Diagnostic/DbMaxPacket.php @@ -43,9 +43,13 @@ public function execute() $formatter = new Formatter\Html(); $pretty = $formatter->getPrettySizeFromBytes($maxPacketBytes['Value'], 'M', $precision = 1); $configured = str_replace(array(' M', ' M'), 'MB', $pretty); - $comment = Piwik::translate('Diagnostics_MysqlMaxPacketSizeWarning', + $comment = Piwik::translate( + 'Diagnostics_MysqlMaxPacketSizeWarning', ['', - '', '64MB', $configured]); + '', + '64MB', + $configured] + ); } return array(DiagnosticResult::singleResult($label, $status, $comment)); diff --git a/plugins/Diagnostics/Diagnostic/RecommendedPrivateDirectories.php b/plugins/Diagnostics/Diagnostic/RecommendedPrivateDirectories.php index 0e4640e0550..bbe26edfffc 100644 --- a/plugins/Diagnostics/Diagnostic/RecommendedPrivateDirectories.php +++ b/plugins/Diagnostics/Diagnostic/RecommendedPrivateDirectories.php @@ -26,11 +26,13 @@ public function __construct(Translator $translator) protected function addError(DiagnosticResult &$result) { - $result->addItem(new DiagnosticResultItem(DiagnosticResult::STATUS_INFORMATIONAL, + $result->addItem(new DiagnosticResultItem( + DiagnosticResult::STATUS_INFORMATIONAL, $this->translator->translate('Diagnostics_UrlsAccessibleViaBrowser') . ' ' . $this->translator->translate('General_ReadThisToLearnMore', [ '', '', - ]))); + ]) + )); } } diff --git a/plugins/Ecommerce/Reports/BaseItem.php b/plugins/Ecommerce/Reports/BaseItem.php index 407ac4e1a18..31bebd385ea 100644 --- a/plugins/Ecommerce/Reports/BaseItem.php +++ b/plugins/Ecommerce/Reports/BaseItem.php @@ -50,8 +50,10 @@ public function getMetricsDocumentation() // we do not check whether it is abandon carts if not set re performance improvements if ($this->isAbandonedCart($fetchIfNotSet = false)) { return array( - 'revenue' => Piwik::translate('Goals_ColumnRevenueDocumentation', - Piwik::translate('Goals_DocumentationRevenueGeneratedByProductSales')), + 'revenue' => Piwik::translate( + 'Goals_ColumnRevenueDocumentation', + Piwik::translate('Goals_DocumentationRevenueGeneratedByProductSales') + ), 'quantity' => Piwik::translate('Goals_ColumnQuantityDocumentation', $this->name), 'orders' => Piwik::translate('Goals_ColumnOrdersDocumentation', $this->name), 'avg_price' => Piwik::translate('Goals_ColumnAveragePriceDocumentation', $this->name), diff --git a/plugins/Ecommerce/Tracker/EcommerceRequestProcessor.php b/plugins/Ecommerce/Tracker/EcommerceRequestProcessor.php index 2bca4163d08..f5e283d2c7f 100644 --- a/plugins/Ecommerce/Tracker/EcommerceRequestProcessor.php +++ b/plugins/Ecommerce/Tracker/EcommerceRequestProcessor.php @@ -68,7 +68,8 @@ public function afterRequestProcessed(VisitProperties $visitProperties, Request $goalsConverted = $request->getMetadata('Goals', 'goalsConverted'); if (!empty($goalsConverted)) { $isThereExistingCartInVisit = $this->goalManager->detectIsThereExistingCartInVisit( - $visitProperties->getProperties()); + $visitProperties->getProperties() + ); $request->setMetadata('Goals', 'isThereExistingCartInVisit', $isThereExistingCartInVisit); } } diff --git a/plugins/Ecommerce/VisitorDetails.php b/plugins/Ecommerce/VisitorDetails.php index e4640cc3c58..30bef067166 100644 --- a/plugins/Ecommerce/VisitorDetails.php +++ b/plugins/Ecommerce/VisitorDetails.php @@ -33,8 +33,10 @@ public function extendVisitorDetails(&$visitor) { if(Site::isEcommerceEnabledFor($visitor['idSite'])) { - $ecommerceMetrics = $this->queryEcommerceConversionsVisitorLifeTimeMetricsForVisitor($visitor['idSite'], - $visitor['visitorId']); + $ecommerceMetrics = $this->queryEcommerceConversionsVisitorLifeTimeMetricsForVisitor( + $visitor['idSite'], + $visitor['visitorId'] + ); $visitor['totalEcommerceRevenue'] = $ecommerceMetrics['totalEcommerceRevenue']; $visitor['totalEcommerceConversions'] = $ecommerceMetrics['totalEcommerceConversions']; $visitor['totalEcommerceItems'] = $ecommerceMetrics['totalEcommerceItems']; diff --git a/plugins/Ecommerce/tests/Fixtures/AbandonedCartWithoutConversions.php b/plugins/Ecommerce/tests/Fixtures/AbandonedCartWithoutConversions.php index ff0905af295..876a024014c 100644 --- a/plugins/Ecommerce/tests/Fixtures/AbandonedCartWithoutConversions.php +++ b/plugins/Ecommerce/tests/Fixtures/AbandonedCartWithoutConversions.php @@ -34,8 +34,14 @@ private function setUpWebsitesAndGoals() if (!self::goalExists($this->idSite, $this->idGoalStandard)) { GoalsAPI::getInstance()->addGoal( - $this->idSite, 'title match, triggered NEVER', 'title', 'saldkfjaslkdfjsalkdjf', 'contains', - $caseSensitive = false, $revenue = 10, $allowMultipleConversions = true + $this->idSite, + 'title match, triggered NEVER', + 'title', + 'saldkfjaslkdfjsalkdjf', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = true ); } } diff --git a/plugins/ExampleLogTables/Dao/CustomGroupLog.php b/plugins/ExampleLogTables/Dao/CustomGroupLog.php index d0a59291fd7..f195112b33f 100644 --- a/plugins/ExampleLogTables/Dao/CustomGroupLog.php +++ b/plugins/ExampleLogTables/Dao/CustomGroupLog.php @@ -55,8 +55,12 @@ public function addGroupInformation($group, $isAdmin) $bind = array_values($columns); $placeholder = Common::getSqlStringFieldsArray($columns); - $sql = sprintf('INSERT INTO %s (`%s`) VALUES(%s)', - $this->tablePrefixed, implode('`,`', array_keys($columns)), $placeholder); + $sql = sprintf( + 'INSERT INTO %s (`%s`) VALUES(%s)', + $this->tablePrefixed, + implode('`,`', array_keys($columns)), + $placeholder + ); $db = $this->getDb(); diff --git a/plugins/ExampleLogTables/Dao/CustomUserLog.php b/plugins/ExampleLogTables/Dao/CustomUserLog.php index e6e51153a54..85b1f210879 100644 --- a/plugins/ExampleLogTables/Dao/CustomUserLog.php +++ b/plugins/ExampleLogTables/Dao/CustomUserLog.php @@ -57,8 +57,12 @@ public function addUserInformation($userId, $group, $gender) $bind = array_values($columns); $placeholder = Common::getSqlStringFieldsArray($columns); - $sql = sprintf('INSERT INTO %s (`%s`) VALUES(%s)', - $this->tablePrefixed, implode('`,`', array_keys($columns)), $placeholder); + $sql = sprintf( + 'INSERT INTO %s (`%s`) VALUES(%s)', + $this->tablePrefixed, + implode('`,`', array_keys($columns)), + $placeholder + ); $db = $this->getDb(); diff --git a/plugins/Feedback/API.php b/plugins/Feedback/API.php index 67e0cc0df25..270d2260b56 100644 --- a/plugins/Feedback/API.php +++ b/plugins/Feedback/API.php @@ -58,7 +58,8 @@ public function sendFeedbackForFeature($featureName, $like = null, $choice = nul $body .= sprintf("Feedback:\n%s\n", trim($message)); - $subject = sprintf("%s for %s", + $subject = sprintf( + "%s for %s", empty($like) ? "-1" : "+1", $featureName ); @@ -106,10 +107,11 @@ public function sendFeedbackForSurvey($question, $message = false) $body .= $feedbackMessage ? $feedbackMessage : " \n"; - $subject = sprintf("%s for %s %s", - empty($like) ? "-1" : "+1", - $featureName, - empty($feedbackMessage) ? "" : "(w/ feedback Survey)" + $subject = sprintf( + "%s for %s %s", + empty($like) ? "-1" : "+1", + $featureName, + empty($feedbackMessage) ? "" : "(w/ feedback Survey)" ); $this->sendMail($subject, $body); diff --git a/plugins/Feedback/tests/Integration/FeedbackTest.php b/plugins/Feedback/tests/Integration/FeedbackTest.php index 3a75112265e..ba48c2626b3 100644 --- a/plugins/Feedback/tests/Integration/FeedbackTest.php +++ b/plugins/Feedback/tests/Integration/FeedbackTest.php @@ -37,17 +37,17 @@ public function setUp(): void $this->userModel = new Model(); $this->userModel->addUser( - 'user1', - 'a98732d98732', - 'user1@example.com', - '2019-03-03' + 'user1', + 'a98732d98732', + 'user1@example.com', + '2019-03-03' ); $this->userModel->addUser( - 'user2', - 'a98732d98732', - 'user2@example.com', - Date('Y-m-d') + 'user2', + 'a98732d98732', + 'user2@example.com', + Date('Y-m-d') ); FakeAccess::$identity = 'user1'; FakeAccess::$superUser = false; diff --git a/plugins/GeoIp2/Commands/ConvertRegionCodesToIso.php b/plugins/GeoIp2/Commands/ConvertRegionCodesToIso.php index be003f7935a..15436bd37f8 100644 --- a/plugins/GeoIp2/Commands/ConvertRegionCodesToIso.php +++ b/plugins/GeoIp2/Commands/ConvertRegionCodesToIso.php @@ -51,11 +51,13 @@ protected function doExecute(): int Db::query('DROP table if exists ' . self::MAPPING_TABLE_NAME); - DbHelper::createTable(self::MAPPING_TABLE_NAME, + DbHelper::createTable( + self::MAPPING_TABLE_NAME, "`country_code` VARCHAR(2) NOT NULL, `fips_code` VARCHAR(2) NOT NULL, `iso_code` VARCHAR(4) NULL DEFAULT NULL, - PRIMARY KEY (`country_code`, `fips_code`)"); + PRIMARY KEY (`country_code`, `fips_code`)" + ); $output->writeln(' โœ“'); diff --git a/plugins/GeoIp2/Controller.php b/plugins/GeoIp2/Controller.php index 9a66c885bbf..e908e9a3bb0 100644 --- a/plugins/GeoIp2/Controller.php +++ b/plugins/GeoIp2/Controller.php @@ -150,7 +150,10 @@ public function downloadMissingGeoIpDb() // download part of the file $result = Http::downloadChunk( - $url, $outputPath, Common::getRequestVar('continue', true, 'int')); + $url, + $outputPath, + Common::getRequestVar('continue', true, 'int') + ); // if the file is done if ($result['current_size'] >= $result['expected_file_size']) { diff --git a/plugins/GeoIp2/GeoIP2AutoUpdater.php b/plugins/GeoIp2/GeoIP2AutoUpdater.php index b4129c9e11d..e33fc735ca3 100644 --- a/plugins/GeoIp2/GeoIP2AutoUpdater.php +++ b/plugins/GeoIp2/GeoIP2AutoUpdater.php @@ -232,8 +232,10 @@ public static function unzipDownloadedFile($path, $dbType, $url, $unlink = false $content = $unzip->listContent(); if (empty($content)) { - throw new Exception(Piwik::translate('GeoIp2_CannotListContent', - array("'$path'", $unzip->errorInfo()))); + throw new Exception(Piwik::translate( + 'GeoIp2_CannotListContent', + array("'$path'", $unzip->errorInfo()) + )); } $fileToExtract = null; @@ -249,16 +251,20 @@ public static function unzipDownloadedFile($path, $dbType, $url, $unlink = false } if ($fileToExtract === null) { - throw new Exception(Piwik::translate('GeoIp2_CannotFindGeoIPDatabaseInArchive', - array("'$path'"))); + throw new Exception(Piwik::translate( + 'GeoIp2_CannotFindGeoIPDatabaseInArchive', + array("'$path'") + )); } // extract JUST the .dat file $unzipped = $unzip->extractInString($fileToExtract); if (empty($unzipped)) { - throw new Exception(Piwik::translate('GeoIp2_CannotUnzipGeoIPFile', - array("'$path'", $unzip->errorInfo()))); + throw new Exception(Piwik::translate( + 'GeoIp2_CannotUnzipGeoIPFile', + array("'$path'", $unzip->errorInfo()) + )); } $dbFilename = basename($fileToExtract); @@ -285,8 +291,10 @@ public static function unzipDownloadedFile($path, $dbType, $url, $unlink = false $success = $unzip->extract($outputPath); if ($success !== true) { - throw new Exception(Piwik::translate('General_CannotUnzipFile', - array("'$path'", $unzip->errorInfo()))); + throw new Exception(Piwik::translate( + 'General_CannotUnzipFile', + array("'$path'", $unzip->errorInfo()) + )); } if ($isDbIpUnknownDbType) { @@ -578,7 +586,8 @@ public static function getMissingDatabases() // if a database of the type does not exist, but there's a url to update, then // a database is missing $path = LocationProviderGeoIp2::getPathToGeoIpDatabase( - LocationProviderGeoIp2::$dbNames[$key]); + LocationProviderGeoIp2::$dbNames[$key] + ); if ($path === false) { $result[] = $key; } diff --git a/plugins/GeoIp2/GeoIp2.php b/plugins/GeoIp2/GeoIp2.php index 273cffeacdd..4eb29a052c1 100644 --- a/plugins/GeoIp2/GeoIp2.php +++ b/plugins/GeoIp2/GeoIp2.php @@ -82,7 +82,10 @@ public function getClientSideTranslationKeys(&$translationKeys) */ public function installationFormInit(FormDefaultSettings $form) { - $form->addElement('checkbox', 'setup_geoip2', null, + $form->addElement( + 'checkbox', + 'setup_geoip2', + null, [ 'content' => '
' . Piwik::translate('GeoIp2_AutomaticSetupDescription', ['','']) . '
  ' . Piwik::translate('GeoIp2_AutomaticSetup') ] @@ -116,8 +119,11 @@ public function installationFormSubmit(FormDefaultSettings $form) // otherwise ensure it will be run soonish as scheduled task if ($cliMulti->supportsAsync()) { $phpCli = new CliMulti\CliPhp(); - $command = sprintf('%s %s/console core:run-scheduled-tasks --force "Piwik\Plugins\GeoIp2\GeoIP2AutoUpdater.update" > /dev/null 2>&1 &', - $phpCli->findPhpBinary(), PIWIK_INCLUDE_PATH); + $command = sprintf( + '%s %s/console core:run-scheduled-tasks --force "Piwik\Plugins\GeoIp2\GeoIP2AutoUpdater.update" > /dev/null 2>&1 &', + $phpCli->findPhpBinary(), + PIWIK_INCLUDE_PATH + ); shell_exec($command); } else { /** @var Scheduler $scheduler */ diff --git a/plugins/GeoIp2/LocationProvider/GeoIp2/Php.php b/plugins/GeoIp2/LocationProvider/GeoIp2/Php.php index 1841c12cd52..03baef50c1d 100644 --- a/plugins/GeoIp2/LocationProvider/GeoIp2/Php.php +++ b/plugins/GeoIp2/LocationProvider/GeoIp2/Php.php @@ -432,8 +432,10 @@ public function getInfo() $desc = Piwik::translate('GeoIp2_LocationProviderDesc_Php') . '

'; if (extension_loaded('maxminddb')) { - $desc .= Piwik::translate('GeoIp2_LocationProviderDesc_Php_WithExtension', - array('', '')); + $desc .= Piwik::translate( + 'GeoIp2_LocationProviderDesc_Php_WithExtension', + array('', '') + ); } $installDocs = '' diff --git a/plugins/GeoIp2/LocationProvider/GeoIp2/ServerModule.php b/plugins/GeoIp2/LocationProvider/GeoIp2/ServerModule.php index 07658e43556..16a7721a95a 100644 --- a/plugins/GeoIp2/LocationProvider/GeoIp2/ServerModule.php +++ b/plugins/GeoIp2/LocationProvider/GeoIp2/ServerModule.php @@ -220,8 +220,10 @@ public function getInfo() . '

' . Piwik::translate('GeoIp2_GeoIPLocationProviderDesc_ServerBasedAnonWarn') . '

' - . Piwik::translate('GeoIp2_LocationProviderDesc_ServerModule2', - array('', '', '', '')); + . Piwik::translate( + 'GeoIp2_LocationProviderDesc_ServerModule2', + array('', '', '', '') + ); $installDocs = '
' diff --git a/plugins/Goals/API.php b/plugins/Goals/API.php index 6c0c12df7ff..7cc4fb10628 100644 --- a/plugins/Goals/API.php +++ b/plugins/Goals/API.php @@ -541,8 +541,10 @@ public function get($idSite, $period, $date, $segment = false, $idGoal = false, } finally { \Piwik\Plugin\Archiver::$ARCHIVE_DEPENDENT = $startingArchiveDependent; } - $tableSegmented->filter('Piwik\Plugins\Goals\DataTable\Filter\AppendNameToColumnNames', - array($appendToMetricName)); + $tableSegmented->filter( + 'Piwik\Plugins\Goals\DataTable\Filter\AppendNameToColumnNames', + array($appendToMetricName) + ); if (!isset($table)) { $table = $tableSegmented; @@ -779,11 +781,19 @@ protected function getGoalSpecificDataTable($recordName, $idSite, $period, $date public function getDaysToConversion($idSite, $period, $date, $segment = false, $idGoal = false) { $dataTable = $this->getGoalSpecificDataTable( - Archiver::DAYS_UNTIL_CONV_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); + Archiver::DAYS_UNTIL_CONV_RECORD_NAME, + $idSite, + $period, + $date, + $segment, + $idGoal + ); $dataTable->queueFilter('Sort', array('label', 'asc', true, false)); $dataTable->queueFilter( - 'BeautifyRangeLabels', array(Piwik::translate('Intl_OneDay'), Piwik::translate('Intl_NDays'))); + 'BeautifyRangeLabels', + array(Piwik::translate('Intl_OneDay'), Piwik::translate('Intl_NDays')) + ); return $dataTable; } @@ -804,11 +814,19 @@ public function getDaysToConversion($idSite, $period, $date, $segment = false, $ public function getVisitsUntilConversion($idSite, $period, $date, $segment = false, $idGoal = false) { $dataTable = $this->getGoalSpecificDataTable( - Archiver::VISITS_UNTIL_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); + Archiver::VISITS_UNTIL_RECORD_NAME, + $idSite, + $period, + $date, + $segment, + $idGoal + ); $dataTable->queueFilter('Sort', array('label', 'asc', true, false)); $dataTable->queueFilter( - 'BeautifyRangeLabels', array(Piwik::translate('General_OneVisit'), Piwik::translate('General_NVisits'))); + 'BeautifyRangeLabels', + array(Piwik::translate('General_OneVisit'), Piwik::translate('General_NVisits')) + ); return $dataTable; } @@ -830,8 +848,14 @@ protected function enrichItemsTableWithViewMetrics($dataTable, $recordName, $idS } // Enrich the datatable with Product/Categories views, and conversion rates - $customVariables = \Piwik\Plugins\CustomVariables\API::getInstance()->getCustomVariables($idSite, $period, $date, $segment, $expanded = false, - $_leavePiwikCoreVariables = true); + $customVariables = \Piwik\Plugins\CustomVariables\API::getInstance()->getCustomVariables( + $idSite, + $period, + $date, + $segment, + $expanded = false, + $_leavePiwikCoreVariables = true + ); $mapping = array( 'Goals_ItemsSku' => '_pks', 'Goals_ItemsName' => '_pkn', diff --git a/plugins/Goals/Commands/CalculateConversionPages.php b/plugins/Goals/Commands/CalculateConversionPages.php index 843c753cc6a..9ee21273ebb 100644 --- a/plugins/Goals/Commands/CalculateConversionPages.php +++ b/plugins/Goals/Commands/CalculateConversionPages.php @@ -32,8 +32,12 @@ protected function configure() $this->setDescription('Calculate the pages before metric for historic conversions'); $this->addOptionalValueOption('dates', null, 'Calculate for conversions in this date range. Eg, 2012-01-01,2013-01-01', null); $this->addOptionalValueOption('last-n', null, 'Calculate just the last n conversions', 0); - $this->addOptionalValueOption('idsite', null, - 'Calculate for conversions belonging to the site with this ID. Comma separated list of website id. Eg, 1, 2, 3, etc. By default conversions from all sites are calculated.', null); + $this->addOptionalValueOption( + 'idsite', + null, + 'Calculate for conversions belonging to the site with this ID. Comma separated list of website id. Eg, 1, 2, 3, etc. By default conversions from all sites are calculated.', + null + ); $this->addOptionalValueOption('idgoal', null, 'Calculate conversions for this goal. A comma separated list of goal ids can be used only if a single site is specified. Eg, 1, 2, 3, etc. By default conversions for all goals are calculated.', null); $this->addOptionalValueOption('force-recalc', null, 'Recalculate for conversions which already have a pages before value', 0); } @@ -70,8 +74,8 @@ protected function doExecute(): int "Preparing to calculate the pages before metric for %s conversions belonging to %s %sfor %s.", $lastN ? "the last " . $lastN : 'all', $idSite ? "website $idSite" : "ALL websites", - !empty($dates) ? "between " . $from . " and " . $to . " " : '', - $idGoal ? "goal id $idGoal" : "ALL goals" + !empty($dates) ? "between " . $from . " and " . $to . " " : '', + $idGoal ? "goal id $idGoal" : "ALL goals" )); $timer = new Timer(); @@ -108,8 +112,10 @@ public static function calculateYesterdayAndToday(): void { $migration = StaticContainer::get(MigrationFactory::class); - $queries = self::getQueries(Date::factory('yesterday')->getDatetime(), - Date::factory('today')->getEndOfDay()->getDatetime()); + $queries = self::getQueries( + Date::factory('yesterday')->getDatetime(), + Date::factory('today')->getEndOfDay()->getDatetime() + ); $migrations = []; foreach ($queries as $query) { diff --git a/plugins/Goals/RecordBuilders/GeneralGoalsRecords.php b/plugins/Goals/RecordBuilders/GeneralGoalsRecords.php index c57205e3b2e..283192e868d 100644 --- a/plugins/Goals/RecordBuilders/GeneralGoalsRecords.php +++ b/plugins/Goals/RecordBuilders/GeneralGoalsRecords.php @@ -69,10 +69,16 @@ protected function aggregate(ArchiveProcessor $archiveProcessor): array if ($siteHasEcommerceOrGoals) { $selects = []; $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - self::VISITS_COUNT_FIELD, Archiver::$visitCountRanges, self::LOG_CONVERSION_TABLE, $prefixes[Archiver::VISITS_UNTIL_RECORD_NAME] + self::VISITS_COUNT_FIELD, + Archiver::$visitCountRanges, + self::LOG_CONVERSION_TABLE, + $prefixes[Archiver::VISITS_UNTIL_RECORD_NAME] )); $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - 'FLOOR(log_conversion.' . self::SECONDS_SINCE_FIRST_VISIT_FIELD . ' / 86400)', Archiver::$daysToConvRanges, self::LOG_CONVERSION_TABLE, $prefixes[Archiver::DAYS_UNTIL_CONV_RECORD_NAME] + 'FLOOR(log_conversion.' . self::SECONDS_SINCE_FIRST_VISIT_FIELD . ' / 86400)', + Archiver::$daysToConvRanges, + self::LOG_CONVERSION_TABLE, + $prefixes[Archiver::DAYS_UNTIL_CONV_RECORD_NAME] )); $query = $logAggregator->queryConversionsByDimension([], false, $selects); diff --git a/plugins/Goals/TranslationHelper.php b/plugins/Goals/TranslationHelper.php index 06d13f64f1a..f85b9530791 100644 --- a/plugins/Goals/TranslationHelper.php +++ b/plugins/Goals/TranslationHelper.php @@ -89,19 +89,22 @@ protected function getTranslationForPattern($patternType, $pattern) { switch ($patternType) { case 'regex': - return sprintf('%s %s', + return sprintf( + '%s %s', Piwik::translate('Goals_Pattern'), Piwik::translate('Goals_MatchesExpression', array($pattern)) ); case 'contains': - return sprintf('%s %s', + return sprintf( + '%s %s', Piwik::translate('Goals_Pattern'), Piwik::translate('Goals_Contains', array($pattern)) ); case 'exact': - return sprintf('%s %s', + return sprintf( + '%s %s', Piwik::translate('Goals_Pattern'), Piwik::translate('Goals_IsExactly', array($pattern)) ); diff --git a/plugins/Goals/tests/System/CalculateConversionPagesCommandTest.php b/plugins/Goals/tests/System/CalculateConversionPagesCommandTest.php index 7933fa885a5..5e64c74a97d 100644 --- a/plugins/Goals/tests/System/CalculateConversionPagesCommandTest.php +++ b/plugins/Goals/tests/System/CalculateConversionPagesCommandTest.php @@ -71,8 +71,10 @@ public function test_CommandSuccessfullyCalculates_ForLastN() */ private function unsetPageviewsBefore(): void { - Db::query('UPDATE ' . Common::prefixTable('log_conversion') . ' SET pageviews_before = NULL WHERE idsite = ?', - [self::$fixture->idSite]); + Db::query( + 'UPDATE ' . Common::prefixTable('log_conversion') . ' SET pageviews_before = NULL WHERE idsite = ?', + [self::$fixture->idSite] + ); } /** diff --git a/plugins/Goals/tests/System/NumericAttributeGoalTrackingTest.php b/plugins/Goals/tests/System/NumericAttributeGoalTrackingTest.php index 0691a5679ba..7dfe4c1ec59 100644 --- a/plugins/Goals/tests/System/NumericAttributeGoalTrackingTest.php +++ b/plugins/Goals/tests/System/NumericAttributeGoalTrackingTest.php @@ -57,7 +57,9 @@ protected static function configureFixture($fixture) private function getConversionCount($idGoal) { - return Db::fetchOne('SELECT COUNT(*) FROM ' . Common::prefixTable('log_conversion') . ' WHERE idsite = ? AND idgoal = ?', - [$this->idSite, $idGoal]); + return Db::fetchOne( + 'SELECT COUNT(*) FROM ' . Common::prefixTable('log_conversion') . ' WHERE idsite = ? AND idgoal = ?', + [$this->idSite, $idGoal] + ); } } diff --git a/plugins/ImageGraph/API.php b/plugins/ImageGraph/API.php index 14f96a7860f..c101330fbdc 100644 --- a/plugins/ImageGraph/API.php +++ b/plugins/ImageGraph/API.php @@ -244,10 +244,10 @@ public function get( $ordinateColumns[] = key($metadata['metrics']); } else { throw new Exception( - Piwik::translate( - 'ImageGraph_ColumnOrdinateMissing', - array(self::DEFAULT_ORDINATE_METRIC, implode(',', array_keys($reportColumns))) - ) + Piwik::translate( + 'ImageGraph_ColumnOrdinateMissing', + array(self::DEFAULT_ORDINATE_METRIC, implode(',', array_keys($reportColumns))) + ) ); } } else { diff --git a/plugins/ImageGraph/StaticGraph.php b/plugins/ImageGraph/StaticGraph.php index 464383007e7..a2830d16476 100644 --- a/plugins/ImageGraph/StaticGraph.php +++ b/plugins/ImageGraph/StaticGraph.php @@ -339,7 +339,9 @@ protected function getTextWidthHeight($text, $fontSize = false) // could not find a way to get pixel perfect width & height info using imageftbbox $textInfo = $this->pImage->drawText( - 0, 0, $text, + 0, + 0, + $text, array( 'Alpha' => 0, 'FontSize' => $fontSize, diff --git a/plugins/Insights/tests/Unit/InsightReportTest.php b/plugins/Insights/tests/Unit/InsightReportTest.php index 19a88dbb030..4ed8def81a2 100644 --- a/plugins/Insights/tests/Unit/InsightReportTest.php +++ b/plugins/Insights/tests/Unit/InsightReportTest.php @@ -438,8 +438,19 @@ private function generateMoverAndShaker($totalValue, $lastTotalValue, $orderBy = $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); $report = $this->insightReport->generateMoverAndShaker( - $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, - $totalValue, $lastTotalValue, $orderBy, $limitIncreaser, $limitDecreaser); + $reportMetadata, + 'day', + '2012-12-12', + '2012-12-11', + 'nb_visits', + $this->currentTable, + $this->pastTable, + $totalValue, + $lastTotalValue, + $orderBy, + $limitIncreaser, + $limitDecreaser + ); return $report; } @@ -453,9 +464,23 @@ private function generateInsight($minMoversPercent, $minNewPercent, $minDisappea $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); $report = $this->insightReport->generateInsight( - $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, - $totalValue = 200, $minMoversPercent, $minNewPercent, $minDisappearedPercent, - $minGrowthPercentPositive, $minGrowthPercentNegative, $orderBy, $limitIncreaser, $limitDecreaser); + $reportMetadata, + 'day', + '2012-12-12', + '2012-12-11', + 'nb_visits', + $this->currentTable, + $this->pastTable, + $totalValue = 200, + $minMoversPercent, + $minNewPercent, + $minDisappearedPercent, + $minGrowthPercentPositive, + $minGrowthPercentNegative, + $orderBy, + $limitIncreaser, + $limitDecreaser + ); return $report; } diff --git a/plugins/Installation/Controller.php b/plugins/Installation/Controller.php index 30d00d32225..2f13ecbfc42 100644 --- a/plugins/Installation/Controller.php +++ b/plugins/Installation/Controller.php @@ -289,9 +289,11 @@ function setupSuperUser() $loginName = $form->getSubmitValue('login'); $email = $form->getSubmitValue('email'); - $this->createSuperUser($loginName, - $form->getSubmitValue('password'), - $email); + $this->createSuperUser( + $loginName, + $form->getSubmitValue('password'), + $email + ); $newsletterPiwikORG = $form->getSubmitValue('subscribe_newsletter_piwikorg'); $newsletterProfessionalServices = $form->getSubmitValue('subscribe_newsletter_professionalservices'); @@ -628,7 +630,8 @@ private function checkPiwikIsNotInstalled($possibleErrorMessage = null) $possibleErrorMessage = $possibleErrorMessage ? sprintf('

Original error was "%s".
', $possibleErrorMessage) : ''; \Piwik\Plugins\Login\Controller::clearSession(); - $message = Piwik::translate('Installation_InvalidStateError', + $message = Piwik::translate( + 'Installation_InvalidStateError', array($possibleErrorMessage . '
', // piwik-is-already-installed is checked against in checkPiwikServerWorking '
', diff --git a/plugins/Installation/Menu.php b/plugins/Installation/Menu.php index 5e20199fae4..836291b752c 100644 --- a/plugins/Installation/Menu.php +++ b/plugins/Installation/Menu.php @@ -17,9 +17,11 @@ class Menu extends \Piwik\Plugin\Menu public function configureAdminMenu(MenuAdmin $menu) { if (Piwik::hasUserSuperUserAccess() && Manager::getInstance()->isPluginActivated('Diagnostics')) { - $menu->addDiagnosticItem('Installation_SystemCheck', - $this->urlForAction('systemCheckPage'), - $order = 1); + $menu->addDiagnosticItem( + 'Installation_SystemCheck', + $this->urlForAction('systemCheckPage'), + $order = 1 + ); } } } diff --git a/plugins/Installation/ServerFilesGenerator.php b/plugins/Installation/ServerFilesGenerator.php index 04e98110909..b92408abfc2 100644 --- a/plugins/Installation/ServerFilesGenerator.php +++ b/plugins/Installation/ServerFilesGenerator.php @@ -128,7 +128,8 @@ protected static function createWebConfigFiles() if (!SettingsServer::isIIS()) { return; } - @file_put_contents(PIWIK_INCLUDE_PATH . '/web.config', + @file_put_contents( + PIWIK_INCLUDE_PATH . '/web.config', ' @@ -167,7 +168,8 @@ protected static function createWebConfigFiles() -'); +' + ); // deny direct access to .php files $directoriesToProtect = array( @@ -183,7 +185,8 @@ protected static function createWebConfigFiles() '; foreach ($directoriesToProtect as $directoryToProtect) { - @file_put_contents(PIWIK_INCLUDE_PATH . $directoryToProtect . '/web.config', + @file_put_contents( + PIWIK_INCLUDE_PATH . $directoryToProtect . '/web.config', ' @@ -195,7 +198,8 @@ protected static function createWebConfigFiles() -'); +' + ); } } diff --git a/plugins/Intl/DateTimeFormatProvider.php b/plugins/Intl/DateTimeFormatProvider.php index e4fa6ac2358..88c1b70793a 100644 --- a/plugins/Intl/DateTimeFormatProvider.php +++ b/plugins/Intl/DateTimeFormatProvider.php @@ -101,7 +101,8 @@ public function getRangeFormatPattern($short = false, $maxDifference = 'Y') 'Intl_Format_Interval_%s_%s', $short ? 'Short' : 'Long', $maxDifference - )); + ) + ); } protected function getTimeFormat() diff --git a/plugins/IntranetMeasurable/tests/Fixtures/IntranetSitesWithVisits.php b/plugins/IntranetMeasurable/tests/Fixtures/IntranetSitesWithVisits.php index 8ed41e8783a..017d8f7172c 100644 --- a/plugins/IntranetMeasurable/tests/Fixtures/IntranetSitesWithVisits.php +++ b/plugins/IntranetMeasurable/tests/Fixtures/IntranetSitesWithVisits.php @@ -38,9 +38,15 @@ private function setUpWebsites() { if (!self::siteCreated($this->idSite)) { Fixture::createWebsite( - '2014-01-02 03:04:05', $ecommerce = 0, $siteName = false, $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = null, Type::ID + '2014-01-02 03:04:05', + $ecommerce = 0, + $siteName = false, + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = null, + Type::ID ); } diff --git a/plugins/LanguagesManager/Commands/SetTranslations.php b/plugins/LanguagesManager/Commands/SetTranslations.php index 29b4c58b3d1..5392890726e 100644 --- a/plugins/LanguagesManager/Commands/SetTranslations.php +++ b/plugins/LanguagesManager/Commands/SetTranslations.php @@ -41,14 +41,16 @@ protected function doExecute(): int $languageCodes = (new API())->getAvailableLanguages(true); if (empty($languageCode) || !in_array($languageCode, $languageCodes)) { - $languageCode = $this->askAndValidate('Please provide a valid language code: ', + $languageCode = $this->askAndValidate( + 'Please provide a valid language code: ', function ($code) use ($languageCodes) { if (!in_array($code, array_values($languageCodes))) { throw new \InvalidArgumentException(sprintf('Language code "%s" is invalid.', $code)); } return $code; - }); + } + ); } if (empty($filename) || !file_exists($filename)) { diff --git a/plugins/LanguagesManager/Menu.php b/plugins/LanguagesManager/Menu.php index 76a46f040a3..951f6421796 100644 --- a/plugins/LanguagesManager/Menu.php +++ b/plugins/LanguagesManager/Menu.php @@ -27,8 +27,10 @@ public function configureTopMenu(MenuTop $menu) public function configureAdminMenu(MenuAdmin $menu) { if (Development::isEnabled() && Piwik::isUserHasSomeAdminAccess()) { - $menu->addDevelopmentItem('LanguagesManager_TranslationSearch', - $this->urlForAction('searchTranslation')); + $menu->addDevelopmentItem( + 'LanguagesManager_TranslationSearch', + $this->urlForAction('searchTranslation') + ); } } } diff --git a/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php b/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php index d04fc22027a..82e223200d8 100644 --- a/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php +++ b/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php @@ -147,8 +147,11 @@ function testTranslationsUseNumberedPlaceholders() $translations = $translator->getAllTranslations(); foreach ($translations as $plugin => $pluginTranslations) { foreach ($pluginTranslations as $key => $pluginTranslation) { - $this->assertLessThanOrEqual(1, substr_count($pluginTranslation, '%s'), - sprintf('%s.%s must use numbered placeholders instead of multiple %%s', $plugin, $key)); + $this->assertLessThanOrEqual( + 1, + substr_count($pluginTranslation, '%s'), + sprintf('%s.%s must use numbered placeholders instead of multiple %%s', $plugin, $key) + ); } } } @@ -173,8 +176,11 @@ function testTranslationsUseEscapedPercentSigns() foreach ($pluginTranslations as $key => $pluginTranslation) { $pluginTranslation = preg_replace('/(%(?:[1-9]\$)?[a-z])/', '', $pluginTranslation); // remove placeholders $pluginTranslation = str_replace('%%', '', $pluginTranslation); // remove already escaped symbols - $this->assertEquals(0, substr_count($pluginTranslation, '%'), - sprintf('%s.%s must use escaped %% symbols', $plugin, $key)); + $this->assertEquals( + 0, + substr_count($pluginTranslation, '%'), + sprintf('%s.%s must use escaped %% symbols', $plugin, $key) + ); } } } diff --git a/plugins/Live/API.php b/plugins/Live/API.php index 5e0e116f382..857e2ab3834 100644 --- a/plugins/Live/API.php +++ b/plugins/Live/API.php @@ -226,8 +226,17 @@ public function getVisitorProfile($idSite, $visitorId = false, $segment = false, $limit = Config::getInstance()->General['live_visitor_profile_max_visits_to_aggregate']; - $visits = $this->loadLastVisitsDetailsFromDatabase($idSite, $period = false, $date = false, $segment, - $offset = 0, $limit, false, false, $visitorId); + $visits = $this->loadLastVisitsDetailsFromDatabase( + $idSite, + $period = false, + $date = false, + $segment, + $offset = 0, + $limit, + false, + false, + $visitorId + ); $this->addFilterToCleanVisitors($visits, $idSite, $flat = false, $doNotFetchActions = false, $filterNow = true); if ($visits->getRowsCount() == 0) { @@ -255,21 +264,38 @@ public function getMostRecentVisitorId($idSite, $segment = false) $minTimestamp = Date::now()->subDay(7)->getTimestamp(); $dataTable = $this->loadLastVisitsDetailsFromDatabase( - $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp + $idSite, + $period = false, + $date = false, + $segment, + $offset = 0, + $limit = 1, + $minTimestamp ); if (0 >= $dataTable->getRowsCount()) { $minTimestamp = Date::now()->subYear(1)->getTimestamp(); // no visitor found in last 7 days, look further back for up to 1 year. This query will be slower $dataTable = $this->loadLastVisitsDetailsFromDatabase( - $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp + $idSite, + $period = false, + $date = false, + $segment, + $offset = 0, + $limit = 1, + $minTimestamp ); } if (0 >= $dataTable->getRowsCount()) { // no visitor found in last year, look over all logs. This query might be quite slow $dataTable = $this->loadLastVisitsDetailsFromDatabase( - $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1 + $idSite, + $period = false, + $date = false, + $segment, + $offset = 0, + $limit = 1 ); } diff --git a/plugins/Live/Model.php b/plugins/Live/Model.php index 226b6db3926..d4546b340ff 100644 --- a/plugins/Live/Model.php +++ b/plugins/Live/Model.php @@ -579,7 +579,8 @@ public function makeLogVisitsQueryString($idSite, $startDate, $endDate, $segment if (!$visitorId) { // for now let's not apply when looking for a specific visitor - $innerQuery['sql'] = DbHelper::addMaxExecutionTimeHintToQuery($innerQuery['sql'], + $innerQuery['sql'] = DbHelper::addMaxExecutionTimeHintToQuery( + $innerQuery['sql'], $this->getLiveQueryMaxExecutionTime() ); } diff --git a/plugins/Live/tests/Integration/ModelTest.php b/plugins/Live/tests/Integration/ModelTest.php index 8b87c885867..20ca59ad102 100644 --- a/plugins/Live/tests/Integration/ModelTest.php +++ b/plugins/Live/tests/Integration/ModelTest.php @@ -215,15 +215,15 @@ public function test_makeLogVisitsQueryString() $model = new Model(); list($dateStart, $dateEnd) = $model->getStartAndEndDate($idSite = 1, 'month', '2010-01-01'); list($sql, $bind) = $model->makeLogVisitsQueryString( - $idSite = 1, - $dateStart, - $dateEnd, - $segment = false, - $offset = 0, - $limit = 100, - $visitorId = false, - $minTimestamp = false, - $filterSortOrder = false + $idSite = 1, + $dateStart, + $dateEnd, + $segment = false, + $offset = 0, + $limit = 100, + $visitorId = false, + $minTimestamp = false, + $filterSortOrder = false ); $expectedSql = ' SELECT log_visit.* FROM ' . Common::prefixTable('log_visit') . ' AS log_visit @@ -250,15 +250,15 @@ public function test_makeLogVisitsQueryString_withMultipleIdSites() $model = new Model(); list($dateStart, $dateEnd) = $model->getStartAndEndDate($idSite = 1, 'month', '2010-01-01'); list($sql, $bind) = $model->makeLogVisitsQueryString( - $idSite = 1, - $dateStart, - $dateEnd, - $segment = false, - $offset = 0, - $limit = 100, - $visitorId = false, - $minTimestamp = false, - $filterSortOrder = false + $idSite = 1, + $dateStart, + $dateEnd, + $segment = false, + $offset = 0, + $limit = 100, + $visitorId = false, + $minTimestamp = false, + $filterSortOrder = false ); $expectedSql = ' SELECT log_visit.* FROM ' . Common::prefixTable('log_visit') . ' AS log_visit @@ -284,15 +284,15 @@ public function test_makeLogVisitsQueryStringWithOffset() list($dateStart, $dateEnd) = $model->getStartAndEndDate($idSite = 1, 'month', '2010-01-01'); list($sql, $bind) = $model->makeLogVisitsQueryString( - $idSite = 1, - $dateStart, - $dateEnd, - $segment = false, - $offset = 15, - $limit = 100, - $visitorId = false, - $minTimestamp = false, - $filterSortOrder = false + $idSite = 1, + $dateStart, + $dateEnd, + $segment = false, + $offset = 15, + $limit = 100, + $visitorId = false, + $minTimestamp = false, + $filterSortOrder = false ); $expectedSql = ' SELECT log_visit.* FROM ' . Common::prefixTable('log_visit') . ' AS log_visit diff --git a/plugins/Login/Emails/PasswordResetEmail.php b/plugins/Login/Emails/PasswordResetEmail.php index c5954b94dcb..636848d311c 100644 --- a/plugins/Login/Emails/PasswordResetEmail.php +++ b/plugins/Login/Emails/PasswordResetEmail.php @@ -65,8 +65,10 @@ private function getDefaultSubject() */ private function getDefaultBodyText(): string { - return Piwik::translate('Login_MailPasswordChangeBody2', - [Common::sanitizeInputValue($this->login), Common::sanitizeInputValue($this->ip), Common::sanitizeInputValue($this->resetUrl)]); + return Piwik::translate( + 'Login_MailPasswordChangeBody2', + [Common::sanitizeInputValue($this->login), Common::sanitizeInputValue($this->ip), Common::sanitizeInputValue($this->resetUrl)] + ); } /** @@ -79,11 +81,13 @@ private function getHTMLBody(): string return '

' . str_replace( "\n\n", "

", - Piwik::translate('Login_MailPasswordChangeBody2', + Piwik::translate( + 'Login_MailPasswordChangeBody2', [Common::sanitizeInputValue($this->login), Common::sanitizeInputValue($this->ip), '

' . - Common::sanitizeInputValue($this->resetUrl) . '

']) + Common::sanitizeInputValue($this->resetUrl) . '

'] + ) ) . "

"; } } diff --git a/plugins/Marketplace/Api/Service.php b/plugins/Marketplace/Api/Service.php index 7d7670e87ff..afbdbb50cda 100644 --- a/plugins/Marketplace/Api/Service.php +++ b/plugins/Marketplace/Api/Service.php @@ -98,17 +98,23 @@ public function download($url, $destinationPath = null, $timeout = null) $file = Http::ensureDestinationDirectoryExists($destinationPath); - $response = Http::sendHttpRequestBy($method, - $url, - $timeout, - $userAgent = null, - $destinationPath, - $file, - $followDepth = 0, - $acceptLanguage = false, - $acceptInvalidSslCertificate = false, - $byteRange = false, $getExtendedInfo = false, $httpMethod = 'POST', - $httpUsername = null, $httpPassword = null, $post); + $response = Http::sendHttpRequestBy( + $method, + $url, + $timeout, + $userAgent = null, + $destinationPath, + $file, + $followDepth = 0, + $acceptLanguage = false, + $acceptInvalidSslCertificate = false, + $byteRange = false, + $getExtendedInfo = false, + $httpMethod = 'POST', + $httpUsername = null, + $httpPassword = null, + $post + ); return $response; } diff --git a/plugins/MobileMessaging/SMSProvider.php b/plugins/MobileMessaging/SMSProvider.php index d27a7d7d731..7a1ab89c137 100644 --- a/plugins/MobileMessaging/SMSProvider.php +++ b/plugins/MobileMessaging/SMSProvider.php @@ -117,7 +117,8 @@ public static function factory($provider) $providers = self::findAvailableSmsProviders(); if (!array_key_exists($provider, $providers)) { - throw new \Exception(Piwik::translate('MobileMessaging_Exception_UnknownProvider', + throw new \Exception(Piwik::translate( + 'MobileMessaging_Exception_UnknownProvider', array($provider, implode(', ', array_keys($providers))) )); } diff --git a/plugins/Monolog/config/config.php b/plugins/Monolog/config/config.php index 59cdc8f0cd2..49d0dec85ed 100644 --- a/plugins/Monolog/config/config.php +++ b/plugins/Monolog/config/config.php @@ -68,8 +68,14 @@ $handler->setLevel(Logger::DEBUG); - $handler = new \Monolog\Handler\FingersCrossedHandler($handler, $activationStrategy = null, $bufferSize = 0, - $bubble = true, $fingersCrossedStopBuffering, $passthruLevel); + $handler = new \Monolog\Handler\FingersCrossedHandler( + $handler, + $activationStrategy = null, + $bufferSize = 0, + $bubble = true, + $fingersCrossedStopBuffering, + $passthruLevel + ); } $writers[$writerName] = $handler; diff --git a/plugins/Morpheus/Controller.php b/plugins/Morpheus/Controller.php index 7e54ffac2db..e8611129e10 100644 --- a/plugins/Morpheus/Controller.php +++ b/plugins/Morpheus/Controller.php @@ -254,7 +254,11 @@ public function demo() // TODOO: handle arrays $snippets[] = $this->formSnippet( - 'language', ['language', 'phoneNumber', 'selectedExpand'], ['1', '[\'1\']', 'null'], [1, ['1'], null], '
+ 'language', + ['language', 'phoneNumber', 'selectedExpand'], + ['1', '[\'1\']', 'null'], + [1, ['1'], null], + '
-
'); +
' + ); $snippets[] = $this->formSnippet('multitupletext', 'values', '[]', [], '
'); - $snippets[] = $this->formSnippet('multitupletextvalue', 'values', + $snippets[] = $this->formSnippet( + 'multitupletextvalue', + 'values', '[{\'index\': \'test\', \'value\':\'myfoo\'},{\'index\': \'test 2\', \'value\':\'myfoo 2\'}]', - [['index' => 'test', 'value' => 'myfoo'], ['index' => 'test 2', 'value' => 'myfoo 2']], '
+ [['index' => 'test', 'value' => 'myfoo'], ['index' => 'test 2', 'value' => 'myfoo 2']], + '
-
'); +
' + ); - $snippets[] = $this->formSnippet('multitupleselect', 'values', + $snippets[] = $this->formSnippet( + 'multitupleselect', + 'values', '[{\'index\': \'test\', \'value\': \'myfoo\'}]', - [["index" => "test", "value" => "myfoo"]], '
+ [["index" => "test", "value" => "myfoo"]], + '
-
'); +
' + ); $snippets[] = $this->formSnippet('multitupletext2', 'values', '[]', [], '
'); - $snippets[] = $this->formSnippet('multitupletextvalue2', 'values', + $snippets[] = $this->formSnippet( + 'multitupletextvalue2', + 'values', "[{'index': 'test', 'value':'myfoo'},{'index': 'test 2', 'value':'myfoo 2'}]", - [["index" => "test", "value" => "myfoo"], ["index" => "test 2", "value" => "myfoo 2"]], '
+ [["index" => "test", "value" => "myfoo"], ["index" => "test 2", "value" => "myfoo 2"]], + '
-
'); +
' + ); - $snippets[] = $this->formSnippet('multitupleselect2', 'values', + $snippets[] = $this->formSnippet( + 'multitupleselect2', + 'values', '[{\'index\': \'test\', \'value\': \'myfoo\'}]', - [['index' => 'test', 'value' => 'myfoo']], '
+ [['index' => 'test', 'value' => 'myfoo']], + '
-
'); +
' + ); $snippets[] = $this->formSnippet('multitupletext3', 'values', '[]', [], '
'); - $snippets[] = $this->formSnippet('multitupletextvalue3', 'values', + $snippets[] = $this->formSnippet( + 'multitupletextvalue3', + 'values', '[{\'index\': \'test\', \'value\':\'myfoo\'},{\'index\': \'test 2\', \'value\':\'myfoo 2\'}]', - [["index" => "test", "value" => "myfoo"], ["index" => "test 2", "value" => "myfoo 2"]], '
+ [["index" => "test", "value" => "myfoo"], ["index" => "test 2", "value" => "myfoo 2"]], + '
-
'); +
' + ); - $snippets[] = $this->formSnippet('multitupleselect3', 'values', - '[{\'index\': \'test\', \'value\': \'myfoo\'}]', - [["index" => "test", "value" => "myfoo"]], '
+ $snippets[] = $this->formSnippet( + 'multitupleselect3', + 'values', + '[{\'index\': \'test\', \'value\': \'myfoo\'}]', + [["index" => "test", "value" => "myfoo"]], + '
-
'); +
' + ); - $snippets[] = $this->formSnippet('multituplesingleselect', 'values', + $snippets[] = $this->formSnippet( + 'multituplesingleselect', + 'values', '[{\'index\': \'test\', \'value\': \'myfoo\'}]', - [["index" => "test", "value" => "myfoo"]], '
+ [["index" => "test", "value" => "myfoo"]], + '
-
'); +
' + ); - $snippets[] = $this->formSnippet('multituplesingletext', 'values', + $snippets[] = $this->formSnippet( + 'multituplesingletext', + 'values', '[{\'index\': \'test\', \'value\': \'myfoo\'}]', - [["index" => "test", "value" => "myfoo"]], '
+ [["index" => "test", "value" => "myfoo"]], + '
-
'); +
' + ); $snippets[] = $this->formSnippet('text-field-array', 'values', "['text one', 'text two']", ['text one', 'text two'], '
'); - $snippets[] = $this->formSnippet('enableFeatures', ['enable', 'enableArray', 'defaultReportDate'], - ['false', '[]', 'null'], [false, [], null], '
+ $snippets[] = $this->formSnippet( + 'enableFeatures', + ['enable', 'enableArray', 'defaultReportDate'], + ['false', '[]', 'null'], + [false, [], null], + '
-
'); +
' + ); $snippets[] = $this->formSnippet('currentsite', ['site', 'isDisabled', 'saveCount', 'isLoading'], ['null', 'false', '0', 'false'], [null, false, 0, false], '
getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin); } } else { - $sites = Request::processRequest('SitesManager.getPatternMatchSites', + $sites = Request::processRequest( + 'SitesManager.getPatternMatchSites', array('pattern' => $pattern, // added because caller could overwrite these 'limit' => SettingsPiwik::getWebsitesCountToDisplay(), 'showColumns' => '', 'hideColumns' => '', - 'format' => 'original')); + 'format' => 'original') + ); if (!empty($sites)) { Site::setSitesFromArray($sites); diff --git a/plugins/Overlay/API.php b/plugins/Overlay/API.php index da0a97e8861..9bdd1f88fc6 100644 --- a/plugins/Overlay/API.php +++ b/plugins/Overlay/API.php @@ -72,8 +72,15 @@ public function getFollowingPages($url, $idSite, $period, $date, $segment = fals try { $limitBeforeGrouping = Config::getInstance()->General['overlay_following_pages_limit']; $transitionsReport = APITransitions::getInstance()->getTransitionsForAction( - $url, $type = 'url', $idSite, $period, $date, $segment, $limitBeforeGrouping, - $part = 'followingActions'); + $url, + $type = 'url', + $idSite, + $period, + $date, + $segment, + $limitBeforeGrouping, + $part = 'followingActions' + ); } catch (Exception $e) { return $resultDataTable; } diff --git a/plugins/PagePerformance/Controller.php b/plugins/PagePerformance/Controller.php index 01440c2fccd..ad9ad89d1b6 100644 --- a/plugins/PagePerformance/Controller.php +++ b/plugins/PagePerformance/Controller.php @@ -87,7 +87,11 @@ public function getRowEvolutionGraph($dataTable = null) // set up the view data table $view = ViewDataTableFactory::build( - StackedBarEvolution::ID, $apiMethod, 'PagePerformance.getRowEvolutionGraph', $forceDefault = true); + StackedBarEvolution::ID, + $apiMethod, + 'PagePerformance.getRowEvolutionGraph', + $forceDefault = true + ); $view->setDataTable($dataTable); $view->config->columns_to_display = array_keys(Metrics::getPagePerformanceMetrics()); diff --git a/plugins/PagePerformance/RecordBuilders/PerformanceTotals.php b/plugins/PagePerformance/RecordBuilders/PerformanceTotals.php index 3823ad0b4d0..e62d2726ceb 100644 --- a/plugins/PagePerformance/RecordBuilders/PerformanceTotals.php +++ b/plugins/PagePerformance/RecordBuilders/PerformanceTotals.php @@ -74,8 +74,16 @@ protected function aggregate(ArchiveProcessor $archiveProcessor): array $joinLogActionOnColumn = array('idaction_url'); $where = sprintf("COALESCE(%s) IS NOT NULL", implode(',', $allColumns)); - $query = $logAggregator->queryActionsByDimension([], $where, $selects, false, null, - $joinLogActionOnColumn, null, -1); + $query = $logAggregator->queryActionsByDimension( + [], + $where, + $selects, + false, + null, + $joinLogActionOnColumn, + null, + -1 + ); $result = $query->fetchAll(); diff --git a/plugins/PagePerformance/tests/Integration/Tracker/PerformanceDataProcessorTest.php b/plugins/PagePerformance/tests/Integration/Tracker/PerformanceDataProcessorTest.php index e57ca759b26..8b1f0bd72d4 100644 --- a/plugins/PagePerformance/tests/Integration/Tracker/PerformanceDataProcessorTest.php +++ b/plugins/PagePerformance/tests/Integration/Tracker/PerformanceDataProcessorTest.php @@ -108,11 +108,14 @@ public function test_shouldNotUseObviouslyTooHighNumbers() protected function checkActionHasTimings($pageViewId, $network = null, $server = null, $transfer = null, $domProcessing = null, $domCompletion = null, $onload = null) { $result = Db::fetchRow( - sprintf('SELECT time_network, time_server, time_transfer, time_dom_processing, time_dom_completion, time_on_load + sprintf( + 'SELECT time_network, time_server, time_transfer, time_dom_processing, time_dom_completion, time_on_load FROM %1$s LEFT JOIN %2$s ON idaction_url = idaction WHERE idpageview = ? AND %2$s.type = 1', Common::prefixTable('log_link_visit_action'), Common::prefixTable('log_action') - ), $pageViewId); + ), + $pageViewId + ); $this->assertEquals([ 'time_network' => $network, diff --git a/plugins/PrivacyManager/Commands/AnonymizeRawData.php b/plugins/PrivacyManager/Commands/AnonymizeRawData.php index 3fd340cb741..1fd45d3df96 100644 --- a/plugins/PrivacyManager/Commands/AnonymizeRawData.php +++ b/plugins/PrivacyManager/Commands/AnonymizeRawData.php @@ -79,19 +79,23 @@ protected function doExecute(): int } if (!empty($visitColumnsToUnset) - && !$this->confirmAnonymize($startDate, - $endDate, - 'unset the log_visit columns "' . implode(', ', $visitColumnsToUnset) . '"')) { + && !$this->confirmAnonymize( + $startDate, + $endDate, + 'unset the log_visit columns "' . implode(', ', $visitColumnsToUnset) . '"' + )) { $visitColumnsToUnset = false; $output->writeln('SKIPPING unset log_visit columns.'); } if (!empty($linkVisitActionColumns) - && !$this->confirmAnonymize($startDate, - $endDate, - 'unset the log_link_visit_action columns "' . implode( - ', ', - $linkVisitActionColumns - ) . '"')) { + && !$this->confirmAnonymize( + $startDate, + $endDate, + 'unset the log_link_visit_action columns "' . implode( + ', ', + $linkVisitActionColumns + ) . '"' + )) { $linkVisitActionColumns = false; $output->writeln('SKIPPING unset log_link_visit_action columns.'); } diff --git a/plugins/PrivacyManager/tests/Integration/DataPurgingTest.php b/plugins/PrivacyManager/tests/Integration/DataPurgingTest.php index 2f9cd86bb05..af058533a77 100644 --- a/plugins/PrivacyManager/tests/Integration/DataPurgingTest.php +++ b/plugins/PrivacyManager/tests/Integration/DataPurgingTest.php @@ -528,7 +528,8 @@ public function testPurgeLogDataConcurrency() $this->unusedIdAction = Db::fetchOne( "SELECT idaction FROM " . Common::prefixTable('log_action') . " WHERE name = ?", - array('whatever.com/_40')); + array('whatever.com/_40') + ); $this->assertTrue($this->unusedIdAction > 0); // purge data @@ -541,7 +542,8 @@ public function testPurgeLogDataConcurrency() // check that the unused action still exists $count = Db::fetchOne( "SELECT COUNT(*) FROM " . Common::prefixTable('log_action') . " WHERE idaction = ?", - array($this->unusedIdAction)); + array($this->unusedIdAction) + ); $this->assertEquals(1, $count); $this->unusedIdAction = null; // so the hook won't get executed twice @@ -680,10 +682,21 @@ protected static function _addLogData() $t->doTrackContentImpression('SugarTransportAd', '/path/ad.jpg', 'http://www.satsumaprovince.jp'); $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.2)); - $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR', $category = 'Electronics & Cameras', - $price = 1500, $quantity = 1); - $t->doTrackEcommerceOrder($orderId = '937nsjusu ' . $dateTime, $grandTotal = 1111.11, $subTotal = 1000, - $tax = 111, $shipping = 0.11, $discount = 666); + $t->addEcommerceItem( + $sku = 'SKU2', + $name = 'Canon SLR', + $category = 'Electronics & Cameras', + $price = 1500, + $quantity = 1 + ); + $t->doTrackEcommerceOrder( + $orderId = '937nsjusu ' . $dateTime, + $grandTotal = 1111.11, + $subTotal = 1000, + $tax = 111, + $shipping = 0.11, + $discount = 666 + ); } Fixture::checkBulkTrackingResponse($t->doBulkTrack()); @@ -720,7 +733,10 @@ protected static function _addReportData() $archive->getNumeric('nb_visits'); APIVisitorInterest::getInstance()->getNumberOfVisitsPerVisitDuration( - self::$idSite, 'week', $dateTime); + self::$idSite, + 'week', + $dateTime + ); } // add segment for one day @@ -728,7 +744,11 @@ protected static function _addReportData() $archive->getNumeric('nb_visits', 'nb_hits'); APIVisitorInterest::getInstance()->getNumberOfVisitsPerVisitDuration( - self::$idSite, 'day', '2012-01-14', 'browserCode==FF'); + self::$idSite, + 'day', + '2012-01-14', + 'browserCode==FF' + ); // add range within January $rangeEnd = Date::factory('2012-01-29'); @@ -784,16 +804,24 @@ protected static function _addReportData() VALUES (10000,?,1,?,?,?,?,?)"; // one metric for jan & one for feb - Db::query(sprintf($sql, Common::prefixTable($archiveTables['numeric'][0])), - array(self::GARBAGE_FIELD, $janDate1, $janDate1, 1, $janDate1, 100)); - Db::query(sprintf($sql, Common::prefixTable($archiveTables['numeric'][1])), - array(self::GARBAGE_FIELD, $febDate1, $febDate1, 1, $febDate1, 200)); + Db::query( + sprintf($sql, Common::prefixTable($archiveTables['numeric'][0])), + array(self::GARBAGE_FIELD, $janDate1, $janDate1, 1, $janDate1, 100) + ); + Db::query( + sprintf($sql, Common::prefixTable($archiveTables['numeric'][1])), + array(self::GARBAGE_FIELD, $febDate1, $febDate1, 1, $febDate1, 200) + ); // add garbage reports - Db::query(sprintf($sql, Common::prefixTable($archiveTables['blob'][0])), - array(self::GARBAGE_FIELD, $janDate1, $janDate1, 10, $janDate1, 'blobval')); - Db::query(sprintf($sql, Common::prefixTable($archiveTables['blob'][1])), - array(self::GARBAGE_FIELD, $febDate1, $febDate1, 20, $febDate1, 'blobval')); + Db::query( + sprintf($sql, Common::prefixTable($archiveTables['blob'][0])), + array(self::GARBAGE_FIELD, $janDate1, $janDate1, 10, $janDate1, 'blobval') + ); + Db::query( + sprintf($sql, Common::prefixTable($archiveTables['blob'][1])), + array(self::GARBAGE_FIELD, $febDate1, $febDate1, 20, $febDate1, 'blobval') + ); } protected function _checkNoDataChanges() diff --git a/plugins/PrivacyManager/tests/System/PurgeDataTest.php b/plugins/PrivacyManager/tests/System/PurgeDataTest.php index 0f5a56056e1..5b15b16f1f7 100644 --- a/plugins/PrivacyManager/tests/System/PurgeDataTest.php +++ b/plugins/PrivacyManager/tests/System/PurgeDataTest.php @@ -201,8 +201,14 @@ private function purgeData($deleteReportsOlderThan, $reportPeriodsToKeep, $keepB $metricsToKeep = PrivacyManager::getAllMetricsToKeep(); $maxRowsToDeletePerQuery = 100000; - $purger = new ReportsPurger($deleteReportsOlderThan, $keepBasicMetrics, $reportPeriodsToKeep, - $keepSegmentReports, $metricsToKeep, $maxRowsToDeletePerQuery); + $purger = new ReportsPurger( + $deleteReportsOlderThan, + $keepBasicMetrics, + $reportPeriodsToKeep, + $keepSegmentReports, + $metricsToKeep, + $maxRowsToDeletePerQuery + ); $purger->getPurgeEstimate(); $purger->purgeData(); } diff --git a/plugins/Referrers/Categories/SearchEnginesSubcategory.php b/plugins/Referrers/Categories/SearchEnginesSubcategory.php index 65dad28d2c9..c15f29e6495 100644 --- a/plugins/Referrers/Categories/SearchEnginesSubcategory.php +++ b/plugins/Referrers/Categories/SearchEnginesSubcategory.php @@ -21,10 +21,13 @@ class SearchEnginesSubcategory extends Subcategory public function getHelp() { return '

' . Piwik::translate('Referrers_SearchEnginesSubcategoryHelp1') . '

' - . '

' . Piwik::translate('Referrers_SearchEnginesSubcategoryHelp2', + . '

' . Piwik::translate( + 'Referrers_SearchEnginesSubcategoryHelp2', ['', '', '', '']) . '

'; + . '" rel="noreferrer noopener" target="_blank">', + ''] + ) . '

'; } } diff --git a/plugins/Referrers/Reports/GetKeywordsFromCampaignId.php b/plugins/Referrers/Reports/GetKeywordsFromCampaignId.php index f97c216ea50..53d3ca745a6 100644 --- a/plugins/Referrers/Reports/GetKeywordsFromCampaignId.php +++ b/plugins/Referrers/Reports/GetKeywordsFromCampaignId.php @@ -20,8 +20,10 @@ protected function init() parent::init(); $this->dimension = new Keyword(); $this->name = Piwik::translate('Referrers_Campaigns'); - $this->documentation = Piwik::translate('Referrers_CampaignsReportDocumentation', - ['
', '', '']); + $this->documentation = Piwik::translate( + 'Referrers_CampaignsReportDocumentation', + ['
', '', ''] + ); $this->isSubtableReport = true; $this->order = 10; } diff --git a/plugins/Referrers/Reports/GetReferrerType.php b/plugins/Referrers/Reports/GetReferrerType.php index 5d41bd334ad..e2c2b04e386 100644 --- a/plugins/Referrers/Reports/GetReferrerType.php +++ b/plugins/Referrers/Reports/GetReferrerType.php @@ -27,12 +27,18 @@ protected function init() $this->name = Piwik::translate('Referrers_Type'); $this->documentation = Piwik::translate('Referrers_TypeReportDocumentation') . '
' . '' . Piwik::translate('Referrers_DirectEntry') . ': ' . Piwik::translate('Referrers_DirectEntryDocumentation') . '
' - . '' . Piwik::translate('Referrers_SearchEngines') . ': ' . Piwik::translate('Referrers_SearchEnginesDocumentation', - array('
', '"' . Piwik::translate('Referrers_SubmenuSearchEngines') . '"')) . '
' - . '' . Piwik::translate('Referrers_Websites') . ': ' . Piwik::translate('Referrers_WebsitesDocumentation', - array('
', '"' . Piwik::translate('Referrers_SubmenuWebsitesOnly') . '"')) . '
' - . '' . Piwik::translate('Referrers_Campaigns') . ': ' . Piwik::translate('Referrers_CampaignsDocumentation', - array('
', '"' . Piwik::translate('Referrers_Campaigns') . '"')); + . '' . Piwik::translate('Referrers_SearchEngines') . ': ' . Piwik::translate( + 'Referrers_SearchEnginesDocumentation', + array('
', '"' . Piwik::translate('Referrers_SubmenuSearchEngines') . '"') + ) . '
' + . '' . Piwik::translate('Referrers_Websites') . ': ' . Piwik::translate( + 'Referrers_WebsitesDocumentation', + array('
', '"' . Piwik::translate('Referrers_SubmenuWebsitesOnly') . '"') + ) . '
' + . '' . Piwik::translate('Referrers_Campaigns') . ': ' . Piwik::translate( + 'Referrers_CampaignsDocumentation', + array('
', '"' . Piwik::translate('Referrers_Campaigns') . '"') + ); $this->constantRowsCount = true; $this->hasGoalMetrics = true; $this->order = 1; diff --git a/plugins/ScheduledReports/Menu.php b/plugins/ScheduledReports/Menu.php index d6df3fd265d..5c8c443aa4a 100644 --- a/plugins/ScheduledReports/Menu.php +++ b/plugins/ScheduledReports/Menu.php @@ -22,7 +22,8 @@ public function configureAdminMenu(MenuAdmin $menu) { $tooltip = Piwik::translate( \Piwik\Plugin\Manager::getInstance()->isPluginActivated('MobileMessaging') - ? 'MobileMessaging_TopLinkTooltip' : 'ScheduledReports_TopLinkTooltip'); + ? 'MobileMessaging_TopLinkTooltip' : 'ScheduledReports_TopLinkTooltip' + ); $menu->addPersonalItem( $this->getTopMenuTranslationKey(), diff --git a/plugins/ScheduledReports/tests/Integration/ApiTest.php b/plugins/ScheduledReports/tests/Integration/ApiTest.php index 9bbeca63c1d..781fd9a3cf0 100644 --- a/plugins/ScheduledReports/tests/Integration/ApiTest.php +++ b/plugins/ScheduledReports/tests/Integration/ApiTest.php @@ -116,8 +116,15 @@ public function getAttachments($report, $processedReports, $prettyDate) }); $idReport = APIScheduledReports::getInstance()->addReport( - $this->idSite, 'send report', 'never', 6, 'dummyreporttype', 'dummyreportformat', - $reportIds, [ScheduledReports::DISPLAY_FORMAT_PARAMETER => ScheduledReports::DISPLAY_FORMAT_TABLES_ONLY]); + $this->idSite, + 'send report', + 'never', + 6, + 'dummyreporttype', + 'dummyreportformat', + $reportIds, + [ScheduledReports::DISPLAY_FORMAT_PARAMETER => ScheduledReports::DISPLAY_FORMAT_TABLES_ONLY] + ); $eventCalledWith = []; Piwik::addAction(APIScheduledReports::SEND_REPORT_EVENT, function ( @@ -436,7 +443,8 @@ public function testGetScheduledTasks() ->disableOriginalConstructor() ->getMock(); $stubbedAPIScheduledReports->expects($this->any())->method('getReports')->will($this->returnValue( - array($report1, $report2, $report3, $report4, $report5, $report6))); + array($report1, $report2, $report3, $report4, $report5, $report6) + )); \Piwik\Plugins\ScheduledReports\API::setSingletonInstance($stubbedAPIScheduledReports); // initialize sites 1 and 2 @@ -498,7 +506,8 @@ public function getGetReportSubjectAndReportTitleTestCases() public function testGetReportSubjectAndReportTitle($expectedReportSubject, $expectedReportTitle, $websiteName, $reports) { $getReportSubjectAndReportTitle = new ReflectionMethod( - '\\Piwik\\Plugins\\ScheduledReports\\API', 'getReportSubjectAndReportTitle' + '\\Piwik\\Plugins\\ScheduledReports\\API', + 'getReportSubjectAndReportTitle' ); $getReportSubjectAndReportTitle->setAccessible(true); @@ -549,8 +558,12 @@ public function test_generateReport_CatchesIndividualReportProcessExceptions_Wit ); ob_start(); - $result = APIScheduledReports::getInstance()->generateReport($idReport, Date::factory('now')->toString(), - $language = false, $outputType = APIScheduledReports::OUTPUT_RETURN); + $result = APIScheduledReports::getInstance()->generateReport( + $idReport, + Date::factory('now')->toString(), + $language = false, + $outputType = APIScheduledReports::OUTPUT_RETURN + ); ob_end_clean(); self::assertStringContainsString('id="VisitsSummary_get"', $result); @@ -578,8 +591,12 @@ public function test_generateReport_throwsIfMultiplePeriodsRequested() array(ScheduledReports::DISPLAY_FORMAT_PARAMETER => ScheduledReports::DISPLAY_FORMAT_TABLES_ONLY) ); - APIScheduledReports::getInstance()->generateReport($idReport, '2012-03-03,2012-03-23', - $language = false, $outputType = APIScheduledReports::OUTPUT_RETURN); + APIScheduledReports::getInstance()->generateReport( + $idReport, + '2012-03-03,2012-03-23', + $language = false, + $outputType = APIScheduledReports::OUTPUT_RETURN + ); } public function test_generateReport_throwsIfInvalidDateRequested(): void @@ -1002,7 +1019,8 @@ private static function updateReport($idReport, $data) $data['type'], $data['format'], $data['reports'], - $data['parameters']); + $data['parameters'] + ); return $idReport; } diff --git a/plugins/SegmentEditor/SegmentQueryDecorator.php b/plugins/SegmentEditor/SegmentQueryDecorator.php index 0d045833a30..1caa1671ab9 100644 --- a/plugins/SegmentEditor/SegmentQueryDecorator.php +++ b/plugins/SegmentEditor/SegmentQueryDecorator.php @@ -43,8 +43,16 @@ public function getSelectQueryString( $orderBy, $limit ) { - $result = parent::getSelectQueryString($segmentExpression, $select, $from, $where, $bind, $groupBy, $orderBy, - $limit); + $result = parent::getSelectQueryString( + $segmentExpression, + $select, + $from, + $where, + $bind, + $groupBy, + $orderBy, + $limit + ); $prefixParts = array(); diff --git a/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php b/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php index 35d2d875d99..49219149f7c 100644 --- a/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php +++ b/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php @@ -156,7 +156,8 @@ public function test_UpdateSegment() 'login' => Piwik::getCurrentUserLogin(), 'deleted' => '0', ); - API::getInstance()->update($idSegment2, + API::getInstance()->update( + $idSegment2, $updatedSegment['name'], $updatedSegment['definition'], $updatedSegment['enable_only_idsite'], diff --git a/plugins/SegmentEditor/tests/Integration/SegmentQueryDecoratorTest.php b/plugins/SegmentEditor/tests/Integration/SegmentQueryDecoratorTest.php index 7cc9158cd0b..3cd8bec568f 100644 --- a/plugins/SegmentEditor/tests/Integration/SegmentQueryDecoratorTest.php +++ b/plugins/SegmentEditor/tests/Integration/SegmentQueryDecoratorTest.php @@ -35,13 +35,15 @@ public function setUp(): void Fixture::createWebsite('2011-01-01'); $this->segmentQueryDecorator = self::$fixture->piwikEnvironment->getContainer()->get( - 'Piwik\Plugins\SegmentEditor\SegmentQueryDecorator'); + 'Piwik\Plugins\SegmentEditor\SegmentQueryDecorator' + ); Rules::setBrowserTriggerArchiving(false); /** @var API $segmentEditorApi */ $segmentEditorApi = self::$fixture->piwikEnvironment->getContainer()->get( - 'Piwik\Plugins\SegmentEditor\API'); + 'Piwik\Plugins\SegmentEditor\API' + ); $segmentEditorApi->add('segment 1', 'visitCount<2', $idSite = false, $autoArchive = true); $segmentEditorApi->add('segment 2', 'countryCode==fr', $idSite = false, $autoArchive = true); $segmentEditorApi->add('segment 3', 'visitCount<2', 1, $autoArchive = true); diff --git a/plugins/SegmentEditor/tests/System/UnprocessedSegmentsTest.php b/plugins/SegmentEditor/tests/System/UnprocessedSegmentsTest.php index b6627a9e26a..a8c0ed89d33 100644 --- a/plugins/SegmentEditor/tests/System/UnprocessedSegmentsTest.php +++ b/plugins/SegmentEditor/tests/System/UnprocessedSegmentsTest.php @@ -118,8 +118,12 @@ public function test_apiOutput_whenPreprocessedSegmentUsed_WithBrowserArchivingD $this->assertNotEmpty($storedSegment); Rules::setBrowserTriggerArchiving(true); - VisitsSummary\API::getInstance()->get(self::$fixture->idSite, 'week', - Date::factory(self::$fixture->dateTime)->toString(), self::TEST_SEGMENT); // archive (make sure there's data for actual test) + VisitsSummary\API::getInstance()->get( + self::$fixture->idSite, + 'week', + Date::factory(self::$fixture->dateTime)->toString(), + self::TEST_SEGMENT + ); // archive (make sure there's data for actual test) Rules::setBrowserTriggerArchiving(false); $segments = Rules::getSegmentsToProcess([self::$fixture->idSite]); @@ -135,8 +139,12 @@ public function test_apiOutput_whenPreprocessedSegmentUsed_WithBrowserArchivingD public function test_apiOutput_whenPreprocessedCustomSegmentUsed_WithBrowserArchivingDisabled() { - VisitsSummary\API::getInstance()->get(self::$fixture->idSite, 'week', - Date::factory(self::$fixture->dateTime)->toString(), self::TEST_SEGMENT); // archive + VisitsSummary\API::getInstance()->get( + self::$fixture->idSite, + 'week', + Date::factory(self::$fixture->dateTime)->toString(), + self::TEST_SEGMENT + ); // archive Rules::setBrowserTriggerArchiving(false); @@ -162,8 +170,12 @@ public function test_apiOutput_whenPreprocessedSegmentUsed_WithNoData_AndBrowser $storedSegment = API::getInstance()->get($idSegment); $this->assertNotEmpty($storedSegment); - VisitsSummary\API::getInstance()->get(self::$fixture->idSite, 'week', - Date::factory(self::$fixture->dateTime)->toString(), self::TEST_SEGMENT); // archive + VisitsSummary\API::getInstance()->get( + self::$fixture->idSite, + 'week', + Date::factory(self::$fixture->dateTime)->toString(), + self::TEST_SEGMENT + ); // archive $segments = Rules::getSegmentsToProcess([self::$fixture->idSite]); self::assertTrue(in_array(self::TEST_SEGMENT, $segments)); diff --git a/plugins/SitesManager/Controller.php b/plugins/SitesManager/Controller.php index ce75d784763..4bf24aa974d 100644 --- a/plugins/SitesManager/Controller.php +++ b/plugins/SitesManager/Controller.php @@ -289,8 +289,10 @@ private function getGoogleAnalyticsImporterInstruction() 'id' => 'GoogleAnalyticsImporter', 'name' => Piwik::translate('CoreAdminHome_ImportFromGoogleAnalytics'), 'type' => SiteContentDetectionAbstract::TYPE_OTHER, - 'othersInstruction' => Piwik::translate('CoreAdminHome_ImportFromGoogleAnalyticsDescription', - ['', '']), + 'othersInstruction' => Piwik::translate( + 'CoreAdminHome_ImportFromGoogleAnalyticsDescription', + ['', ''] + ), ]; } @@ -321,29 +323,37 @@ private function renderOthersTab($othersInstructions): string 'id' => 'ImageTracking', 'name' => Piwik::translate('CoreAdminHome_ImageTracking'), 'type' => SiteContentDetectionAbstract::TYPE_OTHER, - 'othersInstruction' => Piwik::translate('SitesManager_ImageTrackingDescription', - ['', '']), + 'othersInstruction' => Piwik::translate( + 'SitesManager_ImageTrackingDescription', + ['', ''] + ), ], [ 'id' => 'LogAnalytics', 'name' => Piwik::translate('SitesManager_LogAnalytics'), 'type' => SiteContentDetectionAbstract::TYPE_OTHER, - 'othersInstruction' => Piwik::translate('SitesManager_LogAnalyticsDescription', - ['', '']), + 'othersInstruction' => Piwik::translate( + 'SitesManager_LogAnalyticsDescription', + ['', ''] + ), ], [ 'id' => 'MobileAppsAndSDKs', 'name' => Piwik::translate('SitesManager_MobileAppsAndSDKs'), 'type' => SiteContentDetectionAbstract::TYPE_OTHER, - 'othersInstruction' => Piwik::translate('SitesManager_MobileAppsAndSDKsDescription', - ['', '']), + 'othersInstruction' => Piwik::translate( + 'SitesManager_MobileAppsAndSDKsDescription', + ['', ''] + ), ], [ 'id' => 'HttpTrackingApi', 'name' => Piwik::translate('CoreAdminHome_HttpTrackingApi'), 'type' => SiteContentDetectionAbstract::TYPE_OTHER, - 'othersInstruction' => Piwik::translate('CoreAdminHome_HttpTrackingApiDescription', - ['', '']), + 'othersInstruction' => Piwik::translate( + 'CoreAdminHome_HttpTrackingApiDescription', + ['', ''] + ), ] ); diff --git a/plugins/SitesManager/Model.php b/plugins/SitesManager/Model.php index a2e472b7265..dc1b33d4369 100644 --- a/plugins/SitesManager/Model.php +++ b/plugins/SitesManager/Model.php @@ -151,10 +151,11 @@ public function getSitesIdFromSiteUrlHavingAccess($login, $urls) WHERE url IN ( ' . Common::getSqlStringFieldsArray($urls) . ')' . 'AND idsite IN (' . $sqlAccessSite . ')', // Bind - array_merge( $urls, - array( $login ), - $urls, - array( $login ) + array_merge( + $urls, + array( $login ), + $urls, + array( $login ) ) ); diff --git a/plugins/SitesManager/SiteContentDetection/MatomoTagManager.php b/plugins/SitesManager/SiteContentDetection/MatomoTagManager.php index d6654e59f94..42028ce54ee 100644 --- a/plugins/SitesManager/SiteContentDetection/MatomoTagManager.php +++ b/plugins/SitesManager/SiteContentDetection/MatomoTagManager.php @@ -51,7 +51,9 @@ public function isDetected(?string $data = null, ?array $headers = null): bool public function renderInstructionsTab(SiteContentDetector $detector): string { return '

' . Piwik::translate('SitesManager_SiteWithoutDataMatomoTagManager') . '

-

' . Piwik::translate( 'SitesManager_SiteWithoutDataMatomoTagManagerNotActive', - ['', '']) . '

'; +

' . Piwik::translate( + 'SitesManager_SiteWithoutDataMatomoTagManagerNotActive', + ['', ''] + ) . '

'; } } diff --git a/plugins/TestRunner/Commands/CodeCoverage.php b/plugins/TestRunner/Commands/CodeCoverage.php index f6916994c7d..674c32b6472 100644 --- a/plugins/TestRunner/Commands/CodeCoverage.php +++ b/plugins/TestRunner/Commands/CodeCoverage.php @@ -66,10 +66,12 @@ protected function doExecute(): int $xdebugFile = trim($extensionDir) . DIRECTORY_SEPARATOR . 'xdebug.so'; if (!file_exists($xdebugFile)) { - $xdebugFile = $this->askAndValidate('xdebug not found. Please provide path to xdebug.so', + $xdebugFile = $this->askAndValidate( + 'xdebug not found. Please provide path to xdebug.so', function ($xdebugFile) { return file_exists($xdebugFile); - }); + } + ); } else { $output->writeln('xdebug extension found in extension path.'); diff --git a/plugins/TestRunner/Commands/TestsRun.php b/plugins/TestRunner/Commands/TestsRun.php index c3b43424fe7..8624ab31b8a 100644 --- a/plugins/TestRunner/Commands/TestsRun.php +++ b/plugins/TestRunner/Commands/TestsRun.php @@ -74,10 +74,12 @@ protected function doExecute(): int $xdebugFile = trim($extensionDir) . DIRECTORY_SEPARATOR . 'xdebug.so'; if (!file_exists($xdebugFile)) { - $xdebugFile = $this->askAndValidate('xdebug not found. Please provide path to xdebug.so', + $xdebugFile = $this->askAndValidate( + 'xdebug not found. Please provide path to xdebug.so', function ($xdebugFile) { return file_exists($xdebugFile); - }); + } + ); } else { $output->writeln('xdebug extension found in extension path.'); diff --git a/plugins/TestRunner/Commands/TestsSetupFixture.php b/plugins/TestRunner/Commands/TestsSetupFixture.php index a4b7013eafa..202347fc52f 100644 --- a/plugins/TestRunner/Commands/TestsSetupFixture.php +++ b/plugins/TestRunner/Commands/TestsSetupFixture.php @@ -49,41 +49,82 @@ protected function configure() $this->setName('tests:setup-fixture'); $this->setDescription('Create a database and fill it with data using a Piwik test fixture.'); - $this->addRequiredArgument('fixture', + $this->addRequiredArgument( + 'fixture', "The class name of the fixture to apply. Doesn't need to have a namespace if it exists in the " . - "Piwik\\Tests\\Fixtures namespace."); - - $this->addRequiredValueOption('db-name', null, - "The name of the database that will contain the fixture data. This option is required to be set."); - $this->addRequiredValueOption('file', null, - "The file location of the fixture. If this option is included the file will be required explicitly."); - $this->addRequiredValueOption('db-host', null, - "The hostname of the MySQL database to use. Uses the default config value if not specified."); - $this->addRequiredValueOption('db-user', null, - "The name of the MySQL user to use. Uses the default config value if not specified."); - $this->addRequiredValueOption('db-pass', null, - "The MySQL user password to use. Uses the default config value if not specified."); - $this->addNoValueOption('teardown', null, + "Piwik\\Tests\\Fixtures namespace." + ); + + $this->addRequiredValueOption( + 'db-name', + null, + "The name of the database that will contain the fixture data. This option is required to be set." + ); + $this->addRequiredValueOption( + 'file', + null, + "The file location of the fixture. If this option is included the file will be required explicitly." + ); + $this->addRequiredValueOption( + 'db-host', + null, + "The hostname of the MySQL database to use. Uses the default config value if not specified." + ); + $this->addRequiredValueOption( + 'db-user', + null, + "The name of the MySQL user to use. Uses the default config value if not specified." + ); + $this->addRequiredValueOption( + 'db-pass', + null, + "The MySQL user password to use. Uses the default config value if not specified." + ); + $this->addNoValueOption( + 'teardown', + null, "If specified, the fixture will be torn down and the database deleted. Won't work if the --db-name " . - "option isn't supplied."); - $this->addNoValueOption('persist-fixture-data', null, + "option isn't supplied." + ); + $this->addNoValueOption( + 'persist-fixture-data', + null, "If specified, the database will not be dropped after the fixture is setup. If the database already " . - "and the fixture was successfully setup before, nothing will happen."); - $this->addNoValueOption('drop', null, + "and the fixture was successfully setup before, nothing will happen." + ); + $this->addNoValueOption( + 'drop', + null, "Forces the database to be dropped before setting up the fixture. Should be used in conjunction with" . - " --persist-fixture-data when updating a pre-existing test database."); - $this->addRequiredValueOption('sqldump', null, - "Creates an SQL dump after setting up the fixture and outputs the dump to the file specified by this option."); - $this->addNoValueOption('save-config', null, + " --persist-fixture-data when updating a pre-existing test database." + ); + $this->addRequiredValueOption( + 'sqldump', + null, + "Creates an SQL dump after setting up the fixture and outputs the dump to the file specified by this option." + ); + $this->addNoValueOption( + 'save-config', + null, "Saves the current configuration file as a config for a new Piwik domain. For example save-config --matomo-domain=mytest.localhost.com will create " - . "a mytest.config.ini.php file in the config/ directory. Using /etc/hosts you can redirect to 127.0.0.1 and use the saved " - . "config."); - $this->addNoValueOption('set-symlinks', null, - "Used by UI tests. Creates symlinks to root directory in tests/PHPUnit/proxy."); - $this->addRequiredValueOption('server-global', null, - "Used by UI tests. Sets the \$_SERVER global variable from a JSON string."); - $this->addRequiredValueOption('plugins', null, - "Used by UI tests. Comma separated list of plugin names to activate and install when setting up a fixture."); + . "a mytest.config.ini.php file in the config/ directory. Using /etc/hosts you can redirect to 127.0.0.1 and use the saved " + . "config." + ); + $this->addNoValueOption( + 'set-symlinks', + null, + "Used by UI tests. Creates symlinks to root directory in tests/PHPUnit/proxy." + ); + $this->addRequiredValueOption( + 'server-global', + null, + "Used by UI tests. Sets the \$_SERVER global variable from a JSON string." + ); + $this->addRequiredValueOption( + 'plugins', + null, + "Used by UI tests. Comma separated list of plugin names to activate and install when setting up a fixture." + ); $this->addNoValueOption('enable-logging', null, 'If enabled, tests will log to the configured log file.'); } diff --git a/plugins/Transitions/API.php b/plugins/Transitions/API.php index f3a3881e461..5c054c8b307 100644 --- a/plugins/Transitions/API.php +++ b/plugins/Transitions/API.php @@ -243,7 +243,12 @@ private function addFollowingActions($logAggregator, &$report, $idaction, $actio { $data = $this->queryFollowingActions( - $idaction, $actionType, $logAggregator, $limitBeforeGrouping, $includeLoops); + $idaction, + $actionType, + $logAggregator, + $limitBeforeGrouping, + $includeLoops + ); foreach ($data as $tableName => $table) { $report[$tableName] = $table; @@ -587,7 +592,11 @@ protected function getTotalTransitionsToFollowingActions() private function addExternalReferrers($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping) { $data = $this->queryExternalReferrers( - $idaction, $actionType, $logAggregator, $limitBeforeGrouping); + $idaction, + $actionType, + $logAggregator, + $limitBeforeGrouping + ); $report['pageMetrics']['entries'] = 0; $report['referrers'] = array(); diff --git a/plugins/Transitions/tests/Integration/TransitionsMaxAllowedPeriodTest.php b/plugins/Transitions/tests/Integration/TransitionsMaxAllowedPeriodTest.php index f430ad8f189..81603377f65 100644 --- a/plugins/Transitions/tests/Integration/TransitionsMaxAllowedPeriodTest.php +++ b/plugins/Transitions/tests/Integration/TransitionsMaxAllowedPeriodTest.php @@ -52,8 +52,13 @@ public function test_ShouldThrowException_IfPeriodNotAllowed() Config::setSetting('Transitions_1', 'max_period_allowed', $period); foreach ($invalids as $ip) { try { - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', - 1, $ip, '2012-08-09'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + $ip, + '2012-08-09' + ); $this->fail("Failed asserting that exception 'PeriodNotAllowed' was thrown"); } catch (\Exception $e) { $this->assertEquals('PeriodNotAllowed', $e->getMessage()); @@ -74,8 +79,13 @@ public function test_ShouldReturnData_IfPeriodAllowed() foreach ($validPeriods as $period => $valids) { Config::setSetting('Transitions_1', 'max_period_allowed', $period); foreach ($valids as $vp) { - $r = $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', - 1, $vp, '2012-08-09'); + $r = $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + $vp, + '2012-08-09' + ); self::assertEquals(1, $r['pageMetrics']['pageviews']); } } @@ -85,14 +95,28 @@ public function test_ShouldThrowException_IfInvalidLimitBeforeGroup() { $this->expectException(\Exception::class); $this->expectExceptionMessage('limitBeforeGrouping has to be an integer.'); - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2012-08-10', false, 'all'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2012-08-10', + false, + 'all' + ); } public function test_ShouldPass_IfLimitBeforeGroupPassingIntAsString() { - $report = $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2012-08-10', false, '100'); + $report = $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2012-08-10', + false, + '100' + ); $this->assertIsArray($report); } @@ -101,8 +125,13 @@ public function test_ShouldThrowException_IfRangeDayCountIsLargerThanDayPeriod() Config::setSetting('Transitions_1', 'max_period_allowed', 'day'); $this->expectException(\Exception::class); $this->expectExceptionMessage('PeriodNotAllowed'); - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2012-08-10'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2012-08-10' + ); } public function test_ShouldThrowException_IfRangeDayCountIsLargerThanWeekPeriod() @@ -110,8 +139,13 @@ public function test_ShouldThrowException_IfRangeDayCountIsLargerThanWeekPeriod( Config::setSetting('Transitions_1', 'max_period_allowed', 'day'); $this->expectException(\Exception::class); $this->expectExceptionMessage('PeriodNotAllowed'); - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2012-08-17'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2012-08-17' + ); } public function test_ShouldThrowException_IfRangeDayCountIsLargerThanMonthPeriod() @@ -119,8 +153,13 @@ public function test_ShouldThrowException_IfRangeDayCountIsLargerThanMonthPeriod Config::setSetting('Transitions_1', 'max_period_allowed', 'day'); $this->expectException(\Exception::class); $this->expectExceptionMessage('PeriodNotAllowed'); - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2012-09-10'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2012-09-10' + ); } public function test_ShouldThrowException_IfRangeDayCountIsLargerThanYearPeriod() @@ -128,8 +167,13 @@ public function test_ShouldThrowException_IfRangeDayCountIsLargerThanYearPeriod( Config::setSetting('Transitions_1', 'max_period_allowed', 'day'); $this->expectException(\Exception::class); $this->expectExceptionMessage('PeriodNotAllowed'); - $this->api->getTransitionsForAction('http://example.org/page/one.html', 'url', 1, - 'range', '2012-08-09,2013-08-10'); + $this->api->getTransitionsForAction( + 'http://example.org/page/one.html', + 'url', + 1, + 'range', + '2012-08-09,2013-08-10' + ); } public function test_ShouldUseSiteConfigInsteadOfGeneral_IfSiteConfigExists() diff --git a/plugins/TwoFactorAuth/Controller.php b/plugins/TwoFactorAuth/Controller.php index 877db981398..da80ab6d6e8 100644 --- a/plugins/TwoFactorAuth/Controller.php +++ b/plugins/TwoFactorAuth/Controller.php @@ -284,8 +284,10 @@ public function showRecoveryCodes() $this->validator->check2FaEnabled(); $regenerateNonce = Common::getRequestVar('regenerateNonce', '', 'string', $_POST); - $postedValidNonce = !empty($regenerateNonce) && Nonce::verifyNonce(self::REGENERATE_CODES_2FA_NONCE, - $regenerateNonce); + $postedValidNonce = !empty($regenerateNonce) && Nonce::verifyNonce( + self::REGENERATE_CODES_2FA_NONCE, + $regenerateNonce + ); $regenerateSuccess = false; $regenerateError = false; diff --git a/plugins/TwoFactorAuth/FormTwoFactorAuthCode.php b/plugins/TwoFactorAuth/FormTwoFactorAuthCode.php index e621d7846ee..0abd0dae803 100644 --- a/plugins/TwoFactorAuth/FormTwoFactorAuthCode.php +++ b/plugins/TwoFactorAuth/FormTwoFactorAuthCode.php @@ -23,8 +23,10 @@ function __construct($id = 'login_form', $method = 'post', $attributes = null, $ function init() { $this->addElement('text', 'form_authcode') - ->addRule('required', - Piwik::translate('General_Required', 'Authentication code')); + ->addRule( + 'required', + Piwik::translate('General_Required', 'Authentication code') + ); $this->addElement('hidden', 'form_nonce'); diff --git a/plugins/TwoFactorAuth/tests/Fixtures/TwoFactorFixture.php b/plugins/TwoFactorAuth/tests/Fixtures/TwoFactorFixture.php index ad62829d44d..9d38705bdc2 100644 --- a/plugins/TwoFactorAuth/tests/Fixtures/TwoFactorFixture.php +++ b/plugins/TwoFactorAuth/tests/Fixtures/TwoFactorFixture.php @@ -70,8 +70,11 @@ public function setUpWebsite() public function setUpUsers() { - \Piwik\Plugins\UsersManager\API::getInstance()->addUser($this->superUserWith2Fa, $this->userPassword, - $this->superUserWith2Fa . '@matomo.org'); + \Piwik\Plugins\UsersManager\API::getInstance()->addUser( + $this->superUserWith2Fa, + $this->userPassword, + $this->superUserWith2Fa . '@matomo.org' + ); $userUpdater = new UserUpdater(); $userUpdater->setSuperUserAccessWithoutCurrentPassword($this->superUserWith2Fa, true); diff --git a/plugins/UserCountry/API.php b/plugins/UserCountry/API.php index dce75bbe7bf..05ae0ab50c2 100644 --- a/plugins/UserCountry/API.php +++ b/plugins/UserCountry/API.php @@ -107,8 +107,11 @@ function ($label) use ($separator, $unk) { $regionCode = getElementFromStringArray($label, $separator, 0, ''); $countryCode = getElementFromStringArray($label, $separator, 1, ''); - list($countryCode, $regionCode) = GeoIp2::convertRegionCodeToIso($countryCode, - $regionCode, true); + list($countryCode, $regionCode) = GeoIp2::convertRegionCodeToIso( + $countryCode, + $regionCode, + true + ); $splitLabel = explode($separator, $label); @@ -140,19 +143,27 @@ function ($label) { $dataTable->filter('AddSegmentByLabel', array($segments, Archiver::LOCATION_SEPARATOR)); // split the label and put the elements into the 'region' and 'country' metadata fields - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'region', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 0, $unk))); - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'country', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 1, $unk))); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'region', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 0, $unk)) + ); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'country', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 1, $unk)) + ); // add country name metadata - $dataTable->filter('MetadataCallbackAddMetadata', - array('country', 'country_name', __NAMESPACE__ . '\CountryTranslate', $applyToSummaryRow = false)); + $dataTable->filter( + 'MetadataCallbackAddMetadata', + array('country', 'country_name', __NAMESPACE__ . '\CountryTranslate', $applyToSummaryRow = false) + ); // get the region name of each row and put it into the 'region_name' metadata - $dataTable->filter('ColumnCallbackAddMetadata', + $dataTable->filter( + 'ColumnCallbackAddMetadata', array('label', 'region_name', __NAMESPACE__ . '\getRegionName', $params = null, - $applyToSummaryRow = false)); + $applyToSummaryRow = false) + ); // add the country flag as a url to the 'logo' metadata field $dataTable->filter('MetadataCallbackAddMetadata', array('country', 'logo', __NAMESPACE__ . '\getFlagFromCode')); @@ -192,8 +203,11 @@ function ($label) use ($separator, $unk) { $regionCode = getElementFromStringArray($label, $separator, 1, ''); $countryCode = getElementFromStringArray($label, $separator, 2, ''); - list($countryCode, $regionCode) = GeoIp2::convertRegionCodeToIso($countryCode, - $regionCode, true); + list($countryCode, $regionCode) = GeoIp2::convertRegionCodeToIso( + $countryCode, + $regionCode, + true + ); $splitLabel = explode($separator, $label); @@ -227,31 +241,45 @@ function ($label) { // split the label and put the elements into the 'city_name', 'region', 'country', // 'lat' & 'long' metadata fields $strUnknown = Piwik::translate('General_Unknown'); - $dataTable->filter('ColumnCallbackAddMetadata', + $dataTable->filter( + 'ColumnCallbackAddMetadata', array('label', 'city_name', __NAMESPACE__ . '\getElementFromStringArray', - array($separator, 0, $strUnknown))); - $dataTable->filter('MetadataCallbackAddMetadata', + array($separator, 0, $strUnknown)) + ); + $dataTable->filter( + 'MetadataCallbackAddMetadata', array('city_name', 'city', function ($city) use ($strUnknown) { if ($city == $strUnknown) { return "xx"; } else { return false; } - })); - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'region', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 1, $unk))); - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'country', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 2, $unk))); + }) + ); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'region', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 1, $unk)) + ); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'country', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 2, $unk)) + ); // backwards compatibility: for reports that have lat|long in label - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'lat', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 3, false))); - $dataTable->filter('ColumnCallbackAddMetadata', - array('label', 'long', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 4, false))); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'lat', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 3, false)) + ); + $dataTable->filter( + 'ColumnCallbackAddMetadata', + array('label', 'long', __NAMESPACE__ . '\getElementFromStringArray', array($separator, 4, false)) + ); // add country name & region name metadata - $dataTable->filter('MetadataCallbackAddMetadata', - array('country', 'country_name', __NAMESPACE__ . '\countryTranslate', $applyToSummaryRow = false)); + $dataTable->filter( + 'MetadataCallbackAddMetadata', + array('country', 'country_name', __NAMESPACE__ . '\countryTranslate', $applyToSummaryRow = false) + ); $getRegionName = '\\Piwik\\Plugins\\UserCountry\\getRegionNameFromCodes'; $dataTable->filter('MetadataCallbackAddMetadata', array( diff --git a/plugins/UserCountry/Commands/AttributeHistoricalDataWithLocations.php b/plugins/UserCountry/Commands/AttributeHistoricalDataWithLocations.php index d84c2e5bafc..b819b967dbb 100644 --- a/plugins/UserCountry/Commands/AttributeHistoricalDataWithLocations.php +++ b/plugins/UserCountry/Commands/AttributeHistoricalDataWithLocations.php @@ -71,9 +71,13 @@ protected function configure() $this->setName('usercountry:attribute'); $this->setDescription("Re-attribute existing raw data (visits & conversions) with geolocated location data, using the specified or configured location provider."); $this->addRequiredArgument(self::DATES_RANGE_ARGUMENT, 'Attribute visits in this date range. Eg, 2012-01-01,2013-01-01'); - $this->addOptionalValueOption(self::PERCENT_STEP_ARGUMENT, null, + $this->addOptionalValueOption( + self::PERCENT_STEP_ARGUMENT, + null, 'How often to display the command progress. A status update will be printed after N percent of visits are processed, ' - . 'where N is the value of this option.', self::PERCENT_STEP_ARGUMENT_DEFAULT); + . 'where N is the value of this option.', + self::PERCENT_STEP_ARGUMENT_DEFAULT + ); $this->addRequiredValueOption(self::PROVIDER_ARGUMENT, null, 'Provider id which should be used to attribute visits. If empty then' . ' Piwik will use the currently configured provider. If no provider is configured, the default provider is used.'); $this->addOptionalValueOption(self::SEGMENT_LIMIT_OPTION, null, 'Number of visits to process at a time.', self::SEGMENT_LIMIT_OPTION_DEFAULT); @@ -96,8 +100,13 @@ protected function doExecute(): int $this->amountOfVisits = $this->dao->countVisitsWithDatesLimit($from, $to); $output->writeln( - sprintf('Re-attribution for date range: %s to %s. %d visits to process with provider "%s".', - $from, $to, $this->amountOfVisits, $this->visitorGeolocator->getProvider()->getId()) + sprintf( + 'Re-attribution for date range: %s to %s. %d visits to process with provider "%s".', + $from, + $to, + $this->amountOfVisits, + $this->visitorGeolocator->getProvider()->getId() + ) ); $this->timer = new Timer(); diff --git a/plugins/UserCountry/Controller.php b/plugins/UserCountry/Controller.php index 6bbce30544e..7217d833039 100644 --- a/plugins/UserCountry/Controller.php +++ b/plugins/UserCountry/Controller.php @@ -124,7 +124,10 @@ public function getLocationUsingProvider() 'lang' => Common::getBrowserLanguage(), 'disable_fallbacks' => true)); $location = LocationProvider::prettyFormatLocation( - $location, $newline = '
', $includeExtra = true); + $location, + $newline = '
', + $includeExtra = true + ); return $location; } diff --git a/plugins/UserCountry/LocationProvider.php b/plugins/UserCountry/LocationProvider.php index 2f0a804fe52..9a4777f87b5 100644 --- a/plugins/UserCountry/LocationProvider.php +++ b/plugins/UserCountry/LocationProvider.php @@ -369,7 +369,8 @@ public static function setCurrentProvider($providerId) $provider = self::getProviderById($providerId); if (empty($provider)) { throw new Exception( - "Invalid provider ID '$providerId'. The provider either does not exist or is not available"); + "Invalid provider ID '$providerId'. The provider either does not exist or is not available" + ); } $provider->activate(); diff --git a/plugins/UserCountry/Menu.php b/plugins/UserCountry/Menu.php index c7890875314..b211ab519e6 100644 --- a/plugins/UserCountry/Menu.php +++ b/plugins/UserCountry/Menu.php @@ -16,9 +16,11 @@ class Menu extends \Piwik\Plugin\Menu public function configureAdminMenu(MenuAdmin $menu) { if (UserCountry::isGeoLocationAdminEnabled() && Piwik::hasUserSuperUserAccess()) { - $menu->addSystemItem('UserCountry_Geolocation', - $this->urlForAction('adminIndex'), - $order = 30); + $menu->addSystemItem( + 'UserCountry_Geolocation', + $this->urlForAction('adminIndex'), + $order = 30 + ); } } } diff --git a/plugins/UserCountry/Reports/Base.php b/plugins/UserCountry/Reports/Base.php index 3439df484c3..5c506f4a268 100644 --- a/plugins/UserCountry/Reports/Base.php +++ b/plugins/UserCountry/Reports/Base.php @@ -22,7 +22,8 @@ protected function init() protected function getGeoIPReportDocSuffix() { - return Piwik::translate('UserCountry_GeoIPDocumentationSuffix', + return Piwik::translate( + 'UserCountry_GeoIPDocumentationSuffix', array('', '', '', @@ -47,14 +48,18 @@ protected function checkIfNoDataForGeoIpReport(ViewDataTable $view) // if GeoIP is working, don't display this part of the message if (!$userCountry->isGeoIPWorking()) { $params = array('module' => 'UserCountry', 'action' => 'adminIndex'); - $footerMessage .= ' ' . Piwik::translate('UserCountry_NoDataForGeoIPReport2', - array('', + $footerMessage .= ' ' . Piwik::translate( + 'UserCountry_NoDataForGeoIPReport2', + array('', '', '', - '')); + '') + ); } else { - $footerMessage .= ' ' . Piwik::translate('UserCountry_ToGeolocateOldVisits', - array('', '')); + $footerMessage .= ' ' . Piwik::translate( + 'UserCountry_ToGeolocateOldVisits', + array('', '') + ); } $view->config->show_footer_message = $footerMessage; diff --git a/plugins/UserCountry/Reports/GetCountry.php b/plugins/UserCountry/Reports/GetCountry.php index af843a153d0..e93dd17ba90 100644 --- a/plugins/UserCountry/Reports/GetCountry.php +++ b/plugins/UserCountry/Reports/GetCountry.php @@ -38,8 +38,10 @@ public function configureView(ViewDataTable $view) if (LocationProvider::getCurrentProviderId() == LocationProvider\DefaultProvider::ID) { // if we're using the default location provider, add a note explaining how it works $footerMessage = Piwik::translate("General_Note") . ': ' - . Piwik::translate('UserCountry_DefaultLocationProviderExplanation', - ['', '']); + . Piwik::translate( + 'UserCountry_DefaultLocationProviderExplanation', + ['', ''] + ); $view->config->show_footer_message = $footerMessage; } diff --git a/plugins/UserCountry/VisitorDetails.php b/plugins/UserCountry/VisitorDetails.php index f3b04f589ed..3fae5146817 100644 --- a/plugins/UserCountry/VisitorDetails.php +++ b/plugins/UserCountry/VisitorDetails.php @@ -70,7 +70,9 @@ protected function getRegionName() $region = $this->getRegionCode(); if ($region != '' && $region != Visit::UNKNOWN_CODE) { return getRegionNameFromCodes( - $this->details['location_country'], $region); + $this->details['location_country'], + $region + ); } return null; diff --git a/plugins/UserId/Reports/GetUsers.php b/plugins/UserId/Reports/GetUsers.php index d2abdbf3935..37c97564537 100644 --- a/plugins/UserId/Reports/GetUsers.php +++ b/plugins/UserId/Reports/GetUsers.php @@ -60,8 +60,11 @@ public function configureView(ViewDataTable $view) $view->config->show_insights = false; $view->config->show_pivot_by_subtable = false; $view->config->no_data_message = Piwik::translate('CoreHome_ThereIsNoDataForThisReport') . '

' - . sprintf(Piwik::translate('UserId_ThereIsNoDataForThisReportHelp'), - "", ""); + . sprintf( + Piwik::translate('UserId_ThereIsNoDataForThisReportHelp'), + "", + "" + ); if ($view->isViewDataTableId(HtmlTable::ID)) { $view->config->disable_row_evolution = false; diff --git a/plugins/UsersManager/Controller.php b/plugins/UsersManager/Controller.php index e4ae50f2c79..f95d650ddcb 100644 --- a/plugins/UsersManager/Controller.php +++ b/plugins/UsersManager/Controller.php @@ -521,12 +521,16 @@ public function recordAnonymousUserSettings() $anonymousDefaultReport = Common::getRequestVar('anonymousDefaultReport'); $anonymousDefaultDate = Common::getRequestVar('anonymousDefaultDate'); $userLogin = 'anonymous'; - APIUsersManager::getInstance()->setUserPreference($userLogin, + APIUsersManager::getInstance()->setUserPreference( + $userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT, - $anonymousDefaultReport); - APIUsersManager::getInstance()->setUserPreference($userLogin, + $anonymousDefaultReport + ); + APIUsersManager::getInstance()->setUserPreference( + $userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE, - $anonymousDefaultDate); + $anonymousDefaultDate + ); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); @@ -566,12 +570,16 @@ public function recordUserSettings() 'use12HourClock' => $timeFormat, ]); - APIUsersManager::getInstance()->setUserPreference($userLogin, + APIUsersManager::getInstance()->setUserPreference( + $userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT, - $defaultReport); - APIUsersManager::getInstance()->setUserPreference($userLogin, + $defaultReport + ); + APIUsersManager::getInstance()->setUserPreference( + $userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE, - $defaultDate); + $defaultDate + ); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); diff --git a/plugins/UsersManager/Model.php b/plugins/UsersManager/Model.php index 288a7a7607b..df93b783210 100644 --- a/plugins/UsersManager/Model.php +++ b/plugins/UsersManager/Model.php @@ -309,8 +309,10 @@ public function generateRandomTokenAuth() private function generateTokenAuth() { - return md5(Common::getRandomString(32, - 'abcdef1234567890') . microtime(true) . Common::generateUniqId() . SettingsPiwik::getSalt()); + return md5(Common::getRandomString( + 32, + 'abcdef1234567890' + ) . microtime(true) . Common::generateUniqId() . SettingsPiwik::getSalt()); } /** @@ -340,8 +342,11 @@ public function addTokenAuth( throw new \Exception('User ' . $login . ' does not exist'); } - BaseValidator::check('Description', $description, - [new NotEmpty(), new CharacterLength(1, self::MAX_LENGTH_TOKEN_DESCRIPTION)]); + BaseValidator::check( + 'Description', + $description, + [new NotEmpty(), new CharacterLength(1, self::MAX_LENGTH_TOKEN_DESCRIPTION)] + ); if (empty($dateExpired)) { $dateExpired = null; @@ -354,8 +359,10 @@ public function addTokenAuth( $tokenAuth = $this->hashTokenAuth($tokenAuth); $db = $this->getDb(); - $db->query($insertSql, - [$login, $description, $tokenAuth, $dateCreated, $dateExpired, $isSystemToken, self::TOKEN_HASH_ALGO, $secureOnly]); + $db->query( + $insertSql, + [$login, $description, $tokenAuth, $dateCreated, $dateExpired, $isSystemToken, self::TOKEN_HASH_ALGO, $secureOnly] + ); return $db->lastInsertId(); } @@ -372,8 +379,10 @@ public function getUserTokenDescriptionByIdTokenAuth($idTokenAuth, $login) { $db = $this->getDb(); - $token = $db->fetchRow("SELECT description FROM " . $this->tokenTable . " WHERE `idusertokenauth` = ? and login = ? LIMIT 1", - array($idTokenAuth, $login)); + $token = $db->fetchRow( + "SELECT description FROM " . $this->tokenTable . " WHERE `idusertokenauth` = ? and login = ? LIMIT 1", + array($idTokenAuth, $login) + ); return $token ? $token['description'] : ''; } @@ -425,16 +434,20 @@ public function deleteExpiredTokens($expiredSince) { $db = $this->getDb(); - return $db->query("DELETE FROM " . $this->tokenTable . " WHERE `date_expired` is not null and date_expired < ?", - $expiredSince); + return $db->query( + "DELETE FROM " . $this->tokenTable . " WHERE `date_expired` is not null and date_expired < ?", + $expiredSince + ); } public function getExpiredInvites($expiredSince) { $db = $this->getDb(); - return $db->fetchAll("SELECT * FROM " . $this->userTable . " WHERE `invite_expired_at` is not null and invite_expired_at < ?", - $expiredSince); + return $db->fetchAll( + "SELECT * FROM " . $this->userTable . " WHERE `invite_expired_at` is not null and invite_expired_at < ?", + $expiredSince + ); } public function checkUserHasUnexpiredToken($login) @@ -442,8 +455,10 @@ public function checkUserHasUnexpiredToken($login) $db = $this->getDb(); $expired = $this->getQueryNotExpiredToken(); $bind = array_merge(array($login), $expired['bind']); - return $db->fetchOne("SELECT idusertokenauth FROM " . $this->tokenTable . " WHERE `login` = ? and " . $expired['sql'], - $bind); + return $db->fetchOne( + "SELECT idusertokenauth FROM " . $this->tokenTable . " WHERE `login` = ? and " . $expired['sql'], + $bind + ); } public function deleteAllTokensForUser($login) @@ -461,8 +476,10 @@ public function getAllNonSystemTokensForLogin($login) $expired = $this->getQueryNotExpiredToken(); $bind = array_merge(array($login), $expired['bind']); - return $db->fetchAll("SELECT * FROM " . $this->tokenTable . " WHERE `login` = ? and system_token = 0 and " . $expired['sql'] . ' order by idusertokenauth ASC', - $bind); + return $db->fetchAll( + "SELECT * FROM " . $this->tokenTable . " WHERE `login` = ? and system_token = 0 and " . $expired['sql'] . ' order by idusertokenauth ASC', + $bind + ); } public function getAllHashedTokensForLogins($logins) @@ -477,8 +494,10 @@ public function getAllHashedTokensForLogins($logins) $expired = $this->getQueryNotExpiredToken(); $bind = array_merge($logins, $expired['bind']); - $tokens = $db->fetchAll("SELECT password FROM " . $this->tokenTable . " WHERE `login` IN (" . $placeholder . ") and " . $expired['sql'], - $bind); + $tokens = $db->fetchAll( + "SELECT password FROM " . $this->tokenTable . " WHERE `login` IN (" . $placeholder . ") and " . $expired['sql'], + $bind + ); return array_column($tokens, 'password'); } @@ -486,8 +505,10 @@ public function deleteToken($idTokenAuth, $login) { $db = $this->getDb(); - return $db->query("DELETE FROM " . $this->tokenTable . " WHERE `idusertokenauth` = ? and login = ?", - array($idTokenAuth, $login)); + return $db->query( + "DELETE FROM " . $this->tokenTable . " WHERE `idusertokenauth` = ? and login = ?", + array($idTokenAuth, $login) + ); } public function setTokenAuthWasUsed($tokenAuth, $dateLastUsed) @@ -522,8 +543,10 @@ private function updateTokenAuthTable($idTokenAuth, $fields) $bind[] = $idTokenAuth; $db = $this->getDb(); - $db->query(sprintf('UPDATE `%s` SET %s WHERE `idusertokenauth` = ?', $this->tokenTable, implode(', ', $set)), - $bind); + $db->query( + sprintf('UPDATE `%s` SET %s WHERE `idusertokenauth` = ?', $this->tokenTable, implode(', ', $set)), + $bind + ); } public function getUserByEmail($userEmail) @@ -737,8 +760,10 @@ public function deleteUserAccess($userLogin, $idSites = null) $db->query("DELETE FROM " . Common::prefixTable("access") . " WHERE login = ?", $userLogin); } else { foreach ($idSites as $idsite) { - $db->query("DELETE FROM " . Common::prefixTable("access") . " WHERE idsite = ? AND login = ?", - [$idsite, $userLogin]); + $db->query( + "DELETE FROM " . Common::prefixTable("access") . " WHERE idsite = ? AND login = ?", + [$idsite, $userLogin] + ); } } } diff --git a/plugins/UsersManager/UsersManager.php b/plugins/UsersManager/UsersManager.php index 128908a8c01..32b337a971a 100644 --- a/plugins/UsersManager/UsersManager.php +++ b/plugins/UsersManager/UsersManager.php @@ -70,8 +70,14 @@ public function addSystemSummaryItems(&$systemSummary) $numUsers--; } - $systemSummary[] = new SystemSummary\Item($key = 'users', Piwik::translate('General_NUsers', $numUsers), - $value = null, array('module' => 'UsersManager', 'action' => 'index'), $icon = 'icon-user', $order = 5); + $systemSummary[] = new SystemSummary\Item( + $key = 'users', + Piwik::translate('General_NUsers', $numUsers), + $value = null, + array('module' => 'UsersManager', 'action' => 'index'), + $icon = 'icon-user', + $order = 5 + ); } public function onPlatformInitialized() @@ -175,12 +181,16 @@ public static function checkPassword($password) Piwik::postEvent('UsersManager.checkPassword', array($password)); if (!self::isValidPasswordString($password)) { - throw new Exception(Piwik::translate('UsersManager_ExceptionInvalidPassword', - array(self::PASSWORD_MIN_LENGTH))); + throw new Exception(Piwik::translate( + 'UsersManager_ExceptionInvalidPassword', + array(self::PASSWORD_MIN_LENGTH) + )); } if (mb_strlen($password) > self::PASSWORD_MAX_LENGTH) { - throw new Exception(Piwik::translate('UsersManager_ExceptionInvalidPasswordTooLong', - array(self::PASSWORD_MAX_LENGTH))); + throw new Exception(Piwik::translate( + 'UsersManager_ExceptionInvalidPasswordTooLong', + array(self::PASSWORD_MAX_LENGTH) + )); } } diff --git a/plugins/UsersManager/tests/Integration/TokenSecureOnlyTest.php b/plugins/UsersManager/tests/Integration/TokenSecureOnlyTest.php index 8ee728610f2..b4ccae0e601 100644 --- a/plugins/UsersManager/tests/Integration/TokenSecureOnlyTest.php +++ b/plugins/UsersManager/tests/Integration/TokenSecureOnlyTest.php @@ -36,8 +36,15 @@ private static function createUserAndTokens() UsersManagerAPI::getInstance()->setUserAccess('user1', 'view', [1]); $userModel = new UsersManagerModel(); - $userModel->addTokenAuth('user1', self::$tokenSecureOnly, 'Secure Only', '2020-01-02 03:04:05', - null, false, true); + $userModel->addTokenAuth( + 'user1', + self::$tokenSecureOnly, + 'Secure Only', + '2020-01-02 03:04:05', + null, + false, + true + ); } } diff --git a/plugins/UsersManager/tests/Integration/UsersManagerTest.php b/plugins/UsersManager/tests/Integration/UsersManagerTest.php index b4a8d745024..dc1fc4551a1 100644 --- a/plugins/UsersManager/tests/Integration/UsersManagerTest.php +++ b/plugins/UsersManager/tests/Integration/UsersManagerTest.php @@ -248,9 +248,11 @@ public function testAddUserWrongEmail() public function testAddUserLongPassword() { $login = "geggeqgeqag"; - $this->api->addUser($login, - "geqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaeg", - "mgeagi@geq.com"); + $this->api->addUser( + $login, + "geqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaegeqgeagaeg", + "mgeagi@geq.com" + ); $user = $this->api->getUser($login); $this->assertEquals($login, $user['login']); } @@ -269,8 +271,10 @@ public function testAddUser() $user = $this->model->getUser($login); // check that the date registered is correct - $this->assertTrue($time <= strtotime($user['date_registered']) && strtotime($user['date_registered']) <= time(), - "the date_registered " . strtotime($user['date_registered']) . " is different from the time() " . time()); + $this->assertTrue( + $time <= strtotime($user['date_registered']) && strtotime($user['date_registered']) <= time(), + "the date_registered " . strtotime($user['date_registered']) . " is different from the time() " . time() + ); // check that password and token are properly set $this->assertEquals(60, strlen($user['password'])); @@ -487,10 +491,14 @@ public function testGetUsers() ); $expectedUsers = array($user1, $user2, $user3); $this->assertEquals($expectedUsers, $users); - $this->assertEquals(array($user1), - $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag'))); - $this->assertEquals(array($user1, $user2), - $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag,geggeqge632ge56a4qag'))); + $this->assertEquals( + array($user1), + $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag')) + ); + $this->assertEquals( + array($user1, $user2), + $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag,geggeqge632ge56a4qag')) + ); } public function testGetUsers_withViewAccess_shouldThrowAnException() @@ -1168,8 +1176,10 @@ private function addSites($numberOfSites) for ($index = 0; $index < $numberOfSites; $index++) { $name = "test" . ($index + 1); - $idSites[] = APISitesManager::getInstance()->addSite($name, - array("http://piwik.net", "http://piwik.com/test/")); + $idSites[] = APISitesManager::getInstance()->addSite( + $name, + array("http://piwik.net", "http://piwik.com/test/") + ); } return $idSites; diff --git a/plugins/VisitFrequency/Controller.php b/plugins/VisitFrequency/Controller.php index 7c6bb1c00c5..4128e42e1ae 100644 --- a/plugins/VisitFrequency/Controller.php +++ b/plugins/VisitFrequency/Controller.php @@ -71,8 +71,13 @@ public function getEvolutionGraph() } } - $view = $this->getLastUnitGraphAcrossPlugins($this->pluginName, __FUNCTION__, $columns, - $selectableColumns, $documentation); + $view = $this->getLastUnitGraphAcrossPlugins( + $this->pluginName, + __FUNCTION__, + $columns, + $selectableColumns, + $documentation + ); if (empty($view->config->columns_to_display)) { $view->config->columns_to_display = array('nb_visits_returning'); diff --git a/plugins/VisitorInterest/API.php b/plugins/VisitorInterest/API.php index 5f08685badf..77b3241bed8 100644 --- a/plugins/VisitorInterest/API.php +++ b/plugins/VisitorInterest/API.php @@ -66,7 +66,13 @@ public function getNumberOfVisitsPerPage($idSite, $period, $date, $segment = fal public function getNumberOfVisitsByDaysSinceLast($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable( - Archiver::DAYS_SINCE_LAST_RECORD_NAME, $idSite, $period, $date, $segment, Metrics::INDEX_NB_VISITS); + Archiver::DAYS_SINCE_LAST_RECORD_NAME, + $idSite, + $period, + $date, + $segment, + Metrics::INDEX_NB_VISITS + ); $dataTable->queueFilter('AddSegmentByRangeLabel', array('daysSinceLastVisit')); $dataTable->queueFilter('BeautifyRangeLabels', array(Piwik::translate('Intl_OneDay'), Piwik::translate('Intl_NDays'))); return $dataTable; @@ -85,7 +91,13 @@ public function getNumberOfVisitsByDaysSinceLast($idSite, $period, $date, $segme public function getNumberOfVisitsByVisitCount($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable( - Archiver::VISITS_COUNT_RECORD_NAME, $idSite, $period, $date, $segment, Metrics::INDEX_NB_VISITS); + Archiver::VISITS_COUNT_RECORD_NAME, + $idSite, + $period, + $date, + $segment, + Metrics::INDEX_NB_VISITS + ); $dataTable->queueFilter('AddSegmentByRangeLabel', array('visitCount')); $dataTable->queueFilter('BeautifyRangeLabels', array( diff --git a/plugins/VisitorInterest/RecordBuilders/Engagement.php b/plugins/VisitorInterest/RecordBuilders/Engagement.php index f92a96551c3..096893dc546 100644 --- a/plugins/VisitorInterest/RecordBuilders/Engagement.php +++ b/plugins/VisitorInterest/RecordBuilders/Engagement.php @@ -43,17 +43,29 @@ protected function aggregate(ArchiveProcessor $archiveProcessor): array // collect our extra aggregate select fields $selects = array(); $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - 'visit_total_time', Archiver::getSecondsGap(), 'log_visit', $prefixes[Archiver::TIME_SPENT_RECORD_NAME] + 'visit_total_time', + Archiver::getSecondsGap(), + 'log_visit', + $prefixes[Archiver::TIME_SPENT_RECORD_NAME] )); $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - 'visit_total_actions', Archiver::$pageGap, 'log_visit', $prefixes[Archiver::PAGES_VIEWED_RECORD_NAME] + 'visit_total_actions', + Archiver::$pageGap, + 'log_visit', + $prefixes[Archiver::PAGES_VIEWED_RECORD_NAME] )); $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - 'visitor_count_visits', Archiver::$visitNumberGap, 'log_visit', $prefixes[Archiver::VISITS_COUNT_RECORD_NAME] + 'visitor_count_visits', + Archiver::$visitNumberGap, + 'log_visit', + $prefixes[Archiver::VISITS_COUNT_RECORD_NAME] )); $selects = array_merge($selects, LogAggregator::getSelectsFromRangedColumn( - 'FLOOR(log_visit.visitor_seconds_since_last / 86400)', Archiver::$daysSinceLastVisitGap, 'log_visit', $prefixes[Archiver::DAYS_SINCE_LAST_RECORD_NAME], + 'FLOOR(log_visit.visitor_seconds_since_last / 86400)', + Archiver::$daysSinceLastVisitGap, + 'log_visit', + $prefixes[Archiver::DAYS_SINCE_LAST_RECORD_NAME], $restrictToReturningVisitors = true )); diff --git a/plugins/VisitsSummary/API.php b/plugins/VisitsSummary/API.php index 4ed57e1e9ac..9c62eadbea9 100644 --- a/plugins/VisitsSummary/API.php +++ b/plugins/VisitsSummary/API.php @@ -118,8 +118,10 @@ public function getSumVisitsLengthPretty($idSite, $period, $date, $segment = fal $table = $this->getSumVisitsLength($idSite, $period, $date, $segment); if (is_object($table)) { - $table->filter('ColumnCallbackReplace', - array('sum_visit_length', array($formatter, 'getPrettyTimeFromSeconds'), array(true))); + $table->filter( + 'ColumnCallbackReplace', + array('sum_visit_length', array($formatter, 'getPrettyTimeFromSeconds'), array(true)) + ); } else { $table = $formatter->getPrettyTimeFromSeconds($table, true); } diff --git a/plugins/VisitsSummary/Controller.php b/plugins/VisitsSummary/Controller.php index 31e00d9b7f8..d399c60358c 100644 --- a/plugins/VisitsSummary/Controller.php +++ b/plugins/VisitsSummary/Controller.php @@ -117,8 +117,13 @@ public function getEvolutionGraph() } // $callingAction may be specified to distinguish between // "VisitsSummary_WidgetLastVisits" and "VisitsSummary_WidgetOverviewGraph" - $view = $this->getLastUnitGraphAcrossPlugins($this->pluginName, __FUNCTION__, $columns, - $selectableColumns, $documentation); + $view = $this->getLastUnitGraphAcrossPlugins( + $this->pluginName, + __FUNCTION__, + $columns, + $selectableColumns, + $documentation + ); if (empty($view->config->columns_to_display)) { $view->config->columns_to_display = array('nb_visits'); diff --git a/tests/PHPUnit/Fixtures/DisablePluginArchive.php b/tests/PHPUnit/Fixtures/DisablePluginArchive.php index ff130924aed..2568e186e93 100644 --- a/tests/PHPUnit/Fixtures/DisablePluginArchive.php +++ b/tests/PHPUnit/Fixtures/DisablePluginArchive.php @@ -61,19 +61,19 @@ private function trackVisits() // testing URL excluded parameters $parameterToExclude = 'excluded_parameter'; APISitesManager::getInstance()->updateSite( - $idSite, - 'new name', - $url = array('http://site.com'), - $ecommerce = 0, - $siteSearch = 0, - $searchKeywordParameters = null, - $searchCategoryParameters = null, - $excludedIps = null, - $parameterToExclude . ',anotherParameter', - $timezone = null, - $currency = null, - $group = null, - $startDate = null + $idSite, + 'new name', + $url = array('http://site.com'), + $ecommerce = 0, + $siteSearch = 0, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = null, + $parameterToExclude . ',anotherParameter', + $timezone = null, + $currency = null, + $group = null, + $startDate = null ); // Record 1st page view diff --git a/tests/PHPUnit/Fixtures/InvalidVisits.php b/tests/PHPUnit/Fixtures/InvalidVisits.php index 881ca250192..319ff2cf677 100644 --- a/tests/PHPUnit/Fixtures/InvalidVisits.php +++ b/tests/PHPUnit/Fixtures/InvalidVisits.php @@ -102,10 +102,26 @@ private function trackVisits() // test unknown url exclusion works $urls = array("http://piwik.net", "http://my.stuff.com/"); - API::getInstance()->updateSite($idSite, $siteName = null, $urls, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParams = null, - $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, - $keepUrlFragments = null, $type = null, $settings = null, $excludeUnknownUrls = 1); + API::getInstance()->updateSite( + $idSite, + $siteName = null, + $urls, + $ecommerce = null, + $siteSearch = null, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = null, + $excludedQueryParams = null, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepUrlFragments = null, + $type = null, + $settings = null, + $excludeUnknownUrls = 1 + ); Cache::regenerateCacheWebsiteAttributes([1]); $t->setIp("125.4.5.6"); @@ -118,10 +134,26 @@ private function trackVisits() // undo exclude unknown urls change (important when multiple fixtures are setup together, as is done in OmniFixture) - API::getInstance()->updateSite($idSite, $siteName = null, $urls, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParams = null, - $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, - $keepUrlFragments = null, $type = null, $settings = null, $excludeUnknownUrls = 0); + API::getInstance()->updateSite( + $idSite, + $siteName = null, + $urls, + $ecommerce = null, + $siteSearch = null, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = null, + $excludedQueryParams = null, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepUrlFragments = null, + $type = null, + $settings = null, + $excludeUnknownUrls = 0 + ); Cache::regenerateCacheWebsiteAttributes([1]); try { diff --git a/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php b/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php index 2c739a06c20..bad019036d2 100644 --- a/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php +++ b/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php @@ -66,13 +66,21 @@ public function setUpWebsitesAndGoals() } if (!self::siteCreated($idSite = 2)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'Piwik test two', - $siteUrl = 'http://example-site-two.com'); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'Piwik test two', + $siteUrl = 'http://example-site-two.com' + ); } if (!self::siteCreated($idSite = 3)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'Piwik test three', - $siteUrl = 'http://example-site-three.com'); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'Piwik test three', + $siteUrl = 'http://example-site-three.com' + ); } } diff --git a/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php b/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php index e47ac948ff1..898990154af 100644 --- a/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php +++ b/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php @@ -72,22 +72,48 @@ public function setUpWebsitesAndGoals() if (!self::goalExists($idSite = 1, $idGoal = 1)) { APIGoals::getInstance()->addGoal( - $this->idSite, $xssTesting->forTwig("goal name"), 'url', 'http', 'contains', false, 5, false, $xssTesting->forTwig("goal description")); + $this->idSite, + $xssTesting->forTwig("goal name"), + 'url', + 'http', + 'contains', + false, + 5, + false, + $xssTesting->forTwig("goal description") + ); } if (!self::siteCreated($idSite = 2)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = $xssTesting->forAngular('Piwik test two'), - $siteUrl = 'http://example-site-two.com'); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = $xssTesting->forAngular('Piwik test two'), + $siteUrl = 'http://example-site-two.com' + ); } if (!self::goalExists($idSite = 2, $idGoal = 2)) { APIGoals::getInstance()->addGoal( - $this->idSite, $xssTesting->forAngular("second goal"), 'url', 'http', 'contains', false, 5, false, $xssTesting->forAngular("goal description")); + $this->idSite, + $xssTesting->forAngular("second goal"), + 'url', + 'http', + 'contains', + false, + 5, + false, + $xssTesting->forAngular("goal description") + ); } if (!self::siteCreated($idSite = 3)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'Piwik test three', - $siteUrl = 'http://example-site-three.com'); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'Piwik test three', + $siteUrl = 'http://example-site-three.com' + ); } } @@ -96,7 +122,11 @@ public function addAnnotations() $xssTesting = new XssTesting(); APIAnnotations::getInstance()->add($this->idSite, '2012-08-09', "Note 1", $starred = 1); APIAnnotations::getInstance()->add( - $this->idSite, '2012-08-08', $xssTesting->forTwig("annotation"), $starred = 0); + $this->idSite, + '2012-08-08', + $xssTesting->forTwig("annotation"), + $starred = 0 + ); APIAnnotations::getInstance()->add($this->idSite, '2012-08-10', $xssTesting->forAngular("Annotation note 3"), $starred = 1); } diff --git a/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php b/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php index 81c510d10b4..76b8f8c04df 100644 --- a/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php +++ b/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php @@ -224,7 +224,8 @@ protected function trackVisit(\MatomoTracker $t, $fixtureCounter, $visitorCounte $date = $date->addHour(0.05); $t->setForceVisitDateTime($date->getDatetime()); - $r = $t->doTrackEvent('Cat' . $visitorCounter, + $r = $t->doTrackEvent( + 'Cat' . $visitorCounter, 'Action' . $visitorCounter, 'Name' . $visitorCounter, 345.678 + $visitorCounter diff --git a/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php b/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php index 9f10cbe46c8..960528a198d 100644 --- a/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php +++ b/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php @@ -250,7 +250,8 @@ private function trackAction(\MatomoTracker $t, $actionType, $visitorCounter, $a { if ($actionType == 'pageview') { self::checkResponse($t->doTrackPageView( - is_null($actionNum) ? "title_$visitorCounter" : "title_$visitorCounter / title_$actionNum")); + is_null($actionNum) ? "title_$visitorCounter" : "title_$visitorCounter / title_$actionNum" + )); } else if ($actionType == 'download') { $root = is_null($actionNum) ? "http://cloudsite$visitorCounter.com" : "http://cloudsite$visitorCounter.com/$actionNum"; diff --git a/tests/PHPUnit/Fixtures/SomePageGoalVisitsWithConversions.php b/tests/PHPUnit/Fixtures/SomePageGoalVisitsWithConversions.php index 97e7035f4c8..284755f0375 100644 --- a/tests/PHPUnit/Fixtures/SomePageGoalVisitsWithConversions.php +++ b/tests/PHPUnit/Fixtures/SomePageGoalVisitsWithConversions.php @@ -47,21 +47,40 @@ private function setUpWebsitesAndGoals() // Newsletter signup goal if (!self::goalExists($idSite = 1, $idGoal = 1)) { - APIGoals::getInstance()->addGoal($this->idSite, 'Goal 1', 'event_action', 'click', - 'contains', false, 10); + APIGoals::getInstance()->addGoal( + $this->idSite, + 'Goal 1', + 'event_action', + 'click', + 'contains', + false, + 10 + ); } // Contact me signup goal if (!self::goalExists($idSite = 1, $idGoal = 2)) { - APIGoals::getInstance()->addGoal($this->idSite, 'Goal "<2~$%+"', 'event_action', 'press', - 'contains', false, 10); + APIGoals::getInstance()->addGoal( + $this->idSite, + 'Goal "<2~$%+"', + 'event_action', + 'press', + 'contains', + false, + 10 + ); } } private function setUpSegment() { - APISegmentEditor::getInstance()->add('goalsByCountry', 'countryCode==' . $this->segmentCountryCode, - $this->idSite, true, true); + APISegmentEditor::getInstance()->add( + 'goalsByCountry', + 'countryCode==' . $this->segmentCountryCode, + $this->idSite, + true, + true + ); } private function doPageVisit($t, string $pageLetter, ?string $subPage = null) diff --git a/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php b/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php index 6739e8580e7..39776a577bb 100644 --- a/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php +++ b/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php @@ -41,16 +41,28 @@ private function setUpWebsitesAndGoals() // First, a goal that is only recorded once per visit if (!self::goalExists($idSite = 1, $idGoal = 1)) { API::getInstance()->addGoal( - $this->idSite, 'triggered js ONCE', 'title', 'Thank you', 'contains', $caseSensitive = false, - $revenue = 10, $allowMultipleConversions = false + $this->idSite, + 'triggered js ONCE', + 'title', + 'Thank you', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = false ); } // Second, a goal allowing multiple conversions if (!self::goalExists($idSite = 1, $idGoal = 2)) { API::getInstance()->addGoal( - $this->idSite, 'triggered js MULTIPLE ALLOWED', 'manually', '', '', $caseSensitive = false, - $revenue = 10, $allowMultipleConversions = true + $this->idSite, + 'triggered js MULTIPLE ALLOWED', + 'manually', + '', + '', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = true ); } diff --git a/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php b/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php index 2835500b46c..0b2646f9763 100644 --- a/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php +++ b/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php @@ -35,8 +35,13 @@ public function tearDown(): void private function setUpWebsitesAndGoals() { if (!self::siteCreated($idSite = 1)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'Piwik test', $siteUrl = false, - $siteSearch = 1); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'Piwik test', + $siteUrl = false, + $siteSearch = 1 + ); } } @@ -117,9 +122,15 @@ private function trackVisits() $this->trackPageView($tracker, 0.2, 'page/one.html', $laterDate); $this->trackPageView($tracker, 0.25, '', $laterDate, $pageViewType = 'download'); $this->trackPageView($tracker, 0.3, 'page/one.html', $laterDate); - $this->trackPageView($tracker, 0.35, 'page/search.html#q=anotherkwd', $laterDate, - $pageViewType = 'site-search', $searchKeyword = 'anotherkwd', - $searchCategory = 'mysearchcat'); + $this->trackPageView( + $tracker, + 0.35, + 'page/search.html#q=anotherkwd', + $laterDate, + $pageViewType = 'site-search', + $searchKeyword = 'anotherkwd', + $searchCategory = 'mysearchcat' + ); $tracker->setIp('156.5.3.8'); diff --git a/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php b/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php index aad330e4509..10833c033a1 100644 --- a/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php +++ b/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php @@ -43,15 +43,27 @@ private function setUpWebsitesAndGoals() if (!self::goalExists($idSite = 1, $idGoal = 1)) { API::getInstance()->addGoal( - $this->idSite, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, - $revenue = 10, $allowMultipleConversions = 1 + $this->idSite, + 'Goal 1 - Thank you', + 'title', + 'Thank you', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = 1 ); } if (!self::goalExists($idSite = 1, $idGoal = 2)) { API::getInstance()->addGoal( - $this->idSite, 'Goal 2 - Hello', 'url', 'hellow', 'contains', $caseSensitive = false, - $revenue = 10, $allowMultipleConversions = 0 + $this->idSite, + 'Goal 2 - Hello', + 'url', + 'hellow', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = 0 ); } diff --git a/tests/PHPUnit/Fixtures/ThreeVisitsWithCustomEvents.php b/tests/PHPUnit/Fixtures/ThreeVisitsWithCustomEvents.php index f13ad515272..f74758b95c3 100644 --- a/tests/PHPUnit/Fixtures/ThreeVisitsWithCustomEvents.php +++ b/tests/PHPUnit/Fixtures/ThreeVisitsWithCustomEvents.php @@ -38,8 +38,18 @@ private function setUpWebsitesAndGoals() // These two goals are to check events don't trigger for URL or Title matching APIGoals::getInstance()->addGoal($this->idSite, 'triggered js', 'url', 'webradio', 'contains'); APIGoals::getInstance()->addGoal($this->idSite, 'triggered js', 'title', 'Music', 'contains'); - $idGoalTriggeredOnEventCategory = APIGoals::getInstance()->addGoal($this->idSite, 'event matching', 'event_category', 'CategoryTriggersGoal', 'contains', false, - 8, true, '', true); + $idGoalTriggeredOnEventCategory = APIGoals::getInstance()->addGoal( + $this->idSite, + 'event matching', + 'event_category', + 'CategoryTriggersGoal', + 'contains', + false, + 8, + true, + '', + true + ); $this->assertEquals($idGoalTriggeredOnEventCategory, self::$idGoalTriggeredOnEventCategory); } diff --git a/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php b/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php index 72761184353..24f9afaaf68 100644 --- a/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php +++ b/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php @@ -47,8 +47,14 @@ private function setUpWebsitesAndGoals() if (!self::goalExists($this->idSite, $this->idGoalStandard)) { API::getInstance()->addGoal( - $this->idSite, 'title match, triggered ONCE', 'title', 'incredible', 'contains', - $caseSensitive = false, $revenue = 10, $allowMultipleConversions = true + $this->idSite, + 'title match, triggered ONCE', + 'title', + 'incredible', + 'contains', + $caseSensitive = false, + $revenue = 10, + $allowMultipleConversions = true ); } } diff --git a/tests/PHPUnit/Fixtures/TwoSitesManyVisitsOverSeveralDaysWithSearchEngineReferrers.php b/tests/PHPUnit/Fixtures/TwoSitesManyVisitsOverSeveralDaysWithSearchEngineReferrers.php index 68233a231d5..1a2642b740f 100644 --- a/tests/PHPUnit/Fixtures/TwoSitesManyVisitsOverSeveralDaysWithSearchEngineReferrers.php +++ b/tests/PHPUnit/Fixtures/TwoSitesManyVisitsOverSeveralDaysWithSearchEngineReferrers.php @@ -43,9 +43,20 @@ private function setUpWebsitesAndGoals() $siteCreated = $this->dateTime; if (!self::siteCreated($idSite = 1)) { - self::createWebsite($siteCreated, 0, false, false, 1, null, - null, null, null, 0, null, - self::EXCLUDED_REFERRER_URL); + self::createWebsite( + $siteCreated, + 0, + false, + false, + 1, + null, + null, + null, + null, + 0, + null, + self::EXCLUDED_REFERRER_URL + ); } if (!self::goalExists($idSite = 1, $idGoal = 1)) { @@ -54,7 +65,15 @@ private function setUpWebsitesAndGoals() if (!self::goalExists($idSite = 1, $idGoal = 2)) { API::getInstance()->addGoal( - $this->idSite, 'another triggered php', 'manually', '', '', false, false, true); + $this->idSite, + 'another triggered php', + 'manually', + '', + '', + false, + false, + true + ); } if (!self::siteCreated($idSite = 2)) { diff --git a/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php b/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php index 26ec6126072..3c66300bd47 100644 --- a/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php +++ b/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php @@ -67,15 +67,39 @@ private function setUpWebsitesAndGoals() } APISitesManager::getInstance()->updateSite( - $this->idSite1, "Site 1", $urls = null, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, - $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, - $startDate = null, $excludedUserAgents = null, $keepURLFragments = 2); // KEEP_URL_FRAGMENT_NO No for idSite 1 + $this->idSite1, + "Site 1", + $urls = null, + $ecommerce = null, + $siteSearch = null, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = null, + $excludedQueryParameters = null, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 2 + ); // KEEP_URL_FRAGMENT_NO No for idSite 1 APISitesManager::getInstance()->updateSite( - $this->idSite2, "Site 2", $urls = null, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, - $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, - $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); // KEEP_URL_FRAGMENT_YES Yes for idSite 2 + $this->idSite2, + "Site 2", + $urls = null, + $ecommerce = null, + $siteSearch = null, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = null, + $excludedQueryParameters = null, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); // KEEP_URL_FRAGMENT_YES Yes for idSite 2 } public function trackVisits() diff --git a/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php b/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php index 5589b50745b..96e48638b31 100644 --- a/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php +++ b/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php @@ -106,12 +106,24 @@ private function trackVisits() self::checkResponse($visitorA->doTrackGoal($idGoal)); if ($this->doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); + $visitorA->setCustomVariable( + $id = 2, + $name = 'var1', + $value = 'looking at "profile page"', + $scope = 'page' + ); + $visitorA->setCustomVariable( + $id = 3, + $name = 'var2', + $value = '\'looking at "\profile page"\'', + $scope = 'page' + ); + $visitorA->setCustomVariable( + $id = 4, + $name = 'var3', + $value = '\\looking at "\profile page"\\', + $scope = 'page' + ); self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); } diff --git a/tests/PHPUnit/Fixtures/VisitsInDifferentTimezones.php b/tests/PHPUnit/Fixtures/VisitsInDifferentTimezones.php index a4f6a21abf5..6315805c240 100644 --- a/tests/PHPUnit/Fixtures/VisitsInDifferentTimezones.php +++ b/tests/PHPUnit/Fixtures/VisitsInDifferentTimezones.php @@ -34,14 +34,28 @@ private function setUpWebsitesAndGoals() { // tests run in UTC, the Tracker in UTC if (!self::siteCreated($idSite = 1)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'site in AST', $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = 'America/Barbados' /* AST = UTC-4 */); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'site in AST', + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = 'America/Barbados' /* AST = UTC-4 */ + ); } if (!self::siteCreated($idSite = 2)) { - self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'site in UTC', $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = 'UTC'); + self::createWebsite( + $this->dateTime, + $ecommerce = 0, + $siteName = 'site in UTC', + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = 'UTC' + ); } } diff --git a/tests/PHPUnit/Framework/TestRequest/Collection.php b/tests/PHPUnit/Framework/TestRequest/Collection.php index 2ac1b517833..fa152db0312 100644 --- a/tests/PHPUnit/Framework/TestRequest/Collection.php +++ b/tests/PHPUnit/Framework/TestRequest/Collection.php @@ -245,7 +245,8 @@ protected function generateApiUrlPermutations($parametersToSet) // if no subtable found, throw if (!isset($parametersToSet['idSubtable'])) { throw new Exception( - "Cannot find subtable to load for $apiId in {$this->testConfig->supertableApi}."); + "Cannot find subtable to load for $apiId in {$this->testConfig->supertableApi}." + ); } } diff --git a/tests/PHPUnit/Integration/ArchiveProcessingTest.php b/tests/PHPUnit/Integration/ArchiveProcessingTest.php index fc67079474b..0ad6f76dd4b 100644 --- a/tests/PHPUnit/Integration/ArchiveProcessingTest.php +++ b/tests/PHPUnit/Integration/ArchiveProcessingTest.php @@ -291,10 +291,13 @@ public function testTableInsertBatch() $table = Common::prefixTable('site_url'); $data = $this->_getDataInsert(); try { - $didWeUseBulk = BatchInsert::tableInsertBatch($table, + $didWeUseBulk = BatchInsert::tableInsertBatch( + $table, array('idsite', 'url'), $data, - $throwException = true, 'utf8'); + $throwException = true, + 'utf8' + ); } catch (Exception $e) { $didWeUseBulk = $e->getMessage(); } @@ -362,10 +365,13 @@ public function testTableInsertBatchBlob() $data = $this->_getBlobDataInsert(); try { - $didWeUseBulk = BatchInsert::tableInsertBatch($table, + $didWeUseBulk = BatchInsert::tableInsertBatch( + $table, array('idarchive', 'name', 'idsite', 'date1', 'date2', 'period', 'ts_archived', 'value'), $data, - $throwException = true, $charset = 'latin1'); + $throwException = true, + $charset = 'latin1' + ); } catch (Exception $e) { $didWeUseBulk = $e->getMessage(); } diff --git a/tests/PHPUnit/Integration/ArchiveProcessor/LoaderTest.php b/tests/PHPUnit/Integration/ArchiveProcessor/LoaderTest.php index 08163f26726..1d46fde2d76 100644 --- a/tests/PHPUnit/Integration/ArchiveProcessor/LoaderTest.php +++ b/tests/PHPUnit/Integration/ArchiveProcessor/LoaderTest.php @@ -1635,8 +1635,10 @@ private function insertArchive(Parameters $params, $tsArchived = null, $visits = $archiveWriter->finalizeArchive(); if ($tsArchived) { - Db::query("UPDATE " . ArchiveTableCreator::getNumericTable($params->getPeriod()->getDateStart()) . " SET ts_archived = ?", - [Date::factory($tsArchived)->getDatetime()]); + Db::query( + "UPDATE " . ArchiveTableCreator::getNumericTable($params->getPeriod()->getDateStart()) . " SET ts_archived = ?", + [Date::factory($tsArchived)->getDatetime()] + ); } } @@ -1657,8 +1659,10 @@ private function insertArchiveData($archiveRows) $table = !empty($row['is_blob_data']) ? ArchiveTableCreator::getBlobTable($d) : ArchiveTableCreator::getNumericTable($d); $tsArchived = isset($row['ts_archived']) ? $row['ts_archived'] : Date::now()->getDatetime(); - Db::query("INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived]); + Db::query( + "INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived] + ); } if (!empty($archiveRows)) { diff --git a/tests/PHPUnit/Integration/ArchiveTest.php b/tests/PHPUnit/Integration/ArchiveTest.php index d90132c768c..6c324af966b 100644 --- a/tests/PHPUnit/Integration/ArchiveTest.php +++ b/tests/PHPUnit/Integration/ArchiveTest.php @@ -292,8 +292,16 @@ public function test_shouldNotArchivePeriodsStartingInTheFuture() public function test_shouldArchivePeriodsStartingInTheFuture_IfWebSiteLocalTimeIsInNextDay() { // Create a site with a timezone ahead of UTC - $idSite = Fixture::createWebsite('2014-05-06', 1, false, false, - 1, null, null, 'Pacific/Auckland'); + $idSite = Fixture::createWebsite( + '2014-05-06', + 1, + false, + false, + 1, + null, + null, + 'Pacific/Auckland' + ); self::$fixture->getTestEnvironment()->overrideConfig('General', 'browser_archiving_disabled_enforce', 0); self::$fixture->getTestEnvironment()->overrideConfig('General', 'archiving_range_force_on_browser_request', 1); @@ -348,8 +356,16 @@ public function test_shouldNotArchivePeriodsStartingInTheFuture_IfWebSiteLocalTi { // Create a site with a timezone behind of UTC - $idSite = Fixture::createWebsite('2014-05-06', 1, false, false, - 1, null, null, 'America/Vancouver'); // -8hrs + $idSite = Fixture::createWebsite( + '2014-05-06', + 1, + false, + false, + 1, + null, + null, + 'America/Vancouver' + ); // -8hrs self::$fixture->getTestEnvironment()->overrideConfig('General', 'browser_archiving_disabled_enforce', 0); self::$fixture->getTestEnvironment()->overrideConfig('General', 'archiving_range_force_on_browser_request', 1); diff --git a/tests/PHPUnit/Integration/Concurrency/DistributedListTest.php b/tests/PHPUnit/Integration/Concurrency/DistributedListTest.php index cd658a5ab9e..7a65bf17a6c 100644 --- a/tests/PHPUnit/Integration/Concurrency/DistributedListTest.php +++ b/tests/PHPUnit/Integration/Concurrency/DistributedListTest.php @@ -140,9 +140,11 @@ private function initOptionValue($data = false) $data = $data ?: self::$defaultOptionValues; $optionTable = Common::prefixTable('option'); - Db::query("INSERT INTO `$optionTable` (option_name, option_value, autoload) VALUES (?, ?, ?) + Db::query( + "INSERT INTO `$optionTable` (option_name, option_value, autoload) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE option_value = ?", - array(self::TEST_OPTION_NAME, serialize($data), 0, serialize($data))); + array(self::TEST_OPTION_NAME, serialize($data), 0, serialize($data)) + ); } private function getOptionValueForList() diff --git a/tests/PHPUnit/Integration/DataAccess/ArchiveInvalidatorTest.php b/tests/PHPUnit/Integration/DataAccess/ArchiveInvalidatorTest.php index 639a0d013d7..78dd626cfcd 100644 --- a/tests/PHPUnit/Integration/DataAccess/ArchiveInvalidatorTest.php +++ b/tests/PHPUnit/Integration/DataAccess/ArchiveInvalidatorTest.php @@ -138,8 +138,14 @@ public function test_markArchivesAsInvalidated_doesNotInvalidatePartialArchives( /** @var ArchiveInvalidator $archiveInvalidator */ $archiveInvalidator = self::$fixture->piwikEnvironment->getContainer()->get('Piwik\Archive\ArchiveInvalidator'); - $archiveInvalidator->markArchivesAsInvalidated([1], ['2020-03-03'], 'day', - null, $cascadeDown = true, false); + $archiveInvalidator->markArchivesAsInvalidated( + [1], + ['2020-03-03'], + 'day', + null, + $cascadeDown = true, + false + ); $invalidatedArchives = $this->getInvalidatedArchives(); $this->assertEmpty($invalidatedArchives); @@ -603,8 +609,16 @@ public function test_markArchivesAsInvalidated_invalidatesPastPurgeThreshold_ifF /** @var ArchiveInvalidator $archiveInvalidator */ $archiveInvalidator = self::$fixture->piwikEnvironment->getContainer()->get('Piwik\Archive\ArchiveInvalidator'); - $result = $archiveInvalidator->markArchivesAsInvalidated(array(1), array($dateBeforeThreshold), 'day', - null, false, false, null, true); + $result = $archiveInvalidator->markArchivesAsInvalidated( + array(1), + array($dateBeforeThreshold), + 'day', + null, + false, + false, + null, + true + ); $this->assertEquals($thresholdDate->toString(), $result->minimumDateWithLogs); @@ -1730,8 +1744,16 @@ public function test_markArchivesAsInvalidated_invalidatesIndividualPluginNames( ]; $plugin = 'ExamplePlugin'; - $this->test_markArchivesAsInvalidated_MarksCorrectArchivesAsInvalidated($idSites, $dates, $period, $segment, $cascadeDown, $expectedIdArchives, - $expectedInvalidatedArchives, $plugin); + $this->test_markArchivesAsInvalidated_MarksCorrectArchivesAsInvalidated( + $idSites, + $dates, + $period, + $segment, + $cascadeDown, + $expectedIdArchives, + $expectedInvalidatedArchives, + $plugin + ); } public function test_markArchivesAsInvalidated_invalidatesIndividualReports() @@ -1750,8 +1772,16 @@ public function test_markArchivesAsInvalidated_invalidatesIndividualReports() ]; $report = 'ExamplePlugin.someReport'; - $this->test_markArchivesAsInvalidated_MarksCorrectArchivesAsInvalidated($idSites, $dates, $period, $segment, $cascadeDown, $expectedIdArchives, - $expectedInvalidatedArchives, $report); + $this->test_markArchivesAsInvalidated_MarksCorrectArchivesAsInvalidated( + $idSites, + $dates, + $period, + $segment, + $cascadeDown, + $expectedIdArchives, + $expectedInvalidatedArchives, + $report + ); } public function test_markArchivesAsInvalidated_doesNotInsertDuplicateInvalidations() @@ -1785,10 +1815,22 @@ public function test_markArchivesAsInvalidated_doesNotInsertDuplicateInvalidatio $this->insertInvalidations($existingInvalidations); - $archiveInvalidator->markArchivesAsInvalidated([1], ['2020-03-04', '2020-05-06'], 'week', - $segment, $cascadeDown = true, false); - $archiveInvalidator->markArchivesAsInvalidated([1], ['2020-05-01'], 'year', - $segment, $cascadeDown = false, 'aReport'); + $archiveInvalidator->markArchivesAsInvalidated( + [1], + ['2020-03-04', '2020-05-06'], + 'week', + $segment, + $cascadeDown = true, + false + ); + $archiveInvalidator->markArchivesAsInvalidated( + [1], + ['2020-05-01'], + 'year', + $segment, + $cascadeDown = false, + 'aReport' + ); $expectedInvalidations = [ array ( diff --git a/tests/PHPUnit/Integration/DataAccess/ArchiveSelectorTest.php b/tests/PHPUnit/Integration/DataAccess/ArchiveSelectorTest.php index 4aef1966620..8b54b49ef36 100644 --- a/tests/PHPUnit/Integration/DataAccess/ArchiveSelectorTest.php +++ b/tests/PHPUnit/Integration/DataAccess/ArchiveSelectorTest.php @@ -61,8 +61,14 @@ public function test_getArchiveIds_handlesCutOffGroupConcat() $this->insertArchiveData($archiveRows); - $archiveIds = ArchiveSelector::getArchiveIds([1], [Factory::build('day', '2020-03-01')], new Segment('', [1]), ['Funnels'], - true, true); + $archiveIds = ArchiveSelector::getArchiveIds( + [1], + [Factory::build('day', '2020-03-01')], + new Segment('', [1]), + ['Funnels'], + true, + true + ); $expected = [ 'done.Funnels' => [ @@ -167,8 +173,10 @@ private function insertArchiveData($archiveRows) $d = Date::factory($row['date1']); $table = !empty($row['is_blob_data']) ? ArchiveTableCreator::getBlobTable($d) : ArchiveTableCreator::getNumericTable($d); $tsArchived = isset($row['ts_archived']) ? $row['ts_archived'] : Date::now()->getDatetime(); - Db::query("INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived]); + Db::query( + "INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived] + ); } } diff --git a/tests/PHPUnit/Integration/DataAccess/ArchiveTableDaoTest.php b/tests/PHPUnit/Integration/DataAccess/ArchiveTableDaoTest.php index d5c6f553c1c..fe0561db33a 100644 --- a/tests/PHPUnit/Integration/DataAccess/ArchiveTableDaoTest.php +++ b/tests/PHPUnit/Integration/DataAccess/ArchiveTableDaoTest.php @@ -33,7 +33,8 @@ public function setUp(): void parent::setUp(); $this->archiveTableDao = self::$fixture->piwikEnvironment->getContainer()->get( - 'Piwik\DataAccess\ArchiveTableDao'); + 'Piwik\DataAccess\ArchiveTableDao' + ); ArchiveTableCreator::getBlobTable(Date::factory('2015-01-01')); ArchiveTableCreator::getNumericTable(Date::factory('2015-01-01')); @@ -50,35 +51,101 @@ public function test_getArchiveTableAnalysis_QueriesNumericAndBlobTable_Includin $this->insertArchive($tableMonth, $idSite = 2, $period = 'day', $date1 = '2015-01-03', $date2 = '2015-01-03'); $this->insertArchive($tableMonth, $idSite = 1, $period = 'week', $date1 = '2015-01-04', $date2 = '2015-01-11'); $this->insertArchive($tableMonth, $idSite = 3, $period = 'month', $date1 = '2015-01-01', $date2 = '2015-01-31'); - $this->insertArchive($tableMonth, $idSite = 4, $period = 'year', $date1 = '2015-01-01', $date2 = '2015-12-31', - $segment = 'browserCode==FF'); + $this->insertArchive( + $tableMonth, + $idSite = 4, + $period = 'year', + $date1 = '2015-01-01', + $date2 = '2015-12-31', + $segment = 'browserCode==FF' + ); $this->insertArchive($tableMonth, $idSite = 1, $period = 'range', $date1 = '2015-01-15', $date2 = '2015-01-20'); // invalid - $this->insertArchive($tableMonth, $idSite = 1, $period = 'day', $date1 = '2015-01-01', $date2 = '2015-01-01', - $segment = false, $doneValue = ArchiveWriter::DONE_INVALIDATED); - $this->insertArchive($tableMonth, $idSite = 1, $period = 'day', $date1 = '2015-01-01', $date2 = '2015-01-01', - $segment = false, $doneValue = ArchiveWriter::DONE_INVALIDATED); - $this->insertArchive($tableMonth, $idSite = 4, $period = 'year', $date1 = '2015-01-01', $date2 = '2015-12-31', - $segment = 'browserCode==FF', $doneValue = ArchiveWriter::DONE_INVALIDATED); + $this->insertArchive( + $tableMonth, + $idSite = 1, + $period = 'day', + $date1 = '2015-01-01', + $date2 = '2015-01-01', + $segment = false, + $doneValue = ArchiveWriter::DONE_INVALIDATED + ); + $this->insertArchive( + $tableMonth, + $idSite = 1, + $period = 'day', + $date1 = '2015-01-01', + $date2 = '2015-01-01', + $segment = false, + $doneValue = ArchiveWriter::DONE_INVALIDATED + ); + $this->insertArchive( + $tableMonth, + $idSite = 4, + $period = 'year', + $date1 = '2015-01-01', + $date2 = '2015-12-31', + $segment = 'browserCode==FF', + $doneValue = ArchiveWriter::DONE_INVALIDATED + ); // temporary - $this->insertArchive($tableMonth, $idSite = 1, $period = 'week', $date1 = '2015-01-04', $date2 = '2015-01-11', - $segment = false, $doneValue = ArchiveWriter::DONE_OK_TEMPORARY); - $this->insertArchive($tableMonth, $idSite = 3, $period = 'month', $date1 = '2015-01-01', $date2 = '2015-01-31', - $segment = 'daysSinceFirstVisit==1', $doneValue = ArchiveWriter::DONE_OK_TEMPORARY); + $this->insertArchive( + $tableMonth, + $idSite = 1, + $period = 'week', + $date1 = '2015-01-04', + $date2 = '2015-01-11', + $segment = false, + $doneValue = ArchiveWriter::DONE_OK_TEMPORARY + ); + $this->insertArchive( + $tableMonth, + $idSite = 3, + $period = 'month', + $date1 = '2015-01-01', + $date2 = '2015-01-31', + $segment = 'daysSinceFirstVisit==1', + $doneValue = ArchiveWriter::DONE_OK_TEMPORARY + ); // error - $this->insertArchive($tableMonth, $idSite = 1, $period = 'week', $date1 = '2015-01-04', $date2 = '2015-01-11', - $segment = false, $doneValue = ArchiveWriter::DONE_ERROR); - $this->insertArchive($tableMonth, $idSite = 3, $period = 'month', $date1 = '2015-01-01', $date2 = '2015-01-31', - $segment = 'daysSinceFirstVisit==1', $doneValue = ArchiveWriter::DONE_ERROR); + $this->insertArchive( + $tableMonth, + $idSite = 1, + $period = 'week', + $date1 = '2015-01-04', + $date2 = '2015-01-11', + $segment = false, + $doneValue = ArchiveWriter::DONE_ERROR + ); + $this->insertArchive( + $tableMonth, + $idSite = 3, + $period = 'month', + $date1 = '2015-01-01', + $date2 = '2015-01-31', + $segment = 'daysSinceFirstVisit==1', + $doneValue = ArchiveWriter::DONE_ERROR + ); // blob only - $this->insertBlobArchive($tableMonth, $idSite = 1, $period = 'day', $date1 = '2015-01-20', - $date2 = '2015-01-20'); - $this->insertBlobArchive($tableMonth, $idSite = 2, $period = 'day', $date1 = '2015-01-21', - $date2 = '2015-01-21', $segment = 'browserCode==SF'); + $this->insertBlobArchive( + $tableMonth, + $idSite = 1, + $period = 'day', + $date1 = '2015-01-20', + $date2 = '2015-01-20' + ); + $this->insertBlobArchive( + $tableMonth, + $idSite = 2, + $period = 'day', + $date1 = '2015-01-21', + $date2 = '2015-01-21', + $segment = 'browserCode==SF' + ); $expectedStats = array( '1.2015-01-01.2015-01-01.1' => array( diff --git a/tests/PHPUnit/Integration/DataAccess/ArchiveWriterTest.php b/tests/PHPUnit/Integration/DataAccess/ArchiveWriterTest.php index 1dc8bff4436..79a791c826b 100644 --- a/tests/PHPUnit/Integration/DataAccess/ArchiveWriterTest.php +++ b/tests/PHPUnit/Integration/DataAccess/ArchiveWriterTest.php @@ -306,8 +306,10 @@ private function insertArchiveData($archiveRows) $table = ArchiveTableCreator::getNumericTable($d); $tsArchived = isset($row['ts_archived']) ? $row['ts_archived'] : Date::now()->getDatetime(); - Db::query("INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived]); + Db::query( + "INSERT INTO `$table` (idarchive, idsite, period, date1, date2, `name`, `value`, ts_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + [$row['idarchive'], $row['idsite'], $row['period'], $row['date1'], $row['date2'], $row['name'], $row['value'], $tsArchived] + ); } } diff --git a/tests/PHPUnit/Integration/DataAccess/LogAggregatorTest.php b/tests/PHPUnit/Integration/DataAccess/LogAggregatorTest.php index 55d79792ad7..872b68bfab7 100644 --- a/tests/PHPUnit/Integration/DataAccess/LogAggregatorTest.php +++ b/tests/PHPUnit/Integration/DataAccess/LogAggregatorTest.php @@ -539,8 +539,16 @@ public function test_queryVisitsByDimension_ShouldAddJoinQueryHintOriginHintMaxE DatabaseConfig::setConfigValue('enable_first_table_join_prefix', '1'); $this->logAggregator->setQueryOriginHint('MyPluginName'); - $query = $this->logAggregator->getQueryByDimensionSql($dimensions, false, [], false, false, - false, 5, false); + $query = $this->logAggregator->getQueryByDimensionSql( + $dimensions, + false, + [], + false, + false, + false, + 5, + false + ); $expected = [ 'sql' => "SELECT /*+ MAX_EXECUTION_TIME(5000) */ /*+ JOIN_PREFIX(log_visit) */ /* sites 1 */ /* 2010-03-01,2010-03-31 */ /* MyPluginName */ diff --git a/tests/PHPUnit/Integration/DataTable/Filter/PivotByDimensionTest.php b/tests/PHPUnit/Integration/DataTable/Filter/PivotByDimensionTest.php index ccc56c4ff56..9a8136201f2 100644 --- a/tests/PHPUnit/Integration/DataTable/Filter/PivotByDimensionTest.php +++ b/tests/PHPUnit/Integration/DataTable/Filter/PivotByDimensionTest.php @@ -211,8 +211,13 @@ public function test_filter_CorrectlyCreatesPivotTable_WhenSubtablesHaveNoRows() $table = $this->getTableToFilter(false); - $pivotFilter = new PivotByDimension($table, "CustomVariables.getCustomVariables", "CustomVariables.CustomVariableValue", - 'nb_visits', $fetchBySegment = false); + $pivotFilter = new PivotByDimension( + $table, + "CustomVariables.getCustomVariables", + "CustomVariables.CustomVariableValue", + 'nb_visits', + $fetchBySegment = false + ); $pivotFilter->filter($table); $expectedRows = array( diff --git a/tests/PHPUnit/Integration/DocumentationGeneratorTest.php b/tests/PHPUnit/Integration/DocumentationGeneratorTest.php index 076f3771667..dd6eb235c48 100644 --- a/tests/PHPUnit/Integration/DocumentationGeneratorTest.php +++ b/tests/PHPUnit/Integration/DocumentationGeneratorTest.php @@ -41,30 +41,36 @@ public function test_CheckDocumentation() public function test_CheckIfMethodComment_ContainsHideAnnotation_andText() { $annotation = '@hideForAll test test'; - EventDispatcher::getInstance()->addObserver('API.DocumentationGenerator.@hideForAll', + EventDispatcher::getInstance()->addObserver( + 'API.DocumentationGenerator.@hideForAll', function (&$hide) { $hide = true; - }); + } + ); $this->assertEquals(Proxy::getInstance()->shouldHideAPIMethod($annotation), true); } public function test_CheckIfMethodComment_ContainsHideAnnotation_only() { $annotation = '@hideForAll'; - EventDispatcher::getInstance()->addObserver('API.DocumentationGenerator.@hideForAll', + EventDispatcher::getInstance()->addObserver( + 'API.DocumentationGenerator.@hideForAll', function (&$hide) { $hide = true; - }); + } + ); $this->assertEquals(Proxy::getInstance()->shouldHideAPIMethod($annotation), true); } public function test_CheckIfMethodComment_DoesNotContainHideAnnotation() { $annotation = '@not found here'; - EventDispatcher::getInstance()->addObserver('API.DocumentationGenerator.@hello', + EventDispatcher::getInstance()->addObserver( + 'API.DocumentationGenerator.@hello', function (&$hide) { $hide = true; - }); + } + ); $this->assertEquals(Proxy::getInstance()->shouldHideAPIMethod($annotation), false); } } diff --git a/tests/PHPUnit/Integration/Measurable/MeasurableSettingsTest.php b/tests/PHPUnit/Integration/Measurable/MeasurableSettingsTest.php index c8e7d26d339..127807b8987 100644 --- a/tests/PHPUnit/Integration/Measurable/MeasurableSettingsTest.php +++ b/tests/PHPUnit/Integration/Measurable/MeasurableSettingsTest.php @@ -35,10 +35,17 @@ public function setUp(): void if (!Fixture::siteCreated($this->idSite)) { $type = WebsiteType::ID; - Fixture::createWebsite('2015-01-01 00:00:00', - $ecommerce = 0, $siteName = false, $siteUrl = false, - $siteSearch = 1, $searchKeywordParameters = null, - $searchCategoryParameters = null, $timezone = null, $type); + Fixture::createWebsite( + '2015-01-01 00:00:00', + $ecommerce = 0, + $siteName = false, + $siteUrl = false, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $timezone = null, + $type + ); } $this->settings = $this->createSettings(); diff --git a/tests/PHPUnit/Integration/ProfessionalSupport/AdvertisingTest.php b/tests/PHPUnit/Integration/ProfessionalSupport/AdvertisingTest.php index c78e3931308..aa33eb46d04 100644 --- a/tests/PHPUnit/Integration/ProfessionalSupport/AdvertisingTest.php +++ b/tests/PHPUnit/Integration/ProfessionalSupport/AdvertisingTest.php @@ -86,8 +86,13 @@ public function test_addPromoCampaignParametersToUrl_withoutContentWithoutQuery( public function test_addPromoCampaignParametersToUrl_withContentWithoutQuery() { - $link = $this->advertising->addPromoCampaignParametersToUrl($this->exampleUrl, 'MyName', 'Installation_Start', - 'MyContent', 'MySource'); + $link = $this->advertising->addPromoCampaignParametersToUrl( + $this->exampleUrl, + 'MyName', + 'Installation_Start', + 'MyContent', + 'MySource' + ); $this->assertSame($this->exampleUrl . '?mtm_campaign=MyName&mtm_source=MySource&mtm_medium=Installation_Start.MyContent', $link); } diff --git a/tests/PHPUnit/Integration/ReleaseCheckListTest.php b/tests/PHPUnit/Integration/ReleaseCheckListTest.php index 091ce661a48..1f101aaa133 100644 --- a/tests/PHPUnit/Integration/ReleaseCheckListTest.php +++ b/tests/PHPUnit/Integration/ReleaseCheckListTest.php @@ -262,11 +262,13 @@ private function assertFilesDoNotContain($files, $patternFailIfFound, $allowedFi } } - $this->assertEmpty($foundPatterns, - sprintf("Forbidden pattern \"%s\" was found in the following files ---> please manually delete these files from Git. \n\n\t%s", - $patternFailIfFound, - implode("\n\t", $foundPatterns) - ) + $this->assertEmpty( + $foundPatterns, + sprintf( + "Forbidden pattern \"%s\" was found in the following files ---> please manually delete these files from Git. \n\n\t%s", + $patternFailIfFound, + implode("\n\t", $foundPatterns) + ) ); } @@ -292,8 +294,11 @@ public function testCheckThatGivenPluginsAreDisabledByDefault() 'DBStats' ); foreach ($pluginsShouldBeDisabled as $pluginName) { - $this->assertNotContains($pluginName, $this->globalConfig['Plugins']['Plugins'], - "Plugin $pluginName is enabled by default but shouldn't."); + $this->assertNotContains( + $pluginName, + $this->globalConfig['Plugins']['Plugins'], + "Plugin $pluginName is enabled by default but shouldn't." + ); } } @@ -398,9 +403,11 @@ public function test_directoriesShouldBeChmod755() $chmod = substr(decoct(fileperms($pathToTest)), -3); $valid = array('777', '775', '755'); $command = "find $pluginsPath -type d -exec chmod 755 {} +"; - $this->assertTrue(in_array($chmod, $valid), - "Some directories within plugins/ are not chmod 755 \n\nGot: $chmod for : $pathToTest \n\n" . - "Run this command to set all directories to 755: \n$command\n"); + $this->assertTrue( + in_array($chmod, $valid), + "Some directories within plugins/ are not chmod 755 \n\nGot: $chmod for : $pathToTest \n\n" . + "Run this command to set all directories to 755: \n$command\n" + ); } } @@ -436,7 +443,8 @@ public function test_DirectoriesInPluginsFolder_areKnown() $enabled = in_array($pluginName, $pluginsBundledWithPiwik); - $this->assertTrue( $enabled + $disabled === 1, + $this->assertTrue( + $enabled + $disabled === 1, "Plugin $pluginName should be either enabled (in global.ini.php) or disabled (in Piwik\\Application\\Kernel\\PluginList). It is currently (enabled=" . (int)$enabled . ", disabled=" . (int)$disabled . ")" ); @@ -503,11 +511,13 @@ public function test_piwikJs_minified_isUpToDate() { shell_exec("sed '//,/<\/DEBUG>/d' < " . PIWIK_DOCUMENT_ROOT . "/js/piwik.js | sed 's/eval/replacedEvilString/' | java -jar " . PIWIK_DOCUMENT_ROOT . "/tests/resources/yuicompressor/yuicompressor-2.4.8.jar --type js --line-break 1000 | sed 's/replacedEvilString/eval/' | sed 's/^[/][*]/\/*!/' > " . PIWIK_DOCUMENT_ROOT . "/piwik-minified.js"); - $this->assertFileEquals(PIWIK_DOCUMENT_ROOT . '/piwik-minified.js', + $this->assertFileEquals( + PIWIK_DOCUMENT_ROOT . '/piwik-minified.js', PIWIK_DOCUMENT_ROOT . '/piwik.js', 'minified /piwik.js is out of date, please re-generate the minified files using instructions in /js/README' ); - $this->assertFileEquals(PIWIK_DOCUMENT_ROOT . '/piwik-minified.js', + $this->assertFileEquals( + PIWIK_DOCUMENT_ROOT . '/piwik-minified.js', PIWIK_DOCUMENT_ROOT . '/js/piwik.min.js', 'minified /js/piwik.min.js is out of date, please re-generate the minified files using instructions in /js/README' ); @@ -619,7 +629,8 @@ public function test_TotalPiwikFilesSize_isWithinReasonnableSize() $this->assertLessThan( $maximumTotalFilesizesExpectedInMb * 1024 * 1024, $sumFilesizes, - sprintf("Sum of all files should be less than $maximumTotalFilesizesExpectedInMb Mb. + sprintf( + "Sum of all files should be less than $maximumTotalFilesizesExpectedInMb Mb. \nGot total file sizes of: %d Mb. \nBiggest files: %s", $sumFilesizes / 1024 / 1024, diff --git a/tests/PHPUnit/Integration/ReportTest.php b/tests/PHPUnit/Integration/ReportTest.php index 4f09c0bfedb..a31b42e0280 100644 --- a/tests/PHPUnit/Integration/ReportTest.php +++ b/tests/PHPUnit/Integration/ReportTest.php @@ -382,7 +382,9 @@ public function test_fetch_ShouldUseCorrectApiUrl() $proxyMock = $this->getMockBuilder('stdClass')->addMethods(array('call', '__construct'))->getMock(); $proxyMock->expects($this->once())->method('call')->with( - '\\Piwik\\Plugins\\ExampleReport\\API', 'getExampleReport', array( + '\\Piwik\\Plugins\\ExampleReport\\API', + 'getExampleReport', + array( 'idSite' => 1, 'date' => '2012-01-02', 'format' => 'original', @@ -406,7 +408,9 @@ public function test_fetchSubtable_ShouldUseCorrectApiUrl() $proxyMock = $this->getMockBuilder('stdClass')->addMethods(array('call', '__construct'))->getMock(); $proxyMock->expects($this->once())->method('call')->with( - '\\Piwik\\Plugins\\Referrers\\API', 'getSearchEnginesFromKeywordId', array( + '\\Piwik\\Plugins\\Referrers\\API', + 'getSearchEnginesFromKeywordId', + array( 'idSubtable' => 23, 'idSite' => 1, 'date' => '2012-01-02', diff --git a/tests/PHPUnit/Integration/ServeStaticFileTest.php b/tests/PHPUnit/Integration/ServeStaticFileTest.php index 062157d0b0e..466c89a7197 100644 --- a/tests/PHPUnit/Integration/ServeStaticFileTest.php +++ b/tests/PHPUnit/Integration/ServeStaticFileTest.php @@ -168,8 +168,10 @@ public function test_firstAccessNoCompression() $this->assertEquals(filesize(TEST_FILE_LOCATION), $responseInfo["size_download"]); // Tests if returned modified date is correctly set - $this->assertEquals(gmdate('D, d M Y H:i:s', filemtime(TEST_FILE_LOCATION)) . ' GMT', - $this->getLastModifiedValue($fullResponse)); + $this->assertEquals( + gmdate('D, d M Y H:i:s', filemtime(TEST_FILE_LOCATION)) . ' GMT', + $this->getLastModifiedValue($fullResponse) + ); // Tests if cache control headers are correctly set $this->assertEquals("public, must-revalidate", $this->getCacheControlValue($fullResponse)); @@ -422,8 +424,11 @@ public function test_partialFileServeNoCompression() // check $partialResponse $this->assertEquals(PARTIAL_BYTE_END - PARTIAL_BYTE_START, $responseInfo["size_download"]); - $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START, - PARTIAL_BYTE_END - PARTIAL_BYTE_START); + $expectedPartialContents = substr( + file_get_contents(TEST_FILE_LOCATION), + PARTIAL_BYTE_START, + PARTIAL_BYTE_END - PARTIAL_BYTE_START + ); $this->assertEquals($expectedPartialContents, $partialResponse); } @@ -450,8 +455,11 @@ public function test_partialFileServeWithCompression() $this->assertFileNotExists($this->getCompressedFileLocation() . ".gz"); // check $partialResponse - $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START, - PARTIAL_BYTE_END - PARTIAL_BYTE_START); + $expectedPartialContents = substr( + file_get_contents(TEST_FILE_LOCATION), + PARTIAL_BYTE_START, + PARTIAL_BYTE_END - PARTIAL_BYTE_START + ); $this->assertEquals($expectedPartialContents, $partialResponse); $this->removeCompressedFiles(); diff --git a/tests/PHPUnit/Integration/Settings/Storage/StorageTest.php b/tests/PHPUnit/Integration/Settings/Storage/StorageTest.php index 1971379a64e..747c391e29e 100644 --- a/tests/PHPUnit/Integration/Settings/Storage/StorageTest.php +++ b/tests/PHPUnit/Integration/Settings/Storage/StorageTest.php @@ -95,8 +95,10 @@ public function test_save_shouldPersistValueInDatabase() $this->storage->setValue($this->settingName, 'myRandomVal'); $this->storage->save(); - $this->assertEquals(array($this->settingName => 'myRandomVal'), - $this->loadValuesFromBackend()); + $this->assertEquals( + array($this->settingName => 'myRandomVal'), + $this->loadValuesFromBackend() + ); } public function test_save_shouldPersistMultipleValues_ContainingInt() @@ -105,8 +107,10 @@ public function test_save_shouldPersistMultipleValues_ContainingInt() $this->storage->setValue('mySecondName', 5); $this->storage->save(); - $this->assertEquals(array($this->settingName => 'myRandomVal', 'mySecondName' => 5), - $this->loadValuesFromBackend()); + $this->assertEquals( + array($this->settingName => 'myRandomVal', 'mySecondName' => 5), + $this->loadValuesFromBackend() + ); } public function test_save_shouldNotClearTrackerCacheEntries_IfThereWasNoChange() diff --git a/tests/PHPUnit/Integration/Tracker/ActionTest.php b/tests/PHPUnit/Integration/Tracker/ActionTest.php index 86877a321d3..6d0b0729c18 100644 --- a/tests/PHPUnit/Integration/Tracker/ActionTest.php +++ b/tests/PHPUnit/Integration/Tracker/ActionTest.php @@ -163,10 +163,22 @@ public function getTestUrls() public function testExcludeQueryParametersNone($url, $filteredUrl) { $this->setUpRootAccess(); - $idSite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = '', $excludedQueryParameters = '', $timezone = null, $currency = null, - $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); + $idSite = API::getInstance()->addSite( + "site1", + array('http://example.org'), + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = '', + $excludedQueryParameters = '', + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); $this->assertEquals($filteredUrl[0], PageUrl::excludeQueryParametersFromUrl($url, $idSite)); } @@ -197,10 +209,22 @@ public function getTestAdvertisingClickIdUrls() public function testExcludeQueryParametersAdvertisingClickIds($url, $filteredUrl) { $this->setUpRootAccess(); - $idSite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = '', $excludedQueryParameters = '', $timezone = null, $currency = null, - $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); + $idSite = API::getInstance()->addSite( + "site1", + array('http://example.org'), + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = '', + $excludedQueryParameters = '', + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); $this->assertEquals($filteredUrl, PageUrl::excludeQueryParametersFromUrl($url, $idSite)); } @@ -234,10 +258,22 @@ public function testExcludeQueryParametersSiteExcluded($url, $filteredUrl) { $excludedQueryParameters = 'p4, p2, var[value][date]'; $this->setUpRootAccess(); - $idSite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = '', $excludedQueryParameters, $timezone = null, $currency = null, - $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); + $idSite = API::getInstance()->addSite( + "site1", + array('http://example.org'), + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = '', + $excludedQueryParameters, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); $this->assertEquals($filteredUrl[1], PageUrl::excludeQueryParametersFromUrl($url, $idSite)); } @@ -249,10 +285,22 @@ public function testExcludeQueryParametersRegExSiteExcluded($url, $filteredUrl) { $excludedQueryParameters = '/p[4|2]/, /^var.*/'; $this->setUpRootAccess(); - $idSite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = '', $excludedQueryParameters, $timezone = null, $currency = null, - $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); + $idSite = API::getInstance()->addSite( + "site1", + array('http://example.org'), + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = '', + $excludedQueryParameters, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); $this->assertEquals($filteredUrl[1], PageUrl::excludeQueryParametersFromUrl($url, $idSite)); } @@ -266,10 +314,22 @@ public function testExcludeQueryParametersSiteAndGlobalExcluded($url, $filteredU $excludedQueryParameters = 'P2,var[value][date]'; $excludedGlobalParameters = 'blabla, P4'; $this->setUpRootAccess(); - $idSite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = '', $excludedQueryParameters, $timezone = null, $currency = null, - $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); + $idSite = API::getInstance()->addSite( + "site1", + array('http://example.org'), + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIps = '', + $excludedQueryParameters, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgents = null, + $keepURLFragments = 1 + ); API::getInstance()->setGlobalExcludedQueryParameters($excludedGlobalParameters); $this->assertEquals($filteredUrl[1], PageUrl::excludeQueryParametersFromUrl($url, $idSite)); } diff --git a/tests/PHPUnit/Integration/Tracker/ModelTest.php b/tests/PHPUnit/Integration/Tracker/ModelTest.php index eb5c2ec80ec..4fb498e3a39 100644 --- a/tests/PHPUnit/Integration/Tracker/ModelTest.php +++ b/tests/PHPUnit/Integration/Tracker/ModelTest.php @@ -222,9 +222,11 @@ private function assertLogActionTableContainsTestAction($idaction) private function insertSingleDuplicateAction() { $logActionTable = Common::prefixTable('log_action'); - Db::query("INSERT INTO $logActionTable (idaction, name, type, url_prefix, hash) VALUES (?, ?, ?, ?, CRC32(?))", + Db::query( + "INSERT INTO $logActionTable (idaction, name, type, url_prefix, hash) VALUES (?, ?, ?, ?, CRC32(?))", array(5, self::TEST_ACTION_NAME, self::TEST_ACTION_TYPE, self::TEST_ACTION_URL_PREFIX, - self::TEST_ACTION_NAME)); + self::TEST_ACTION_NAME) + ); } private function insertManyActions() diff --git a/tests/PHPUnit/Integration/Tracker/TrackerCodeGeneratorTest.php b/tests/PHPUnit/Integration/Tracker/TrackerCodeGeneratorTest.php index a63b26cd8d5..3c1ed9b0862 100644 --- a/tests/PHPUnit/Integration/Tracker/TrackerCodeGeneratorTest.php +++ b/tests/PHPUnit/Integration/Tracker/TrackerCodeGeneratorTest.php @@ -30,13 +30,22 @@ public function testJavascriptTrackingCode_withAllOptions() 'https://another-domain/piwik' ); $idSite = \Piwik\Plugins\SitesManager\API::getInstance()->addSite('Site name here <-->', $urls); - $jsTag = $generator->generate($idSite, 'http://piwik-server/piwik', - $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true, + $jsTag = $generator->generate( + $idSite, + 'http://piwik-server/piwik', + $mergeSubdomains = true, + $groupPageTitlesByDomain = true, + $mergeAliasUrls = true, $visitorCustomVariables = array(array("name", "value"), array("name 2", "value 2")), $pageCustomVariables = array(array("page cvar", "page cvar value")), - $customCampaignNameQueryParam = "campaignKey", $customCampaignKeywordParam = "keywordKey", - $doNotTrack = true, $disableCookies = false, $trackNoScript = true, - $crossDomain = true, $excludedQueryParams = array("uid", "aid")); + $customCampaignNameQueryParam = "campaignKey", + $customCampaignKeywordParam = "keywordKey", + $doNotTrack = true, + $disableCookies = false, + $trackNoScript = true, + $crossDomain = true, + $excludedQueryParams = array("uid", "aid") + ); $expected = "<!-- Matomo --> <script> @@ -109,13 +118,22 @@ public function testJavascriptTrackingCode_withAllOptionsAndProtocolOverwrite() $codeImpl['protocol'] = 'https://'; }); - $jsTag = $generator->generate($idSite = 1, $piwikUrl = 'http://localhost/piwik', - $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true, + $jsTag = $generator->generate( + $idSite = 1, + $piwikUrl = 'http://localhost/piwik', + $mergeSubdomains = true, + $groupPageTitlesByDomain = true, + $mergeAliasUrls = true, $visitorCustomVariables = array(array("name", "value"), array("name 2", "value 2")), $pageCustomVariables = array(array("page cvar", "page cvar value")), - $customCampaignNameQueryParam = "campaignKey", $customCampaignKeywordParam = "keywordKey", - $doNotTrack = true, $disableCookies = false, $trackNoScript = false, - $crossDomain = false, $excludedQueryParams = array("uid", "aid")); + $customCampaignNameQueryParam = "campaignKey", + $customCampaignKeywordParam = "keywordKey", + $doNotTrack = true, + $disableCookies = false, + $trackNoScript = false, + $crossDomain = false, + $excludedQueryParams = array("uid", "aid") + ); $expected = "<!-- Matomo --> <script> @@ -158,13 +176,22 @@ public function testJavascriptTrackingCode_withAllOptionsAndOptionsBeforeTracker $codeImpl['optionsBeforeTrackerUrl'] .= "_paq.push(['setAPIUrl', 'http://localhost/statistics']);\n "; }); - $jsTag = $generator->generate($idSite = 1, $piwikUrl = 'http://localhost/piwik', - $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true, + $jsTag = $generator->generate( + $idSite = 1, + $piwikUrl = 'http://localhost/piwik', + $mergeSubdomains = true, + $groupPageTitlesByDomain = true, + $mergeAliasUrls = true, $visitorCustomVariables = array(array("name", "value"), array("name 2", "value 2")), $pageCustomVariables = array(array("page cvar", "page cvar value")), - $customCampaignNameQueryParam = "campaignKey", $customCampaignKeywordParam = "keywordKey", - $doNotTrack = true, $disableCookies = false, $trackNoScript = false, - $crossDomain = false, $excludedQueryParams = array("uid", "aid")); + $customCampaignNameQueryParam = "campaignKey", + $customCampaignKeywordParam = "keywordKey", + $doNotTrack = true, + $disableCookies = false, + $trackNoScript = false, + $crossDomain = false, + $excludedQueryParams = array("uid", "aid") + ); $expected = "<!-- Matomo --> <script> @@ -208,8 +235,13 @@ public function testJavascriptTrackingCode_loadSync() $codeImpl['loadAsync'] = false; }); - $jsTag = $generator->generate($idSite = 1, $piwikUrl = 'http://localhost/piwik', - $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true); + $jsTag = $generator->generate( + $idSite = 1, + $piwikUrl = 'http://localhost/piwik', + $mergeSubdomains = true, + $groupPageTitlesByDomain = true, + $mergeAliasUrls = true + ); $expected = "<!-- Matomo --> <script> diff --git a/tests/PHPUnit/Integration/Tracker/VisitTest.php b/tests/PHPUnit/Integration/Tracker/VisitTest.php index ac8d1d80ac4..255e55c1036 100644 --- a/tests/PHPUnit/Integration/Tracker/VisitTest.php +++ b/tests/PHPUnit/Integration/Tracker/VisitTest.php @@ -98,8 +98,15 @@ public function test_worksWhenSiteDoesNotExist() */ public function testIsVisitorIpExcluded($excludedIp, $tests) { - $idsite = API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIp); + $idsite = API::getInstance()->addSite( + "name", + "http://piwik.net/", + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIp + ); $request = new RequestAuthenticated(array('idsite' => $idsite)); @@ -186,8 +193,14 @@ public function testExcludeByUrl($siteUrls, $excludeUnknownUrls, array $urlsTrac */ public function testVisitShouldNotBeExcluded_IfMadeViaChromeDataSaverCompressionProxy($ip, $isNonHumanBot) { - $idsite = API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null); + $idsite = API::getInstance()->addSite( + "name", + "http://piwik.net/", + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null + ); $request = new RequestAuthenticated(array('idsite' => $idsite, 'cip' => $ip)); @@ -259,10 +272,21 @@ public function getExcludedUserAgentTestData() */ public function testIsVisitorUserAgentExcluded($excludedUserAgent, $tests) { - $idsite = API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIp = null, - $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, - $excludedUserAgent); + $idsite = API::getInstance()->addSite( + "name", + "http://piwik.net/", + $ecommerce = 0, + $siteSearch = 1, + $searchKeywordParameters = null, + $searchCategoryParameters = null, + $excludedIp = null, + $excludedQueryParameters = null, + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + $excludedUserAgent + ); $request = new Request(array('idsite' => $idsite)); @@ -435,13 +459,17 @@ public function test_markArchivedReportsAsInvalidIfArchiveAlreadyFinished_should $oneHourAfterMidnight = $midnight->addHour(1)->getDatetime(); $oneHourBeforeMidnight = $midnight->subHour(1)->getDatetime(); - $idsite = API::getInstance()->addSite('name', 'http://piwik.net/', $ecommerce = null, + $idsite = API::getInstance()->addSite( + 'name', + 'http://piwik.net/', + $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, - $timezone = 'UTC+5'); + $timezone = 'UTC+5' + ); $expectedRemembered = array( substr($oneHourAfterMidnight, 0, 10) => array($idsite), diff --git a/tests/PHPUnit/Integration/Tracker/VisitorRecognizerTest.php b/tests/PHPUnit/Integration/Tracker/VisitorRecognizerTest.php index ffe1e59868d..25c36b4bd4e 100644 --- a/tests/PHPUnit/Integration/Tracker/VisitorRecognizerTest.php +++ b/tests/PHPUnit/Integration/Tracker/VisitorRecognizerTest.php @@ -32,8 +32,13 @@ class VisitorRecognizerTest extends IntegrationTestCase public function setUp(): void { parent::setUp(); - $this->recognizer = new VisitorRecognizer(true, 1800, 24000, - new Model(), EventDispatcher::getInstance()); + $this->recognizer = new VisitorRecognizer( + true, + 1800, + 24000, + new Model(), + EventDispatcher::getInstance() + ); Fixture::createWebsite('2020-01-01 02:03:04'); } diff --git a/tests/PHPUnit/System/DataComparisonTest.php b/tests/PHPUnit/System/DataComparisonTest.php index 39a823c5aec..7d27bd4d62c 100644 --- a/tests/PHPUnit/System/DataComparisonTest.php +++ b/tests/PHPUnit/System/DataComparisonTest.php @@ -34,7 +34,10 @@ public static function setUpBeforeClass(): void // the specific site and will be invalid in global context // Added to avoid further regressions like: https://github.com/matomo-org/matomo/issues/21573 $idDimension = \Piwik\Plugins\CustomDimensions\API::getInstance()->configureNewCustomDimension( - self::$fixture->idSite, 'test', CustomDimensions::SCOPE_VISIT, true + self::$fixture->idSite, + 'test', + CustomDimensions::SCOPE_VISIT, + true ); Fixture::clearInMemoryCaches(false); \Piwik\Plugins\SegmentEditor\API::getInstance()->add('custom dimension', "dimension$idDimension==test", self::$fixture->idSite); diff --git a/tests/PHPUnit/System/LabelFilterTest.php b/tests/PHPUnit/System/LabelFilterTest.php index 868bfabfb80..c57f2a107be 100644 --- a/tests/PHPUnit/System/LabelFilterTest.php +++ b/tests/PHPUnit/System/LabelFilterTest.php @@ -100,7 +100,8 @@ public function getApiForTesting() ' ' . // test trimming urlencode('incredible parent title! <>,;') . '>' . - urlencode('subtitle <>,;')), + urlencode('subtitle <>,;') + ), 'expanded' => 0 ) )); diff --git a/tests/PHPUnit/System/OneVisitorTwoVisitsTest.php b/tests/PHPUnit/System/OneVisitorTwoVisitsTest.php index ac3bec5097f..91d636a8606 100644 --- a/tests/PHPUnit/System/OneVisitorTwoVisitsTest.php +++ b/tests/PHPUnit/System/OneVisitorTwoVisitsTest.php @@ -222,7 +222,12 @@ public function testArchiveSitesWhenRestrictingToLogin() try { Archive::build( - 'all', 'day', self::$fixture->dateTime, $segment = false, $_restrictToLogin = 'anotherLogin'); + 'all', + 'day', + self::$fixture->dateTime, + $segment = false, + $_restrictToLogin = 'anotherLogin' + ); $this->fail("Restricting sites to invalid login did not return 0 sites."); } catch (Exception $ex) { diff --git a/tests/PHPUnit/Unit/ConfigTest.php b/tests/PHPUnit/Unit/ConfigTest.php index 567767c0cad..67255d7e470 100644 --- a/tests/PHPUnit/Unit/ConfigTest.php +++ b/tests/PHPUnit/Unit/ConfigTest.php @@ -30,12 +30,12 @@ public function __construct($configLocal, $configGlobal, $configCommon, $configC parent::__construct(); $this->iniFileChain = new DumpConfigTestMockIniFileChain( - array( + array( $this->pathGlobal => $configGlobal, $this->pathCommon => $configCommon, $this->pathLocal => $configLocal, - ), - $configCache + ), + $configCache ); } } diff --git a/tests/PHPUnit/Unit/DataTable/Filter/PrependSegmentFilterTest.php b/tests/PHPUnit/Unit/DataTable/Filter/PrependSegmentFilterTest.php index 79de18937ab..77e62be1de3 100644 --- a/tests/PHPUnit/Unit/DataTable/Filter/PrependSegmentFilterTest.php +++ b/tests/PHPUnit/Unit/DataTable/Filter/PrependSegmentFilterTest.php @@ -50,13 +50,15 @@ public function test_filter_shouldRemoveAllMetadataEntriesHavingTheGivenName() $this->table->filter($this->filter, array($prepend)); $metadata = $this->table->getRowsMetadata('segment'); - $this->assertSame(array( + $this->assertSame( + array( false, $prepend . 'country=NZ', false, $prepend . 'country=AU', $prepend), - $metadata); + $metadata + ); // should be still the same $metadata = $this->table->getRowsMetadata('test'); diff --git a/tests/PHPUnit/Unit/Tracker/ResponseTest.php b/tests/PHPUnit/Unit/Tracker/ResponseTest.php index 5fad45d72b1..1264278f37e 100644 --- a/tests/PHPUnit/Unit/Tracker/ResponseTest.php +++ b/tests/PHPUnit/Unit/Tracker/ResponseTest.php @@ -128,8 +128,10 @@ public function test_outputResponse_shouldOutputPiwikMessage_InCaseNothingWasTra $tracker->setCountOfLoggedRequests(0); $this->response->outputResponse($tracker); - $this->assertEquals("This resource is part of Matomo. Keep full control of your data with the leading free and open source web analytics & conversion optimisation platform.
\nThis file is the endpoint for the Matomo tracking API. If you want to access the Matomo UI or use the Reporting API, please use index.php instead.\n", - $this->response->getOutput()); + $this->assertEquals( + "This resource is part of Matomo. Keep full control of your data with the leading free and open source web analytics & conversion optimisation platform.
\nThis file is the endpoint for the Matomo tracking API. If you want to access the Matomo UI or use the Reporting API, please use index.php instead.\n", + $this->response->getOutput() + ); } public function test_getMessageFromException_ShouldNotOutputAnyDetails_IfErrorContainsDbCredentials() diff --git a/tests/PHPUnit/Unit/UrlHelperTest.php b/tests/PHPUnit/Unit/UrlHelperTest.php index 6f19e03f5a3..d5a1f8e2a36 100644 --- a/tests/PHPUnit/Unit/UrlHelperTest.php +++ b/tests/PHPUnit/Unit/UrlHelperTest.php @@ -169,24 +169,34 @@ public function testGetPathAndQueryFromUrl() $this->assertEquals('test/index.php?module=CoreHome', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php?module=CoreHome')); // Add parameters to existing params - $this->assertEquals('test/index.php?module=CoreHome&abc=123&def=456', - UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php?module=CoreHome', ['abc' => '123', 'def' => '456'])); + $this->assertEquals( + 'test/index.php?module=CoreHome&abc=123&def=456', + UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php?module=CoreHome', ['abc' => '123', 'def' => '456']) + ); // Add parameters with no existing params - $this->assertEquals('test/index.php?abc=123&def=456', - UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php', ['abc' => '123', 'def' => '456'])); + $this->assertEquals( + 'test/index.php?abc=123&def=456', + UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php', ['abc' => '123', 'def' => '456']) + ); // Preserve anchor - $this->assertEquals('test/index.php#anchor', - UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], true)); + $this->assertEquals( + 'test/index.php#anchor', + UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], true) + ); // Do not preserve anchor - $this->assertEquals('test/index.php', - UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], false)); + $this->assertEquals( + 'test/index.php', + UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], false) + ); // Add parameters with existing params, preserve anchor - $this->assertEquals('test/index.php#anchor?abc=123&def=456', - UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', ['abc' => '123', 'def' => '456'], true)); + $this->assertEquals( + 'test/index.php#anchor?abc=123&def=456', + UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', ['abc' => '123', 'def' => '456'], true) + ); } /** diff --git a/tests/PHPUnit/Unit/UrlTest.php b/tests/PHPUnit/Unit/UrlTest.php index 8f97831f621..7dd0cb6c8be 100644 --- a/tests/PHPUnit/Unit/UrlTest.php +++ b/tests/PHPUnit/Unit/UrlTest.php @@ -481,12 +481,16 @@ public function testAddCampaignParametersToMatomoLink_exceptIfDisabled() $_GET['action'] = 'trackingCodeGenerator'; Config::getInstance()->General['disable_tracking_matomo_app_links'] = 1; - $this->assertEquals('https://matomo.org/faq/123', - Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123')); + $this->assertEquals( + 'https://matomo.org/faq/123', + Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123') + ); Config::getInstance()->General['disable_tracking_matomo_app_links'] = 0; - $this->assertEquals('https://matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', - Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123')); + $this->assertEquals( + 'https://matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', + Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123') + ); } /**