diff options
author | Thomas Steur <thomas.steur@googlemail.com> | 2014-09-30 09:37:32 +0400 |
---|---|---|
committer | Thomas Steur <thomas.steur@googlemail.com> | 2014-09-30 09:37:32 +0400 |
commit | a00487b0b841c4b15463b591c7f62176c4b84d15 (patch) | |
tree | 6eb893ce356a4740e044c9cdadaf84ffb2095b9d /plugins | |
parent | 0edef3332289a7cbe54b58084b967907d1086d29 (diff) |
coding style fixes, some PHPStorm inspection fixes, improved readability of code, few refactorings, all as part of our code cleanup strategy
Diffstat (limited to 'plugins')
70 files changed, 1189 insertions, 601 deletions
diff --git a/plugins/API/API.php b/plugins/API/API.php index 00758ca6bb..c65c04fffe 100644 --- a/plugins/API/API.php +++ b/plugins/API/API.php @@ -259,7 +259,7 @@ class API extends \Piwik\Plugin\API SegmentExpression::MATCH_IS_NULL_OR_EMPTY, SegmentExpression::MATCH_NOT_EQUAL, ); - if(in_array($matchType, $acceptedMatches)) { + if (in_array($matchType, $acceptedMatches)) { return $value; } $message = "Invalid Segment match type: try using 'userId' segment with one of the following match types: %s."; @@ -524,7 +524,7 @@ class API extends \Piwik\Plugin\API */ public function getSuggestedValuesForSegment($segmentName, $idSite) { - if(empty(Config::getInstance()->General['enable_segment_suggested_values'])) { + if (empty(Config::getInstance()->General['enable_segment_suggested_values'])) { return array(); } Piwik::checkUserHasViewAccess($idSite); @@ -549,7 +549,7 @@ class API extends \Piwik\Plugin\API } // if period=range is disabled, do not proceed - if(!Period\Factory::isPeriodEnabledForAPI('range')) { + if (!Period\Factory::isPeriodEnabledForAPI('range')) { return array(); } diff --git a/plugins/API/Controller.php b/plugins/API/Controller.php index 9a6b3fc5e7..18e39d58a2 100644 --- a/plugins/API/Controller.php +++ b/plugins/API/Controller.php @@ -60,7 +60,7 @@ class Controller extends \Piwik\Plugin\Controller foreach ($segments as $segment) { // Eg. Event Value is a metric, not in the Visit metric category, // we make sure it is displayed along with the Events dimensions - if($segment['type'] == 'metric' && $segment['category'] != Piwik::translate('General_Visit')) { + if ($segment['type'] == 'metric' && $segment['category'] != Piwik::translate('General_Visit')) { $segment['type'] = 'dimension'; } diff --git a/plugins/API/RowEvolution.php b/plugins/API/RowEvolution.php index 7a5290c44f..b57a788050 100644 --- a/plugins/API/RowEvolution.php +++ b/plugins/API/RowEvolution.php @@ -279,7 +279,7 @@ class RowEvolution // note: some reports should not be filtered with AddColumnProcessedMetrics // specifically, reports without the Metrics::INDEX_NB_VISITS metric such as Goals.getVisitsUntilConversion & Goal.getDaysToConversion // this is because the AddColumnProcessedMetrics filter removes all datable rows lacking this metric - if( isset($metadata['metrics']['nb_visits']) + if ( isset($metadata['metrics']['nb_visits']) && !empty($label)) { $parameters['filter_add_columns_when_show_all_columns'] = '1'; } @@ -430,7 +430,7 @@ class RowEvolution $labelRow, $apiModule, $apiAction, $labelUseAbsoluteUrl); $prettyLabel = $labelRow->getColumn('label_html'); - if($prettyLabel !== false) { + if ($prettyLabel !== false) { $actualLabels[$labelIdx] = $prettyLabel; } diff --git a/plugins/Actions/Actions/ActionSiteSearch.php b/plugins/Actions/Actions/ActionSiteSearch.php index 9631aa0473..d19cfaa6fc 100644 --- a/plugins/Actions/Actions/ActionSiteSearch.php +++ b/plugins/Actions/Actions/ActionSiteSearch.php @@ -73,7 +73,7 @@ class ActionSiteSearch extends Action { $siteSearch = $this->detectSiteSearch($this->originalUrl); - if(empty($siteSearch)) { + if (empty($siteSearch)) { return false; } @@ -169,10 +169,10 @@ class ActionSiteSearch extends Action // @see excludeQueryParametersFromUrl() // Excluded the detected parameters from the URL $parametersToExclude = array($categoryParameterRaw, $keywordParameterRaw); - if(isset($parsedUrl['query'])) { + if (isset($parsedUrl['query'])) { $parsedUrl['query'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($parsedUrl['query']), $parametersToExclude); } - if(isset($parsedUrl['fragment'])) { + if (isset($parsedUrl['fragment'])) { $parsedUrl['fragment'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($parsedUrl['fragment']), $parametersToExclude); } } diff --git a/plugins/Actions/Archiver.php b/plugins/Actions/Archiver.php index 14d4214744..67408ced64 100644 --- a/plugins/Actions/Archiver.php +++ b/plugins/Actions/Archiver.php @@ -241,7 +241,7 @@ class Archiver extends \Piwik\Plugin\Archiver // 1) No result Keywords // 2) For each page view, count number of times the referrer page was a Site Search if ($this->isSiteSearchEnabled()) { - $this->updateQuerySelectFromForSiteSearch($select, $from); + $this->updateQuerySelectFromForSiteSearch($select, $from); } $this->archiveDayQueryProcess($select, $from, $where, $orderBy, $groupBy, "idaction_name", $rankingQuery); diff --git a/plugins/Annotations/AnnotationList.php b/plugins/Annotations/AnnotationList.php index 89a5b9131f..cf068e6f35 100755 --- a/plugins/Annotations/AnnotationList.php +++ b/plugins/Annotations/AnnotationList.php @@ -331,7 +331,7 @@ class AnnotationList if ($serialized !== false) { $result[$id] = @unserialize($serialized); - if(empty($result[$id])) { + if (empty($result[$id])) { // in case unserialize failed $result[$id] = array(); } diff --git a/plugins/CoreAdminHome/API.php b/plugins/CoreAdminHome/API.php index 530cc10156..a25a522cb4 100644 --- a/plugins/CoreAdminHome/API.php +++ b/plugins/CoreAdminHome/API.php @@ -66,19 +66,23 @@ class API extends \Piwik\Plugin\API public function invalidateArchivedReports($idSites, $dates, $period = false) { $idSites = Site::getIdSitesFromIdSitesString($idSites); + if (empty($idSites)) { throw new Exception("Specify a value for &idSites= as a comma separated list of website IDs, for which your token_auth has 'admin' permission"); } + Piwik::checkUserHasAdminAccess($idSites); - if(!empty($period)) { + if (!empty($period)) { $period = Period\Factory::build($period, Date::today()); } // Ensure the specified dates are valid $toInvalidate = $invalidDates = array(); + $dates = explode(',', trim($dates)); $dates = array_unique($dates); + foreach ($dates as $theDate) { $theDate = trim($theDate); try { @@ -141,7 +145,7 @@ class API extends \Piwik\Plugin\API } } - if(empty($minDate)) { + if (empty($minDate)) { throw new Exception("Check the 'dates' parameter is a valid date."); } @@ -169,7 +173,7 @@ class API extends \Piwik\Plugin\API $sql = implode(" OR ", $sql); $sqlPeriod = ""; - if($invalidateForPeriod) { + if ($invalidateForPeriod) { $sqlPeriod = " AND period = ? "; $bind[] = $invalidateForPeriod; } diff --git a/plugins/CoreAdminHome/Controller.php b/plugins/CoreAdminHome/Controller.php index 6b672d07e8..d1278607fd 100644 --- a/plugins/CoreAdminHome/Controller.php +++ b/plugins/CoreAdminHome/Controller.php @@ -278,7 +278,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin $successLogo = $logo->copyUploadedLogoToFilesystem(); $successFavicon = $logo->copyUploadedFaviconToFilesystem(); - if($successLogo || $successFavicon) { + if ($successLogo || $successFavicon) { return '1'; } return '0'; @@ -291,7 +291,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin private function saveGeneralSettings() { - if(!self::isGeneralSettingsAdminEnabled()) { + if (!self::isGeneralSettingsAdminEnabled()) { // General settings + Beta channel + SMTP settings is disabled return; } @@ -339,7 +339,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin { // Whether to display or not the general settings (cron, beta, smtp) $view->isGeneralSettingsAdminEnabled = self::isGeneralSettingsAdminEnabled(); - if($view->isGeneralSettingsAdminEnabled) { + if ($view->isGeneralSettingsAdminEnabled) { $this->displayWarningIfConfigFileNotWritable(); } diff --git a/plugins/CoreAdminHome/CustomLogo.php b/plugins/CoreAdminHome/CustomLogo.php index fe7e78ac6e..eda7ef0638 100644 --- a/plugins/CoreAdminHome/CustomLogo.php +++ b/plugins/CoreAdminHome/CustomLogo.php @@ -88,7 +88,7 @@ class CustomLogo */ public function isCustomLogoWritable() { - if(Config::getInstance()->General['enable_custom_logo_check'] == 0) { + if (Config::getInstance()->General['enable_custom_logo_check'] == 0) { return true; } $pathUserLogo = $this->getPathUserLogo(); @@ -196,7 +196,7 @@ class CustomLogo $image = imagecreatefrompng($file); break; case 'image/gif': - $image = imagecreatefromgif($file); + $image = imagecreatefromgif ($file); break; default: return false; diff --git a/plugins/CoreAdminHome/Tasks.php b/plugins/CoreAdminHome/Tasks.php index 461ca5ca52..d633b9fd5d 100644 --- a/plugins/CoreAdminHome/Tasks.php +++ b/plugins/CoreAdminHome/Tasks.php @@ -35,7 +35,7 @@ class Tasks extends \Piwik\Plugin\Tasks list($year, $month) = explode('_', $date); // Somehow we may have archive tables created with older dates, prevent exception from being thrown - if($year > 1990) { + if ($year > 1990) { ArchivePurger::purgeOutdatedArchives(Date::factory("$year-$month-15")); } } diff --git a/plugins/CoreConsole/Commands/GenerateTest.php b/plugins/CoreConsole/Commands/GenerateTest.php index a9ace19a8b..ff68eec784 100644 --- a/plugins/CoreConsole/Commands/GenerateTest.php +++ b/plugins/CoreConsole/Commands/GenerateTest.php @@ -42,7 +42,7 @@ class GenerateTest extends GeneratePluginBase ); $testClass = $this->getTestClass($testType); - if(!empty($testClass)) { + if (!empty($testClass)) { $replace['\PHPUnit_Framework_TestCase'] = $testClass; } @@ -167,7 +167,7 @@ class GenerateTest extends GeneratePluginBase */ protected function getTestFilesWhitelist($testType) { - if('Integration' == $testType) { + if ('Integration' == $testType) { return array( '/.gitignore', '/tests', diff --git a/plugins/CoreConsole/TravisYmlView.php b/plugins/CoreConsole/TravisYmlView.php index cb4fabfda2..a89b5f1df5 100644 --- a/plugins/CoreConsole/TravisYmlView.php +++ b/plugins/CoreConsole/TravisYmlView.php @@ -89,6 +89,7 @@ class TravisYmlView extends View $this->pluginName = $pluginName; $customTravisBuildSteps = array(); + foreach (self::$travisYmlExtendableSectionNames as $name) { $customTravisBuildSteps[$name] = array(); @@ -102,6 +103,7 @@ class TravisYmlView extends View $customTravisBuildSteps[$name]['after'] = $this->changeIndent(file_get_contents($afterStepsTemplate), ' '); } } + $this->customTravisBuildSteps = $customTravisBuildSteps; } @@ -160,12 +162,14 @@ class TravisYmlView extends View preg_match_all("/^[a-zA-Z_]+:/m", $yamlText, $allMatches, PREG_OFFSET_CAPTURE); $result = array(); + foreach ($allMatches[0] as $match) { $matchLength = strlen($match[0]); $sectionName = substr($match[0], 0, $matchLength - 1); $result[$sectionName] = $match[1] + $matchLength; } + return $result; } @@ -206,6 +210,7 @@ class TravisYmlView extends View $testsToExclude[] = array('php' => '5.4', 'env' => 'TEST_SUITE=PluginTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable'); } + if ($this->isTargetPluginContainsUITests()) { $testsToRun[] = array('name' => 'UITests', 'vars' => "MYSQL_ADAPTER=PDO_MYSQL"); diff --git a/plugins/CoreHome/Columns/VisitGoalBuyer.php b/plugins/CoreHome/Columns/VisitGoalBuyer.php index 1fcf91cb96..8867efd708 100644 --- a/plugins/CoreHome/Columns/VisitGoalBuyer.php +++ b/plugins/CoreHome/Columns/VisitGoalBuyer.php @@ -72,7 +72,7 @@ class VisitGoalBuyer extends VisitDimension // Ecommerce buyer status $visitEcommerceStatus = $this->getBuyerType($request, $goalBuyer); - if($visitEcommerceStatus != self::TYPE_BUYER_NONE + if ($visitEcommerceStatus != self::TYPE_BUYER_NONE // only update if the value has changed (prevents overwriting the value in case a request has // updated it in the meantime) && $visitEcommerceStatus != $goalBuyer) { diff --git a/plugins/CoreHome/Controller.php b/plugins/CoreHome/Controller.php index b0d3770cbe..387c31e9e9 100644 --- a/plugins/CoreHome/Controller.php +++ b/plugins/CoreHome/Controller.php @@ -103,9 +103,11 @@ class Controller extends \Piwik\Plugin\Controller ) { $module = 'MultiSites'; } + if ($defaultReport == Piwik::getLoginPluginName()) { $module = Piwik::getLoginPluginName(); } + $idSite = Common::getRequestVar('idSite', false, 'int'); parent::redirectToIndex($module, $action, $idSite); } @@ -113,10 +115,12 @@ class Controller extends \Piwik\Plugin\Controller public function showInContext() { $controllerName = Common::getRequestVar('moduleToLoad'); - $actionName = Common::getRequestVar('actionToLoad', 'index'); + $actionName = Common::getRequestVar('actionToLoad', 'index'); + if ($actionName == 'showInContext') { throw new Exception("Preventing infinite recursion..."); } + $view = $this->getDefaultIndexView(); $view->content = FrontController::getInstance()->fetchDispatch($controllerName, $actionName); return $view->render(); @@ -146,12 +150,16 @@ class Controller extends \Piwik\Plugin\Controller ) { return; } + $websiteId = Common::getRequestVar('idSite', false, 'int'); + if ($websiteId) { + $website = new Site($websiteId); - $datetimeCreationDate = $website->getCreationDate()->getDatetime(); + $datetimeCreationDate = $website->getCreationDate()->getDatetime(); $creationDateLocalTimezone = Date::factory($datetimeCreationDate, $website->getTimezone())->toString('Y-m-d'); - $todayLocalTimezone = Date::factory('now', $website->getTimezone())->toString('Y-m-d'); + $todayLocalTimezone = Date::factory('now', $website->getTimezone())->toString('Y-m-d'); + if ($creationDateLocalTimezone == $todayLocalTimezone) { Piwik::redirectToModule('CoreHome', 'index', array('date' => 'today', diff --git a/plugins/CoreHome/DataTableRowAction/RowEvolution.php b/plugins/CoreHome/DataTableRowAction/RowEvolution.php index 915139d300..b0922f05bf 100644 --- a/plugins/CoreHome/DataTableRowAction/RowEvolution.php +++ b/plugins/CoreHome/DataTableRowAction/RowEvolution.php @@ -86,7 +86,7 @@ class RowEvolution if (empty($this->apiMethod)) throw new Exception("Parameter apiMethod not set."); $this->label = ResponseBuilder::getLabelFromRequest($_GET); - if(!is_array($this->label)) { + if (!is_array($this->label)) { throw new Exception("Expected label to be an array, got instead: " . $this->label); } $this->label = $this->label[0]; @@ -337,7 +337,7 @@ class RowEvolution $labelPretty = $dataTableMap->getColumn('label_html'); $labelPretty = array_filter($labelPretty, 'strlen'); $labelPretty = current($labelPretty); - if(!empty($labelPretty)) { + if (!empty($labelPretty)) { return $labelPretty; } return $rowLabel; diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php index 01c2837857..70942c7715 100644 --- a/plugins/CorePluginsAdmin/Controller.php +++ b/plugins/CorePluginsAdmin/Controller.php @@ -293,7 +293,7 @@ class Controller extends Plugin\ControllerAdmin $suffix = Piwik::translate('CorePluginsAdmin_PluginNotWorkingAlternative'); // If the plugin has been renamed, we do not show message to ask user to update plugin - if($pluginName != Request::renameModule($pluginName)) { + if ($pluginName != Request::renameModule($pluginName)) { $suffix = "You may uninstall the plugin or manually delete the files in piwik/plugins/$pluginName/"; } @@ -359,7 +359,7 @@ class Controller extends Plugin\ControllerAdmin return $message; } - if(Common::isPhpCliMode()) { + if (Common::isPhpCliMode()) { Piwik_ExitWithMessage("Error:" . var_export($lastError, true)); } diff --git a/plugins/CorePluginsAdmin/PluginInstaller.php b/plugins/CorePluginsAdmin/PluginInstaller.php index 58fd074909..8bb9c475d0 100644 --- a/plugins/CorePluginsAdmin/PluginInstaller.php +++ b/plugins/CorePluginsAdmin/PluginInstaller.php @@ -155,7 +155,7 @@ class PluginInstaller private function makeSureThereAreNoMissingRequirements($metadata) { $requires = array(); - if(!empty($metadata->require)) { + if (!empty($metadata->require)) { $requires = (array) $metadata->require; } diff --git a/plugins/CorePluginsAdmin/UpdateCommunication.php b/plugins/CorePluginsAdmin/UpdateCommunication.php index ad6c570e7e..3ed004993f 100644 --- a/plugins/CorePluginsAdmin/UpdateCommunication.php +++ b/plugins/CorePluginsAdmin/UpdateCommunication.php @@ -109,34 +109,8 @@ class UpdateCommunication $hasPluginUpdate = $hasPluginUpdate || !$plugin['isTheme']; } - $subject = Piwik::translate('CoreUpdater_NotificationSubjectAvailablePluginUpdate'); - $message = Piwik::translate('ScheduledReports_EmailHello'); - $message .= "\n\n"; - $message .= Piwik::translate('CoreUpdater_ThereIsNewPluginVersionAvailableForUpdate'); - $message .= "\n\n"; - - foreach ($pluginsToBeNotified as $plugin) { - $message .= sprintf(' * %s %s', $plugin['name'], $plugin['latestVersion']); - $message .= "\n"; - } - - $message .= "\n"; - - $host = SettingsPiwik::getPiwikUrl(); - if ($hasThemeUpdate) { - $message .= Piwik::translate('CoreUpdater_NotificationClickToUpdateThemes') . "\n"; - $message .= $host. 'index.php?module=CorePluginsAdmin&action=themes'; - } - if ($hasPluginUpdate) { - if ($hasThemeUpdate) { - $message .= "\n\n"; - } - $message .= Piwik::translate('CoreUpdater_NotificationClickToUpdatePlugins') . "\n"; - $message .= $host. 'index.php?module=CorePluginsAdmin&action=plugins'; - } - - $message .= "\n\n"; - $message .= Piwik::translate('Installation_HappyAnalysing'); + $subject = Piwik::translate('CoreUpdater_NotificationSubjectAvailablePluginUpdate'); + $message = $this->buildNotificationMessage($pluginsToBeNotified, $hasThemeUpdate, $hasPluginUpdate); $this->sendEmailNotification($subject, $message); } @@ -161,24 +135,24 @@ class UpdateCommunication } } - private function setHasLatestUpdateNotificationReceived($plugin) + protected function setHasLatestUpdateNotificationReceived($plugin) { $latestVersion = $this->getLatestVersion($plugin); Option::set($this->getNotificationSentOptionName($plugin), $latestVersion); } - private function getLatestVersionSent($plugin) + protected function getLatestVersionSent($plugin) { return Option::get($this->getNotificationSentOptionName($plugin)); } - private function getLatestVersion($plugin) + protected function getLatestVersion($plugin) { return $plugin['latestVersion']; } - private function hasNotificationAlreadyReceived($plugin) + protected function hasNotificationAlreadyReceived($plugin) { $latestVersion = $this->getLatestVersion($plugin); $lastVersionSent = $this->getLatestVersionSent($plugin); @@ -192,7 +166,7 @@ class UpdateCommunication return false; } - private function getNotificationSentOptionName($plugin) + protected function getNotificationSentOptionName($plugin) { return 'last_update_communication_sent_plugin_' . $plugin['name']; } @@ -207,4 +181,39 @@ class UpdateCommunication return $plugins; } + + protected function buildNotificationMessage($pluginsToBeNotified, $hasThemeUpdate, $hasPluginUpdate) + { + $message = Piwik::translate('ScheduledReports_EmailHello'); + $message .= "\n\n"; + $message .= Piwik::translate('CoreUpdater_ThereIsNewPluginVersionAvailableForUpdate'); + $message .= "\n\n"; + + foreach ($pluginsToBeNotified as $plugin) { + $message .= sprintf(' * %s %s', $plugin['name'], $plugin['latestVersion']); + $message .= "\n"; + } + + $message .= "\n"; + + $host = SettingsPiwik::getPiwikUrl(); + + if ($hasThemeUpdate) { + $message .= Piwik::translate('CoreUpdater_NotificationClickToUpdateThemes') . "\n"; + $message .= $host . 'index.php?module=CorePluginsAdmin&action=themes'; + } + + if ($hasPluginUpdate) { + if ($hasThemeUpdate) { + $message .= "\n\n"; + } + $message .= Piwik::translate('CoreUpdater_NotificationClickToUpdatePlugins') . "\n"; + $message .= $host . 'index.php?module=CorePluginsAdmin&action=plugins'; + } + + $message .= "\n\n"; + $message .= Piwik::translate('Installation_HappyAnalysing'); + + return $message; + } } diff --git a/plugins/CoreUpdater/Commands/Update.php b/plugins/CoreUpdater/Commands/Update.php index e5a0e39d33..108281c460 100644 --- a/plugins/CoreUpdater/Commands/Update.php +++ b/plugins/CoreUpdater/Commands/Update.php @@ -40,7 +40,7 @@ class Update extends ConsoleCommand try { $this->makeUpdate($input, $output, $doDryRun); - if(!$doDryRun) { + if (!$doDryRun) { $this->writeSuccessMessage($output, array("Piwik has been successfully updated!")); } diff --git a/plugins/CoreUpdater/Controller.php b/plugins/CoreUpdater/Controller.php index 1d1d689b56..cc27c3e9aa 100644 --- a/plugins/CoreUpdater/Controller.php +++ b/plugins/CoreUpdater/Controller.php @@ -327,11 +327,11 @@ class Controller extends \Piwik\Plugin\Controller $doExecuteUpdates = Common::getRequestVar('updateCorePlugins', 0, 'integer') == 1; - if(is_null($doDryRun)) { + if (is_null($doDryRun)) { $doDryRun = !$doExecuteUpdates; } - if($doDryRun) { + if ($doDryRun) { $viewWelcome->queries = $updater->getSqlQueriesToExecute(); $viewWelcome->isMajor = $updater->hasMajorDbUpdate(); $this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile); diff --git a/plugins/CoreUpdater/UpdateCommunication.php b/plugins/CoreUpdater/UpdateCommunication.php index 5a113f74d5..cd52e80a3e 100644 --- a/plugins/CoreUpdater/UpdateCommunication.php +++ b/plugins/CoreUpdater/UpdateCommunication.php @@ -76,7 +76,7 @@ class UpdateCommunication $this->sendEmailNotification($subject, $message); } - private function isVersionLike($latestVersion) + protected function isVersionLike($latestVersion) { return strlen($latestVersion) < 18; } @@ -101,7 +101,7 @@ class UpdateCommunication } } - private function isNewVersionAvailable() + protected function isNewVersionAvailable() { UpdateCheck::check(); @@ -119,7 +119,7 @@ class UpdateCommunication return $hasUpdate; } - private function hasNotificationAlreadyReceived() + protected function hasNotificationAlreadyReceived() { $latestVersion = $this->getLatestVersion(); $lastVersionSent = $this->getLatestVersionSent(); diff --git a/plugins/CustomVariables/Archiver.php b/plugins/CustomVariables/Archiver.php index 241e2772a0..47e1363dc4 100644 --- a/plugins/CustomVariables/Archiver.php +++ b/plugins/CustomVariables/Archiver.php @@ -39,7 +39,7 @@ class Archiver extends \Piwik\Plugin\Archiver { parent::__construct($processor); - if($processor->getParams()->getSite()->isEcommerceEnabled()) { + if ($processor->getParams()->getSite()->isEcommerceEnabled()) { $this->maximumRowsInDataTableLevelZero = self::MAX_ROWS_WHEN_ECOMMERCE; $this->maximumRowsInSubDataTable = self::MAX_ROWS_WHEN_ECOMMERCE; } else { diff --git a/plugins/Dashboard/Controller.php b/plugins/Dashboard/Controller.php index 5e319ddb25..c7a89a75a5 100644 --- a/plugins/Dashboard/Controller.php +++ b/plugins/Dashboard/Controller.php @@ -104,38 +104,13 @@ class Controller extends \Piwik\Plugin\Controller $session->dashboardLayout = $layout; $session->setExpirationSeconds(1800); } else { - $this->saveLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard, $layout); + $this->getModel()->updateLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard, $layout); } } - /** - * Records the layout in the DB for the given user. - * - * @param string $login - * @param int $idDashboard - * @param string $layout - */ - protected function saveLayoutForUser($login, $idDashboard, $layout) - { - $paramsBind = array($login, $idDashboard, $layout, $layout); - $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', - Common::prefixTable('user_dashboard')); - Db::query($query, $paramsBind); - } - - /** - * Updates the name of a dashboard - * - * @param string $login - * @param int $idDashboard - * @param string $name - */ - protected function updateDashboardName($login, $idDashboard, $name) + private function getModel() { - $paramsBind = array($name, $login, $idDashboard); - $query = sprintf('UPDATE %s SET name = ? WHERE login = ? AND iddashboard = ?', - Common::prefixTable('user_dashboard')); - Db::query($query, $paramsBind); + return new Model(); } /** @@ -153,9 +128,7 @@ class Controller extends \Piwik\Plugin\Controller // first layout can't be removed if ($idDashboard != 1) { - $query = sprintf('DELETE FROM %s WHERE iddashboard = ? AND login = ?', - Common::prefixTable('user_dashboard')); - Db::query($query, array($idDashboard, Piwik::getCurrentUserLogin())); + $this->getModel()->deleteDashboardForUser($idDashboard, Piwik::getCurrentUserLogin()); } } @@ -171,7 +144,7 @@ class Controller extends \Piwik\Plugin\Controller return '[]'; } - $login = Piwik::getCurrentUserLogin(); + $login = Piwik::getCurrentUserLogin(); $dashboards = $this->dashboard->getAllDashboards($login); Json::sendHeaderJSON(); @@ -189,38 +162,22 @@ class Controller extends \Piwik\Plugin\Controller if (Piwik::isUserIsAnonymous()) { return '0'; } - $user = Piwik::getCurrentUserLogin(); - $nextId = $this->getNextIdDashboard($user); - $name = urldecode(Common::getRequestVar('name', '', 'string')); - $type = urldecode(Common::getRequestVar('type', 'default', 'string')); + $name = urldecode(Common::getRequestVar('name', '', 'string')); + $type = urldecode(Common::getRequestVar('type', 'default', 'string')); $layout = '{}'; + $login = Piwik::getCurrentUserLogin(); if ($type == 'default') { $layout = $this->dashboard->getDefaultLayout(); } - $query = sprintf('INSERT INTO %s (login, iddashboard, name, layout) VALUES (?, ?, ?, ?)', - Common::prefixTable('user_dashboard')); - Db::query($query, array($user, $nextId, $name, $layout)); + $nextId = $this->getModel()->createNewDashboardForUser($login, $name, $layout); Json::sendHeaderJSON(); return Common::json_encode($nextId); } - private function getNextIdDashboard($login) - { - $nextIdQuery = sprintf('SELECT MAX(iddashboard)+1 FROM %s WHERE login = ?', - Common::prefixTable('user_dashboard')); - $nextId = Db::fetchOne($nextIdQuery, array($login)); - - if (empty($nextId)) { - $nextId = 1; - return $nextId; - } - return $nextId; - } - public function copyDashboardToUser() { $this->checkTokenInUrl(); @@ -228,18 +185,16 @@ class Controller extends \Piwik\Plugin\Controller if (!Piwik::hasUserSuperUserAccess()) { return '0'; } + $login = Piwik::getCurrentUserLogin(); - $name = urldecode(Common::getRequestVar('name', '', 'string')); - $user = urldecode(Common::getRequestVar('user', '', 'string')); + $name = urldecode(Common::getRequestVar('name', '', 'string')); + $user = urldecode(Common::getRequestVar('user', '', 'string')); $idDashboard = Common::getRequestVar('dashboardId', 0, 'int'); + $layout = $this->dashboard->getLayoutForUser($login, $idDashboard); if ($layout !== false) { - $nextId = $this->getNextIdDashboard($user); - - $query = sprintf('INSERT INTO %s (login, iddashboard, name, layout) VALUES (?, ?, ?, ?)', - Common::prefixTable('user_dashboard')); - Db::query($query, array($user, $nextId, $name, $layout)); + $nextId = $this->getModel()->createNewDashboardForUser($user, $name, $layout); Json::sendHeaderJSON(); return Common::json_encode($nextId); @@ -255,17 +210,18 @@ class Controller extends \Piwik\Plugin\Controller { $this->checkTokenInUrl(); - $layout = Common::unsanitizeInputValue(Common::getRequestVar('layout')); + $layout = Common::unsanitizeInputValue(Common::getRequestVar('layout')); $idDashboard = Common::getRequestVar('idDashboard', 1, 'int'); - $name = Common::getRequestVar('name', '', 'string'); + $name = Common::getRequestVar('name', '', 'string'); + if (Piwik::isUserIsAnonymous()) { $session = new SessionNamespace("Dashboard"); $session->dashboardLayout = $layout; $session->setExpirationSeconds(1800); } else { - $this->saveLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard, $layout); + $this->getModel()->updateLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard, $layout); if (!empty($name)) { - $this->updateDashboardName(Piwik::getCurrentUserLogin(), $idDashboard, $name); + $this->getModel()->updateDashboardName(Piwik::getCurrentUserLogin(), $idDashboard, $name); } } } @@ -279,10 +235,7 @@ class Controller extends \Piwik\Plugin\Controller if (Piwik::hasUserSuperUserAccess()) { $layout = Common::unsanitizeInputValue(Common::getRequestVar('layout')); - $paramsBind = array('', '1', $layout, $layout); - $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', - Common::prefixTable('user_dashboard')); - Db::query($query, $paramsBind); + $this->getModel()->createOrUpdateDashboard('', '1', $layout); } } diff --git a/plugins/Dashboard/Dashboard.php b/plugins/Dashboard/Dashboard.php index cb545465ff..1ff5a98182 100644 --- a/plugins/Dashboard/Dashboard.php +++ b/plugins/Dashboard/Dashboard.php @@ -10,7 +10,6 @@ namespace Piwik\Plugins\Dashboard; use Piwik\Common; use Piwik\Db; -use Piwik\DbHelper; use Piwik\Piwik; use Piwik\WidgetsList; @@ -42,10 +41,7 @@ class Dashboard extends \Piwik\Plugin */ public function getLayoutForUser($login, $idDashboard) { - $paramsBind = array($login, $idDashboard); - $query = sprintf('SELECT layout FROM %s WHERE login = ? AND iddashboard = ?', - Common::prefixTable('user_dashboard')); - $return = Db::fetchAll($query, $paramsBind); + $return = $this->getModel()->getLayoutForUser($login, $idDashboard); if (count($return) == 0) { return false; @@ -54,6 +50,11 @@ class Dashboard extends \Piwik\Plugin return $return[0]['layout']; } + private function getModel() + { + return new Model(); + } + public function getDefaultLayout() { $defaultLayout = $this->getLayoutForUser('', 1); @@ -107,9 +108,7 @@ class Dashboard extends \Piwik\Plugin public function getAllDashboards($login) { - $dashboards = Db::fetchAll('SELECT iddashboard, name, layout - FROM ' . Common::prefixTable('user_dashboard') . - ' WHERE login = ? ORDER BY iddashboard', array($login)); + $dashboards = $this->getModel()->getAllDashboardsForUser($login); $nameless = 1; foreach ($dashboards as &$dashboard) { @@ -219,23 +218,17 @@ class Dashboard extends \Piwik\Plugin public function deleteDashboardLayout($userLogin) { - Db::query('DELETE FROM ' . Common::prefixTable('user_dashboard') . ' WHERE login = ?', array($userLogin)); + $this->getModel()->deleteAllLayoutsForUser($userLogin); } public function install() { - $dashboard = "login VARCHAR( 100 ) NOT NULL , - iddashboard INT NOT NULL , - name VARCHAR( 100 ) NULL DEFAULT NULL , - layout TEXT NOT NULL, - PRIMARY KEY ( login , iddashboard )"; - - DbHelper::createTable('user_dashboard', $dashboard); + Model::install(); } public function uninstall() { - Db::dropTables(Common::prefixTable('user_dashboard')); + Model::uninstall(); } public function getClientSideTranslationKeys(&$translationKeys) diff --git a/plugins/Dashboard/Model.php b/plugins/Dashboard/Model.php new file mode 100644 index 0000000000..39dcb06557 --- /dev/null +++ b/plugins/Dashboard/Model.php @@ -0,0 +1,147 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ +namespace Piwik\Plugins\Dashboard; + +use Piwik\Common; +use Piwik\Db; +use Piwik\DbHelper; + +class Model +{ + private static $rawPrefix = 'user_dashboard'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + + /** + * Returns the layout in the DB for the given user, or false if the layout has not been set yet. + * Parameters must be checked BEFORE this function call + * + * @param string $login + * @param int $idDashboard + * + * @return bool|string + */ + public function getLayoutForUser($login, $idDashboard) + { + $query = sprintf('SELECT layout FROM %s WHERE login = ? AND iddashboard = ?', + $this->table); + $bind = array($login, $idDashboard); + $layouts = Db::fetchAll($query, $bind); + + return $layouts; + } + + public function getAllDashboardsForUser($login) + { + $dashboards = Db::fetchAll('SELECT iddashboard, name, layout FROM ' . $this->table . + ' WHERE login = ? ORDER BY iddashboard', array($login)); + + return $dashboards; + } + + public function deleteAllLayoutsForUser($userLogin) + { + Db::query('DELETE FROM ' . $this->table . ' WHERE login = ?', array($userLogin)); + } + + /** + * Updates the name of a dashboard + * + * @param string $login + * @param int $idDashboard + * @param string $name + */ + public function updateDashboardName($login, $idDashboard, $name) + { + $bind = array($name, $login, $idDashboard); + $query = sprintf('UPDATE %s SET name = ? WHERE login = ? AND iddashboard = ?', $this->table); + Db::query($query, $bind); + } + + /** + * Removes the dashboard with the given id + */ + public function deleteDashboardForUser($idDashboard, $login) + { + $query = sprintf('DELETE FROM %s WHERE iddashboard = ? AND login = ?', $this->table); + Db::query($query, array($idDashboard, $login)); + } + + /** + * Creates a new dashboard for the current user + * User needs to be logged in + */ + public function createNewDashboardForUser($login, $name, $layout) + { + $nextId = $this->getNextIdDashboard($login); + + $query = sprintf('INSERT INTO %s (login, iddashboard, name, layout) VALUES (?, ?, ?, ?)', $this->table); + $bind = array($login, $nextId, $name, $layout); + Db::query($query, $bind); + + return $nextId; + } + + /** + * Saves the layout as default + */ + 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); + Db::query($query, $bind); + } + + private function getNextIdDashboard($login) + { + $nextIdQuery = sprintf('SELECT MAX(iddashboard)+1 FROM %s WHERE login = ?', $this->table); + $nextId = Db::fetchOne($nextIdQuery, array($login)); + + if (empty($nextId)) { + $nextId = 1; + } + + return $nextId; + } + + /** + * Records the layout in the DB for the given user. + * + * @param string $login + * @param int $idDashboard + * @param string $layout + */ + 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); + Db::query($query, $bind); + } + + public static function install() + { + $dashboard = "login VARCHAR( 100 ) NOT NULL , + iddashboard INT NOT NULL , + name VARCHAR( 100 ) NULL DEFAULT NULL , + layout TEXT NOT NULL, + PRIMARY KEY ( login , iddashboard )"; + + DbHelper::createTable(self::$rawPrefix, $dashboard); + } + + public static function uninstall() + { + Db::dropTables(Common::prefixTable(self::$rawPrefix)); + } +} diff --git a/plugins/DevicesDetection/functions.php b/plugins/DevicesDetection/functions.php index af76162f01..0a3de1c367 100644 --- a/plugins/DevicesDetection/functions.php +++ b/plugins/DevicesDetection/functions.php @@ -179,7 +179,7 @@ function getOSFamilyFullNameExtended($label) return 'Bot'; } $label = OperatingSystemParser::getOsFamily($label); - if($label !== false) { + if ($label !== false) { return $label; } return Piwik::translate('General_Unknown'); diff --git a/plugins/Events/API.php b/plugins/Events/API.php index 361f0ef965..890979db2c 100644 --- a/plugins/Events/API.php +++ b/plugins/Events/API.php @@ -94,7 +94,7 @@ class API extends \Piwik\Plugin\API */ public function getDefaultSecondaryDimension($apiMethod) { - if(isset($this->defaultMappingApiToSecondaryDimension[$apiMethod])) { + if (isset($this->defaultMappingApiToSecondaryDimension[$apiMethod])) { return $this->defaultMappingApiToSecondaryDimension[$apiMethod]; } return false; @@ -106,11 +106,11 @@ class API extends \Piwik\Plugin\API $secondaryDimension = $this->getDefaultSecondaryDimension($apiMethod); } $record = $this->mappingApiToRecord[$apiMethod]; - if(!is_array($record)) { + if (!is_array($record)) { return $record; } // when secondaryDimension is incorrectly set - if(empty($record[$secondaryDimension])) { + if (empty($record[$secondaryDimension])) { return key($record); } return $record[$secondaryDimension]; @@ -124,7 +124,7 @@ class API extends \Piwik\Plugin\API public function getSecondaryDimensions($apiMethod) { $records = $this->mappingApiToRecord[$apiMethod]; - if(!is_array($records)) { + if (!is_array($records)) { return false; } return array_keys($records); diff --git a/plugins/Events/Archiver.php b/plugins/Events/Archiver.php index 02fe3a8d83..eb33d4899f 100644 --- a/plugins/Events/Archiver.php +++ b/plugins/Events/Archiver.php @@ -225,7 +225,7 @@ class Archiver extends \Piwik\Plugin\Archiver */ protected function getDataArray($name) { - if(empty($this->arrays[$name])) { + if (empty($this->arrays[$name])) { $this->arrays[$name] = new DataArray(); } return $this->arrays[$name]; diff --git a/plugins/Events/Events.php b/plugins/Events/Events.php index 3d335bd229..6a55588af4 100644 --- a/plugins/Events/Events.php +++ b/plugins/Events/Events.php @@ -184,7 +184,7 @@ class Events extends \Piwik\Plugin private function addRelatedReports($view, $secondaryDimension) { - if(empty($secondaryDimension)) { + if (empty($secondaryDimension)) { // eg. Row Evolution return; } @@ -194,7 +194,7 @@ class Events extends \Piwik\Plugin $apiMethod = $view->requestConfig->getApiMethodToRequest(); $secondaryDimensions = API::getInstance()->getSecondaryDimensions($apiMethod); - if(empty($secondaryDimensions)) { + if (empty($secondaryDimensions)) { return; } @@ -205,7 +205,7 @@ class Events extends \Piwik\Plugin . Piwik::translate('Events_SwitchToSecondaryDimension', ''); foreach($secondaryDimensions as $dimension) { - if($dimension == $secondaryDimension) { + if ($dimension == $secondaryDimension) { // don't show as related report the currently selected dimension continue; } diff --git a/plugins/ExampleRssWidget/RssRenderer.php b/plugins/ExampleRssWidget/RssRenderer.php index 254a30ce6f..7990b1acb8 100644 --- a/plugins/ExampleRssWidget/RssRenderer.php +++ b/plugins/ExampleRssWidget/RssRenderer.php @@ -54,7 +54,7 @@ class RssRenderer $i = 0; $items = array(); - if(!empty($rss->channel->item)) { + if (!empty($rss->channel->item)) { $items = $rss->channel->item; } foreach ($items as $post) { diff --git a/plugins/Goals/API.php b/plugins/Goals/API.php index 176cafad24..ffc5bfe467 100644 --- a/plugins/Goals/API.php +++ b/plugins/Goals/API.php @@ -54,14 +54,15 @@ class API extends \Piwik\Plugin\API //TODO calls to this function could be cached as static // would help UI at least, since some UI requests would call this 2-3 times.. $idSite = Site::getIdSitesFromIdSitesString($idSite); + if (empty($idSite)) { return array(); } + Piwik::checkUserHasViewAccess($idSite); - $goals = Db::fetchAll("SELECT * - FROM " . Common::prefixTable('goal') . " - WHERE idsite IN (" . implode(", ", $idSite) . ") - AND deleted = 0"); + + $goals = $this->getModel()->getActiveGoals($idSite); + $cleanedGoals = array(); foreach ($goals as &$goal) { if ($goal['match_attribute'] == 'manually') { @@ -71,6 +72,7 @@ class API extends \Piwik\Plugin\API } $cleanedGoals[$goal['idgoal']] = $goal; } + return $cleanedGoals; } @@ -91,35 +93,33 @@ class API extends \Piwik\Plugin\API public function addGoal($idSite, $name, $matchAttribute, $pattern, $patternType, $caseSensitive = false, $revenue = false, $allowMultipleConversionsPerVisit = false) { Piwik::checkUserHasAdminAccess($idSite); + $this->checkPatternIsValid($patternType, $pattern, $matchAttribute); - $name = $this->checkName($name); + $name = $this->checkName($name); $pattern = $this->checkPattern($pattern); - // save in db - $db = Db::get(); - $idGoal = $db->fetchOne("SELECT max(idgoal) + 1 - FROM " . Common::prefixTable('goal') . " - WHERE idsite = ?", $idSite); - if ($idGoal == false) { - $idGoal = 1; - } - $db->insert(Common::prefixTable('goal'), - array( - 'idsite' => $idSite, - 'idgoal' => $idGoal, - 'name' => $name, - 'match_attribute' => $matchAttribute, - 'pattern' => $pattern, - 'pattern_type' => $patternType, - 'case_sensitive' => (int)$caseSensitive, - 'allow_multiple' => (int)$allowMultipleConversionsPerVisit, - 'revenue' => (float)$revenue, - 'deleted' => 0, - )); + $goal = array( + 'name' => $name, + 'match_attribute' => $matchAttribute, + 'pattern' => $pattern, + 'pattern_type' => $patternType, + 'case_sensitive' => (int)$caseSensitive, + 'allow_multiple' => (int)$allowMultipleConversionsPerVisit, + 'revenue' => (float)$revenue, + 'deleted' => 0, + ); + + $idGoal = $this->getModel()->createGoalForSite($idSite, $goal); + Cache::regenerateCacheWebsiteAttributes($idSite); return $idGoal; } + private function getModel() + { + return new Model(); + } + /** * Updates a Goal description. * Will not update or re-process the conversions already recorded @@ -139,21 +139,21 @@ class API extends \Piwik\Plugin\API public function updateGoal($idSite, $idGoal, $name, $matchAttribute, $pattern, $patternType, $caseSensitive = false, $revenue = false, $allowMultipleConversionsPerVisit = false) { Piwik::checkUserHasAdminAccess($idSite); - $name = $this->checkName($name); + + $name = $this->checkName($name); $pattern = $this->checkPattern($pattern); $this->checkPatternIsValid($patternType, $pattern, $matchAttribute); - Db::get()->update(Common::prefixTable('goal'), - array( - 'name' => $name, - 'match_attribute' => $matchAttribute, - 'pattern' => $pattern, - 'pattern_type' => $patternType, - 'case_sensitive' => (int)$caseSensitive, - 'allow_multiple' => (int)$allowMultipleConversionsPerVisit, - 'revenue' => (float)$revenue, - ), - "idsite = '$idSite' AND idgoal = '$idGoal'" - ); + + $this->getModel()->updateGoal($idSite, $idGoal, array( + 'name' => $name, + 'match_attribute' => $matchAttribute, + 'pattern' => $pattern, + 'pattern_type' => $patternType, + 'case_sensitive' => (int) $caseSensitive, + 'allow_multiple' => (int) $allowMultipleConversionsPerVisit, + 'revenue' => (float) $revenue, + )); + Cache::regenerateCacheWebsiteAttributes($idSite); } @@ -188,11 +188,9 @@ class API extends \Piwik\Plugin\API public function deleteGoal($idSite, $idGoal) { Piwik::checkUserHasAdminAccess($idSite); - Db::query("UPDATE " . Common::prefixTable('goal') . " - SET deleted = 1 - WHERE idsite = ? - AND idgoal = ?", - array($idSite, $idGoal)); + + $this->getModel()->deleteGoal($idSite, $idGoal); + Db::deleteAllRows(Common::prefixTable("log_conversion"), "WHERE idgoal = ? AND idsite = ?", "idvisit", 100000, array($idGoal, $idSite)); Cache::regenerateCacheWebsiteAttributes($idSite); } @@ -204,11 +202,13 @@ class API extends \Piwik\Plugin\API protected function getItems($recordName, $idSite, $period, $date, $abandonedCarts, $segment) { Piwik::checkUserHasViewAccess($idSite); + $recordNameFinal = $recordName; if ($abandonedCarts) { $recordNameFinal = Archiver::getItemRecordNameAbandonedCart($recordName); } - $archive = Archive::build($idSite, $period, $date, $segment); + + $archive = Archive::build($idSite, $period, $date, $segment); $dataTable = $archive->getDataTable($recordNameFinal); $dataTable->filter('Sort', array(Metrics::INDEX_ECOMMERCE_ITEM_REVENUE)); @@ -250,6 +250,7 @@ class API extends \Piwik\Plugin\API } return; } + $rowNotDefined = $dataTable->getRowFromLabel(\Piwik\Plugins\CustomVariables\Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED); if ($rowNotDefined) { $rowNotDefined->setColumn('label', $notDefinedStringPretty); diff --git a/plugins/Goals/Controller.php b/plugins/Goals/Controller.php index f5a3f1f735..e7af6d6243 100644 --- a/plugins/Goals/Controller.php +++ b/plugins/Goals/Controller.php @@ -98,7 +98,7 @@ class Controller extends \Piwik\Plugin\Controller { $saveGET = $_GET; $filterEcommerce = Common::getRequestVar('filterEcommerce', self::ECOMMERCE_LOG_SHOW_ORDERS, 'int'); - if($filterEcommerce == self::ECOMMERCE_LOG_SHOW_ORDERS) { + if ($filterEcommerce == self::ECOMMERCE_LOG_SHOW_ORDERS) { $segment = urlencode('visitEcommerceStatus==ordered,visitEcommerceStatus==orderedThenAbandonedCart'); } else { $segment = urlencode('visitEcommerceStatus==abandonedCart,visitEcommerceStatus==orderedThenAbandonedCart'); @@ -458,7 +458,7 @@ class Controller extends \Piwik\Plugin\Controller foreach ($allReports as $category => $reports) { $categoryText = Piwik::translate('Goals_ViewGoalsBy', $category); foreach ($reports as $report) { - if(empty($report['viewDataTable'])) { + if (empty($report['viewDataTable'])) { $report['viewDataTable'] = 'tableGoals'; } $customParams['viewDataTable'] = $report['viewDataTable']; diff --git a/plugins/Goals/Goals.php b/plugins/Goals/Goals.php index 39a7c0b2dc..381c37f7ee 100644 --- a/plugins/Goals/Goals.php +++ b/plugins/Goals/Goals.php @@ -135,7 +135,8 @@ class Goals extends \Piwik\Plugin */ public function deleteSiteGoals($idSite) { - Db::query("DELETE FROM " . Common::prefixTable('goal') . " WHERE idsite = ? ", array($idSite)); + $model = new Model(); + $model->deleteGoalsForSite($idSite); } /** diff --git a/plugins/Goals/Model.php b/plugins/Goals/Model.php new file mode 100644 index 0000000000..93a9e9fd40 --- /dev/null +++ b/plugins/Goals/Model.php @@ -0,0 +1,87 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + */ +namespace Piwik\Plugins\Goals; + +use Piwik\Common; +use Piwik\Db; + +class Model +{ + private static $rawPrefix = 'goal'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + + private function getNextIdGoal($idSite) + { + $db = $this->getDb(); + $idGoal = $db->fetchOne("SELECT max(idgoal) + 1 FROM " . $this->table . " + WHERE idsite = ?", $idSite); + + if (empty($idGoal)) { + $idGoal = 1; + } + + return $idGoal; + } + + public function createGoalForSite($idSite, $goal) + { + $db = $this->getDb(); + $goalId = $this->getNextIdGoal($idSite); + + $goal['idgoal'] = $goalId; + $goal['idsite'] = $idSite; + + $db->insert($this->table, $goal); + + return $goalId; + } + + public function updateGoal($idSite, $idGoal, $goal) + { + $idSite = (int) $idSite; + $idGoal = (int) $idGoal; + + $db = $this->getDb(); + $db->update($this->table, $goal, "idsite = '$idSite' AND idgoal = '$idGoal'"); + } + + public function getActiveGoals($idSite) + { + $idSite = array_map('intval', $idSite); + $goals = Db::fetchAll("SELECT * FROM " . $this->table . " + WHERE idsite IN (" . implode(", ", $idSite) . ") + AND deleted = 0"); + + return $goals; + } + + public function deleteGoalsForSite($idSite) + { + Db::query("DELETE FROM " . $this->table . " WHERE idsite = ? ", array($idSite)); + } + + public function deleteGoal($idSite, $idGoal) + { + $query = "UPDATE " . $this->table . " SET deleted = 1 + WHERE idsite = ? AND idgoal = ?"; + $bind = array($idSite, $idGoal); + + Db::query($query, $bind); + } + + private function getDb() + { + return Db::get(); + } +} diff --git a/plugins/Goals/Visualizations/Goals.php b/plugins/Goals/Visualizations/Goals.php index 0b8c2c5365..9808621b14 100644 --- a/plugins/Goals/Visualizations/Goals.php +++ b/plugins/Goals/Visualizations/Goals.php @@ -31,7 +31,7 @@ class Goals extends HtmlTable { parent::beforeLoadDataTable(); - if($this->config->disable_subtable_when_show_goals) { + if ($this->config->disable_subtable_when_show_goals) { $this->config->subtable_controller_action = null; } diff --git a/plugins/ImageGraph/StaticGraph/GridGraph.php b/plugins/ImageGraph/StaticGraph/GridGraph.php index 3eeb1393db..4ffde4c2c4 100644 --- a/plugins/ImageGraph/StaticGraph/GridGraph.php +++ b/plugins/ImageGraph/StaticGraph/GridGraph.php @@ -419,11 +419,11 @@ abstract class GridGraph extends StaticGraph // see https://github.com/piwik/piwik/issues/3396 // protected function displayMinMaxValues() // { -// if($displayMinMax) +// if ($displayMinMax) // { // // when plotting multiple metrics, display min & max on both series // // to fix: in vertical bars, labels are hidden when multiple metrics are plotted, hence the restriction on count($this->ordinateSeries) == 1 -// if($this->multipleMetrics && count($this->ordinateSeries) == 1) +// if ($this->multipleMetrics && count($this->ordinateSeries) == 1) // { // $colorIndex = 1; // foreach($this->ordinateSeries as $column => $data) @@ -467,13 +467,13 @@ abstract class GridGraph extends StaticGraph // $maxValueIndex = 0; // foreach($data as $index => $value) // { -// if($value > $maxValue) +// if ($value > $maxValue) // { // $maxValue = $value; // $maxValueIndex = $index; // } // -// if($value < $minValue) +// if ($value < $minValue) // { // $minValue = $value; // $minValueIndex = $index; diff --git a/plugins/Installation/Controller.php b/plugins/Installation/Controller.php index d3da5402f0..aaeb2a6b0e 100644 --- a/plugins/Installation/Controller.php +++ b/plugins/Installation/Controller.php @@ -84,7 +84,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin // Delete merged js/css files to force regenerations based on updated activated plugin list Filesystem::deleteAllCacheOnUpdate(); - if(empty($message)) { + if (empty($message)) { $this->checkPiwikIsNotInstalled(); } $view = new View( @@ -234,7 +234,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin ); $result = $this->updateComponents(); - if($result === false) { + if ($result === false) { $this->redirectToNextStep('tablesCreation'); } @@ -259,7 +259,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin $this->checkPiwikIsNotInstalled(); $this->initObjectsToCallAPI(); - if(count(APIUsersManager::getInstance()->getUsersHavingSuperUserAccess()) > 0) { + if (count(APIUsersManager::getInstance()->getUsersHavingSuperUserAccess()) > 0) { $this->redirectToNextStep('setupSuperUser'); } @@ -303,7 +303,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin $this->initObjectsToCallAPI(); - if(count(APISitesManager::getInstance()->getAllSitesId()) > 0) { + if (count(APISitesManager::getInstance()->getAllSitesId()) > 0) { // if there is a already a website, skip this step and trackingCode step $this->redirectToNextStep('trackingCode'); } @@ -336,7 +336,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin } // Display previous step success message, when current step form was not submitted yet - if(count($form->getErrorMessages()) == 0) { + if (count($form->getErrorMessages()) == 0) { $view->displayGeneralSetupSuccess = true; } @@ -513,7 +513,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin private function checkPiwikIsNotInstalled() { - if(!SettingsPiwik::isPiwikInstalled()) { + if (!SettingsPiwik::isPiwikInstalled()) { return; } \Piwik\Plugins\Login\Controller::clearSession(); @@ -658,7 +658,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin private function deleteConfigFileIfNeeded() { $config = Config::getInstance(); - if($config->existsLocalConfig()) { + if ($config->existsLocalConfig()) { $config->deleteLocalConfig(); } } diff --git a/plugins/Installation/FormFirstWebsiteSetup.php b/plugins/Installation/FormFirstWebsiteSetup.php index 83c68bea34..93eced71b4 100644 --- a/plugins/Installation/FormFirstWebsiteSetup.php +++ b/plugins/Installation/FormFirstWebsiteSetup.php @@ -31,7 +31,7 @@ class FormFirstWebsiteSetup extends QuickForm2 HTML_QuickForm2_Factory::registerRule('checkTimezone', 'Piwik\Plugins\Installation\Rule_isValidTimezone'); $urlExample = 'http://example.org'; - $javascriptOnClickUrlExample = "javascript:if(this.value=='$urlExample'){this.value='http://';} this.style.color='black';"; + $javascriptOnClickUrlExample = "javascript:if (this.value=='$urlExample'){this.value='http://';} this.style.color='black';"; $timezones = API::getInstance()->getTimezonesList(); $timezones = array_merge(array('No timezone' => Piwik::translate('SitesManager_SelectACity')), $timezones); diff --git a/plugins/Installation/ServerFilesGenerator.php b/plugins/Installation/ServerFilesGenerator.php index 5ce2abf844..9551340e4a 100644 --- a/plugins/Installation/ServerFilesGenerator.php +++ b/plugins/Installation/ServerFilesGenerator.php @@ -18,7 +18,7 @@ class ServerFilesGenerator */ public static function createHtAccessFiles() { - if(!SettingsServer::isApache()) { + if (!SettingsServer::isApache()) { return; } $denyAll = self::getDenyAllHtaccessContent(); diff --git a/plugins/Installation/SystemCheck.php b/plugins/Installation/SystemCheck.php index f6d8c42e02..29f87f2415 100644 --- a/plugins/Installation/SystemCheck.php +++ b/plugins/Installation/SystemCheck.php @@ -140,7 +140,7 @@ class SystemCheck } $sessionAutoStarted = (int)ini_get('session.auto_start'); - if($sessionAutoStarted) { + if ($sessionAutoStarted) { $infos['missing_desired_functions'][] = 'session.auto_start'; } diff --git a/plugins/LanguagesManager/API.php b/plugins/LanguagesManager/API.php index e95931ae87..e715770279 100644 --- a/plugins/LanguagesManager/API.php +++ b/plugins/LanguagesManager/API.php @@ -9,7 +9,6 @@ */ namespace Piwik\Plugins\LanguagesManager; -use Piwik\Common; use Piwik\Db; use Piwik\Filesystem; use Piwik\Piwik; @@ -229,12 +228,20 @@ class API extends \Piwik\Plugin\API */ public function getLanguageForUser($login) { - if($login == 'anonymous') { + if ($login == 'anonymous') { return false; } + Piwik::checkUserHasSuperUserAccessOrIsTheUser($login); - return Db::fetchOne('SELECT language FROM ' . Common::prefixTable('user_language') . - ' WHERE login = ? ', array($login)); + + $lang = $this->getModel()->getLanguageForUser($login); + + return $lang; + } + + private function getModel() + { + return new Model(); } /** @@ -248,15 +255,13 @@ class API extends \Piwik\Plugin\API { Piwik::checkUserHasSuperUserAccessOrIsTheUser($login); Piwik::checkUserIsNotAnonymous(); + if (!$this->isLanguageAvailable($languageCode)) { return false; } - $paramsBind = array($login, $languageCode, $languageCode); - Db::query('INSERT INTO ' . Common::prefixTable('user_language') . - ' (login, language) - VALUES (?,?) - ON DUPLICATE KEY UPDATE language=?', - $paramsBind); + + $this->getModel()->setLanguageForUser($login, $languageCode); + return true; } diff --git a/plugins/LanguagesManager/Commands/CompareKeys.php b/plugins/LanguagesManager/Commands/CompareKeys.php index 088bb492ae..821342a90c 100644 --- a/plugins/LanguagesManager/Commands/CompareKeys.php +++ b/plugins/LanguagesManager/Commands/CompareKeys.php @@ -62,7 +62,7 @@ class CompareKeys extends ConsoleCommand { if (!empty($englishFromOTrance[$category])) { foreach ($englishFromOTrance[$category] as $key => $value) { - if(!array_key_exists($category, $availableTranslations) || !array_key_exists($key, $availableTranslations[$category])) { + if (!array_key_exists($category, $availableTranslations) || !array_key_exists($key, $availableTranslations[$category])) { $unnecessary[] = sprintf('%s_%s', $category, $key); continue; } else if (html_entity_decode($availableTranslations[$category][$key]) != html_entity_decode($englishFromOTrance[$category][$key])) { @@ -73,7 +73,7 @@ class CompareKeys extends ConsoleCommand } if (!empty($availableTranslations[$category])) { foreach ($availableTranslations[$category] as $key => $value) { - if(!array_key_exists($category, $englishFromOTrance) || !array_key_exists($key, $englishFromOTrance[$category])) { + if (!array_key_exists($category, $englishFromOTrance) || !array_key_exists($key, $englishFromOTrance[$category])) { $missing[] = sprintf('%s_%s', $category, $key); continue; } diff --git a/plugins/LanguagesManager/LanguagesManager.php b/plugins/LanguagesManager/LanguagesManager.php index 66fba008e5..6a0fcf10e1 100644 --- a/plugins/LanguagesManager/LanguagesManager.php +++ b/plugins/LanguagesManager/LanguagesManager.php @@ -14,7 +14,6 @@ use Piwik\Common; use Piwik\Config; use Piwik\Cookie; use Piwik\Db; -use Piwik\DbHelper; use Piwik\Piwik; use Piwik\Translate; use Piwik\View; @@ -102,7 +101,8 @@ class LanguagesManager extends \Piwik\Plugin public function deleteUserLanguage($userLogin) { - Db::query('DELETE FROM ' . Common::prefixTable('user_language') . ' WHERE login = ?', $userLogin); + $model = new Model(); + $model->deleteUserLanguage($userLogin); } /** @@ -110,10 +110,7 @@ class LanguagesManager extends \Piwik\Plugin */ public function install() { - $userLanguage = "login VARCHAR( 100 ) NOT NULL , - language VARCHAR( 10 ) NOT NULL , - PRIMARY KEY ( login )"; - DbHelper::createTable('user_language', $userLanguage); + Model::install(); } /** @@ -121,7 +118,7 @@ class LanguagesManager extends \Piwik\Plugin */ public function uninstall() { - Db::dropTables(Common::prefixTable('user_language')); + Model::uninstall(); } /** diff --git a/plugins/LanguagesManager/Model.php b/plugins/LanguagesManager/Model.php new file mode 100644 index 0000000000..e40452c134 --- /dev/null +++ b/plugins/LanguagesManager/Model.php @@ -0,0 +1,72 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * + */ +namespace Piwik\Plugins\LanguagesManager; + +use Piwik\Common; +use Piwik\Db; +use Piwik\DbHelper; + +class Model +{ + private static $rawPrefix = 'user_language'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + + public function deleteUserLanguage($userLogin) + { + Db::query('DELETE FROM ' . $this->table . ' WHERE login = ?', $userLogin); + } + + /** + * Returns the language for the user + * + * @param string $userLogin + * @return string + */ + public function getLanguageForUser($userLogin) + { + return Db::fetchOne('SELECT language FROM ' . $this->table . + ' WHERE login = ? ', array($userLogin)); + } + + /** + * Sets the language for the user + * + * @param string $login + * @param string $languageCode + * @return bool + */ + public function setLanguageForUser($login, $languageCode) + { + $query = 'INSERT INTO ' . $this->table . + ' (login, language) VALUES (?,?) ON DUPLICATE KEY UPDATE language=?'; + $bind = array($login, $languageCode, $languageCode); + Db::query($query, $bind); + + return true; + } + + public static function install() + { + $userLanguage = "login VARCHAR( 100 ) NOT NULL , + language VARCHAR( 10 ) NOT NULL , + PRIMARY KEY ( login )"; + DbHelper::createTable(self::$rawPrefix, $userLanguage); + } + + public static function uninstall() + { + Db::dropTables(Common::prefixTable(self::$rawPrefix)); + } +} diff --git a/plugins/Live/API.php b/plugins/Live/API.php index c2acabb619..d15cca9e36 100644 --- a/plugins/Live/API.php +++ b/plugins/Live/API.php @@ -306,7 +306,7 @@ class API extends \Piwik\Plugin\API $cities[$countryCode] = array(); } $city = $visit->getColumn('city'); - if(!empty($city)) { + if (!empty($city)) { $cities[$countryCode][] = $city; } } @@ -325,7 +325,7 @@ class API extends \Piwik\Plugin\API 'nb_visits' => $nbVisits, 'flag' => \Piwik\Plugins\UserCountry\getFlagFromCode($countryCode), 'prettyName' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode)); - if(!empty($cities[$countryCode])) { + if (!empty($cities[$countryCode])) { $countryInfo['cities'] = array_unique($cities[$countryCode]); } $result['countries'][] = $countryInfo; @@ -476,8 +476,7 @@ class API extends \Piwik\Plugin\API $segment = new Segment($segment, $idSite); $queryInfo = $segment->getSelectQuery($select, $from, $where, $whereBind, $orderBy, $groupBy); - $sql = "SELECT sub.idvisitor, sub.visit_last_action_time - FROM ({$queryInfo['sql']}) as sub + $sql = "SELECT sub.idvisitor, sub.visit_last_action_time FROM ({$queryInfo['sql']}) as sub WHERE $visitLastActionTimeCondition LIMIT 1"; $bind = array_merge($queryInfo['bind'], array($visitLastActionTime)); @@ -589,7 +588,7 @@ class API extends \Piwik\Plugin\API $visitorDetailsArray['serverTimestamp'] = $visitorDetailsArray['lastActionTimestamp']; $dateTimeVisit = Date::factory($visitorDetailsArray['lastActionTimestamp'], $timezone); - if($dateTimeVisit) { + if ($dateTimeVisit) { $visitorDetailsArray['serverTimePretty'] = $dateTimeVisit->getLocalized('%time%'); $visitorDetailsArray['serverDatePretty'] = $dateTimeVisit->getLocalized(Piwik::translate('CoreHome_ShortDateFormat')); } @@ -703,8 +702,7 @@ class API extends \Piwik\Plugin\API // Group by idvisit so that a visitor converting 2 goals only appears once $sql = " - SELECT sub.* - FROM ( + SELECT sub.* FROM ( " . $subQuery['sql'] . " $sqlLimit ) AS sub diff --git a/plugins/Live/Visitor.php b/plugins/Live/Visitor.php index ae01ed4e18..55fd3fed83 100644 --- a/plugins/Live/Visitor.php +++ b/plugins/Live/Visitor.php @@ -309,7 +309,7 @@ class Visitor implements VisitorInterface } elseif ($actionDetail['type'] == Action::TYPE_EVENT_CATEGORY) { // Handle Event - if(strlen($actionDetail['pageTitle']) > 0) { + if (strlen($actionDetail['pageTitle']) > 0) { $actionDetail['eventName'] = $actionDetail['pageTitle']; } @@ -322,8 +322,8 @@ class Visitor implements VisitorInterface } // Event value / Generation time - if($actionDetail['type'] == Action::TYPE_EVENT_CATEGORY) { - if(strlen($actionDetail['custom_float']) > 0) { + if ($actionDetail['type'] == Action::TYPE_EVENT_CATEGORY) { + if (strlen($actionDetail['custom_float']) > 0) { $actionDetail['eventValue'] = round($actionDetail['custom_float'], self::EVENT_VALUE_PRECISION); } } elseif ($actionDetail['custom_float'] > 0) { diff --git a/plugins/Live/VisitorLog.php b/plugins/Live/VisitorLog.php index 2afc67349b..054b2f50ae 100644 --- a/plugins/Live/VisitorLog.php +++ b/plugins/Live/VisitorLog.php @@ -105,7 +105,7 @@ class VisitorLog extends Visualization && $filterEcommerce == \Piwik\Plugins\Goals\Controller::ECOMMERCE_LOG_SHOW_ORDERS; $isAbandonedCart = $action['type'] == 'ecommerceAbandonedCart' && $filterEcommerce == \Piwik\Plugins\Goals\Controller::ECOMMERCE_LOG_SHOW_ABANDONED_CARTS; - if($isAbandonedCart || $isEcommerceOrder) { + if ($isAbandonedCart || $isEcommerceOrder) { return true; } } diff --git a/plugins/Login/Controller.php b/plugins/Login/Controller.php index 82ae9ccab2..3831e89c79 100644 --- a/plugins/Login/Controller.php +++ b/plugins/Login/Controller.php @@ -330,4 +330,4 @@ class Controller extends \Piwik\Plugin\Controller Url::redirectToUrl($logoutUrl); } } -}
\ No newline at end of file +} diff --git a/plugins/Login/Login.php b/plugins/Login/Login.php index 4c33579176..8b65e2e175 100644 --- a/plugins/Login/Login.php +++ b/plugins/Login/Login.php @@ -85,7 +85,7 @@ class Login extends \Piwik\Plugin */ public static function initAuthenticationFromCookie(\Piwik\Auth $auth, $activateCookieAuth) { - if(self::isModuleIsAPI() && !$activateCookieAuth) { + if (self::isModuleIsAPI() && !$activateCookieAuth) { return; } diff --git a/plugins/MultiSites/API.php b/plugins/MultiSites/API.php index 41031fae8f..ea393414f7 100755 --- a/plugins/MultiSites/API.php +++ b/plugins/MultiSites/API.php @@ -346,7 +346,7 @@ class API extends \Piwik\Plugin\API { $metrics = self::$baseMetrics; - if(Common::isActionsPluginEnabled()) { + if (Common::isActionsPluginEnabled()) { $metrics[self::NB_PAGEVIEWS_LABEL] = array( self::METRIC_TRANSLATION_KEY => 'General_ColumnPageviews', self::METRIC_EVOLUTION_COL_NAME_KEY => 'pageviews_evolution', diff --git a/plugins/PrivacyManager/DoNotTrackHeaderChecker.php b/plugins/PrivacyManager/DoNotTrackHeaderChecker.php index b857debf85..14938f426e 100644 --- a/plugins/PrivacyManager/DoNotTrackHeaderChecker.php +++ b/plugins/PrivacyManager/DoNotTrackHeaderChecker.php @@ -26,7 +26,7 @@ class DoNotTrackHeaderChecker */ public function checkHeaderInTracker(&$exclude) { - if($exclude) { + if ($exclude) { Common::printDebug("Visit is already excluded, no need to check DoNotTrack support."); return; } diff --git a/plugins/PrivacyManager/LogDataPurger.php b/plugins/PrivacyManager/LogDataPurger.php index 2ec73deb81..6fe1381c50 100755 --- a/plugins/PrivacyManager/LogDataPurger.php +++ b/plugins/PrivacyManager/LogDataPurger.php @@ -173,7 +173,7 @@ class LogDataPurger private function getLogTableDeleteCount($table, $maxIdVisit) { $sql = "SELECT COUNT(*) FROM $table WHERE idvisit <= ?"; - return (int)Db::fetchOne($sql, array($maxIdVisit)); + return (int) Db::fetchOne($sql, array($maxIdVisit)); } private function createTempTable() diff --git a/plugins/PrivacyManager/ReportsPurger.php b/plugins/PrivacyManager/ReportsPurger.php index a35169e6ef..9889c00e9d 100755 --- a/plugins/PrivacyManager/ReportsPurger.php +++ b/plugins/PrivacyManager/ReportsPurger.php @@ -260,12 +260,11 @@ class ReportsPurger { $maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM $table"); - $sql = "SELECT COUNT(*) - FROM $table - WHERE name NOT IN ('" . implode("','", $this->metricsToKeep) . "') - AND name NOT LIKE 'done%' - AND idarchive >= ? - AND idarchive < ?"; + $sql = "SELECT COUNT(*) FROM $table + WHERE name NOT IN ('" . implode("','", $this->metricsToKeep) . "') + AND name NOT LIKE 'done%' + AND idarchive >= ? + AND idarchive < ?"; $segments = Db::segmentedFetchOne($sql, 0, $maxIdArchive, self::$selectSegmentSize); return array_sum($segments); @@ -275,11 +274,10 @@ class ReportsPurger { $maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM $table"); - $sql = "SELECT COUNT(*) - FROM $table - WHERE " . $this->getBlobTableWhereExpr($oldNumericTables, $table) . " - AND idarchive >= ? - AND idarchive < ?"; + $sql = "SELECT COUNT(*) FROM $table + WHERE " . $this->getBlobTableWhereExpr($oldNumericTables, $table) . " + AND idarchive >= ? + AND idarchive < ?"; $segments = Db::segmentedFetchOne($sql, 0, $maxIdArchive, self::$selectSegmentSize); return array_sum($segments); @@ -325,12 +323,11 @@ class ReportsPurger $maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM $table"); - $sql = "SELECT idarchive - FROM $table - WHERE name != 'done' - AND name LIKE 'done_%.%' - AND idarchive >= ? - AND idarchive < ?"; + $sql = "SELECT idarchive FROM $table + WHERE name != 'done' + AND name LIKE 'done_%.%' + AND idarchive >= ? + AND idarchive < ?"; if (is_null($this->segmentArchiveIds)) { $this->segmentArchiveIds = array(); diff --git a/plugins/Referrers/Columns/Base.php b/plugins/Referrers/Columns/Base.php index de871401b3..a69fcc54bf 100644 --- a/plugins/Referrers/Columns/Base.php +++ b/plugins/Referrers/Columns/Base.php @@ -244,14 +244,14 @@ abstract class Base extends VisitDimension protected function detectCampaignKeywordFromReferrerUrl() { - if(!empty($this->nameReferrerAnalyzed) + if (!empty($this->nameReferrerAnalyzed) && !empty($this->keywordReferrerAnalyzed)) { // keyword is already set, we skip return true; } // Set the Campaign keyword to the keyword found in the Referrer URL if any - if(!empty($this->nameReferrerAnalyzed)) { + if (!empty($this->nameReferrerAnalyzed)) { $referrerUrlInfo = UrlHelper::extractSearchEngineInformationFromUrl($this->referrerUrl); if (!empty($referrerUrlInfo['keywords'])) { $this->keywordReferrerAnalyzed = $referrerUrlInfo['keywords']; @@ -270,7 +270,7 @@ abstract class Base extends VisitDimension $parsedAdsenseReferrerUrl = parse_url($value); if (!empty($parsedAdsenseReferrerUrl['host'])) { - if(empty($this->nameReferrerAnalyzed)) { + if (empty($this->nameReferrerAnalyzed)) { $type = $this->getParameterValueFromReferrerUrl('ad_type'); $type = $type ? " ($type)" : ''; $this->nameReferrerAnalyzed = self::LABEL_ADWORDS_NAME . $type; @@ -304,7 +304,7 @@ abstract class Base extends VisitDimension return false; } // if we detected a campaign but there is still no keyword set, we set the keyword to the Referrer host - if(empty($this->keywordReferrerAnalyzed)) { + if (empty($this->keywordReferrerAnalyzed)) { $this->keywordReferrerAnalyzed = $this->referrerHost; } diff --git a/plugins/Referrers/Controller.php b/plugins/Referrers/Controller.php index e683cb7f9e..f01c61f647 100644 --- a/plugins/Referrers/Controller.php +++ b/plugins/Referrers/Controller.php @@ -332,7 +332,7 @@ function DisplayTopKeywords($url = "") $url = empty($url) ? "http://". $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] : $url; $api = "' . $api . '&url=" . urlencode($url); $keywords = @unserialize(file_get_contents($api)); - if($keywords === false || isset($keywords["result"])) { + if ($keywords === false || isset($keywords["result"])) { // DEBUG ONLY: uncomment for troubleshooting an empty output (the URL output reveals the token_auth) // echo "Error while fetching the <a href=\'$api\'>Top Keywords from Piwik</a>"; return; @@ -344,7 +344,7 @@ function DisplayTopKeywords($url = "") foreach($keywords as $keyword) { $output .= "<li>". $keyword . "</li>"; } - if(empty($keywords)) { $output .= "Nothing yet..."; } + if (empty($keywords)) { $output .= "Nothing yet..."; } $output .= "</ul>"; echo $output; } diff --git a/plugins/Referrers/functions.php b/plugins/Referrers/functions.php index 8f7a4023df..e0fee30833 100644 --- a/plugins/Referrers/functions.php +++ b/plugins/Referrers/functions.php @@ -39,7 +39,7 @@ function getSocialMainUrl($url) $social = getSocialNetworkFromDomain($url); foreach (Common::getSocialUrls() as $domain => $name) { - if($name == $social) { + if ($name == $social) { return $domain; } @@ -57,7 +57,7 @@ function getSocialNetworkFromDomain($url) { foreach (Common::getSocialUrls() as $domain => $name) { - if(preg_match('/(^|[\.\/])'.$domain.'([\.\/]|$)/', $url)) { + if (preg_match('/(^|[\.\/])'.$domain.'([\.\/]|$)/', $url)) { return $name; } diff --git a/plugins/ScheduledReports/API.php b/plugins/ScheduledReports/API.php index 3ea8a05c28..a42b5bb209 100644 --- a/plugins/ScheduledReports/API.php +++ b/plugins/ScheduledReports/API.php @@ -53,6 +53,9 @@ class API extends \Piwik\Plugin\API const REPORT_TRUNCATE = 23; + // static cache storing reports + public static $cache = array(); + /** * Creates a new report and schedules it. * @@ -84,29 +87,20 @@ class API extends \Piwik\Plugin\API // validation of requested reports $reports = self::validateRequestedReports($idSite, $reportType, $reports); - $db = Db::get(); - $idReport = $db->fetchOne("SELECT max(idreport) + 1 FROM " . Common::prefixTable('report')); - - if ($idReport == false) { - $idReport = 1; - } - - $db->insert(Common::prefixTable('report'), - array( - 'idreport' => $idReport, - 'idsite' => $idSite, - 'login' => $currentUser, - 'description' => $description, - 'idsegment' => $idSegment, - 'period' => $period, - 'hour' => $hour, - 'type' => $reportType, - 'format' => $reportFormat, - 'parameters' => $parameters, - 'reports' => $reports, - 'ts_created' => Date::now()->getDatetime(), - 'deleted' => 0, - )); + $idReport = $this->getModel()->createReport(array( + 'idsite' => $idSite, + 'login' => $currentUser, + 'description' => $description, + 'idsegment' => $idSegment, + 'period' => $period, + 'hour' => $hour, + 'type' => $reportType, + 'format' => $reportFormat, + 'parameters' => $parameters, + 'reports' => $reports, + 'ts_created' => Date::now()->getDatetime(), + 'deleted' => 0, + )); return $idReport; } @@ -130,7 +124,7 @@ class API extends \Piwik\Plugin\API Piwik::checkUserHasViewAccess($idSite); $scheduledReports = $this->getReports($idSite, $periodSearch = false, $idReport); - $report = reset($scheduledReports); + $report = reset($scheduledReports); $idReport = $report['idreport']; $currentUser = Piwik::getCurrentUserLogin(); @@ -144,19 +138,16 @@ class API extends \Piwik\Plugin\API // validation of requested reports $reports = self::validateRequestedReports($idSite, $reportType, $reports); - Db::get()->update(Common::prefixTable('report'), - array( - 'description' => $description, - 'idsegment' => $idSegment, - 'period' => $period, - 'hour' => $hour, - 'type' => $reportType, - 'format' => $reportFormat, - 'parameters' => $parameters, - 'reports' => $reports, - ), - "idreport = '$idReport'" - ); + $this->getModel()->updateReport($idReport, array( + 'description' => $description, + 'idsegment' => $idSegment, + 'period' => $period, + 'hour' => $hour, + 'type' => $reportType, + 'format' => $reportFormat, + 'parameters' => $parameters, + 'reports' => $reports, + )); self::$cache = array(); } @@ -172,18 +163,13 @@ class API extends \Piwik\Plugin\API $report = reset($APIScheduledReports); Piwik::checkUserHasSuperUserAccessOrIsTheUser($report['login']); - Db::get()->update(Common::prefixTable('report'), - array( - 'deleted' => 1, - ), - "idreport = '$idReport'" - ); + $this->getModel()->updateReport($idReport, array( + 'deleted' => 1, + )); + self::$cache = array(); } - // static cache storing reports - public static $cache = array(); - /** * Returns the list of reports matching the passed parameters * @@ -198,6 +184,7 @@ class API extends \Piwik\Plugin\API public function getReports($idSite = false, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = false, $idSegment = false) { Piwik::checkUserHasSomeViewAccess(); + $cacheKey = (int)$idSite . '.' . (string)$period . '.' . (int)$idReport . '.' . (int)$ifSuperUserReturnOnlySuperUserReports; if (isset(self::$cache[$cacheKey])) { return self::$cache[$cacheKey]; @@ -427,7 +414,7 @@ class API extends \Piwik\Plugin\API array(&$reportRenderer, $reportType, $outputType, $report) ); - if(is_null($reportRenderer)) { + if (is_null($reportRenderer)) { throw new Exception("A report renderer was not supplied in the event " . self::GET_RENDERER_INSTANCE_EVENT); } @@ -556,10 +543,8 @@ class API extends \Piwik\Plugin\API ); // Update flag in DB - Db::get()->update(Common::prefixTable('report'), - array('ts_last_sent' => Date::now()->getDatetime()), - "idreport = " . $report['idreport'] - ); + $now = Date::now()->getDatetime(); + $this->getModel()->updateReport($report['idreport'], array('ts_last_sent' => $now)); // If running from piwik.php with debug, do not delete the PDF after sending the email if (!isset($GLOBALS['PIWIK_TRACKER_DEBUG']) || !$GLOBALS['PIWIK_TRACKER_DEBUG']) { @@ -567,6 +552,11 @@ class API extends \Piwik\Plugin\API } } + private function getModel() + { + return new Model(); + } + private static function getReportSubjectAndReportTitle($websiteName, $reports) { // if the only report is "All websites", we don't display the site name diff --git a/plugins/ScheduledReports/Model.php b/plugins/ScheduledReports/Model.php new file mode 100644 index 0000000000..01507f65f9 --- /dev/null +++ b/plugins/ScheduledReports/Model.php @@ -0,0 +1,93 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + */ +namespace Piwik\Plugins\ScheduledReports; + +use Piwik\Common; +use Piwik\Db; +use Piwik\DbHelper; +use Piwik\ReportRenderer; +use Piwik\Translate; + +class Model +{ + private static $rawPrefix = 'report'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + + public function deleteUserReportForSite($userLogin, $idSite) + { + $query = 'DELETE FROM ' . $this->table . ' WHERE login = ? and idsite = ?'; + $bind = array($userLogin, $idSite); + Db::query($query, $bind); + } + + public function deleteAllReportForUser($userLogin) + { + Db::query('DELETE FROM ' . $this->table . ' WHERE login = ?', $userLogin); + } + + public function updateReport($idReport, $report) + { + $idReport = (int) $idReport; + + $this->getDb()->update($this->table, $report, "idreport = " . $idReport); + } + + public function createReport($report) + { + $nextId = $this->getNextReportId(); + $report['idreport'] = $nextId; + + $this->getDb()->insert($this->table, $report); + + return $nextId; + } + + private function getNextReportId() + { + $db = $this->getDb(); + $idReport = $db->fetchOne("SELECT max(idreport) + 1 FROM " . $this->table); + + if ($idReport == false) { + $idReport = 1; + } + + return $idReport; + } + + private function getDb() + { + return Db::get(); + } + + public static function install() + { + $reportTable = "`idreport` INT(11) NOT NULL AUTO_INCREMENT, + `idsite` INTEGER(11) NOT NULL, + `login` VARCHAR(100) NOT NULL, + `description` VARCHAR(255) NOT NULL, + `idsegment` INT(11), + `period` VARCHAR(10) NOT NULL, + `hour` tinyint NOT NULL default 0, + `type` VARCHAR(10) NOT NULL, + `format` VARCHAR(10) NOT NULL, + `reports` TEXT NOT NULL, + `parameters` TEXT NULL, + `ts_created` TIMESTAMP NULL, + `ts_last_sent` TIMESTAMP NULL, + `deleted` tinyint(4) NOT NULL default 0, + PRIMARY KEY (`idreport`)"; + + DbHelper::createTable(self::$rawPrefix, $reportTable); + } +} diff --git a/plugins/ScheduledReports/ScheduledReports.php b/plugins/ScheduledReports/ScheduledReports.php index ca5ebb9b41..e59e9140ab 100644 --- a/plugins/ScheduledReports/ScheduledReports.php +++ b/plugins/ScheduledReports/ScheduledReports.php @@ -9,9 +9,7 @@ namespace Piwik\Plugins\ScheduledReports; use Exception; -use Piwik\Common; use Piwik\Db; -use Piwik\DbHelper; use Piwik\Mail; use Piwik\Piwik; use Piwik\Plugins\MobileMessaging\MobileMessaging; @@ -469,27 +467,27 @@ class ScheduledReports extends \Piwik\Plugin $reportsNeedSegment = array(); - if(!$updatedSegment['enable_all_users']) { + if (!$updatedSegment['enable_all_users']) { // which reports would become invisible to other users? foreach($reportsUsingSegment as $report) { - if($report['login'] == Piwik::getCurrentUserLogin()) { + if ($report['login'] == Piwik::getCurrentUserLogin()) { continue; } $reportsNeedSegment[] = $report; } } - if($updatedSegment['enable_only_idsite']) { + if ($updatedSegment['enable_only_idsite']) { // which reports from other websites are set to use this segment restricted to one website? foreach($reportsUsingSegment as $report) { - if($report['idsite'] == $updatedSegment['enable_only_idsite']) { + if ($report['idsite'] == $updatedSegment['enable_only_idsite']) { continue; } $reportsNeedSegment[] = $report; } } - if(empty($reportsNeedSegment)) { + if (empty($reportsNeedSegment)) { return; } @@ -526,7 +524,7 @@ class ScheduledReports extends \Piwik\Plugin public function deleteUserReport($userLogin) { - Db::query('DELETE FROM ' . Common::prefixTable('report') . ' WHERE login = ?', $userLogin); + $this->getModel()->deleteAllReportForUser($userLogin); } public function deleteUserReportForSites($userLogin, $idSites) @@ -535,33 +533,21 @@ class ScheduledReports extends \Piwik\Plugin return; } - $table = Common::prefixTable('report'); + $model = $this->getModel(); foreach ($idSites as $idSite) { - Db::query('DELETE FROM ' . $table . ' WHERE login = ? and idsite = ?', - array($userLogin, $idSite)); + $model->deleteUserReportForSite($userLogin, $idSite); } } + private function getModel() + { + return new Model(); + } + public function install() { - $reportTable = "`idreport` INT(11) NOT NULL AUTO_INCREMENT, - `idsite` INTEGER(11) NOT NULL, - `login` VARCHAR(100) NOT NULL, - `description` VARCHAR(255) NOT NULL, - `idsegment` INT(11), - `period` VARCHAR(10) NOT NULL, - `hour` tinyint NOT NULL default 0, - `type` VARCHAR(10) NOT NULL, - `format` VARCHAR(10) NOT NULL, - `reports` TEXT NOT NULL, - `parameters` TEXT NULL, - `ts_created` TIMESTAMP NULL, - `ts_last_sent` TIMESTAMP NULL, - `deleted` tinyint(4) NOT NULL default 0, - PRIMARY KEY (`idreport`)"; - - DbHelper::createTable('report', $reportTable); + Model::install(); } private static function checkAdditionalEmails($additionalEmails) diff --git a/plugins/SegmentEditor/API.php b/plugins/SegmentEditor/API.php index 98b752cc2a..699ad3a4ea 100644 --- a/plugins/SegmentEditor/API.php +++ b/plugins/SegmentEditor/API.php @@ -103,6 +103,7 @@ class API extends \Piwik\Plugin\API if (empty($segment)) { throw new Exception("Requested segment not found"); } + return $segment; } @@ -128,7 +129,7 @@ class API extends \Piwik\Plugin\API public function isUserCanAddNewSegment($idSite) { - if(Piwik::isUserIsAnonymous()) { + if (Piwik::isUserIsAnonymous()) { return false; } @@ -145,13 +146,13 @@ class API extends \Piwik\Plugin\API protected function checkUserCanEditOrDeleteSegment($segment) { - if(Piwik::hasUserSuperUserAccess()) { + if (Piwik::hasUserSuperUserAccess()) { return; } $this->checkUserIsNotAnonymous(); - if($segment['login'] != Piwik::getCurrentUserLogin()) { + if ($segment['login'] != Piwik::getCurrentUserLogin()) { throw new Exception($this->getMessageCannotEditSegmentCreatedBySuperUser()); } } @@ -177,11 +178,16 @@ class API extends \Piwik\Plugin\API */ Piwik::postEvent('SegmentEditor.deactivate', array($idSegment)); - $db = Db::get(); - $db->delete(Common::prefixTable('segment'), 'idsegment = ' . $idSegment); + $this->getModel()->deleteSegment($idSegment); + return true; } + private function getModel() + { + return new Model(); + } + /** * Modifies an existing stored segment. * @@ -201,9 +207,9 @@ class API extends \Piwik\Plugin\API $idSite = $this->checkIdSite($idSite); $this->checkSegmentName($name); - $definition = $this->checkSegmentValue($definition, $idSite); + $definition = $this->checkSegmentValue($definition, $idSite); $enabledAllUsers = $this->checkEnabledAllUsers($enabledAllUsers); - $autoArchive = $this->checkAutoArchive($autoArchive, $idSite); + $autoArchive = $this->checkAutoArchive($autoArchive, $idSite); $bind = array( 'name' => $name, @@ -224,11 +230,8 @@ class API extends \Piwik\Plugin\API */ Piwik::postEvent('SegmentEditor.update', array($idSegment, $bind)); - $db = Db::get(); - $db->update(Common::prefixTable("segment"), - $bind, - "idsegment = $idSegment" - ); + $this->getModel()->updateSegment($idSegment, $bind); + return true; } @@ -252,7 +255,6 @@ class API extends \Piwik\Plugin\API $enabledAllUsers = $this->checkEnabledAllUsers($enabledAllUsers); $autoArchive = $this->checkAutoArchive($autoArchive, $idSite); - $db = Db::get(); $bind = array( 'name' => $name, 'definition' => $definition, @@ -263,8 +265,10 @@ class API extends \Piwik\Plugin\API 'ts_created' => Date::now()->getDatetime(), 'deleted' => 0, ); - $db->insert(Common::prefixTable("segment"), $bind); - return $db->lastInsertId(); + + $id = $this->getModel()->createSegment($bind); + + return $id; } /** @@ -277,12 +281,12 @@ class API extends \Piwik\Plugin\API public function get($idSegment) { Piwik::checkUserHasSomeViewAccess(); + if (!is_numeric($idSegment)) { throw new Exception("idSegment should be numeric."); } - $segment = Db::get()->fetchRow("SELECT * " . - " FROM " . Common::prefixTable("segment") . - " WHERE idsegment = ?", $idSegment); + + $segment = $this->getModel()->getSegment($idSegment); if (empty($segment)) { return false; @@ -300,6 +304,7 @@ class API extends \Piwik\Plugin\API if ($segment['deleted']) { throw new Exception("This segment is marked as deleted. "); } + return $segment; } @@ -319,7 +324,7 @@ class API extends \Piwik\Plugin\API $userLogin = Piwik::getCurrentUserLogin(); - $model = new Model(); + $model = $this->getModel(); if (empty($idSite)) { $segments = $model->getAllSegments($userLogin); } else { diff --git a/plugins/SegmentEditor/Model.php b/plugins/SegmentEditor/Model.php index 54c0e07ddf..8bfcc957ae 100644 --- a/plugins/SegmentEditor/Model.php +++ b/plugins/SegmentEditor/Model.php @@ -10,12 +10,21 @@ namespace Piwik\Plugins\SegmentEditor; use Piwik\Common; use Piwik\Db; +use Piwik\DbHelper; /** * The SegmentEditor Model lets you persist and read custom Segments from the backend without handling any logic. */ class Model { + private static $rawPrefix = 'segment'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + /** * Returns all stored segments. * @@ -36,7 +45,7 @@ class Model $sql = $this->buildQuerySortedByName("($whereIdSite enable_only_idsite = 0) AND deleted = 0 AND auto_archive = 1"); - $segments = Db::get()->fetchAll($sql, $bind); + $segments = $this->getDb()->fetchAll($sql, $bind); return $segments; } @@ -52,7 +61,7 @@ class Model $bind = array($userLogin); $sql = $this->buildQuerySortedByName('deleted = 0 AND (enable_all_users = 1 OR login = ?)'); - $segments = Db::get()->fetchAll($sql, $bind); + $segments = $this->getDb()->fetchAll($sql, $bind); return $segments; } @@ -70,16 +79,69 @@ class Model $sql = $this->buildQuerySortedByName('(enable_only_idsite = ? OR enable_only_idsite = 0) AND deleted = 0 AND (enable_all_users = 1 OR login = ?)'); - $segments = Db::get()->fetchAll($sql, $bind); + $segments = $this->getDb()->fetchAll($sql, $bind); return $segments; } + public function deleteSegment($idSegment) + { + $db = $this->getDb(); + $db->delete($this->table, 'idsegment = ' . (int) $idSegment); + } + + public function updateSegment($idSegment, $segment) + { + $idSegment = (int) $idSegment; + + $db = $this->getDb(); + $db->update($this->table, $segment, "idsegment = $idSegment"); + + return true; + } + + public function createSegment($segment) + { + $db = $this->getDb(); + $db->insert($this->table, $segment); + $id = $db->lastInsertId(); + + return $id; + } + + public function getSegment($idSegment) + { + $db = $this->getDb(); + $segment = $db->fetchRow("SELECT * FROM " . $this->table . " WHERE idsegment = ?", $idSegment); + + return $segment; + } + + private function getDb() + { + return Db::get(); + } + private function buildQuerySortedByName($where) { - $sql = "SELECT * FROM " . Common::prefixTable("segment") . - " WHERE $where ORDER BY name ASC"; + return "SELECT * FROM " . $this->table . " WHERE $where ORDER BY name ASC"; + } + + public static function install() + { + $segmentTable = "`idsegment` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(255) NOT NULL, + `definition` TEXT NOT NULL, + `login` VARCHAR(100) NOT NULL, + `enable_all_users` tinyint(4) NOT NULL default 0, + `enable_only_idsite` INTEGER(11) NULL, + `auto_archive` tinyint(4) NOT NULL default 0, + `ts_created` TIMESTAMP NULL, + `ts_last_edit` TIMESTAMP NULL, + `deleted` tinyint(4) NOT NULL default 0, + PRIMARY KEY (`idsegment`)"; - return $sql; + DbHelper::createTable(self::$rawPrefix, $segmentTable); } + } diff --git a/plugins/SegmentEditor/SegmentEditor.php b/plugins/SegmentEditor/SegmentEditor.php index bd957c54c0..aef619156d 100644 --- a/plugins/SegmentEditor/SegmentEditor.php +++ b/plugins/SegmentEditor/SegmentEditor.php @@ -67,27 +67,17 @@ class SegmentEditor extends \Piwik\Plugin { $model = new Model(); $segmentToAutoArchive = $model->getSegmentsToAutoArchive($idSite); + foreach ($segmentToAutoArchive as $segmentInfo) { $segments[] = $segmentInfo['definition']; } + $segments = array_unique($segments); } public function install() { - $segmentTable = "`idsegment` INT(11) NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NOT NULL, - `definition` TEXT NOT NULL, - `login` VARCHAR(100) NOT NULL, - `enable_all_users` tinyint(4) NOT NULL default 0, - `enable_only_idsite` INTEGER(11) NULL, - `auto_archive` tinyint(4) NOT NULL default 0, - `ts_created` TIMESTAMP NULL, - `ts_last_edit` TIMESTAMP NULL, - `deleted` tinyint(4) NOT NULL default 0, - PRIMARY KEY (`idsegment`)"; - - DbHelper::createTable('segment', $segmentTable); + Model::install(); } public function getJsFiles(&$jsFiles) diff --git a/plugins/SitesManager/API.php b/plugins/SitesManager/API.php index 5b856cd862..0d8a85c11c 100644 --- a/plugins/SitesManager/API.php +++ b/plugins/SitesManager/API.php @@ -143,11 +143,9 @@ class API extends \Piwik\Plugin\API public function getSitesFromGroup($group) { Piwik::checkUserHasSuperUserAccess(); - $group = trim($group); - $sites = Db::get()->fetchAll("SELECT * - FROM " . Common::prefixTable("site") . " - WHERE `group` = ?", $group); + $group = trim($group); + $sites = $this->getModel()->getSitesFromGroup($group); Site::setSitesFromArray($sites); return $sites; @@ -162,12 +160,10 @@ class API extends \Piwik\Plugin\API public function getSitesGroups() { Piwik::checkUserHasSuperUserAccess(); - $groups = Db::get()->fetchAll("SELECT DISTINCT `group` FROM " . Common::prefixTable("site")); - $cleanedGroups = array(); - foreach ($groups as $group) { - $cleanedGroups[] = $group['group']; - } - $cleanedGroups = array_map('trim', $cleanedGroups); + + $groups = $this->getModel()->getSitesGroups(); + $cleanedGroups = array_map('trim', $groups); + return $cleanedGroups; } @@ -219,12 +215,15 @@ class API extends \Piwik\Plugin\API public function getAllSites() { Piwik::checkUserHasSuperUserAccess(); - $sites = Db::get()->fetchAll("SELECT * FROM " . Common::prefixTable("site") . " ORDER BY idsite ASC"); + + $sites = $this->getModel()->getAllSites(); $return = array(); foreach ($sites as $site) { $return[$site['idsite']] = $site; } + Site::setSitesFromArray($return); + return $return; } @@ -258,24 +257,16 @@ class API extends \Piwik\Plugin\API if (empty($timestamp)) $timestamp = time(); - $time = Date::factory((int)$timestamp)->getDatetime(); - $result = Db::fetchAll(" - SELECT - idsite - FROM - " . Common::prefixTable('site') . " s - WHERE EXISTS ( - SELECT 1 - FROM " . Common::prefixTable('log_visit') . " v - WHERE v.idsite = s.idsite - AND visit_last_action_time > ? - AND visit_last_action_time <= ? - LIMIT 1) - ", array($time, $now = Date::now()->addHour(1)->getDatetime())); + $time = Date::factory((int)$timestamp)->getDatetime(); + $now = Date::now()->addHour(1)->getDatetime(); + + $result = $this->getModel()->getSitesWithVisits($time, $now); + $idSites = array(); foreach ($result as $idSite) { $idSites[] = $idSite['idsite']; } + return $idSites; } @@ -291,9 +282,11 @@ class API extends \Piwik\Plugin\API $sitesId = $this->getSitesIdWithAdminAccess(); $sites = $this->getSitesFromIds($sitesId); - if ($fetchAliasUrls) - foreach ($sites as &$site) + if ($fetchAliasUrls) { + foreach ($sites as &$site) { $site['alias_urls'] = API::getInstance()->getSiteUrlsFromId($site['idsite']); + } + } return $sites; } @@ -373,10 +366,12 @@ class API extends \Piwik\Plugin\API } $accessRaw = Access::getInstance()->getRawSitesWithSomeViewAccess($_restrictSitesToLogin); - $sitesId = array(); + $sitesId = array(); + foreach ($accessRaw as $access) { $sitesId[] = $access['idsite']; } + return $sitesId; } else { return Access::getInstance()->getSitesIdWithAtLeastViewAccess(); @@ -407,6 +402,7 @@ class API extends \Piwik\Plugin\API } else { $urlBis = str_replace('://', '://www.', $url); } + return array($url, $urlBis); } @@ -420,28 +416,12 @@ class API extends \Piwik\Plugin\API { $url = $this->removeTrailingSlash($url); list($url, $urlBis) = $this->getNormalizedUrls($url); + if (Piwik::hasUserSuperUserAccess()) { - $ids = Db::get()->fetchAll( - 'SELECT idsite - FROM ' . Common::prefixTable('site') . ' - WHERE (main_url = ? OR main_url = ?) ' . - 'UNION - SELECT idsite - FROM ' . Common::prefixTable('site_url') . ' - WHERE (url = ? OR url = ?) ', array($url, $urlBis, $url, $urlBis)); + $ids = $this->getModel()->getAllSitesIdFromSiteUrl($url, $urlBis); } else { $login = Piwik::getCurrentUserLogin(); - $ids = Db::get()->fetchAll( - 'SELECT idsite - FROM ' . Common::prefixTable('site') . ' - WHERE (main_url = ? OR main_url = ?)' . - 'AND idsite IN (' . Access::getSqlAccessSite('idsite') . ') ' . - 'UNION - SELECT idsite - FROM ' . Common::prefixTable('site_url') . ' - WHERE (url = ? OR url = ?)' . - 'AND idsite IN (' . Access::getSqlAccessSite('idsite') . ')', - array($url, $urlBis, $login, $url, $urlBis, $login)); + $ids = $this->getModel()->getSitesIdFromSiteUrlHavingAccess($url, $urlBis, $login); } return $ids; @@ -457,18 +437,17 @@ class API extends \Piwik\Plugin\API public function getSitesIdFromTimezones($timezones) { Piwik::checkUserHasSuperUserAccess(); + $timezones = Piwik::getArrayFromApiParameter($timezones); $timezones = array_unique($timezones); - $ids = Db::get()->fetchAll( - 'SELECT idsite - FROM ' . Common::prefixTable('site') . ' - WHERE timezone IN (' . Common::getSqlStringFieldsArray($timezones) . ') - ORDER BY idsite ASC', - $timezones); + + $ids = $this->getModel()->getSitesFromTimezones($timezones); + $return = array(); foreach ($ids as $id) { $return[] = $id['idsite']; } + return $return; } @@ -540,7 +519,7 @@ class API extends \Piwik\Plugin\API $db = Db::get(); - $url = $urls[0]; + $url = $urls[0]; $urls = array_slice($urls, 1); $bind = array('name' => $siteName, @@ -619,16 +598,7 @@ class API extends \Piwik\Plugin\API throw new Exception(Piwik::translate("SitesManager_ExceptionDeleteSite")); } - $db = Db::get(); - - $db->query("DELETE FROM " . Common::prefixTable("site") . " - WHERE idsite = ?", $idSite); - - $db->query("DELETE FROM " . Common::prefixTable("site_url") . " - WHERE idsite = ?", $idSite); - - $db->query("DELETE FROM " . Common::prefixTable("access") . " - WHERE idsite = ?", $idSite); + $this->getModel()->deleteSite($idSite); // we do not delete logs here on purpose (you can run these queries on the log_ tables to delete all data) Cache::deleteCacheWebsiteAttributes($idSite); @@ -682,12 +652,14 @@ class API extends \Piwik\Plugin\API private function checkAndReturnType($type) { - if(empty($type)) { + if (empty($type)) { $type = Site::DEFAULT_SITE_TYPE; } - if(!is_string($type)) { + + if (!is_string($type)) { throw new Exception("Invalid website type $type"); } + return $type; } @@ -704,14 +676,17 @@ class API extends \Piwik\Plugin\API if (empty($excludedIps)) { return ''; } + $ips = explode(',', $excludedIps); $ips = array_map('trim', $ips); $ips = array_filter($ips, 'strlen'); + foreach ($ips as $ip) { if (!$this->isValidIp($ip)) { throw new Exception(Piwik::translate('SitesManager_ExceptionInvalidIPFormat', array($ip, "1.2.3.4, 1.2.3.*, or 1.2.3.4/5"))); } } + $ips = implode(',', $ips); return $ips; } @@ -756,7 +731,7 @@ class API extends \Piwik\Plugin\API $urls = $this->cleanParameterUrls($urls); $this->checkUrls($urls); - $this->deleteSiteAliasUrls($idSite); + $this->getModel()->deleteSiteAliasUrls($idSite); $this->insertSiteUrls($idSite, $urls); $this->postUpdateWebsite($idSite); @@ -1131,17 +1106,15 @@ class API extends \Piwik\Plugin\API $bind['sitesearch_category_parameters'] = $searchCategoryParameters; $bind['type'] = $this->checkAndReturnType($type); - $db = Db::get(); - $db->update(Common::prefixTable("site"), - $bind, - "idsite = $idSite" - ); + $this->getModel()->updateSite($bind, $idSite); // we now update the main + alias URLs - $this->deleteSiteAliasUrls($idSite); + $this->getModel()->deleteSiteAliasUrls($idSite); + if (count($urls) > 1) { $this->addSiteAliasUrls($idSite, array_slice($urls, 1)); } + $this->postUpdateWebsite($idSite); } @@ -1158,14 +1131,9 @@ class API extends \Piwik\Plugin\API $idSites = Site::getIdSitesFromIdSitesString($idSites); Piwik::checkUserHasAdminAccess($idSites); - // Update piwik_site.ts_created - $query = "UPDATE " . Common::prefixTable("site") . - " SET ts_created = ?" . - " WHERE idsite IN ( " . implode(",", $idSites) . " ) - AND ts_created > ?"; $minDateSql = $minDate->subDay(1)->getDatetime(); - $bind = array($minDateSql, $minDateSql); - Db::query($query, $bind); + + $this->getModel()->updateSiteCreatedTime($idSites, $minDateSql); } private function checkAndReturnCommaSeparatedStringList($parameters) @@ -1296,12 +1264,8 @@ class API extends \Piwik\Plugin\API public function getUniqueSiteTimezones() { Piwik::checkUserHasSuperUserAccess(); - $results = Db::fetchAll("SELECT distinct timezone FROM " . Common::prefixTable('site')); - $timezones = array(); - foreach ($results as $result) { - $timezones[] = $result['timezone']; - } - return $timezones; + + return $this->getModel()->getUniqueSiteTimezones(); } /** @@ -1311,14 +1275,9 @@ class API extends \Piwik\Plugin\API private function insertSiteUrls($idSite, $urls) { if (count($urls) != 0) { - $db = Db::get(); foreach ($urls as $url) { try { - $db->insert(Common::prefixTable("site_url"), array( - 'idsite' => $idSite, - 'url' => $url - ) - ); + $this->getModel()->insertSiteUrl($idSite, $url); } catch(Exception $e) { // See bug #4149 } @@ -1327,16 +1286,6 @@ class API extends \Piwik\Plugin\API } /** - * Delete all the alias URLs for the given idSite. - */ - private function deleteSiteAliasUrls($idsite) - { - $db = Db::get(); - $db->query("DELETE FROM " . Common::prefixTable("site_url") . " - WHERE idsite = ?", $idsite); - } - - /** * Remove the final slash in the URLs if found * * @param string $url @@ -1350,6 +1299,7 @@ class API extends \Piwik\Plugin\API ) { $url = substr($url, 0, strlen($url) - 1); } + return $url; } @@ -1404,6 +1354,7 @@ class API extends \Piwik\Plugin\API if (empty($searchKeywordParameters)) { $searchKeywordParameters = ''; } + if (empty($searchCategoryParameters)) { $searchCategoryParameters = ''; } @@ -1439,9 +1390,10 @@ class API extends \Piwik\Plugin\API if (!is_array($urls)) { $urls = array($urls); } - $urls = array_filter($urls); + $urls = array_filter($urls); $urls = array_map('urldecode', $urls); + foreach ($urls as &$url) { $url = $this->removeTrailingSlash($url); if (strpos($url, 'http') !== 0) { @@ -1450,6 +1402,7 @@ class API extends \Piwik\Plugin\API $url = trim($url); $url = Common::sanitizeInputValue($url); } + $urls = array_unique($urls); return $urls; } @@ -1489,30 +1442,9 @@ class API extends \Piwik\Plugin\API return array(); } - $ids_str = ''; - foreach ($ids as $id_val) { - $ids_str .= $id_val . ' , '; - } - $ids_str .= $id_val; - - $db = Db::get(); - $bind = array('%' . $pattern . '%', 'http%' . $pattern . '%', '%' . $pattern . '%'); + $limit = SettingsPiwik::getWebsitesCountToDisplay(); + $sites = $this->getModel()->getPatternMatchSites($ids, $pattern, $limit); - // Also match the idsite - $where = ''; - if (is_numeric($pattern)) { - $bind[] = $pattern; - $where = 'OR s.idsite = ?'; - } - $sites = $db->fetchAll("SELECT idsite, name, main_url, `group` - FROM " . Common::prefixTable('site') . " s - WHERE ( s.name like ? - OR s.main_url like ? - OR s.`group` like ? - $where ) - AND idsite in ($ids_str) - LIMIT " . SettingsPiwik::getWebsitesCountToDisplay(), - $bind); return $sites; } diff --git a/plugins/SitesManager/Model.php b/plugins/SitesManager/Model.php index 207f59bdfd..7aa779b530 100644 --- a/plugins/SitesManager/Model.php +++ b/plugins/SitesManager/Model.php @@ -8,13 +8,162 @@ */ namespace Piwik\Plugins\SitesManager; +use Piwik\Access; +use Piwik\Date; use Piwik\Db; use Piwik\Common; use Exception; -use Piwik\Site; class Model { + private static $rawPrefix = 'site'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + + /** + * Returns all websites belonging to the specified group + * @param string $group Group name + * @return array of sites + */ + public function getSitesFromGroup($group) + { + $sites = $this->getDb()->fetchAll("SELECT * FROM " . $this->table . " + WHERE `group` = ?", $group); + + return $sites; + } + + /** + * Returns the list of website groups, including the empty group + * if no group were specified for some websites + * + * @return array of group names strings + */ + public function getSitesGroups() + { + $groups = $this->getDb()->fetchAll("SELECT DISTINCT `group` FROM " . $this->table); + + $cleanedGroups = array(); + foreach ($groups as $group) { + $cleanedGroups[] = $group['group']; + } + + return $cleanedGroups; + } + + /** + * Returns all websites + * + * @return array The list of websites, indexed by idsite + */ + public function getAllSites() + { + $sites = $this->getDb()->fetchAll("SELECT * FROM " . $this->table . " ORDER BY idsite ASC"); + + return $sites; + } + + /** + * Returns the list of the website IDs that received some visits since the specified timestamp. + * + * @param \Piwik\Date $time + * @param \Piwik\Date $now + * @return array The list of website IDs + */ + public function getSitesWithVisits($time, $now) + { + $sites = Db::fetchAll(" + SELECT idsite FROM " . $this->table . " s + WHERE EXISTS ( + SELECT 1 + FROM " . Common::prefixTable('log_visit') . " v + WHERE v.idsite = s.idsite + AND visit_last_action_time > ? + AND visit_last_action_time <= ? + LIMIT 1) + ", array($time, $now)); + + return $sites; + } + + + /** + * Returns the list of websites ID associated with a URL. + * + * @param string $url + * @param string $urlBis + * @return array list of websites ID + */ + public function getAllSitesIdFromSiteUrl($url, $urlBis) + { + $siteUrlTable = Common::prefixTable('site_url'); + + $ids = $this->getDb()->fetchAll( + 'SELECT idsite FROM ' . $this->table . ' + WHERE (main_url = ? OR main_url = ?) ' . + 'UNION + SELECT idsite FROM ' . $siteUrlTable . ' + WHERE (url = ? OR url = ?) ', array($url, $urlBis, $url, $urlBis)); + + return $ids; + } + + /** + * Returns the list of websites ID associated with a URL. + * + * @param string $url + * @return array list of websites ID + */ + public function getSitesIdFromSiteUrlHavingAccess($url, $urlBis, $login) + { + $siteUrlTable = Common::prefixTable('site_url'); + $sqlAccessSite = Access::getSqlAccessSite('idsite'); + + $ids = $this->getDb()->fetchAll( + 'SELECT idsite + FROM ' . $this->table . ' + WHERE (main_url = ? OR main_url = ?)' . + 'AND idsite IN (' . $sqlAccessSite . ') ' . + 'UNION + SELECT idsite + FROM ' . $siteUrlTable . ' + WHERE (url = ? OR url = ?)' . + 'AND idsite IN (' . $sqlAccessSite . ')', + array($url, $urlBis, $login, $url, $urlBis, $login)); + + return $ids; + } + + /** + * Returns all websites with a timezone matching one the specified timezones + * + * @param array $timezones + * @return array + * @ignore + */ + public function getSitesFromTimezones($timezones) + { + $query = 'SELECT idsite FROM ' . $this->table . ' + WHERE timezone IN (' . Common::getSqlStringFieldsArray($timezones) . ') + ORDER BY idsite ASC'; + $sites = $this->getDb()->fetchAll($query, $timezones); + + return $sites; + } + + public function deleteSite($idSite) + { + $db = $this->getDb(); + + $db->query("DELETE FROM " . $this->table . " WHERE idsite = ?", $idSite); + $db->query("DELETE FROM " . Common::prefixTable("site_url") . " WHERE idsite = ?", $idSite); + $db->query("DELETE FROM " . Common::prefixTable("access") . " WHERE idsite = ?", $idSite); + } + /** * Returns the list of websites from the ID array in parameters. * @@ -36,11 +185,10 @@ class Model $idSites = array_map('intval', $idSites); - $db = Db::get(); - $sites = $db->fetchAll("SELECT * - FROM " . Common::prefixTable("site") . " - WHERE idsite IN (" . implode(", ", $idSites) . ") - ORDER BY idsite ASC $limit"); + $db = $this->getDb(); + $sites = $db->fetchAll("SELECT * FROM " . $this->table . " + WHERE idsite IN (" . implode(", ", $idSites) . ") + ORDER BY idsite ASC $limit"); return $sites; } @@ -54,9 +202,8 @@ class Model */ public function getSiteFromId($idSite) { - $site = Db::get()->fetchRow("SELECT * - FROM " . Common::prefixTable("site") . " - WHERE idsite = ?", $idSite); + $site = Db::get()->fetchRow("SELECT * FROM " . $this->table . " + WHERE idsite = ?", $idSite); return $site; } @@ -69,11 +216,13 @@ class Model */ public function getSitesId() { - $result = Db::fetchAll("SELECT idsite FROM " . Common::prefixTable('site')); + $result = Db::fetchAll("SELECT idsite FROM " . Common::prefixTable('site')); + $idSites = array(); foreach ($result as $idSite) { $idSites[] = $idSite['idsite']; } + return $idSites; } @@ -87,7 +236,6 @@ class Model public function getSiteUrlsFromId($idSite) { $urls = $this->getAliasSiteUrlsFromId($idSite); - $site = $this->getSiteFromId($idSite); if (empty($site)) { @@ -106,14 +254,119 @@ class Model */ public function getAliasSiteUrlsFromId($idSite) { - $db = Db::get(); - $result = $db->fetchAll("SELECT url - FROM " . Common::prefixTable("site_url") . " - WHERE idsite = ?", $idSite); + $db = $this->getDb(); + $result = $db->fetchAll("SELECT url FROM " . Common::prefixTable("site_url") . " + WHERE idsite = ?", $idSite); $urls = array(); foreach ($result as $url) { $urls[] = $url['url']; } + return $urls; } + + public function updateSite($site, $idSite) + { + $idSite = (int) $idSite; + + $db = $this->getDb(); + $db->update($this->table, $site, "idsite = $idSite"); + } + + /** + * Returns the list of unique timezones from all configured sites. + * + * @return array ( string ) + */ + public function getUniqueSiteTimezones() + { + $results = Db::fetchAll("SELECT distinct timezone FROM " . $this->table); + + $timezones = array(); + foreach ($results as $result) { + $timezones[] = $result['timezone']; + } + + return $timezones; + } + + /** + * Updates the field ts_created for the specified websites. + * + * @param $idSites int Id Site to update ts_created + * @param string Date to set as creation date. + * + * @ignore + */ + public function updateSiteCreatedTime($idSites, $minDateSql) + { + $idSites = array_map('intval', $idSites); + + $query = "UPDATE " . $this->table . " SET ts_created = ?" . + " WHERE idsite IN ( " . implode(",", $idSites) . " ) AND ts_created > ?"; + + $bind = array($minDateSql, $minDateSql); + + Db::query($query, $bind); + } + + /** + * Insert the list of alias URLs for the website. + * The URLs must not exist already for this website! + */ + public function insertSiteUrl($idSite, $url) + { + $db = $this->getDb(); + $db->insert(Common::prefixTable("site_url"), array( + 'idsite' => (int) $idSite, + 'url' => $url + ) + ); + } + + public function getPatternMatchSites($ids, $pattern, $limit) + { + $ids_str = ''; + foreach ($ids as $id_val) { + $ids_str .= (int) $id_val . ' , '; + } + $ids_str .= (int) $id_val; + + $bind = array('%' . $pattern . '%', 'http%' . $pattern . '%', '%' . $pattern . '%'); + + // Also match the idsite + $where = ''; + if (is_numeric($pattern)) { + $bind[] = $pattern; + $where = 'ORs s.idsite = ?'; + } + + $query = "SELECT idsite, name, main_url, `group` + FROM " . $this->table . " s + WHERE ( s.name like ? + OR s.main_url like ? + OR s.`group` like ? + $where ) + AND idsite in ($ids_str) + LIMIT " . (int) $limit; + + $db = $this->getDb(); + $sites = $db->fetchAll($query, $bind); + + return $sites; + } + + /** + * Delete all the alias URLs for the given idSite. + */ + public function deleteSiteAliasUrls($idsite) + { + $db = $this->getDb(); + $db->query("DELETE FROM " . Common::prefixTable("site_url") . " WHERE idsite = ?", $idsite); + } + + private function getDb() + { + return Db::get(); + } } diff --git a/plugins/Transitions/API.php b/plugins/Transitions/API.php index faeddf9f0b..32abffdc06 100644 --- a/plugins/Transitions/API.php +++ b/plugins/Transitions/API.php @@ -172,7 +172,6 @@ class API extends \Piwik\Plugin\API */ private function addInternalReferrers($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping) { - $data = $this->queryInternalReferrers($idaction, $actionType, $logAggregator, $limitBeforeGrouping); if ($data['pageviews'] == 0) { @@ -198,7 +197,6 @@ class API extends \Piwik\Plugin\API */ private function addFollowingActions($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops = false) { - $data = $this->queryFollowingActions( $idaction, $actionType, $logAggregator, $limitBeforeGrouping, $includeLoops); @@ -225,7 +223,7 @@ class API extends \Piwik\Plugin\API if ($actionType != 'title') { // specific setup for page urls $types[Action::TYPE_PAGE_URL] = 'followingPages'; - $dimension = 'IF( idaction_url IS NULL, idaction_name, idaction_url )'; + $dimension = 'if ( idaction_url IS NULL, idaction_name, idaction_url )'; // site search referrers are logged with url=NULL // when we find one, we have to join on name $joinLogActionColumn = $dimension; @@ -408,7 +406,7 @@ class API extends \Piwik\Plugin\API if ($dimension == 'idaction_url_ref') { // site search referrers are logged with url_ref=NULL // when we find one, we have to join on name_ref - $dimension = 'IF( idaction_url_ref IS NULL, idaction_name_ref, idaction_url_ref )'; + $dimension = 'if ( idaction_url_ref IS NULL, idaction_name_ref, idaction_url_ref )'; $joinLogActionOn = $dimension; } else { $joinLogActionOn = $dimension; @@ -514,7 +512,6 @@ class API extends \Piwik\Plugin\API */ private function addExternalReferrers($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping) { - $data = $this->queryExternalReferrers( $idaction, $actionType, $logAggregator, $limitBeforeGrouping); diff --git a/plugins/UserCountry/Controller.php b/plugins/UserCountry/Controller.php index 483b2d844f..a6ed712dbe 100644 --- a/plugins/UserCountry/Controller.php +++ b/plugins/UserCountry/Controller.php @@ -369,7 +369,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin private function dieIfGeolocationAdminIsDisabled() { - if(!UserCountry::isGeoLocationAdminEnabled()) { + if (!UserCountry::isGeoLocationAdminEnabled()) { throw new \Exception('Geo location setting page has been disabled.'); } } diff --git a/plugins/UsersManager/API.php b/plugins/UsersManager/API.php index 61b26323da..79587e37b2 100644 --- a/plugins/UsersManager/API.php +++ b/plugins/UsersManager/API.php @@ -435,7 +435,7 @@ class API extends \Piwik\Plugin\API $this->checkEmail($email); } - $alias = $this->getCleanAlias($alias, $userLogin); + $alias = $this->getCleanAlias($alias, $userLogin); $token_auth = $this->getTokenAuth($userLogin, $password); $this->model->updateUser($userLogin, $password, $email, $alias, $token_auth); diff --git a/plugins/UsersManager/Controller.php b/plugins/UsersManager/Controller.php index 56974b1efc..d22240b977 100644 --- a/plugins/UsersManager/Controller.php +++ b/plugins/UsersManager/Controller.php @@ -177,7 +177,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin ); // assertion - if(count($dates) != count($mappingDatesToPeriods)) { + if (count($dates) != count($mappingDatesToPeriods)) { throw new Exception("some metadata is missing in getDefaultDates()"); } @@ -251,7 +251,7 @@ class Controller extends \Piwik\Plugin\ControllerAdmin Piwik::checkUserIsNotAnonymous(); $salt = Common::getRequestVar('ignoreSalt', false, 'string'); - if($salt !== $this->getIgnoreCookieSalt()) { + if ($salt !== $this->getIgnoreCookieSalt()) { throw new Exception("Not authorized"); } diff --git a/plugins/UsersManager/Model.php b/plugins/UsersManager/Model.php index 872d693ee6..3c39516cb5 100644 --- a/plugins/UsersManager/Model.php +++ b/plugins/UsersManager/Model.php @@ -26,6 +26,14 @@ use Piwik\Piwik; */ class Model { + private static $rawPrefix = 'user'; + private $table; + + public function __construct() + { + $this->table = Common::prefixTable(self::$rawPrefix); + } + /** * Returns the list of all the users * @@ -39,11 +47,10 @@ class Model if (!empty($userLogins)) { $where = 'WHERE login IN (' . Common::getSqlStringFieldsArray($userLogins) . ')'; - $bind = $userLogins; + $bind = $userLogins; } - $users = Db::get()->fetchAll("SELECT * - FROM " . Common::prefixTable("user") . " + $users = Db::get()->fetchAll("SELECT * FROM " . $this->table . " $where ORDER BY login ASC", $bind); @@ -57,9 +64,8 @@ class Model */ public function getUsersLogin() { - $users = Db::get()->fetchAll("SELECT login - FROM " . Common::prefixTable("user") . " - ORDER BY login ASC"); + $users = Db::get()->fetchAll("SELECT login FROM " . $this->table . " ORDER BY login ASC"); + $return = array(); foreach ($users as $login) { $return[] = $login['login']; @@ -70,10 +76,9 @@ class Model public function getUsersSitesFromAccess($access) { - $users = Db::get()->fetchAll("SELECT login,idsite - FROM " . Common::prefixTable("access") - . " WHERE access = ? - ORDER BY login, idsite", $access); + $users = $this->getDb()->fetchAll("SELECT login,idsite FROM " . Common::prefixTable("access") + . " WHERE access = ? + ORDER BY login, idsite", $access); $return = array(); foreach ($users as $user) { @@ -85,9 +90,8 @@ class Model public function getUsersAccessFromSite($idSite) { - $users = Db::get()->fetchAll("SELECT login,access - FROM " . Common::prefixTable("access") - . " WHERE idsite = ?", $idSite); + $users = $this->getDb()->fetchAll("SELECT login,access FROM " . Common::prefixTable("access") + . " WHERE idsite = ?", $idSite); $return = array(); foreach ($users as $user) { @@ -99,9 +103,9 @@ class Model public function getUsersLoginWithSiteAccess($idSite, $access) { - $users = Db::get()->fetchAll("SELECT login - FROM " . Common::prefixTable("access") - . " WHERE idsite = ? AND access = ?", array($idSite, $access)); + $users = $this->getDb()->fetchAll("SELECT login + FROM " . Common::prefixTable("access") + . " WHERE idsite = ? AND access = ?", array($idSite, $access)); $logins = array(); foreach ($users as $user) { @@ -129,9 +133,8 @@ class Model */ public function getSitesAccessFromUser($userLogin) { - $users = Db::get()->fetchAll("SELECT idsite,access - FROM " . Common::prefixTable("access") - . " WHERE login = ?", $userLogin); + $users = $this->getDb()->fetchAll("SELECT idsite,access FROM " . Common::prefixTable("access") + . " WHERE login = ?", $userLogin); $return = array(); foreach ($users as $user) { @@ -146,23 +149,20 @@ class Model public function getUser($userLogin) { - return Db::get()->fetchRow("SELECT * - FROM " . Common::prefixTable("user") - . " WHERE login = ?", $userLogin); + return $this->getDb()->fetchRow("SELECT * FROM " . $this->table + . " WHERE login = ?", $userLogin); } public function getUserByEmail($userEmail) { - return Db::get()->fetchRow("SELECT * - FROM " . Common::prefixTable("user") - . " WHERE email = ?", $userEmail); + return $this->getDb()->fetchRow("SELECT * FROM " . $this->table + . " WHERE email = ?", $userEmail); } public function getUserByTokenAuth($tokenAuth) { - return Db::get()->fetchRow('SELECT * - FROM ' . Common::prefixTable('user') . ' - WHERE token_auth = ?', $tokenAuth); + return $this->getDb()->fetchRow('SELECT * FROM ' . $this->table . ' + WHERE token_auth = ?', $tokenAuth); } public function addUser($userLogin, $passwordTransformed, $email, $alias, $tokenAuth, $dateRegistered) @@ -177,12 +177,12 @@ class Model 'superuser_access' => 0 ); - Db::get()->insert(Common::prefixTable("user"), $user); + $this->getDb()->insert($this->table, $user); } public function setSuperUserAccess($userLogin, $hasSuperUserAccess) { - Db::get()->update(Common::prefixTable("user"), + $this->getDb()->update($this->table, array( 'superuser_access' => $hasSuperUserAccess ? 1 : 0 ), @@ -192,17 +192,17 @@ class Model public function getUsersHavingSuperUserAccess() { - $users = Db::get()->fetchAll("SELECT login, email - FROM " . Common::prefixTable("user") . " - WHERE superuser_access = 1 - ORDER BY date_registered ASC"); + $users = $this->getDb()->fetchAll("SELECT login, email + FROM " . Common::prefixTable("user") . " + WHERE superuser_access = 1 + ORDER BY date_registered ASC"); return $users; } public function updateUser($userLogin, $password, $email, $alias, $tokenAuth) { - Db::get()->update(Common::prefixTable("user"), + $this->getDb()->update($this->table, array( 'password' => $password, 'alias' => $alias, @@ -215,24 +215,22 @@ class Model public function userExists($userLogin) { - $count = Db::get()->fetchOne("SELECT count(*) - FROM " . Common::prefixTable("user") . " - WHERE login = ?", $userLogin); + $count = $this->getDb()->fetchOne("SELECT count(*) FROM " . $this->table . " + WHERE login = ?", $userLogin); return $count != 0; } public function userEmailExists($userEmail) { - $count = Db::get()->fetchOne("SELECT count(*) - FROM " . Common::prefixTable("user") . " - WHERE email = ?", $userEmail); + $count = $this->getDb()->fetchOne("SELECT count(*) FROM " . $this->table . " + WHERE email = ?", $userEmail); return $count != 0; } public function addUserAccess($userLogin, $access, $idSites) { foreach ($idSites as $idsite) { - Db::get()->insert(Common::prefixTable("access"), + $this->getDb()->insert(Common::prefixTable("access"), array("idsite" => $idsite, "login" => $userLogin, "access" => $access) @@ -242,7 +240,7 @@ class Model public function deleteUserOnly($userLogin) { - Db::get()->query("DELETE FROM " . Common::prefixTable("user") . " WHERE login = ?", $userLogin); + $this->getDb()->query("DELETE FROM " . $this->table . " WHERE login = ?", $userLogin); /** * Triggered after a user has been deleted. @@ -258,12 +256,12 @@ class Model public function deleteUserAccess($userLogin, $idSites = null) { if (is_null($idSites)) { - Db::get()->query("DELETE FROM " . Common::prefixTable("access") . + $this->getDb()->query("DELETE FROM " . Common::prefixTable("access") . " WHERE login = ?", array($userLogin)); } else { foreach ($idSites as $idsite) { - Db::get()->query("DELETE FROM " . Common::prefixTable("access") . + $this->getDb()->query("DELETE FROM " . Common::prefixTable("access") . " WHERE idsite = ? AND login = ?", array($idsite, $userLogin) ); @@ -271,4 +269,9 @@ class Model } } + private function getDb() + { + return Db::get(); + } + } diff --git a/plugins/VisitsSummary/Controller.php b/plugins/VisitsSummary/Controller.php index 903b2477cf..63fe8ef205 100644 --- a/plugins/VisitsSummary/Controller.php +++ b/plugins/VisitsSummary/Controller.php @@ -159,7 +159,7 @@ class Controller extends \Piwik\Plugin\Controller $view->maxActions = (int)$dataRow->getColumn('max_actions'); $view->nbActionsPerVisit = $dataRow->getColumn('nb_actions_per_visit'); - if(Common::isActionsPluginEnabled()) { + if (Common::isActionsPluginEnabled()) { $view->showActionsPluginReports = true; $dataTableActions = APIActions::getInstance()->get($idSite, Common::getRequestVar('period'), Common::getRequestVar('date'), \Piwik\API\Request::getRawSegmentFromRequest()); |