diff --git a/core/API/DataTableManipulator.php b/core/API/DataTableManipulator.php index 1fce679f95a..e93c1f5c87d 100644 --- a/core/API/DataTableManipulator.php +++ b/core/API/DataTableManipulator.php @@ -14,7 +14,7 @@ use Piwik\DataTable\Row; use Piwik\Period\Range; use Piwik\DataTable; -use Piwik_API_API; +use Piwik\Plugins\API\API; use Piwik\API\Proxy; use Piwik\API\ResponseBuilder; @@ -126,7 +126,7 @@ protected function loadSubtable($dataTable, $row) } } - $class = 'Piwik_' . $this->apiModule . '_API'; + $class = Request::getClassNameAPI( $this->apiModule ); $method = $this->getApiMethodForSubtable(); $this->manipulateSubtableRequest($request); @@ -166,7 +166,7 @@ protected abstract function manipulateSubtableRequest(&$request); private function getApiMethodForSubtable() { if (!$this->apiMethodForSubtable) { - $meta = Piwik_API_API::getInstance()->getMetadata('all', $this->apiModule, $this->apiMethod); + $meta = API::getInstance()->getMetadata('all', $this->apiModule, $this->apiMethod); if (isset($meta[0]['actionToLoadSubTables'])) { $this->apiMethodForSubtable = $meta[0]['actionToLoadSubTables']; } else { diff --git a/core/API/DocumentationGenerator.php b/core/API/DocumentationGenerator.php index ae1b1557bfa..50362fc60ba 100644 --- a/core/API/DocumentationGenerator.php +++ b/core/API/DocumentationGenerator.php @@ -33,9 +33,9 @@ public function __construct() { $plugins = PluginsManager::getInstance()->getLoadedPluginsName(); foreach ($plugins as $plugin) { - $plugin = Common::unprefixClass($plugin); try { - Proxy::getInstance()->registerClass('Piwik_' . $plugin . '_API'); + $className = Request::getClassNameAPI($plugin); + Proxy::getInstance()->registerClass($className); } catch (Exception $e) { } } diff --git a/core/API/Proxy.php b/core/API/Proxy.php index e3861facb1e..981452f41f8 100644 --- a/core/API/Proxy.php +++ b/core/API/Proxy.php @@ -88,7 +88,7 @@ public function getMetadata() * * The method will introspect the methods, their parameters, etc. * - * @param string $className ModuleName eg. "Piwik_UserSettings_API" + * @param string $className ModuleName eg. "API" */ public function registerClass($className) { @@ -146,7 +146,7 @@ public function getCountRegisteredClasses() * It also logs the API calls, with the parameters values, the returned value, the performance, etc. * You can enable logging in config/global.ini.php (log_api_call) * - * @param string $className The class name (eg. Piwik_Referers_API) + * @param string $className The class name (eg. API) * @param string $methodName The method name * @param array $parametersRequest The parameters pairs (name=>value) * @@ -186,16 +186,14 @@ public function call($className, $methodName, $parametersRequest) $returnedValue = call_user_func_array(array($object, $methodName), $finalParameters); // allow plugins to manipulate the value - if (substr($className, 0, 6) == 'Piwik_' && substr($className, -4) == '_API') { - $pluginName = substr($className, 6, -4); - Piwik_PostEvent('API.Proxy.processReturnValue', array( - &$returnedValue, - array('className' => $className, - 'module' => $pluginName, - 'action' => $methodName, - 'parameters' => &$parametersRequest) - )); - } + $pluginName = $this->getModuleNameFromClassName($className); + Piwik_PostEvent('API.Proxy.processReturnValue', array( + &$returnedValue, + array('className' => $className, + 'module' => $pluginName, + 'action' => $methodName, + 'parameters' => &$parametersRequest) + )); // Restore the request $_GET = $saveGET; @@ -242,12 +240,12 @@ public function getParametersList($class, $name) /** * Returns the 'moduleName' part of 'Piwik_moduleName_API' classname * - * @param string $className "Piwik_Referers_API" + * @param string $className "API" * @return string "Referers" */ public function getModuleNameFromClassName($className) { - return str_replace(array('Piwik_', '_API'), '', $className); + return str_replace(array('\\Piwik\\Plugins\\', '\\API'), '', $className); } /** @@ -308,9 +306,9 @@ private function getRequestParametersArray($requiredParameters, $parametersReque } /** - * Includes the class Piwik_UserSettings_API by looking up plugins/UserSettings/API.php + * Includes the class API by looking up plugins/UserSettings/API.php * - * @param string $fileName api class name eg. "Piwik_UserSettings_API" + * @param string $fileName api class name eg. "API" * @throws Exception */ private function includeApiFile($fileName) @@ -403,7 +401,7 @@ private function isMethodAvailable($className, $methodName) private function checkClassIsSingleton($className) { if (!method_exists($className, "getInstance")) { - throw new Exception("Objects that provide an API must be Singleton and have a 'static public function getInstance()' method."); + throw new Exception("$className that provide an API must be Singleton and have a 'static public function getInstance()' method."); } } } diff --git a/core/API/Request.php b/core/API/Request.php index 91d664af56b..f627dd5f0bf 100644 --- a/core/API/Request.php +++ b/core/API/Request.php @@ -149,12 +149,12 @@ public function process() if (!PluginsManager::getInstance()->isPluginActivated($module)) { throw new PluginDeactivatedException($module); } - $moduleClass = "Piwik_" . $module . "_API"; + $apiClassName = $this->getClassNameAPI($module); self::reloadAuthUsingTokenAuth($this->request); // call the method - $returnedValue = Proxy::getInstance()->call($moduleClass, $method, $this->request); + $returnedValue = Proxy::getInstance()->call($apiClassName, $method, $this->request); $toReturn = $response->getResponse($returnedValue, $module, $method); } catch (Exception $e) { @@ -163,6 +163,11 @@ public function process() return $toReturn; } + static public function getClassNameAPI($module) + { + return "\\Piwik\\Plugins\\$module\\API"; + } + /** * If the token_auth is found in the $request parameter, * the current session will be authenticated using this token_auth. diff --git a/core/Access.php b/core/Access.php index 7f1f89c6167..48660808126 100644 --- a/core/Access.php +++ b/core/Access.php @@ -212,7 +212,7 @@ protected function reloadAccessSuperUser() $this->isSuperUser = true; try { - $allSitesId = \Piwik_SitesManager_API::getInstance()->getAllSitesId(); + $allSitesId = Plugins\SitesManager\API::getInstance()->getAllSitesId(); } catch(\Exception $e) { $allSitesId = array(); } diff --git a/core/AssetManager.php b/core/AssetManager.php index ed64a1121bd..df3448126e7 100644 --- a/core/AssetManager.php +++ b/core/AssetManager.php @@ -133,7 +133,7 @@ private static function prepareMergedCssFile() // Disable Merged Assets ==> Check on each request if file needs re-compiling if ($mergedCssAlreadyGenerated - && $isDevelopingPiwik + && !$isDevelopingPiwik ) { $pathMerged = self::getAbsoluteMergedFileLocation(self::MERGED_CSS_FILE); $f = fopen($pathMerged, 'r'); diff --git a/core/Common.php b/core/Common.php index 0fbf8f8ddf9..2a1bae68d92 100644 --- a/core/Common.php +++ b/core/Common.php @@ -15,7 +15,7 @@ use Piwik\Tracker; use Piwik\Tracker\Cache; use Piwik\PluginsManager; -use Piwik_UserCountry_LocationProvider_Default; +use Piwik\Plugins\UserCountry\LocationProvider\DefaultProvider; /** * Static class providing functions used by both the CORE of Piwik and the visitor Tracking engine. @@ -28,8 +28,6 @@ */ class Common { - const CLASSES_PREFIX = 'Piwik_'; - /** * Const used to map the referer type to an integer in the log_visit table */ @@ -1554,26 +1552,10 @@ public static function getCurrentLocationProviderId() { $cache = Cache::getCacheGeneral(); return empty($cache['currentLocationProviderId']) - ? Piwik_UserCountry_LocationProvider_Default::ID + ? DefaultProvider::ID : $cache['currentLocationProviderId']; } - /** - * Unprefix class name (if needed) - * - * @param string $class - * @return string - */ - public static function unprefixClass($class) - { - $lenPrefix = strlen(self::CLASSES_PREFIX); - if (!strncmp($class, self::CLASSES_PREFIX, $lenPrefix)) { - return substr($class, $lenPrefix); - } - return $class; - } - - /** * Mark orphaned object for garbage collection * diff --git a/core/Controller.php b/core/Controller.php index 9c1fe1519b0..dd122579bdb 100644 --- a/core/Controller.php +++ b/core/Controller.php @@ -21,13 +21,13 @@ use Piwik\Access; use Piwik\Date; use Piwik\Site; -use Piwik_API_API; +use Piwik\Plugins\API\API; use Piwik\API\Request; use Piwik\FrontController; -use Piwik_LanguagesManager; -use Piwik_SitesManager_API; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Piwik\Plugins\SitesManager\API as SitesManagerAPI; use Piwik\Url; -use Piwik_UsersManager_API; +use Piwik\Plugins\UsersManager\API as UsersManagerAPI; use Piwik\View; use Piwik\ViewDataTable; use Piwik\ViewDataTable\GenerateGraphHTML\ChartEvolution; @@ -81,8 +81,9 @@ public function __construct() protected function init() { - $aPluginName = explode('_', get_class($this)); - $this->pluginName = $aPluginName[1]; + $aPluginName = explode('\\', get_class($this)); + $this->pluginName = $aPluginName[2]; + $date = Common::getRequestVar('date', 'yesterday', 'string'); try { $this->idSite = Common::getRequestVar('idSite', false, 'int'); @@ -202,7 +203,7 @@ protected function getLastUnitGraphAcrossPlugins($currentModuleName, $currentCon $idSite = Common::getRequestVar('idSite'); $period = Common::getRequestVar('period'); $date = Common::getRequestVar('date'); - $meta = Piwik_API_API::getInstance()->getReportMetadata($idSite, $period, $date); + $meta = API::getInstance()->getReportMetadata($idSite, $period, $date); $columns = array_merge($columnsToDisplay, $selectableColumns); $translations = array(); @@ -423,8 +424,8 @@ protected function setGeneralVariablesView($view) $view->startDate = $dateStart; $view->endDate = $dateEnd; - $language = Piwik_LanguagesManager::getLanguageForSession(); - $view->language = !empty($language) ? $language : Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); + $language = LanguagesManager::getLanguageForSession(); + $view->language = !empty($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); $view->config_action_url_category_delimiter = Config::getInstance()->General['action_url_category_delimiter']; @@ -447,10 +448,10 @@ protected function setBasicVariablesView($view) $view->isSuperUser = Access::getInstance()->isSuperUser(); $view->hasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $view->isCustomLogo = Config::getInstance()->branding['use_custom_logo']; - $view->logoHeader = Piwik_API_API::getInstance()->getHeaderLogoUrl(); - $view->logoLarge = Piwik_API_API::getInstance()->getLogoUrl(); - $view->logoSVG = Piwik_API_API::getInstance()->getSVGLogoUrl(); - $view->hasSVGLogo = Piwik_API_API::getInstance()->hasSVGLogo(); + $view->logoHeader = API::getInstance()->getHeaderLogoUrl(); + $view->logoLarge = API::getInstance()->getLogoUrl(); + $view->logoSVG = API::getInstance()->getSVGLogoUrl(); + $view->hasSVGLogo = API::getInstance()->hasSVGLogo(); $view->enableFrames = Config::getInstance()->General['enable_framed_pages'] || @Config::getInstance()->General['enable_framed_logins']; @@ -669,7 +670,7 @@ protected function getDefaultWebsiteId() $defaultWebsiteId = false; // User preference: default website ID to load - $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); + $defaultReport = UsersManagerAPI::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), UsersManagerAPI::PREFERENCE_DEFAULT_REPORT); if (is_numeric($defaultReport)) { $defaultWebsiteId = $defaultReport; } @@ -680,7 +681,7 @@ protected function getDefaultWebsiteId() return $defaultWebsiteId; } - $sitesId = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess(); + $sitesId = SitesManagerAPI::getInstance()->getSitesIdWithAtLeastViewAccess(); if (!empty($sitesId)) { return $sitesId[0]; } @@ -695,7 +696,7 @@ protected function getDefaultWebsiteId() protected function getDefaultDate() { // NOTE: a change in this function might mean a change in plugins/UsersManager/javascripts/usersSettings.js as well - $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE); + $userSettingsDate = UsersManagerAPI::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), UsersManagerAPI::PREFERENCE_DEFAULT_REPORT_DATE); if ($userSettingsDate == 'yesterday') { return $userSettingsDate; } @@ -715,7 +716,7 @@ protected function getDefaultDate() */ protected function getDefaultPeriod() { - $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE); + $userSettingsDate = UsersManagerAPI::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), UsersManagerAPI::PREFERENCE_DEFAULT_REPORT_DATE); if ($userSettingsDate === false) { return Config::getInstance()->General['default_period']; } diff --git a/core/DataTable/Filter/ColumnCallbackAddColumnPercentage.php b/core/DataTable/Filter/ColumnCallbackAddColumnPercentage.php index 92ad07185c5..d22c61a83fb 100644 --- a/core/DataTable/Filter/ColumnCallbackAddColumnPercentage.php +++ b/core/DataTable/Filter/ColumnCallbackAddColumnPercentage.php @@ -22,7 +22,7 @@ * You can also specify the precision of the percentage value to be displayed (defaults to 0, eg "11%") * * Usage: - * $nbVisits = Piwik_VisitsSummary_API::getInstance()->getVisits($idSite, $period, $date); + * $nbVisits = API::getInstance()->getVisits($idSite, $period, $date); * $dataTable->queueFilter('ColumnCallbackAddColumnPercentage', array('nb_visits', 'nb_visits_percentage', $nbVisits, 1)); * * @package Piwik diff --git a/core/DataTable/Renderer.php b/core/DataTable/Renderer.php index bdec4b87ca6..0cefcc5f29a 100644 --- a/core/DataTable/Renderer.php +++ b/core/DataTable/Renderer.php @@ -299,7 +299,7 @@ protected function getApiMetaData() $this->apiMetaData = false; } - $api = \Piwik_API_API::getInstance(); + $api = \Piwik\Plugins\API\API::getInstance(); $meta = $api->getMetadata($this->idSite, $apiModule, $apiAction); if (is_array($meta[0])) { $meta = $meta[0]; diff --git a/core/Db/Schema.php b/core/Db/Schema.php index 9064a6a9087..4a86ce97638 100644 --- a/core/Db/Schema.php +++ b/core/Db/Schema.php @@ -116,7 +116,7 @@ public static function getSchemas($adapterName) $schemas = array(); foreach ($schemaNames as $schemaName) { - $className = 'Piwik_Db_Schema_' . $schemaName; + $className = __NAMESPACE__ . '\\Schema\\' . $schemaName; if (call_user_func(array($className, 'isAvailable'))) { $schemas[] = $schemaName; } diff --git a/core/FrontController.php b/core/FrontController.php index fc33f3eae25..5837256a556 100644 --- a/core/FrontController.php +++ b/core/FrontController.php @@ -99,7 +99,7 @@ public function dispatch($module = null, $action = null, $parameters = null) throw new PluginDeactivatedException($module); } - $controllerClassName = 'Piwik_' . $module . '_Controller'; + $controllerClassName = $this->getClassNameController( $module ); // FrontController's autoloader if (!class_exists($controllerClassName, false)) { @@ -110,7 +110,9 @@ public function dispatch($module = null, $action = null, $parameters = null) require_once $moduleController; // prefixed by PIWIK_INCLUDE_PATH } - $controller = new $controllerClassName(); + $class = $this->getClassNameController($module); + /** @var $controller Controller */ + $controller = new $class; if ($action === false) { $action = $controller->getDefaultAction(); } @@ -135,6 +137,11 @@ public function dispatch($module = null, $action = null, $parameters = null) } } + protected function getClassNameController($module) + { + return "\\Piwik\\Plugins\\$module\\Controller"; + } + /** * Often plugins controller display stuff using echo/print. * Using this function instead of dispatch() returns the output string form the actions calls. diff --git a/core/Loader.php b/core/Loader.php index fc913112e93..927fbdc797f 100644 --- a/core/Loader.php +++ b/core/Loader.php @@ -46,7 +46,13 @@ protected static function getClassFileName($class) return $class; } - $vendorPrefixToRemove = 'Piwik/'; + $class = self::removePrefix($class, 'Piwik/'); + $class = self::removePrefix($class, 'Plugins/'); + return $class; + } + + protected static function removePrefix($class, $vendorPrefixToRemove) + { if (strpos($class, $vendorPrefixToRemove) === 0) { return substr($class, strlen($vendorPrefixToRemove)); } diff --git a/core/Menu/MenuAbstract.php b/core/Menu/MenuAbstract.php index 5bb4adb39cb..a0fa8c4c2ba 100644 --- a/core/Menu/MenuAbstract.php +++ b/core/Menu/MenuAbstract.php @@ -11,7 +11,7 @@ namespace Piwik\Menu; use Piwik\Common; -use Piwik_SitesManager_API; +use Piwik\Plugins\SitesManager\API; /** * @package Piwik_Menu @@ -60,7 +60,7 @@ public function add($menuName, $subMenuName, $url, $displayedForCurrentUser, $or if ($displayedForCurrentUser) { // make sure the idSite value used is numeric (hack-y fix for #3426) if (!is_numeric(Common::getRequestVar('idSite', false))) { - $idSites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess(); + $idSites = API::getInstance()->getSitesIdWithAtLeastViewAccess(); $url['idSite'] = reset($idSites); } diff --git a/core/Period.php b/core/Period.php index 3c04d543081..f846ef60065 100644 --- a/core/Period.php +++ b/core/Period.php @@ -19,16 +19,6 @@ use Piwik\Period\Year; /** - * Creating a new Period subclass: - * - * Every overloaded method must start with the code - * if(!$this->subperiodsProcessed) - * { - * $this->generate(); - * } - * that checks whether the subperiods have already been computed. - * This is for performance improvements, computing the subperiods is done a per demand basis. - * * @package Piwik * @subpackage Period */ @@ -174,6 +164,7 @@ public function getDateStart() return $this->getDate(); } $periods = $this->getSubperiods(); + /** @var $currentPeriod Period */ $currentPeriod = $periods[0]; while ($currentPeriod->getNumberOfSubperiods() > 0) { $periods = $currentPeriod->getSubperiods(); @@ -196,6 +187,7 @@ public function getDateEnd() return $this->getDate(); } $periods = $this->getSubperiods(); + /** @var $currentPeriod Period */ $currentPeriod = $periods[count($periods) - 1]; while ($currentPeriod->getNumberOfSubperiods() > 0) { $periods = $currentPeriod->getSubperiods(); diff --git a/core/Piwik.php b/core/Piwik.php index de54f033ad7..7dff9430aa7 100644 --- a/core/Piwik.php +++ b/core/Piwik.php @@ -24,7 +24,7 @@ use Piwik\Tracker\Cache; use Piwik\Tracker\GoalManager; use Piwik\Url; -use Piwik_UsersManager_API; +use Piwik\Plugins\UsersManager\API; use Piwik\View; use Piwik\Log\ScreenFormatter; use Zend_Registry; @@ -1572,7 +1572,7 @@ static public function getKnownSegmentsToArchiveForSite($idSite) static public function getCurrentUserEmail() { if (!Piwik::isUserIsSuperUser()) { - $user = Piwik_UsersManager_API::getInstance()->getUser(Piwik::getCurrentUserLogin()); + $user = API::getInstance()->getUser(Piwik::getCurrentUserLogin()); return $user['email']; } return self::getSuperUserEmail(); diff --git a/core/Plugin.php b/core/Plugin.php index 578d38c5f5c..756d4ae4f3c 100644 --- a/core/Plugin.php +++ b/core/Plugin.php @@ -48,7 +48,8 @@ class Plugin public function __construct($pluginName = false) { if (empty($pluginName)) { - $pluginName = Common::unprefixClass(get_class($this)); + $pluginName = explode('\\', get_class($this)); + $pluginName = end($pluginName); } $this->pluginName = $pluginName; @@ -162,7 +163,7 @@ final public function isTheme() /** * Returns the plugin's base class name without the "Piwik_" prefix, - * e.g., "UserCountry" when the plugin class is "Piwik_UserCountry" + * e.g., "UserCountry" when the plugin class is "UserCountry" * * @return string */ diff --git a/core/PluginsArchiver.php b/core/PluginsArchiver.php index dd49ba37e7c..eb3b24592d2 100644 --- a/core/PluginsArchiver.php +++ b/core/PluginsArchiver.php @@ -36,8 +36,8 @@ abstract public function archivePeriod(); // todo: review this concept, each plugin should somehow maintain the list of report names they generate public function shouldArchive() { - $pluginName = Common::unprefixClass(get_class($this)); - $pluginName = str_replace("_Archiver", "", $pluginName); + $className = get_class($this); + $pluginName = str_replace(array("\\Piwik\\Plugins\\", "\\Archiver"), "", $className); return $this->getProcessor()->shouldProcessReportsForPlugin($pluginName); } diff --git a/core/PluginsManager.php b/core/PluginsManager.php index 0626db36a37..b4af8fbac07 100644 --- a/core/PluginsManager.php +++ b/core/PluginsManager.php @@ -399,13 +399,13 @@ public function postLoadPlugins() } /** - * Returns an array containing the plugins class names (eg. 'Piwik_UserCountry' and NOT 'UserCountry') + * Returns an array containing the plugins class names (eg. 'UserCountry' and NOT 'UserCountry') * * @return array */ public function getLoadedPluginsName() { - return array_map('get_class', $this->getLoadedPlugins()); + return array_keys($this->getLoadedPlugins()); } /** @@ -460,7 +460,7 @@ private function reloadPlugins() /** * Loads the plugin filename and instantiates the plugin with the given name, eg. UserCountry - * Do NOT give the class name ie. Piwik_UserCountry, but give the plugin name ie. UserCountry + * Do NOT give the class name ie. UserCountry, but give the plugin name ie. UserCountry * * @param string $pluginName * @throws \Exception @@ -488,7 +488,7 @@ public function loadPlugin($pluginName) protected function makePluginClass($pluginName) { $pluginFileName = sprintf("%s/%s.php", $pluginName, $pluginName); - $pluginClassName = sprintf('Piwik_%s', $pluginName); + $pluginClassName = $pluginName; if (!Common::isValidFilename($pluginName)) { throw new \Exception(sprintf("The plugin filename '%s' is not a valid filename", $pluginFileName)); @@ -504,10 +504,11 @@ protected function makePluginClass($pluginName) require_once $path; - if (!class_exists($pluginClassName, false)) { + $namespacedClass = $this->getClassNamePlugin($pluginName); + if(!class_exists($namespacedClass, false)) { throw new \Exception("The class $pluginClassName couldn't be found in the file '$path'"); } - $newPlugin = new $pluginClassName(); + $newPlugin = new $namespacedClass; if (!($newPlugin instanceof Plugin)) { throw new \Exception("The plugin $pluginClassName in the file $path must inherit from Plugin."); @@ -515,6 +516,15 @@ protected function makePluginClass($pluginName) return $newPlugin; } + protected function getClassNamePlugin($pluginName) + { + $className = $pluginName; + if($pluginName == 'API') { + $className = 'Plugin'; + } + return "\\Piwik\\Plugins\\$pluginName\\$className"; + } + /** * Unload plugin * @@ -663,6 +673,7 @@ private function installPluginIfNecessary(Plugin $plugin) // is the plugin already installed or is it the first time we activate it? $pluginsInstalled = $this->getInstalledPluginsName(); + if (!in_array($pluginName, $pluginsInstalled)) { $this->installPlugin($plugin); $pluginsInstalled[] = $pluginName; diff --git a/core/ReportRenderer.php b/core/ReportRenderer.php index d2d51f1425f..f7249352097 100644 --- a/core/ReportRenderer.php +++ b/core/ReportRenderer.php @@ -17,7 +17,7 @@ use Piwik\DataTable; use Piwik\Loader; use Piwik\API\Request; -use Piwik_ImageGraph_API; +use Piwik\Plugins\ImageGraph\API; /** * A Report Renderer produces user friendly renderings of any given Piwik report. @@ -122,7 +122,7 @@ abstract public function renderFrontPage($reportTitle, $prettyDate, $description * Render the provided report. * Multiple calls to this method before calling outputRendering appends each report content. * - * @param array $processedReport @see Piwik_API_API::getProcessedReport() + * @param array $processedReport @see API::getProcessedReport() */ abstract public function renderReport($processedReport); @@ -235,7 +235,7 @@ public static function getStaticGraph($reportMetadata, $width, $height, $evoluti } $requestGraph = $imageGraphUrl . - '&outputType=' . Piwik_ImageGraph_API::GRAPH_OUTPUT_PHP . + '&outputType=' . API::GRAPH_OUTPUT_PHP . '&format=original&serialize=0' . '&filter_truncate=' . '&width=' . $width . diff --git a/core/ReportRenderer/Html.php b/core/ReportRenderer/Html.php index e1d30734c4f..cb8d33faa03 100644 --- a/core/ReportRenderer/Html.php +++ b/core/ReportRenderer/Html.php @@ -13,7 +13,7 @@ use Piwik\Piwik; use Piwik\View; use Piwik\ReportRenderer; -use Piwik_API_API; +use Piwik\Plugins\API\API; /** * @@ -121,7 +121,7 @@ private function assignCommonParameters(View $view) $view->assign("reportTableRowTextSize", self::REPORT_TABLE_ROW_TEXT_SIZE); $view->assign("reportBackToTopTextSize", self::REPORT_BACK_TO_TOP_TEXT_SIZE); $view->assign("currentPath", Piwik::getPiwikUrl()); - $view->assign("logoHeader", Piwik_API_API::getInstance()->getHeaderLogoUrl()); + $view->assign("logoHeader", API::getInstance()->getHeaderLogoUrl()); } public function renderReport($processedReport) diff --git a/core/ReportRenderer/Pdf.php b/core/ReportRenderer/Pdf.php index 192a7f91330..c3ab722e27c 100644 --- a/core/ReportRenderer/Pdf.php +++ b/core/ReportRenderer/Pdf.php @@ -13,7 +13,7 @@ use Piwik\Common; use Piwik\TCPDF; use Piwik\ReportRenderer; -use Piwik_API_API; +use Piwik\Plugins\API\API; /** * @see libs/tcpdf @@ -166,7 +166,7 @@ public function renderFrontPage($reportTitle, $prettyDate, $description, $report $this->TCPDF->Bookmark(Piwik_Translate('PDFReports_FrontPage')); // logo - $this->TCPDF->Image(Piwik_API_API::getInstance()->getLogoUrl(true), $this->logoImagePosition[0], $this->logoImagePosition[1], 180 / $factor = 2, 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300); + $this->TCPDF->Image(API::getInstance()->getLogoUrl(true), $this->logoImagePosition[0], $this->logoImagePosition[1], 180 / $factor = 2, 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300); $this->TCPDF->Ln(8); // report title diff --git a/core/ScheduledTask.php b/core/ScheduledTask.php index 8d9c368c54d..5262e7cbc38 100644 --- a/core/ScheduledTask.php +++ b/core/ScheduledTask.php @@ -66,7 +66,7 @@ class ScheduledTask function __construct($_objectInstance, $_methodName, $_methodParameter, $_scheduledTime, $_priority = self::NORMAL_PRIORITY) { - $this->className = get_class($_objectInstance); + $this->className = $this->getClassNameFromInstance($_objectInstance); if ($_priority < self::HIGHEST_PRIORITY || $_priority > self::LOWEST_PRIORITY) { throw new Exception("Invalid priority for ScheduledTask '$this->className.$_methodName': $_priority"); @@ -79,6 +79,13 @@ function __construct($_objectInstance, $_methodName, $_methodParameter, $_schedu $this->priority = $_priority; } + protected function getClassNameFromInstance($_objectInstance) + { + $namespaced = get_class($_objectInstance); + $class = explode('\\', $namespaced); + return end($class); + } + /** * Return the object instance on which the method should be executed * @return string diff --git a/core/Segment.php b/core/Segment.php index cfc82c86e70..8687362a56b 100644 --- a/core/Segment.php +++ b/core/Segment.php @@ -12,7 +12,7 @@ use Exception; use Piwik\Piwik; use Piwik\Common; -use Piwik_API_API; +use Piwik\Plugins\API\API; use Piwik\SegmentExpression; /** @@ -90,7 +90,7 @@ public function isEmpty() protected function getCleanedExpression($expression) { if (empty($this->availableSegments)) { - $this->availableSegments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSites, $_hideImplementationData = false); + $this->availableSegments = API::getInstance()->getSegmentsMetadata($this->idSites, $_hideImplementationData = false); } $name = $expression[0]; @@ -121,7 +121,7 @@ protected function getCleanedExpression($expression) $value = call_user_func($segment['sqlFilter'], $value, $segment['sqlSegment'], $matchType, $name); // sqlFilter-callbacks might return arrays for more complex cases - // e.g. see Piwik_Actions::getIdActionFromSegment() + // e.g. see Actions::getIdActionFromSegment() if (is_array($value) && isset($value['SQL']) ) { diff --git a/core/Site.php b/core/Site.php index b0824e77eee..eb13215e342 100644 --- a/core/Site.php +++ b/core/Site.php @@ -12,7 +12,7 @@ namespace Piwik; use Exception; use Piwik\Date; -use Piwik_SitesManager_API; +use Piwik\Plugins\SitesManager\API; /** * @@ -37,7 +37,7 @@ function __construct($idsite) { $this->id = (int)$idsite; if (!isset(self::$infoSites[$this->id])) { - self::$infoSites[$this->id] = Piwik_SitesManager_API::getInstance()->getSiteFromId($this->id); + self::$infoSites[$this->id] = API::getInstance()->getSiteFromId($this->id); } } @@ -215,7 +215,7 @@ function isSiteSearchEnabled() static public function getIdSitesFromIdSitesString($ids, $_restrictSitesToLogin = false) { if ($ids === 'all') { - return Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin); + return API::getInstance()->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin); } if (!is_array($ids)) { @@ -256,7 +256,7 @@ static protected function getFor($idsite, $field) $idsite = (int)$idsite; if (!isset(self::$infoSites[$idsite])) { - self::$infoSites[$idsite] = Piwik_SitesManager_API::getInstance()->getSiteFromId($idsite); + self::$infoSites[$idsite] = API::getInstance()->getSiteFromId($idsite); } return self::$infoSites[$idsite][$field]; diff --git a/core/Tracker/Cache.php b/core/Tracker/Cache.php index 1e6423d8f6b..7319818e412 100644 --- a/core/Tracker/Cache.php +++ b/core/Tracker/Cache.php @@ -15,7 +15,7 @@ use Piwik\Piwik; use Piwik\CacheFile; use Piwik\Tracker; -use Piwik_UserCountry_LocationProvider; +use Piwik\Plugins\UserCountry\LocationProvider; /** * Simple cache mechanism used in Tracker to avoid requesting settings from mysql on every request @@ -104,7 +104,7 @@ static public function getCacheGeneral() $cacheContent = array( 'isBrowserTriggerEnabled' => Rules::isBrowserTriggerEnabled(), 'lastTrackerCronRun' => Piwik_GetOption('lastTrackerCronRun'), - 'currentLocationProviderId' => Piwik_UserCountry_LocationProvider::getCurrentProviderId(), + 'currentLocationProviderId' => LocationProvider::getCurrentProviderId(), ); self::setCacheGeneral($cacheContent); return $cacheContent; diff --git a/core/Tracker/Request.php b/core/Tracker/Request.php index 668d23fa1e6..e52e89424a3 100644 --- a/core/Tracker/Request.php +++ b/core/Tracker/Request.php @@ -8,7 +8,7 @@ use Piwik\IP; use Piwik\Tracker; use Piwik\Tracker\Cache; -use Piwik_UserCountry_LocationProvider; +use Piwik\Plugins\UserCountry\LocationProvider; /** * Piwik - Open source web analytics @@ -27,6 +27,8 @@ class Request */ protected $params; + protected $forcedVisitorId = false; + public function __construct($params, $tokenAuth = false) { if (!is_array($params)) { @@ -434,7 +436,9 @@ public function getIp() public function setForceIp($ip) { - $this->enforcedIp = $ip; + if(!empty($ip)) { + $this->enforcedIp = $ip; + } } public function setForceDateTime($dateTime) @@ -442,12 +446,16 @@ public function setForceDateTime($dateTime) if (!is_numeric($dateTime)) { $dateTime = strtotime($dateTime); } - $this->timestamp = $dateTime; + if(!empty($dateTime)) { + $this->timestamp = $dateTime; + } } public function setForcedVisitorId($visitorId) { - $this->forcedVisitorId = $visitorId; + if(!empty($visitorId)) { + $this->forcedVisitorId = $visitorId; + } } public function getForcedVisitorId() @@ -463,11 +471,11 @@ public function enrichLocation($location) // check for location override query parameters (ie, lat, long, country, region, city) $locationOverrideParams = array( - 'country' => array('string', Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY), - 'region' => array('string', Piwik_UserCountry_LocationProvider::REGION_CODE_KEY), - 'city' => array('string', Piwik_UserCountry_LocationProvider::CITY_NAME_KEY), - 'lat' => array('float', Piwik_UserCountry_LocationProvider::LATITUDE_KEY), - 'long' => array('float', Piwik_UserCountry_LocationProvider::LONGITUDE_KEY), + 'country' => array('string', LocationProvider::COUNTRY_CODE_KEY), + 'region' => array('string', LocationProvider::REGION_CODE_KEY), + 'city' => array('string', LocationProvider::CITY_NAME_KEY), + 'lat' => array('float', LocationProvider::LATITUDE_KEY), + 'long' => array('float', LocationProvider::LONGITUDE_KEY), ); foreach ($locationOverrideParams as $queryParamName => $info) { list($type, $locationResultKey) = $info; diff --git a/core/Tracker/Visit.php b/core/Tracker/Visit.php index 3590b4c3194..91219363397 100644 --- a/core/Tracker/Visit.php +++ b/core/Tracker/Visit.php @@ -32,7 +32,7 @@ function handle(); use Piwik\Tracker\Referrer; use Exception; use Piwik\Tracker\VisitExcluded; -use Piwik_UserCountry_LocationProvider; +use Piwik\Plugins\UserCountry\LocationProvider; use UserAgentParser; /** @@ -504,7 +504,7 @@ static private function cleanupVisitTotalTime($t) * Returns the location of the visitor, based on the visitor's IP and browser language. * * @param string $browserLang - * @return array See Piwik_UserCountry_LocationProvider::getLocation for more info. + * @return array See LocationProvider::getLocation for more info. */ private function getVisitorLocation($browserLang) { @@ -525,19 +525,19 @@ private function getVisitorLocation($browserLang) /** * Sets visitor info array with location info. * - * @param array $location See Piwik_UserCountry_LocationProvider::getLocation for more info. + * @param array $location See LocationProvider::getLocation for more info. */ private function updateVisitInfoWithLocation($location) { static $logVisitToLowerLocationMapping = array( - 'location_country' => Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY, + 'location_country' => LocationProvider::COUNTRY_CODE_KEY, ); static $logVisitToLocationMapping = array( - 'location_region' => Piwik_UserCountry_LocationProvider::REGION_CODE_KEY, - 'location_city' => Piwik_UserCountry_LocationProvider::CITY_NAME_KEY, - 'location_latitude' => Piwik_UserCountry_LocationProvider::LATITUDE_KEY, - 'location_longitude' => Piwik_UserCountry_LocationProvider::LONGITUDE_KEY, + 'location_region' => LocationProvider::REGION_CODE_KEY, + 'location_city' => LocationProvider::CITY_NAME_KEY, + 'location_latitude' => LocationProvider::LATITUDE_KEY, + 'location_longitude' => LocationProvider::LONGITUDE_KEY, ); foreach ($logVisitToLowerLocationMapping as $column => $locationKey) { @@ -553,17 +553,17 @@ private function updateVisitInfoWithLocation($location) } // if the location has provider/organization info, set it - if (!empty($location[Piwik_UserCountry_LocationProvider::ISP_KEY])) { - $providerValue = $location[Piwik_UserCountry_LocationProvider::ISP_KEY]; + if (!empty($location[LocationProvider::ISP_KEY])) { + $providerValue = $location[LocationProvider::ISP_KEY]; // if the org is set and not the same as the isp, add it to the provider value - if (!empty($location[Piwik_UserCountry_LocationProvider::ORG_KEY]) - && $location[Piwik_UserCountry_LocationProvider::ORG_KEY] != $providerValue + if (!empty($location[LocationProvider::ORG_KEY]) + && $location[LocationProvider::ORG_KEY] != $providerValue ) { - $providerValue .= ' - ' . $location[Piwik_UserCountry_LocationProvider::ORG_KEY]; + $providerValue .= ' - ' . $location[LocationProvider::ORG_KEY]; } - } else if (!empty($location[Piwik_UserCountry_LocationProvider::ORG_KEY])) { - $providerValue = $location[Piwik_UserCountry_LocationProvider::ORG_KEY]; + } else if (!empty($location[LocationProvider::ORG_KEY])) { + $providerValue = $location[LocationProvider::ORG_KEY]; } if (isset($providerValue)) { diff --git a/core/Twig.php b/core/Twig.php index 5a316c65ce0..ae79b90e89d 100644 --- a/core/Twig.php +++ b/core/Twig.php @@ -11,6 +11,7 @@ namespace Piwik; use Exception; +use Piwik\API\Request; use Piwik\Piwik; use Piwik\Common; use Piwik\AssetManager; @@ -230,7 +231,6 @@ private function addPluginNamespaces(Twig_Loader_Filesystem $loader) { $plugins = PluginsManager::getInstance()->getLoadedPluginsName(); foreach ($plugins as $name) { - $name = Common::unprefixClass($name); $path = sprintf("%s/plugins/%s/templates/", PIWIK_INCLUDE_PATH, $name); if (is_dir($path)) { $loader->addPath(PIWIK_INCLUDE_PATH . '/plugins/' . $name . '/templates', $name); diff --git a/core/UpdateCheck.php b/core/UpdateCheck.php index 2c301246765..29261f8341d 100644 --- a/core/UpdateCheck.php +++ b/core/UpdateCheck.php @@ -14,7 +14,7 @@ use Piwik\Config; use Piwik\Common; use Piwik\Http; -use Piwik_SitesManager_API; +use Piwik\Plugins\SitesManager\API; use Piwik\Url; use Piwik\Version; @@ -55,7 +55,7 @@ public static function check($force = false, $interval = null) 'php_version' => PHP_VERSION, 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), - 'timezone' => Piwik_SitesManager_API::getInstance()->getDefaultTimezone(), + 'timezone' => API::getInstance()->getDefaultTimezone(), ); $url = Config::getInstance()->General['api_service_url'] diff --git a/core/Updater.php b/core/Updater.php index 740bb2e031b..b6b13de4c67 100644 --- a/core/Updater.php +++ b/core/Updater.php @@ -138,6 +138,7 @@ public function getSqlQueriesToExecute() private function getUpdateClassName($componentName, $fileVersion) { + ////unprefixClass TODOA FIXME $suffix = strtolower(str_replace(array('-', '.'), '_', $fileVersion)); if ($componentName == 'core') { return 'Piwik_Updates_' . $suffix; diff --git a/core/Updates/0.2.34.php b/core/Updates/0.2.34.php index 785627f8752..5ad44f5268e 100644 --- a/core/Updates/0.2.34.php +++ b/core/Updates/0.2.34.php @@ -9,6 +9,7 @@ * @package Updates */ use Piwik\Piwik; +use Piwik\Plugins\SitesManager\API; use Piwik\Tracker\Cache; use Piwik\Updates; @@ -21,7 +22,7 @@ static function update($schema = 'Myisam') { // force regeneration of cache files following #648 Piwik::setUserIsSuperUser(); - $allSiteIds = Piwik_SitesManager_API::getInstance()->getAllSitesId(); + $allSiteIds = API::getInstance()->getAllSitesId(); Cache::regenerateCacheWebsiteAttributes($allSiteIds); } } diff --git a/core/Updates/0.6.2.php b/core/Updates/0.6.2.php index 74bbe6b6b62..af541713a23 100644 --- a/core/Updates/0.6.2.php +++ b/core/Updates/0.6.2.php @@ -9,6 +9,7 @@ * @package Updates */ use Piwik\Piwik; +use Piwik\Plugins\SitesManager\API; use Piwik\Tracker\Cache; use Piwik\Updates; @@ -39,7 +40,7 @@ static function update() // force regeneration of cache files Piwik::setUserIsSuperUser(); - $allSiteIds = Piwik_SitesManager_API::getInstance()->getAllSitesId(); + $allSiteIds = API::getInstance()->getAllSitesId(); Cache::regenerateCacheWebsiteAttributes($allSiteIds); } } diff --git a/core/Updates/1.8.3-b1.php b/core/Updates/1.8.3-b1.php index 84d9ce56d54..f217635ebca 100644 --- a/core/Updates/1.8.3-b1.php +++ b/core/Updates/1.8.3-b1.php @@ -9,6 +9,7 @@ * @package Updates */ use Piwik\Common; +use Piwik\Plugins\PDFReports\PDFReports; use Piwik\Updater; use Piwik\Updates; use Piwik\Db; @@ -78,11 +79,11 @@ static function update() $parameters = array(); if (!is_null($additional_emails)) { - $parameters[Piwik_PDFReports::ADDITIONAL_EMAILS_PARAMETER] = preg_split('/,/', $additional_emails); + $parameters[PDFReports::ADDITIONAL_EMAILS_PARAMETER] = preg_split('/,/', $additional_emails); } - $parameters[Piwik_PDFReports::EMAIL_ME_PARAMETER] = is_null($email_me) ? Piwik_PDFReports::EMAIL_ME_PARAMETER_DEFAULT_VALUE : (bool)$email_me; - $parameters[Piwik_PDFReports::DISPLAY_FORMAT_PARAMETER] = $display_format; + $parameters[PDFReports::EMAIL_ME_PARAMETER] = is_null($email_me) ? PDFReports::EMAIL_ME_PARAMETER_DEFAULT_VALUE : (bool)$email_me; + $parameters[PDFReports::DISPLAY_FORMAT_PARAMETER] = $display_format; Db::query( 'INSERT INTO `' . Common::prefixTable('report') . '` SET @@ -94,9 +95,9 @@ static function update() $idsite, $login, $description, - is_null($period) ? Piwik_PDFReports::DEFAULT_PERIOD : $period, - Piwik_PDFReports::EMAIL_TYPE, - is_null($format) ? Piwik_PDFReports::DEFAULT_REPORT_FORMAT : $format, + is_null($period) ? PDFReports::DEFAULT_PERIOD : $period, + PDFReports::EMAIL_TYPE, + is_null($format) ? PDFReports::DEFAULT_REPORT_FORMAT : $format, Common::json_encode(preg_split('/,/', $reports)), Common::json_encode($parameters), $ts_created, diff --git a/core/View.php b/core/View.php index e765791b72f..9d221c9d9cb 100644 --- a/core/View.php +++ b/core/View.php @@ -20,8 +20,8 @@ use Piwik\UpdateCheck; use Piwik\Twig; use Piwik\QuickForm2; -use Piwik_SitesManager_API; -use Piwik_UsersManager_API; +use Piwik\Plugins\SitesManager\API as SitesManagerAPI; +use Piwik\Plugins\UsersManager\API as UsersManagerAPI; use Piwik\View\ViewInterface; use Twig_Environment; use Zend_Registry; @@ -110,7 +110,7 @@ public function render() $count = Piwik::getWebsitesCountToDisplay(); - $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess($count); + $sites = SitesManagerAPI::getInstance()->getSitesWithAtLeastViewAccess($count); usort($sites, create_function('$site1, $site2', 'return strcasecmp($site1["name"], $site2["name"]);')); $this->sites = $sites; $this->url = Common::sanitizeInputValue(Url::getCurrentUrl()); @@ -128,7 +128,7 @@ public function render() $this->loginModule = Piwik::getLoginPluginName(); - $user = Piwik_UsersManager_API::getInstance()->getUser($userLogin); + $user = UsersManagerAPI::getInstance()->getUser($userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { // can fail, for example at installation (no plugin loaded yet) diff --git a/core/ViewDataTable.php b/core/ViewDataTable.php index 386d41e6cb5..e6ee1289be7 100644 --- a/core/ViewDataTable.php +++ b/core/ViewDataTable.php @@ -13,6 +13,7 @@ use Piwik\Config; use Piwik\Metrics; use Piwik\Period; +use Piwik\API\Request; use Piwik\Period\Range; use Piwik\Piwik; use Piwik\Common; @@ -22,7 +23,7 @@ use Piwik\Site; use Piwik\ViewDataTable\Properties; use Piwik\ViewDataTable\VisualizationPropertiesProxy; -use Piwik_API_API; +use Piwik\Plugins\API\API; /** * This class is used to load (from the API) and customize the output of a given DataTable. @@ -610,7 +611,7 @@ protected function loadDataTableFromAPI() $requestArray = $this->getRequestArray(); // we make the request to the API - $request = new API\Request($requestArray); + $request = new Request($requestArray); // and get the DataTable structure $dataTable = $request->process(); @@ -699,13 +700,13 @@ protected function postDataTableLoadedFromAPI() if (!$this->areGenericFiltersDisabled()) { // Second, generic filters (Sort, Limit, Replace Column Names, etc.) $requestArray = $this->getRequestArray(); - $request = API\Request::getRequestArrayFromString($requestArray); + $request = Request::getRequestArrayFromString($requestArray); if ($this->viewProperties['enable_sort'] === false) { $request['filter_sort_column'] = $request['filter_sort_order'] = ''; } - $genericFilter = new API\DataTableGenericFilter($request); + $genericFilter = new \Piwik\API\DataTableGenericFilter($request); $genericFilter->filter($this->dataTable); } @@ -815,7 +816,7 @@ protected function getRequestArray() } } - $segment = \Piwik\API\Request::getRawSegmentFromRequest(); + $segment = Request::getRawSegmentFromRequest(); if(!empty($segment)) { $requestArray['segment'] = $segment; } @@ -848,7 +849,7 @@ protected function getJavascriptVariablesToSet() // build javascript variables to set $javascriptVariablesToSet = array(); - $genericFilters = API\DataTableGenericFilter::getGenericFiltersInformation(); + $genericFilters = \Piwik\API\DataTableGenericFilter::getGenericFiltersInformation(); foreach ($genericFilters as $filter) { foreach ($filter as $filterVariableName => $filterInfo) { // if there is a default value for this filter variable we set it @@ -938,7 +939,7 @@ protected function getJavascriptVariablesToSet() } } - $rawSegment = \Piwik\API\Request::getRawSegmentFromRequest(); + $rawSegment = Request::getRawSegmentFromRequest(); if(!empty($rawSegment)) { $javascriptVariablesToSet['segment'] = $rawSegment; } @@ -982,7 +983,7 @@ private function loadDocumentation() { $this->viewProperties['metrics_documentation'] = array(); - $report = Piwik_API_API::getInstance()->getMetadata(0, $this->currentControllerName, $this->currentControllerAction); + $report = API::getInstance()->getMetadata(0, $this->currentControllerName, $this->currentControllerAction); $report = $report[0]; if (isset($report['metricsDocumentation'])) { @@ -1096,8 +1097,9 @@ public function hasReportBeenPurged() $reportYear = $reportDate->toString('Y'); $reportMonth = $reportDate->toString('m'); - if (class_exists('Piwik_PrivacyManager') - && \Piwik_PrivacyManager::shouldReportBePurged($reportYear, $reportMonth) + //TODOA + if (class_exists('Piwik\Plugins\PrivacyManager\PrivacyManager') + && Plugins\PrivacyManager\PrivacyManager::shouldReportBePurged($reportYear, $reportMonth) ) { return true; } @@ -1117,7 +1119,7 @@ public function hasReportBeenPurged() private function getBaseReportUrl($module, $action, $queryParams = array()) { $params = array_merge($queryParams, array('module' => $module, 'action' => $action)); - return API\Request::getCurrentUrlWithoutGenericFilters($params); + return Request::getCurrentUrlWithoutGenericFilters($params); } /** @@ -1131,9 +1133,10 @@ private function getBaseReportUrl($module, $action, $queryParams = array()) */ static public function renderReport($pluginName, $apiAction, $fetch = true) { - $apiClassName = 'Piwik_' . $pluginName . '_API'; - if (!method_exists($apiClassName::getInstance(), $apiAction)) { - throw new \Exception("Invalid action name '$apiAction' for '$pluginName' plugin."); + //TODOA + $namespacedApiClassName = "\\Piwik\\Plugins\\$pluginName\\API"; + if (!method_exists($namespacedApiClassName::getInstance(), $apiAction)) { + throw new \Exception("$namespacedApiClassName Invalid action name '$apiAction' for '$pluginName' plugin."); } $view = self::factory(null, $pluginName.'.'.$apiAction); @@ -1263,4 +1266,4 @@ private function setPropertyDefaults($defaultValues) } } } -} \ No newline at end of file +} diff --git a/core/ViewDataTable/HtmlTable/Goals.php b/core/ViewDataTable/HtmlTable/Goals.php index 414e78d6bac..88f3ab4b1a9 100644 --- a/core/ViewDataTable/HtmlTable/Goals.php +++ b/core/ViewDataTable/HtmlTable/Goals.php @@ -15,7 +15,7 @@ use Piwik\Site; use Piwik\ViewDataTable\HtmlTable; use Piwik\DataTable\Filter\AddColumnsProcessedMetricsGoal; -use Piwik_Goals_API; +use Piwik\Plugins\Goals\API; /** * @package Piwik @@ -197,7 +197,7 @@ protected function overrideViewProperties() $goals = array(); $idSite = $this->getIdSite(); if ($idSite) { - $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); + $goals = API::getInstance()->getGoals($idSite); $ecommerceGoal = array( 'idgoal' => Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER, diff --git a/misc/cron/archive.php b/misc/cron/archive.php index 1f63c26ebf5..cf6d2a5e448 100644 --- a/misc/cron/archive.php +++ b/misc/cron/archive.php @@ -6,6 +6,8 @@ use Piwik\Date; use Piwik\FrontController; use Piwik\Http; +use Piwik\Plugins\CoreAdminHome\API as CoreAdminHomeAPI; +use Piwik\Plugins\SitesManager\API as SitesManagerAPI; use Piwik\Version; use Piwik\Url; use Piwik\Timer; @@ -327,13 +329,13 @@ public function run() // Remove this website from the list of websites to be invalidated // since it's now just been re-processing the reports, job is done! if ($websiteIsOldDataInvalidate) { - $websiteIdsInvalidated = Piwik_CoreAdminHome_API::getWebsiteIdsToInvalidate(); + $websiteIdsInvalidated = CoreAdminHomeAPI::getWebsiteIdsToInvalidate(); if (count($websiteIdsInvalidated)) { $found = array_search($idsite, $websiteIdsInvalidated); if ($found !== false) { unset($websiteIdsInvalidated[$found]); // $this->log("Websites left to invalidate: " . implode(", ", $websiteIdsInvalidated)); - Piwik_SetOption(Piwik_CoreAdminHome_API::OPTION_INVALIDATED_IDSITES, serialize($websiteIdsInvalidated)); + Piwik_SetOption(CoreAdminHomeAPI::OPTION_INVALIDATED_IDSITES, serialize($websiteIdsInvalidated)); } } } @@ -394,8 +396,8 @@ public function run() private function initSegmentsToArchive() { -// Fetching segments to process - $this->segments = Piwik_CoreAdminHome_API::getInstance()->getKnownSegmentsToArchive(); + // Fetching segments to process + $this->segments = CoreAdminHomeAPI::getInstance()->getKnownSegmentsToArchive(); if (empty($this->segments)) $this->segments = array(); if (!empty($this->segments)) { $this->log("- Will pre-process " . count($this->segments) . " Segments for each website and each period: " . implode(", ", $this->segments)); @@ -720,7 +722,7 @@ private function initStateFromParameters() // Fetching websites to process private function initWebsitesToProcess() { - $this->allWebsites = Piwik_SitesManager_API::getInstance()->getAllSitesId(); + $this->allWebsites = SitesManagerAPI::getInstance()->getAllSitesId(); if ($this->shouldArchiveAllWebsites) { $this->websites = $this->allWebsites; @@ -734,7 +736,7 @@ private function initWebsitesToProcess() . Piwik::getPrettyTimeFromSeconds($this->firstRunActiveWebsitesWithTraffic, true, false) ); } - $this->websites = Piwik_SitesManager_API::getInstance()->getSitesIdWithVisits($timestampActiveTraffic); + $this->websites = SitesManagerAPI::getInstance()->getSitesIdWithVisits($timestampActiveTraffic); $websiteIds = !empty($this->websites) ? ", IDs: " . implode(", ", $this->websites) : ""; $prettySeconds = Piwik::getPrettyTimeFromSeconds(empty($this->timeLastCompleted) ? $this->firstRunActiveWebsitesWithTraffic @@ -747,7 +749,7 @@ private function initWebsitesToProcess() // 2) All websites that had reports in the past invalidated recently // eg. when using Python log import script - $this->idSitesInvalidatedOldReports = Piwik_CoreAdminHome_API::getWebsiteIdsToInvalidate(); + $this->idSitesInvalidatedOldReports = CoreAdminHomeAPI::getWebsiteIdsToInvalidate(); $this->idSitesInvalidatedOldReports = array_intersect($this->idSitesInvalidatedOldReports, $this->allWebsites); if (count($this->idSitesInvalidatedOldReports) > 0) { @@ -758,7 +760,7 @@ private function initWebsitesToProcess() // 3) Also process all other websites which days have finished since the last run. // This ensures we process the previous day/week/month/year that just finished, even if there was no new visit - $uniqueTimezones = Piwik_SitesManager_API::getInstance()->getUniqueSiteTimezones(); + $uniqueTimezones = SitesManagerAPI::getInstance()->getUniqueSiteTimezones(); $timezoneToProcess = array(); foreach ($uniqueTimezones as &$timezone) { $processedDateInTz = Date::factory((int)$timestampActiveTraffic, $timezone); @@ -769,7 +771,7 @@ private function initWebsitesToProcess() } } - $websiteDayHasFinishedSinceLastRun = Piwik_SitesManager_API::getInstance()->getSitesIdFromTimezones($timezoneToProcess); + $websiteDayHasFinishedSinceLastRun = SitesManagerAPI::getInstance()->getSitesIdFromTimezones($timezoneToProcess); $websiteDayHasFinishedSinceLastRun = array_diff($websiteDayHasFinishedSinceLastRun, $this->websites); $this->websiteDayHasFinishedSinceLastRun = $websiteDayHasFinishedSinceLastRun; if (count($websiteDayHasFinishedSinceLastRun) > 0) { diff --git a/misc/others/geoipUpdateRows.php b/misc/others/geoipUpdateRows.php index b0ffb11d7c5..d0392c9f3b2 100755 --- a/misc/others/geoipUpdateRows.php +++ b/misc/others/geoipUpdateRows.php @@ -5,6 +5,9 @@ use Piwik\FrontController; use Piwik\IP; use Piwik\Db; +use Piwik\Plugins\UserCountry\LocationProvider; +use Piwik\Plugins\UserCountry\LocationProvider\GeoIp\Php; +use Piwik\Plugins\UserCountry\LocationProvider\GeoIp\Pecl; ini_set("memory_limit", "512M"); error_reporting(E_ALL | E_NOTICE); @@ -120,7 +123,7 @@ function geoipUpdateError($message) $displayNotes = $start == 0; // try getting the pecl location provider -$provider = new Piwik_UserCountry_LocationProvider_GeoIp_Pecl(); +$provider = new Pecl(); if (!$provider->isAvailable()) { if ($displayNotes) { Piwik::log("[note] The GeoIP PECL extension is not installed."); @@ -146,7 +149,7 @@ function geoipUpdateError($message) Piwik::log("[note] Falling back to PHP API. This may become too slow for you. If so, you can read this link on how to install the PECL extension: http://piwik.org/faq/how-to/#faq_164"); } - $provider = new Piwik_UserCountry_LocationProvider_GeoIp_Php(); + $provider = new Php(); if (!$provider->isAvailable()) { if ($displayNotes) { Piwik::log("[note] The GeoIP PHP API is not available. This means you do not have a GeoIP location database in your ./misc directory. The database must be named either GeoIP.dat or GeoIPCity.dat based on the type of database it is."); @@ -173,11 +176,11 @@ function geoipUpdateError($message) } // perform update -$logVisitFieldsToUpdate = array('location_country' => Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY, - 'location_region' => Piwik_UserCountry_LocationProvider::REGION_CODE_KEY, - 'location_city' => Piwik_UserCountry_LocationProvider::CITY_NAME_KEY, - 'location_latitude' => Piwik_UserCountry_LocationProvider::LATITUDE_KEY, - 'location_longitude' => Piwik_UserCountry_LocationProvider::LONGITUDE_KEY); +$logVisitFieldsToUpdate = array('location_country' => LocationProvider::COUNTRY_CODE_KEY, + 'location_region' => LocationProvider::REGION_CODE_KEY, + 'location_city' => LocationProvider::CITY_NAME_KEY, + 'location_latitude' => LocationProvider::LATITUDE_KEY, + 'location_longitude' => LocationProvider::LONGITUDE_KEY); if ($displayNotes) { Piwik::log("\n$count rows to process in " . Common::prefixTable('log_visit') @@ -208,9 +211,9 @@ function geoipUpdateError($message) $ip = IP::N2P($row['location_ip']); $location = $provider->getLocation(array('ip' => $ip)); - if (!empty($location[Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY])) { - $location[Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY] = - strtolower($location[Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY]); + if (!empty($location[LocationProvider::COUNTRY_CODE_KEY])) { + $location[LocationProvider::COUNTRY_CODE_KEY] = + strtolower($location[LocationProvider::COUNTRY_CODE_KEY]); } $row['location_country'] = strtolower($row['location_country']); diff --git a/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php b/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php index e9c6b324496..69154a4b133 100644 --- a/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php +++ b/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php @@ -4,6 +4,7 @@ use Piwik\Piwik; use Piwik\Common; use Piwik\FrontController; +use Piwik\Plugins\SitesManager\API; exit; @@ -19,7 +20,7 @@ Piwik::setUserIsSuperUser(); $count = 100; for ($i = 0; $i <= $count; $i++) { - $id = Piwik_SitesManager_API::getInstance()->addSite(Common::getRandomString(), 'http://piwik.org'); + $id = API::getInstance()->addSite(Common::getRandomString(), 'http://piwik.org'); $t = new PiwikTracker($id, 'http://localhost/trunk/piwik.php'); echo $id . "
"; } diff --git a/plugins/API/API.php b/plugins/API/API.php index d1ea3c6eb84..7058bdb0ce3 100644 --- a/plugins/API/API.php +++ b/plugins/API/API.php @@ -8,6 +8,8 @@ * @category Piwik_Plugins * @package Piwik_API */ +namespace Piwik\Plugins\API; + use Piwik\API\Request; use Piwik\API\Proxy; use Piwik\DataTable\Filter\ColumnDelete; @@ -20,55 +22,10 @@ use Piwik\DataTable; use Piwik\Tracker\GoalManager; use Piwik\Version; -use Piwik\Plugin; use Piwik\Translate; require_once PIWIK_INCLUDE_PATH . '/core/Config.php'; -/** - * @package Piwik_API - */ -class Piwik_API extends Plugin -{ - /** - * @see Piwik_Plugin::getListHooksRegistered - */ - public function getListHooksRegistered() - { - return array( - 'AssetManager.getCssFiles' => 'getCssFiles', - 'TopMenu.add' => 'addTopMenu', - ); - } - - public function addTopMenu() - { - $apiUrlParams = array('module' => 'API', 'action' => 'listAllAPI', 'segment' => false); - $tooltip = Piwik_Translate('API_TopLinkTooltip'); - - Piwik_AddTopMenu('General_API', $apiUrlParams, true, 7, $isHTML = false, $tooltip); - - $this->addTopMenuMobileApp(); - } - - protected function addTopMenuMobileApp() - { - if (empty($_SERVER['HTTP_USER_AGENT'])) { - return; - } - require_once PIWIK_INCLUDE_PATH . '/libs/UserAgentParser/UserAgentParser.php'; - $os = UserAgentParser::getOperatingSystem($_SERVER['HTTP_USER_AGENT']); - if ($os && in_array($os['id'], array('AND', 'IPD', 'IPA', 'IPH'))) { - Piwik_AddTopMenu('Piwik Mobile App', array('module' => 'Proxy', 'action' => 'redirect', 'url' => 'http://piwik.org/mobile/'), true, 4); - } - } - - public function getCssFiles(&$cssFiles) - { - $cssFiles[] = "plugins/API/stylesheets/listAllAPI.less"; - } -} - /** * This API is the Metadata API: it gives information about all other available APIs methods, as well as providing * human readable and more complete outputs than normal API methods. @@ -87,12 +44,12 @@ public function getCssFiles(&$cssFiles) * * @package Piwik_API */ -class Piwik_API_API +class API { static private $instance = null; /** - * @return Piwik_API_API + * @return \Piwik\Plugins\API\API */ static public function getInstance() { @@ -230,7 +187,7 @@ public function getSegmentsMetadata($idSites = array(), $_hideImplementationData 'acceptedValues' => implode(", ", self::$visitEcommerceStatus) . '. ' . Piwik_Translate('General_EcommerceVisitStatusEg', '"&segment=visitEcommerceStatus==ordered,visitEcommerceStatus==orderedThenAbandonedCart"'), 'sqlSegment' => 'log_visit.visit_goal_buyer', - 'sqlFilter' => array('Piwik_API_API', 'getVisitEcommerceStatus'), + 'sqlFilter' => __NAMESPACE__ . '\API::getVisitEcommerceStatus', ); $segments[] = array( @@ -268,7 +225,7 @@ public function getSegmentsMetadata($idSites = array(), $_hideImplementationData static public function getVisitEcommerceStatusFromId($id) { if (!isset(self::$visitEcommerceStatus[$id])) { - throw new Exception("Unexpected ECommerce status value "); + throw new \Exception("Unexpected ECommerce status value "); } return self::$visitEcommerceStatus[$id]; } @@ -280,7 +237,7 @@ static public function getVisitEcommerceStatus($status) { $id = array_search($status, self::$visitEcommerceStatus); if ($id === false) { - throw new Exception("Invalid 'visitEcommerceStatus' segment value"); + throw new \Exception("Invalid 'visitEcommerceStatus' segment value"); } return $id; } @@ -396,8 +353,8 @@ public function getMetadata($idSite, $apiModule, $apiAction, $apiParameters = ar $period = false, $date = false, $hideMetricsDoc = false, $showSubtableReports = false) { Translate::getInstance()->reloadLanguage($language); - $reporter = new Piwik_API_ProcessedReport(); - $metadata = $reporter->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date, $hideMetricsDoc, $showSubtableReports); + $reporter = new ProcessedReport(); + $metadata = $reporter->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date, $hideMetricsDoc, $showSubtableReports); return $metadata; } @@ -415,8 +372,8 @@ public function getMetadata($idSite, $apiModule, $apiAction, $apiParameters = ar public function getReportMetadata($idSites = '', $period = false, $date = false, $hideMetricsDoc = false, $showSubtableReports = false) { - $reporter = new Piwik_API_ProcessedReport(); - $metadata = $reporter->getReportMetadata($idSites, $period, $date, $hideMetricsDoc, $showSubtableReports); + $reporter = new ProcessedReport(); + $metadata = $reporter->getReportMetadata($idSites, $period, $date, $hideMetricsDoc, $showSubtableReports); return $metadata; } @@ -424,8 +381,8 @@ public function getProcessedReport($idSite, $period, $date, $apiModule, $apiActi $apiParameters = false, $idGoal = false, $language = false, $showTimer = true, $hideMetricsDoc = false, $idSubtable = false, $showRawMetrics = false) { - $reporter = new Piwik_API_ProcessedReport(); - $processed = $reporter->getProcessedReport( $idSite, $period, $date, $apiModule, $apiAction, $segment, + $reporter = new ProcessedReport(); + $processed = $reporter->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment, $apiParameters, $idGoal, $language, $showTimer, $hideMetricsDoc, $idSubtable, $showRawMetrics); return $processed; @@ -446,7 +403,7 @@ public function get($idSite, $period, $date, $segment = false, $columns = false) // find out which columns belong to which plugin $columnsByPlugin = array(); - $meta = Piwik_API_API::getInstance()->getReportMetadata($idSite, $period, $date); + $meta = \Piwik\Plugins\API\API::getInstance()->getReportMetadata($idSite, $period, $date); foreach ($meta as $reportMeta) { // scan all *.get reports if ($reportMeta['action'] == 'get' @@ -472,7 +429,7 @@ public function get($idSite, $period, $date, $segment = false, $columns = false) $params = compact('idSite', 'period', 'date', 'segment', 'idGoal'); foreach ($columnsByPlugin as $plugin => $columns) { // load the data - $className = 'Piwik_' . $plugin . '_API'; + $className = Request::getClassNameAPI($plugin); $params['columns'] = implode(',', $columns); $dataTable = Proxy::getInstance()->call($className, 'get', $params); // make sure the table has all columns @@ -549,7 +506,7 @@ private function mergeDataTables($table1, $table2) */ public function getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label = false, $segment = false, $column = false, $language = false, $idGoal = false, $legendAppendMetric = true, $labelUseAbsoluteUrl = true) { - $rowEvolution = new Piwik_API_RowEvolution(); + $rowEvolution = new RowEvolution(); return $rowEvolution->getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label, $segment, $column, $language, $idGoal, $legendAppendMetric, $labelUseAbsoluteUrl); } @@ -603,12 +560,12 @@ public function getSuggestedValuesForSegment($segmentName, $idSite) $startDate = Date::now()->subDay(60)->toString(); $requestLastVisits = "method=Live.getLastVisitsDetails - &idSite=$idSite - &period=range - &date=$startDate,today - &format=original - &serialize=0 - &flat=1"; + &idSite=$idSite + &period=range + &date=$startDate,today + &format=original + &serialize=0 + &flat=1"; // Select non empty fields only // Note: this optimization has only a very minor impact @@ -663,3 +620,53 @@ protected function doesSegmentNeedActionsData($segmentName) return $doesSegmentNeedActionsInfo; } } + +/** + * @package Piwik_API + */ +class Plugin extends \Piwik\Plugin +{ + public function __construct() + { + // this class is named 'Plugin', manually set the 'API' plugin + parent::__construct($pluginName = 'API'); + } + + /** + * @see Piwik_Plugin::getListHooksRegistered + */ + public function getListHooksRegistered() + { + return array( + 'AssetManager.getCssFiles' => 'getCssFiles', + 'TopMenu.add' => 'addTopMenu', + ); + } + + public function addTopMenu() + { + $apiUrlParams = array('module' => 'API', 'action' => 'listAllAPI', 'segment' => false); + $tooltip = Piwik_Translate('API_TopLinkTooltip'); + + Piwik_AddTopMenu('General_API', $apiUrlParams, true, 7, $isHTML = false, $tooltip); + + $this->addTopMenuMobileApp(); + } + + protected function addTopMenuMobileApp() + { + if (empty($_SERVER['HTTP_USER_AGENT'])) { + return; + } + require_once PIWIK_INCLUDE_PATH . '/libs/UserAgentParser/UserAgentParser.php'; + $os = \UserAgentParser::getOperatingSystem($_SERVER['HTTP_USER_AGENT']); + if ($os && in_array($os['id'], array('AND', 'IPD', 'IPA', 'IPH'))) { + Piwik_AddTopMenu('Piwik Mobile App', array('module' => 'Proxy', 'action' => 'redirect', 'url' => 'http://piwik.org/mobile/'), true, 4); + } + } + + public function getCssFiles(&$cssFiles) + { + $cssFiles[] = "plugins/API/stylesheets/listAllAPI.less"; + } +} \ No newline at end of file diff --git a/plugins/API/Controller.php b/plugins/API/Controller.php index ed4addae2cb..ac8e31ac848 100644 --- a/plugins/API/Controller.php +++ b/plugins/API/Controller.php @@ -8,19 +8,21 @@ * @category Piwik_Plugins * @package Piwik_API */ +namespace Piwik\Plugins\API; + use Piwik\API\DocumentationGenerator; use Piwik\API\Request; use Piwik\API\Proxy; use Piwik\Config; use Piwik\Common; -use Piwik\Controller; +use Piwik\Plugins\API\API; use Piwik\View; /** * * @package Piwik_API */ -class Piwik_API_Controller extends Controller +class Controller extends \Piwik\Controller { function index() { @@ -51,7 +53,7 @@ public function listAllAPI() public function listSegments() { - $segments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSite); + $segments = API::getInstance()->getSegmentsMetadata($this->idSite); $tableDimensions = $tableMetrics = ''; $customVariables = 0; @@ -98,7 +100,6 @@ public function listSegments() } } - if ($segment['type'] == 'dimension') { $tableDimensions .= $output; } else { diff --git a/plugins/API/ProcessedReport.php b/plugins/API/ProcessedReport.php index b30a3d79018..8e46cec774b 100644 --- a/plugins/API/ProcessedReport.php +++ b/plugins/API/ProcessedReport.php @@ -1,4 +1,16 @@ loadRowEvolutionDataFromAPI($idSite, $period, $date, $apiModule, $apiAction, $labels, $segment, $idGoal); if (empty($labels)) { @@ -273,8 +275,8 @@ private function getRowEvolutionMetaData($idSite, $period, $date, $apiModule, $a if (!empty($idGoal) && $idGoal > 0) { $apiParameters = array('idGoal' => $idGoal); } - $reportMetadata = Piwik_API_API::getInstance()->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, - $period, $date, $hideMetricsDoc = false, $showSubtableReports = true); + $reportMetadata = API::getInstance()->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, + $period, $date, $hideMetricsDoc = false, $showSubtableReports = true); if (empty($reportMetadata)) { throw new Exception("Requested report $apiModule.$apiAction for Website id=$idSite " @@ -463,17 +465,14 @@ private function getMultiRowEvolution($dataTable, $metadata, $apiModule, $apiAct private function getRowEvolutionRowFromLabelIdx($table, $labelIdx) { $labelIdx = (int)$labelIdx; - foreach ($table->getRows() as $row) - { - if ($row->getMetadata(LabelFilter::FLAG_IS_ROW_EVOLUTION) === $labelIdx) - { + foreach ($table->getRows() as $row) { + if ($row->getMetadata(LabelFilter::FLAG_IS_ROW_EVOLUTION) === $labelIdx) { return $row; } } return false; } - /** * Returns a prettier, more comprehensible version of a row evolution label * for display. diff --git a/plugins/Actions/API.php b/plugins/Actions/API.php index 263e3e4a6b6..1804ca4a07c 100644 --- a/plugins/Actions/API.php +++ b/plugins/Actions/API.php @@ -6,15 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Actions + * @package Actions */ +namespace Piwik\Plugins\Actions; + +use Exception; use Piwik\Archive; use Piwik\Metrics; use Piwik\Piwik; use Piwik\Common; use Piwik\Date; use Piwik\DataTable; +use Piwik\Plugins\Actions\Actions; use Piwik\Tracker\Action; +use Piwik\Plugins\Actions\Archiver; +use Piwik\Plugins\Actions\ArchivingHelper; +use Piwik\Plugins\CustomVariables\API as CustomVariablesAPI; /** * The Actions API lets you request reports for all your Visitor Actions: Page URLs, Page titles (Piwik Events), @@ -28,14 +35,14 @@ * and an outlink via "getOutlink". * * Note: pageName, pageUrl, outlinkUrl, downloadUrl parameters must be URL encoded before you call the API. - * @package Piwik_Actions + * @package Actions */ -class Piwik_Actions_API +class API { static private $instance = null; /** - * @return Piwik_Actions_API + * @return \Piwik\Plugins\Actions\API */ static public function getInstance() { @@ -60,7 +67,7 @@ public function get($idSite, $period, $date, $segment = false, $columns = false) Piwik::checkUserHasViewAccess($idSite); $archive = Archive::build($idSite, $period, $date, $segment); - $metrics = Piwik_Actions_Archiver::$actionsAggregateMetrics; + $metrics = Archiver::$actionsAggregateMetrics; $metrics['Actions_avg_time_generation'] = 'avg_time_generation'; // get requested columns @@ -89,13 +96,13 @@ public function get($idSite, $period, $date, $segment = false, $columns = false) } if ($avgGenerationTimeRequested) { - $tempColumns[] = Piwik_Actions_Archiver::METRIC_SUM_TIME_RECORD_NAME; - $tempColumns[] = Piwik_Actions_Archiver::METRIC_HITS_TIMED_RECORD_NAME; + $tempColumns[] = Archiver::METRIC_SUM_TIME_RECORD_NAME; + $tempColumns[] = Archiver::METRIC_HITS_TIMED_RECORD_NAME; $columns = array_merge($columns, $tempColumns); $columns = array_unique($columns); - $nameReplace[Piwik_Actions_Archiver::METRIC_SUM_TIME_RECORD_NAME] = 'sum_time_generation'; - $nameReplace[Piwik_Actions_Archiver::METRIC_HITS_TIMED_RECORD_NAME] = 'nb_hits_with_time_generation'; + $nameReplace[Archiver::METRIC_SUM_TIME_RECORD_NAME] = 'sum_time_generation'; + $nameReplace[Archiver::METRIC_HITS_TIMED_RECORD_NAME] = 'nb_hits_with_time_generation'; } $table = $archive->getDataTableFromNumeric($columns); @@ -327,8 +334,8 @@ public function getSiteSearchNoResultKeywords($idSite, $period, $date, $segment */ public function getSiteSearchCategories($idSite, $period, $date, $segment = false) { - Piwik_Actions::checkCustomVariablesPluginEnabled(); - $customVariables = Piwik_CustomVariables_API::getInstance()->getCustomVariables($idSite, $period, $date, $segment, $expanded = false, $_leavePiwikCoreVariables = true); + Actions::checkCustomVariablesPluginEnabled(); + $customVariables = CustomVariablesAPI::getInstance()->getCustomVariables($idSite, $period, $date, $segment, $expanded = false, $_leavePiwikCoreVariables = true); $customVarNameToLookFor = Action::CVAR_KEY_SEARCH_CATEGORY; @@ -347,7 +354,7 @@ public function getSiteSearchCategories($idSite, $period, $date, $segment = fals if ($row) { $dateRewrite = $customVariableTableForDate->metadata['period']->getDateStart()->toString(); $idSubtable = $row->getIdSubDataTable(); - $categories = Piwik_CustomVariables_API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $dateRewrite, $idSubtable, $segment); + $categories = CustomVariablesAPI::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $dateRewrite, $idSubtable, $segment); $dataTable->addTable($categories, $key); } } @@ -356,7 +363,7 @@ public function getSiteSearchCategories($idSite, $period, $date, $segment = fals $row = $customVariables->getRowFromLabel($customVarNameToLookFor); if ($row) { $idSubtable = $row->getIdSubDataTable(); - $dataTable = Piwik_CustomVariables_API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment); + $dataTable = CustomVariablesAPI::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment); } } $this->filterActionsDataTable($dataTable); @@ -383,8 +390,8 @@ protected function getFilterPageDatatableSearch($callBackParameters, $search, $a $searchedString = $search; } } - Piwik_Actions_ArchivingHelper::reloadConfig(); - $searchTree = Piwik_Actions_ArchivingHelper::getActionExplodedNames($searchedString, $actionType); + ArchivingHelper::reloadConfig(); + $searchTree = ArchivingHelper::getActionExplodedNames($searchedString, $actionType); } if ($table === false) { @@ -405,7 +412,6 @@ protected function getFilterPageDatatableSearch($callBackParameters, $search, $a return $newTableArray; } - } return $this->doFilterPageDatatableSearch($callBackParameters, $table, $searchTree); diff --git a/plugins/Actions/Actions.php b/plugins/Actions/Actions.php index fdd116c6716..665e0511f11 100644 --- a/plugins/Actions/Actions.php +++ b/plugins/Actions/Actions.php @@ -6,8 +6,10 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Actions + * @package Actions */ +namespace Piwik\Plugins\Actions; + use Piwik\API\Request; use Piwik\ArchiveProcessor; use Piwik\Piwik; @@ -15,7 +17,6 @@ use Piwik\Tracker\Action; use Piwik\ViewDataTable; use Piwik\WidgetsList; -use Piwik\Plugin; use Piwik\SegmentExpression; use Piwik\Db; use Piwik\Site; @@ -25,18 +26,18 @@ * * Reports about the page views, the outlinks and downloads. * - * @package Piwik_Actions + * @package Actions */ -class Piwik_Actions extends Plugin +class Actions extends \Piwik\Plugin { const ACTIONS_REPORT_ROWS_DISPLAY = 100; - + private $columnTranslations; - + public function __construct() { parent::__construct(); - + $this->columnTranslations = array( 'nb_hits' => Piwik_Translate('General_ColumnPageviews'), 'nb_visits' => Piwik_Translate('General_ColumnUniquePageviews'), @@ -63,7 +64,7 @@ public function getListHooksRegistered() ); return $hooks; } - + public function getSegmentsMetadata(&$segments) { $sqlFilter = array($this, 'getIdActionFromSegment'); @@ -211,7 +212,7 @@ public function getReportMetadata(&$reports) 'nb_uniq_outlinks' => Piwik_Translate('Actions_ColumnUniqueOutlinks'), 'nb_searches' => Piwik_Translate('Actions_ColumnSearches'), 'nb_keywords' => Piwik_Translate('Actions_ColumnSiteSearchKeywords'), - 'avg_time_generation' => Piwik_Translate('General_ColumnAverageGenerationTime'), + 'avg_time_generation' => Piwik_Translate('General_ColumnAverageGenerationTime'), ), 'metricsDocumentation' => array( 'nb_pageviews' => Piwik_Translate('General_ColumnPageviewsDocumentation'), @@ -221,7 +222,7 @@ public function getReportMetadata(&$reports) 'nb_outlinks' => Piwik_Translate('Actions_ColumnClicksDocumentation'), 'nb_uniq_outlinks' => Piwik_Translate('Actions_ColumnUniqueClicksDocumentation'), 'nb_searches' => Piwik_Translate('Actions_ColumnSearchesDocumentation'), - 'avg_time_generation' => Piwik_Translate('General_ColumnAverageGenerationTimeDocumentation'), + 'avg_time_generation' => Piwik_Translate('General_ColumnAverageGenerationTimeDocumentation'), // 'nb_keywords' => Piwik_Translate('Actions_ColumnSiteSearchKeywords'), ), 'processedMetrics' => false, @@ -581,16 +582,16 @@ protected function isSiteSearchEnabled() */ public function archiveDay(ArchiveProcessor\Day $archiveProcessor) { - $archiving = new Piwik_Actions_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archiveDay(); } } function archivePeriod(ArchiveProcessor\Period $archiveProcessor) { - $archiving = new Piwik_Actions_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archivePeriod(); } } @@ -631,20 +632,20 @@ protected function guessActionTypeFromSegment($segmentName) public function getReportDisplayProperties(&$properties) { $properties['Actions.getPageUrls'] = $this->getDisplayPropertiesForPageUrls(); - $properties['Actions.getEntryPageUrls'] = $this->getDisplayPropertiesForEntryPageUrls(); - $properties['Actions.getExitPageUrls'] = $this->getDisplayPropertiesForExitPageUrls(); - $properties['Actions.getSiteSearchKeywords'] = $this->getDisplayPropertiesForSiteSearchKeywords(); - $properties['Actions.getSiteSearchNoResultKeywords'] = $this->getDisplayPropertiesForSiteSearchNoResultKeywords(); - $properties['Actions.getSiteSearchCategories'] = $this->getDisplayPropertiesForSiteSearchCategories(); - $properties['Actions.getPageUrlsFollowingSiteSearch'] = $this->getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch(false); - $properties['Actions.getPageTitlesFollowingSiteSearch'] = $this->getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch(true); - $properties['Actions.getPageTitles'] = $this->getDisplayPropertiesForGetPageTitles(); - $properties['Actions.getEntryPageTitles'] = $this->getDisplayPropertiesForGetEntryPageTitles(); - $properties['Actions.getExitPageTitles'] = $this->getDisplayPropertiesForGetExitPageTitles(); - $properties['Actions.getDownloads'] = $this->getDisplayPropertiesForGetDownloads(); - $properties['Actions.getOutlinks'] = $this->getDisplayPropertiesForGetOutlinks(); + $properties['Actions.getEntryPageUrls'] = $this->getDisplayPropertiesForEntryPageUrls(); + $properties['Actions.getExitPageUrls'] = $this->getDisplayPropertiesForExitPageUrls(); + $properties['Actions.getSiteSearchKeywords'] = $this->getDisplayPropertiesForSiteSearchKeywords(); + $properties['Actions.getSiteSearchNoResultKeywords'] = $this->getDisplayPropertiesForSiteSearchNoResultKeywords(); + $properties['Actions.getSiteSearchCategories'] = $this->getDisplayPropertiesForSiteSearchCategories(); + $properties['Actions.getPageUrlsFollowingSiteSearch'] = $this->getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch(false); + $properties['Actions.getPageTitlesFollowingSiteSearch'] = $this->getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch(true); + $properties['Actions.getPageTitles'] = $this->getDisplayPropertiesForGetPageTitles(); + $properties['Actions.getEntryPageTitles'] = $this->getDisplayPropertiesForGetEntryPageTitles(); + $properties['Actions.getExitPageTitles'] = $this->getDisplayPropertiesForGetExitPageTitles(); + $properties['Actions.getDownloads'] = $this->getDisplayPropertiesForGetDownloads(); + $properties['Actions.getOutlinks'] = $this->getDisplayPropertiesForGetOutlinks(); } - + private function addBaseDisplayProperties(&$result) { $result['datatable_css_class'] = 'dataTableActions'; @@ -654,34 +655,34 @@ private function addBaseDisplayProperties(&$result) $result['show_all_views_icons'] = false; $result['show_table_all_columns'] = false; $result['filter_limit'] = self::ACTIONS_REPORT_ROWS_DISPLAY; - + // if the flat parameter is not provided, make sure it is set to 0 in the URL, // so users can see that they can set it to 1 (see #3365) $result['custom_parameters'] = array('flat' => 0); - + if (ViewDataTable::shouldLoadExpanded()) { $result['show_expanded'] = true; - + $result['filters'][] = function ($dataTable) { - Piwik_Actions::setDataTableRowLevels($dataTable); + Actions::setDataTableRowLevels($dataTable); }; } - + return $result; } - + public static function setDataTableRowLevels($dataTable, $level = 0) { foreach ($dataTable->getRows() as $row) { - $row->setMetadata('css_class', 'level'.$level); - + $row->setMetadata('css_class', 'level' . $level); + $subtable = $row->getSubtable(); if ($subtable) { self::setDataTableRowLevels($subtable, $level + 1); } } } - + private function addExcludeLowPopDisplayProperties(&$result) { if (Common::getRequestVar('enable_filter_excludelowpop', '0', 'string') != '0') { @@ -691,60 +692,60 @@ private function addExcludeLowPopDisplayProperties(&$result) $visitsInfo = Piwik_VisitsSummary_Controller::getVisitsSummary()->getFirstRow(); $nbActions = $visitsInfo->getColumn('nb_actions'); $nbActionsLowPopulationThreshold = floor(0.02 * $nbActions); - + // we remove 1 to make sure some actions/downloads are displayed in the case we have a very few of them // and each of them has 1 or 2 hits... return min($visitsInfo->getColumn('max_actions') - 1, $nbActionsLowPopulationThreshold - 1); }; } } - + private function addPageDisplayProperties(&$result) { // add common translations $result['translations'] += array( - 'nb_hits' => Piwik_Translate('General_ColumnPageviews'), - 'nb_visits' => Piwik_Translate('General_ColumnUniquePageviews'), - 'avg_time_on_page' => Piwik_Translate('General_ColumnAverageTimeOnPage'), - 'bounce_rate' => Piwik_Translate('General_ColumnBounceRate'), - 'exit_rate' => Piwik_Translate('General_ColumnExitRate'), + 'nb_hits' => Piwik_Translate('General_ColumnPageviews'), + 'nb_visits' => Piwik_Translate('General_ColumnUniquePageviews'), + 'avg_time_on_page' => Piwik_Translate('General_ColumnAverageTimeOnPage'), + 'bounce_rate' => Piwik_Translate('General_ColumnBounceRate'), + 'exit_rate' => Piwik_Translate('General_ColumnExitRate'), 'avg_time_generation' => Piwik_Translate('General_ColumnAverageGenerationTime'), ); - + // prettify avg_time_on_page column $getPrettyTimeFromSeconds = '\Piwik\Piwik::getPrettyTimeFromSeconds'; $result['filters'][] = array('ColumnCallbackReplace', array('avg_time_on_page', $getPrettyTimeFromSeconds)); - + // prettify avg_time_generation column $avgTimeCallback = function ($time) { return $time ? Piwik::getPrettyTimeFromSeconds($time, true, true, false) : "-"; }; $result['filters'][] = array('ColumnCallbackReplace', array('avg_time_generation', $avgTimeCallback)); - + // add avg_generation_time tooltip $tooltipCallback = function ($hits, $min, $max) { if (!$hits) { return false; } - + return Piwik_Translate("Actions_AvgGenerationTimeTooltip", array( - $hits, - "
", - Piwik::getPrettyTimeFromSeconds($min), - Piwik::getPrettyTimeFromSeconds($max) - )); + $hits, + "
", + Piwik::getPrettyTimeFromSeconds($min), + Piwik::getPrettyTimeFromSeconds($max) + )); }; $result['filters'][] = array('ColumnCallbackAddMetadata', - array( - array('nb_hits_with_time_generation', 'min_time_generation', 'max_time_generation'), - 'avg_time_generation_tooltip', - $tooltipCallback - ) + array( + array('nb_hits_with_time_generation', 'min_time_generation', 'max_time_generation'), + 'avg_time_generation_tooltip', + $tooltipCallback + ) ); - + $this->addExcludeLowPopDisplayProperties($result); } - + public function getDisplayPropertiesForPageUrls() { $result = array( @@ -752,26 +753,26 @@ public function getDisplayPropertiesForPageUrls() 'columns_to_display' => array('label', 'nb_hits', 'nb_visits', 'bounce_rate', 'avg_time_on_page', 'exit_rate', 'avg_time_generation'), ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } - + public function getDisplayPropertiesForEntryPageUrls() { // link to the page, not just the report, but only if not a widget $widget = Common::getRequestVar('widget', false); $reportUrl = Request::getCurrentUrlWithoutGenericFilters(array( - 'module' => 'Actions', - 'action' => $widget === false ? 'indexEntryPageUrls' : 'getEntryPageUrls' - )); - + 'module' => 'Actions', + 'action' => $widget === false ? 'indexEntryPageUrls' : 'getEntryPageUrls' + )); + $result = array( - 'translations' => array('label' => Piwik_Translate('Actions_ColumnEntryPageURL'), + 'translations' => array('label' => Piwik_Translate('Actions_ColumnEntryPageURL'), 'entry_bounce_count' => Piwik_Translate('General_ColumnBounces'), - 'entry_nb_visits' => Piwik_Translate('General_ColumnEntrances')), + 'entry_nb_visits' => Piwik_Translate('General_ColumnEntrances')), 'columns_to_display' => array('label', 'entry_nb_visits', 'entry_bounce_count', 'bounce_rate'), 'filter_sort_column' => 'entry_nb_visits', 'filter_sort_order' => 'desc', @@ -781,24 +782,24 @@ public function getDisplayPropertiesForEntryPageUrls() ), 'self_url' => $reportUrl ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } - + public function getDisplayPropertiesForExitPageUrls() { // link to the page, not just the report, but only if not a widget $widget = Common::getRequestVar('widget', false); $reportUrl = Request::getCurrentUrlWithoutGenericFilters(array( - 'module' => 'Actions', - 'action' => $widget === false ? 'indexExitPageUrls' : 'getExitPageUrls' - )); - + 'module' => 'Actions', + 'action' => $widget === false ? 'indexExitPageUrls' : 'getExitPageUrls' + )); + $result = array( - 'translations' => array('label' => Piwik_Translate('Actions_ColumnExitPageURL'), + 'translations' => array('label' => Piwik_Translate('Actions_ColumnExitPageURL'), 'exit_nb_visits' => Piwik_Translate('General_ColumnExits')), 'columns_to_display' => array('label', 'exit_nb_visits', 'nb_visits', 'exit_rate'), 'filter_sort_column' => 'exit_nb_visits', @@ -809,13 +810,13 @@ public function getDisplayPropertiesForExitPageUrls() ), 'self_url' => $reportUrl, ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } - + private function addSiteSearchDisplayProperties(&$result) { $result['translations'] += array( @@ -826,16 +827,16 @@ private function addSiteSearchDisplayProperties(&$result) $result['show_bar_chart'] = false; $result['show_table_all_columns'] = false; } - + public function getDisplayPropertiesForSiteSearchKeywords() { $result = array( 'translations' => array('label' => Piwik_Translate('Actions_ColumnSearchKeyword')), 'columns_to_display' => array('label', 'nb_visits', 'nb_pages_per_search', 'exit_rate'), ); - + $this->addSiteSearchDisplayProperties($result); - + return $result; } @@ -845,9 +846,9 @@ public function getDisplayPropertiesForSiteSearchNoResultKeywords() 'translations' => array('label', Piwik_Translate('Actions_ColumnNoResultKeyword')), 'columns_to_display' => array('label', 'nb_visits', 'exit_rate') ); - + $this->addSiteSearchDisplayProperties($result); - + return $result; } @@ -870,12 +871,12 @@ public function getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch($i { $title = $isTitle ? Piwik_Translate('Actions_WidgetPageTitlesFollowingSearch') : Piwik_Translate('Actions_WidgetPageUrlsFollowingSearch'); - + $relatedReports = array( 'Actions.getPageTitlesFollowingSiteSearch' => Piwik_Translate('Actions_WidgetPageTitlesFollowingSearch'), - 'Actions.getPageUrlsFollowingSiteSearch' => Piwik_Translate('Actions_WidgetPageUrlsFollowingSearch'), + 'Actions.getPageUrlsFollowingSiteSearch' => Piwik_Translate('Actions_WidgetPageUrlsFollowingSearch'), ); - + $result = array( 'translations' => array( 'label' => Piwik_Translate('General_ColumnDestinationPage'), @@ -889,10 +890,10 @@ public function getDisplayPropertiesForGetPageUrlsOrTitlesFollowingSiteSearch($i 'title' => $title, 'relatedReports' => $relatedReports ); - + $this->addExcludeLowPopDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } @@ -901,10 +902,10 @@ public function getDisplayPropertiesForGetPageTitles() // link to the page, not just the report, but only if not a widget $widget = Common::getRequestVar('widget', false); $reportUrl = Request::getCurrentUrlWithoutGenericFilters(array( - 'module' => 'Actions', - 'action' => $widget === false ? 'indexPageTitles' : 'getPageTitles' - )); - + 'module' => 'Actions', + 'action' => $widget === false ? 'indexPageTitles' : 'getPageTitles' + )); + $result = array( 'translations' => array('label' => Piwik_Translate('Actions_ColumnPageName')), 'columns_to_display' => array('label', 'nb_hits', 'nb_visits', 'bounce_rate', @@ -916,10 +917,10 @@ public function getDisplayPropertiesForGetPageTitles() ), 'self_url' => $reportUrl ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } @@ -927,7 +928,7 @@ public function getDisplayPropertiesForGetEntryPageTitles() { $entryPageUrlAction = Common::getRequestVar('widget', false) === false ? 'indexEntryPageUrls' : 'getEntryPageUrls'; - + $result = array( 'translations' => array( 'label' => Piwik_Translate('Actions_ColumnEntryPageTitle'), @@ -941,10 +942,10 @@ public function getDisplayPropertiesForGetEntryPageTitles() "Actions.$entryPageUrlAction" => Piwik_Translate('Actions_SubmenuPagesEntry') ), ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } @@ -952,7 +953,7 @@ public function getDisplayPropertiesForGetExitPageTitles() { $exitPageUrlAction = Common::getRequestVar('widget', false) === false ? 'indexExitPageUrls' : 'getExitPageUrls'; - + $result = array( 'translations' => array( 'label' => Piwik_Translate('Actions_ColumnExitPageTitle'), @@ -965,10 +966,10 @@ public function getDisplayPropertiesForGetExitPageTitles() "Actions.$exitPageUrlAction" => Piwik_Translate('Actions_SubmenuPagesExit'), ), ); - + $this->addPageDisplayProperties($result); $this->addBaseDisplayProperties($result); - + return $result; } @@ -983,9 +984,9 @@ public function getDisplayPropertiesForGetDownloads() 'columns_to_display' => array('label', 'nb_visits', 'nb_hits'), 'show_exclude_low_population' => false ); - + $this->addBaseDisplayProperties($result); - + return $result; } @@ -1000,9 +1001,9 @@ public function getDisplayPropertiesForGetOutlinks() 'columns_to_display' => array('label', 'nb_visits', 'nb_hits'), 'show_exclude_low_population' => false ); - + $this->addBaseDisplayProperties($result); - + return $result; } } diff --git a/plugins/Actions/Archiver.php b/plugins/Actions/Archiver.php index f3dfa31138b..c177a73ffea 100644 --- a/plugins/Actions/Archiver.php +++ b/plugins/Actions/Archiver.php @@ -6,8 +6,10 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Actions + * @package Actions */ +namespace Piwik\Plugins\Actions; + use Piwik\Config; use Piwik\DataTable\Manager; use Piwik\DataTable\Row\DataTableSummaryRow; @@ -16,13 +18,14 @@ use Piwik\RankingQuery; use Piwik\PluginsArchiver; use Piwik\Tracker\Action; +use Piwik\Plugins\Actions\ArchivingHelper; /** * Class encapsulating logic to process Day/Period Archiving for the Actions reports * - * @package Piwik_Actions + * @package Actions */ -class Piwik_Actions_Archiver extends PluginsArchiver +class Archiver extends PluginsArchiver { const DOWNLOADS_RECORD_NAME = 'Actions_downloads'; const OUTLINKS_RECORD_NAME = 'Actions_outlink'; @@ -42,15 +45,15 @@ class Piwik_Actions_Archiver extends PluginsArchiver const METRIC_KEYWORDS_RECORD_NAME = 'Actions_nb_keywords'; /* Metrics in use by the API Actions.get */ - public static $actionsAggregateMetrics = array( - self::METRIC_PAGEVIEWS_RECORD_NAME => 'nb_pageviews', - self::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME => 'nb_uniq_pageviews', - self::METRIC_DOWNLOADS_RECORD_NAME => 'nb_downloads', - self::METRIC_UNIQ_DOWNLOADS_RECORD_NAME => 'nb_uniq_downloads', - self::METRIC_OUTLINKS_RECORD_NAME => 'nb_outlinks', - self::METRIC_UNIQ_OUTLINKS_RECORD_NAME => 'nb_uniq_outlinks', - self::METRIC_SEARCHES_RECORD_NAME => 'nb_searches', - self::METRIC_KEYWORDS_RECORD_NAME => 'nb_keywords', + public static $actionsAggregateMetrics = array( + self::METRIC_PAGEVIEWS_RECORD_NAME => 'nb_pageviews', + self::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME => 'nb_uniq_pageviews', + self::METRIC_DOWNLOADS_RECORD_NAME => 'nb_downloads', + self::METRIC_UNIQ_DOWNLOADS_RECORD_NAME => 'nb_uniq_downloads', + self::METRIC_OUTLINKS_RECORD_NAME => 'nb_outlinks', + self::METRIC_UNIQ_OUTLINKS_RECORD_NAME => 'nb_uniq_outlinks', + self::METRIC_SEARCHES_RECORD_NAME => 'nb_searches', + self::METRIC_KEYWORDS_RECORD_NAME => 'nb_keywords', ); public static $actionTypes = array( @@ -93,24 +96,24 @@ public function archiveDay() $rankingQueryLimit = self::getRankingQueryLimit(); // FIXME: This is a quick fix for #3482. The actual cause of the bug is that - // the site search & performance metrics additions to - // Piwik_Actions_ArchivingHelper::updateActionsTableWithRowQuery expect every + // the site search & performance metrics additions to + // ArchivingHelper::updateActionsTableWithRowQuery expect every // row to have 'type' data, but not all of the SQL queries that are run w/o // ranking query join on the log_action table and thus do not select the // log_action.type column. - // + // // NOTES: Archiving logic can be generalized as follows: // 0) Do SQL query over log_link_visit_action & join on log_action to select // some metrics (like visits, hits, etc.) // 1) For each row, cache the action row & metrics. (This is done by - // updateActionsTableWithRowQuery for result set rows that have + // updateActionsTableWithRowQuery for result set rows that have // name & type columns.) // 2) Do other SQL queries for metrics we can't put in the first query (like // entry visits, exit vists, etc.) w/o joining log_action. // 3) For each row, find the cached row by idaction & add the new metrics to // it. (This is done by updateActionsTableWithRowQuery for result set rows // that DO NOT have name & type columns.) - // + // // The site search & performance metrics additions expect a 'type' all the time // which breaks the original pre-rankingquery logic. Ranking query requires a // join, so the bug is only seen when ranking query is disabled. @@ -118,7 +121,7 @@ public function archiveDay() $rankingQueryLimit = 100000; } - Piwik_Actions_ArchivingHelper::reloadConfig(); + ArchivingHelper::reloadConfig(); $this->initActionsTables(); $this->archiveDayActions($rankingQueryLimit); @@ -159,7 +162,7 @@ private function initActionsTables() $this->actionsTablesByType = array(); foreach (self::$actionTypes as $type) { $dataTable = new DataTable(); - $dataTable->setMaximumAllowedRows(Piwik_Actions_ArchivingHelper::$maximumRowsInDataTableLevelZero); + $dataTable->setMaximumAllowedRows(ArchivingHelper::$maximumRowsInDataTableLevelZero); if ($type == Action::TYPE_ACTION_URL || $type == Action::TYPE_ACTION_NAME @@ -271,7 +274,6 @@ protected function archiveDayQueryProcess($select, $from, $where, $orderBy, $gro // to the outer select. therefore, $segment needs to know about it. $select = sprintf($select, $sprintfField); - // get query with segmentation $query = $this->getLogAggregator()->generateQuery($select, $from, $where, $groupBy, $orderBy); @@ -285,7 +287,7 @@ protected function archiveDayQueryProcess($select, $from, $where, $orderBy, $gro // get result $resultSet = $this->getLogAggregator()->getDb()->query($querySql, $query['bind']); - $modified = Piwik_Actions_ArchivingHelper::updateActionsTableWithRowQuery($resultSet, $sprintfField, $this->actionsTablesByType); + $modified = ArchivingHelper::updateActionsTableWithRowQuery($resultSet, $sprintfField, $this->actionsTablesByType); return $modified; } @@ -435,7 +437,7 @@ protected function archiveDayActionsTime($rankingQueryLimit) */ protected function recordDayReports() { - Piwik_Actions_ArchivingHelper::clearActionsCache(); + ArchivingHelper::clearActionsCache(); $this->recordPageUrlsReports(); $this->recordDownloadsReports(); @@ -450,12 +452,12 @@ protected function recordPageUrlsReports() $this->recordDataTable($dataTable, self::PAGE_URLS_RECORD_NAME); $records = array( - self::METRIC_PAGEVIEWS_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_NB_HITS)), + self::METRIC_PAGEVIEWS_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_NB_HITS)), self::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_NB_VISITS)), - self::METRIC_SUM_TIME_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_SUM_TIME_GENERATION)), - self::METRIC_HITS_TIMED_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION)) + self::METRIC_SUM_TIME_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_SUM_TIME_GENERATION)), + self::METRIC_HITS_TIMED_RECORD_NAME => array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION)) ); - $this->getProcessor()->insertNumericRecords( $records ); + $this->getProcessor()->insertNumericRecords($records); } /** @@ -470,7 +472,7 @@ protected function getDataTable($typeId) protected function recordDataTable($dataTable, $recordName) { self::deleteInvalidSummedColumnsFromDataTable($dataTable); - $s = $dataTable->getSerialized(Piwik_Actions_ArchivingHelper::$maximumRowsInDataTableLevelZero, Piwik_Actions_ArchivingHelper::$maximumRowsInSubDataTable, Piwik_Actions_ArchivingHelper::$columnToSortByBeforeTruncation); + $s = $dataTable->getSerialized(ArchivingHelper::$maximumRowsInDataTableLevelZero, ArchivingHelper::$maximumRowsInSubDataTable, ArchivingHelper::$columnToSortByBeforeTruncation); $this->getProcessor()->insertBlobRecord($recordName, $s); } @@ -566,15 +568,15 @@ protected function deleteUnusedColumnsFromKeywordsDataTable($dataTable) public function archivePeriod() { - Piwik_Actions_ArchivingHelper::reloadConfig(); + ArchivingHelper::reloadConfig(); $dataTableToSum = array( self::PAGE_TITLES_RECORD_NAME, self::PAGE_URLS_RECORD_NAME, ); $this->getProcessor()->aggregateDataTableReports($dataTableToSum, - Piwik_Actions_ArchivingHelper::$maximumRowsInDataTableLevelZero, - Piwik_Actions_ArchivingHelper::$maximumRowsInSubDataTable, - Piwik_Actions_ArchivingHelper::$columnToSortByBeforeTruncation, + ArchivingHelper::$maximumRowsInDataTableLevelZero, + ArchivingHelper::$maximumRowsInSubDataTable, + ArchivingHelper::$columnToSortByBeforeTruncation, self::$actionColumnAggregationOperations, self::$invalidSummedColumnNameToRenamedNameFromPeriodArchive ); @@ -586,9 +588,9 @@ public function archivePeriod() ); $aggregation = null; $nameToCount = $this->getProcessor()->aggregateDataTableReports($dataTableToSum, - Piwik_Actions_ArchivingHelper::$maximumRowsInDataTableLevelZero, - Piwik_Actions_ArchivingHelper::$maximumRowsInSubDataTable, - Piwik_Actions_ArchivingHelper::$columnToSortByBeforeTruncation, + ArchivingHelper::$maximumRowsInDataTableLevelZero, + ArchivingHelper::$maximumRowsInSubDataTable, + ArchivingHelper::$columnToSortByBeforeTruncation, $aggregation, self::$invalidSummedColumnNameToRenamedNameFromPeriodArchive ); diff --git a/plugins/Actions/ArchivingHelper.php b/plugins/Actions/ArchivingHelper.php index 8c95ae629f5..e66cf73a979 100644 --- a/plugins/Actions/ArchivingHelper.php +++ b/plugins/Actions/ArchivingHelper.php @@ -6,29 +6,33 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Actions + * @package Actions */ +namespace Piwik\Plugins\Actions; + +use PDOStatement; use Piwik\Config; use Piwik\DataTable\Row; use Piwik\Metrics; use Piwik\DataTable; use Piwik\Tracker\Action; +use Zend_Db_Statement; /** * This static class provides: * - logic to parse/cleanup Action names, * - logic to efficiently process aggregate the array data during Archiving * - * @package Piwik_Actions + * @package Actions */ -class Piwik_Actions_ArchivingHelper +class ArchivingHelper { const OTHERS_ROW_KEY = ''; /** - * FIXME See FIXME related to this function at Piwik_Actions_Archiver::archiveDay. - * + * FIXME See FIXME related to this function at Archiver::archiveDay. + * * @param Zend_Db_Statement|PDOStatement $query * @param string|bool $fieldQueried * @param array $actionsTablesByType @@ -91,7 +95,6 @@ static public function updateActionsTableWithRowQuery($query, $fieldQueried, & $ } } - if (is_null($actionRow)) { continue; } @@ -226,7 +229,6 @@ static public function reloadConfig() DataTable::setMaximumDepthLevelAllowedAtLeast(self::getSubCategoryLevelLimit() + 1); } - /** * The default row is used when archiving, if data is inconsistent in the DB, * there could be pages that have exit/entry hits, but don't yet @@ -242,11 +244,11 @@ static private function getDefaultRow() // but this action was not properly recorded when it was hit in the first place // so we add this fake row information to make sure there is a nb_hits, etc. column for every action $row = new Row(array( - Row::COLUMNS => array( - Metrics::INDEX_NB_VISITS => 1, - Metrics::INDEX_NB_UNIQ_VISITORS => 1, - Metrics::INDEX_PAGE_NB_HITS => 1, - ))); + Row::COLUMNS => array( + Metrics::INDEX_NB_VISITS => 1, + Metrics::INDEX_NB_UNIQ_VISITORS => 1, + Metrics::INDEX_PAGE_NB_HITS => 1, + ))); } return $row; } @@ -287,7 +289,7 @@ protected static function getActionRow($actionName, $actionType, $urlPrefix = nu /** * Explodes action name into an array of elements. * - * NOTE: before calling this function make sure Piwik_Actions_ArchivingHelper::reloadConfig(); is called + * NOTE: before calling this function make sure ArchivingHelper::reloadConfig(); is called * * for downloads: * we explode link http://piwik.org/some/path/piwik.zip into an array( 'piwik.org', '/some/path/piwik.zip' ); @@ -357,7 +359,6 @@ static public function getActionExplodedNames($name, $type, $urlPrefix = null) $categoryDelimiter = self::$actionUrlCategoryDelimiter; } - if ($isUrl) { $urlFragment = Action::processUrlFragment($urlFragment); if (!empty($urlFragment)) { @@ -504,8 +505,8 @@ private static function getDefaultRowColumns() private static function createSummaryRow() { return new Row(array( - Row::COLUMNS => - array('label' => DataTable::LABEL_SUMMARY_ROW) + self::getDefaultRowColumns() - )); + Row::COLUMNS => + array('label' => DataTable::LABEL_SUMMARY_ROW) + self::getDefaultRowColumns() + )); } } diff --git a/plugins/Actions/Controller.php b/plugins/Actions/Controller.php index 9ce7800197f..e6342352f65 100644 --- a/plugins/Actions/Controller.php +++ b/plugins/Actions/Controller.php @@ -6,23 +6,24 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Actions + * @package Actions */ -use Piwik\Controller; +namespace Piwik\Plugins\Actions; + use Piwik\ViewDataTable; use Piwik\View; /** * Actions controller * - * @package Piwik_Actions + * @package Actions */ -class Piwik_Actions_Controller extends Controller +class Controller extends \Piwik\Controller { - // + // // Actions that render whole pages - // - + // + public function indexPageUrls($fetch = false) { return View::singleReport( @@ -80,16 +81,16 @@ public function indexOutlinks($fetch = false) Piwik_Translate('Actions_SubmenuOutlinks'), $this->getOutlinks(true), $fetch); } - - // + + // // Actions that render individual reports - // - + // + public function getPageUrls($fetch = false) { return ViewDataTable::renderReport($this->pluginName, __FUNCTION__, $fetch); } - + public function getEntryPageUrls($fetch = false) { return ViewDataTable::renderReport($this->pluginName, __FUNCTION__, $fetch); diff --git a/plugins/Alerts/README.md b/plugins/Alerts/README.md deleted file mode 100644 index 292963a7012..00000000000 --- a/plugins/Alerts/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Alerts - - diff --git a/plugins/Annotations/API.php b/plugins/Annotations/API.php index b165f1ba01a..cf0b9de7bf5 100755 --- a/plugins/Annotations/API.php +++ b/plugins/Annotations/API.php @@ -6,13 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Annotations + * @package Annotations */ +namespace Piwik\Plugins\Annotations; + +use Exception; use Piwik\Period; use Piwik\Period\Range; use Piwik\Piwik; use Piwik\Date; +use Piwik\Plugins\Annotations\AnnotationList; use Piwik\ViewDataTable; + /** * @see plugins/Annotations/AnnotationList.php */ @@ -22,16 +27,16 @@ * API for annotations plugin. Provides methods to create, modify, delete & query * annotations. * - * @package Piwik_Annotations + * @package Annotations */ -class Piwik_Annotations_API +class API { static private $instance = null; /** * Returns this API's singleton instance. * - * @return Piwik_Annotations_API + * @return \Piwik\Plugins\Annotations\API */ static public function getInstance() { @@ -47,7 +52,7 @@ static public function getInstance() * @param string $idSite The site ID to add the annotation to. * @param string $date The date the annotation is attached to. * @param string $note The text of the annotation. - * @param int $starred Either 0 or 1. Whether the annotation should be starred. + * @param int $starred Either 0 or 1. Whether the annotation should be starred. * @return array Returns an array of two elements. The first element (indexed by * 'annotation') is the new annotation. The second element (indexed * by 'idNote' is the new note's ID). @@ -59,7 +64,7 @@ public function add($idSite, $date, $note, $starred = 0) $this->checkUserCanAddNotesFor($idSite); // add, save & return a new annotation - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); $newAnnotation = $annotations->add($idSite, $date, $note, $starred); $annotations->save($idSite); @@ -95,7 +100,7 @@ public function save($idSite, $idNote, $date = null, $note = null, $starred = nu $this->checkDateIsValid($date, $canBeNull = true); // get the annotations for the site - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); // check permissions $this->checkUserCanModifyOrDelete($idSite, $annotations->get($idSite, $idNote)); @@ -123,7 +128,7 @@ public function delete($idSite, $idNote) { $this->checkSingleIdSite($idSite, $extraMessage = "Note: Cannot delete multiple notes."); - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); // check permissions $this->checkUserCanModifyOrDelete($idSite, $annotations->get($idSite, $idNote)); @@ -152,7 +157,7 @@ public function get($idSite, $idNote) Piwik::checkUserHasViewAccess($idSite); // get single annotation - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); return $annotations->get($idSite, $idNote); } @@ -180,7 +185,7 @@ public function getAll($idSite, $date = false, $period = 'day', $lastN = false) { Piwik::checkUserHasViewAccess($idSite); - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); // if date/period are supplied, determine start/end date for search list($startDate, $endDate) = self::getDateRangeForPeriod($date, $period, $lastN); @@ -232,7 +237,7 @@ public function getAnnotationCountForDates($idSite, $date, $period, $lastN = fal $dates[] = $startDate; // get annotations for the site - $annotations = new Piwik_Annotations_AnnotationList($idSite); + $annotations = new AnnotationList($idSite); // create result w/ 0-counts $result = array(); @@ -290,7 +295,7 @@ private function checkUserCanModifyOrDelete($idSite, $annotation) */ private static function checkUserCanAddNotesFor($idSite) { - if (!Piwik_Annotations_AnnotationList::canUserAddNotesFor($idSite)) { + if (!AnnotationList::canUserAddNotesFor($idSite)) { throw new Exception("The current user is not allowed to add notes for site #$idSite."); } } @@ -301,7 +306,7 @@ private static function checkUserCanAddNotesFor($idSite) * * @param string|bool $date The start date of the period (or the date range of a range * period). - * @param string $period The period type ('day', 'week', 'month', 'year' or 'range'). + * @param string $period The period type ('day', 'week', 'month', 'year' or 'range'). * @param bool|int $lastN Whether to include the last N periods in the range or not. * Ignored if period == range. * diff --git a/plugins/Annotations/AnnotationList.php b/plugins/Annotations/AnnotationList.php index 0f5ba42ae91..75b4d95df13 100755 --- a/plugins/Annotations/AnnotationList.php +++ b/plugins/Annotations/AnnotationList.php @@ -6,8 +6,11 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Annotations + * @package Annotations */ +namespace Piwik\Plugins\Annotations; + +use Exception; use Piwik\Piwik; use Piwik\Date; use Piwik\Site; @@ -17,7 +20,7 @@ * at once. * * Example use: - * $annotations = new Piwik_Annotations_AnnotationList($idSites = "1,2,5"); + * $annotations = new AnnotationList($idSites = "1,2,5"); * $annotation = $annotations->get($idSite = 1, $idNote = 4); * // do stuff w/ annotation * $annotations->update($idSite = 2, $idNote = 4, $note = "This is the new text."); @@ -27,9 +30,9 @@ * an annotation for the same site, it's possible one of their changes will * never get made (as it will be overwritten by the other's). * - * @package Piwik_Annotations + * @package Annotations */ -class Piwik_Annotations_AnnotationList +class AnnotationList { const ANNOTATION_COLLECTION_OPTION_SUFFIX = '_annotations'; diff --git a/plugins/Annotations/Annotations.php b/plugins/Annotations/Annotations.php index 5b29ec48b5b..3b756314c95 100755 --- a/plugins/Annotations/Annotations.php +++ b/plugins/Annotations/Annotations.php @@ -6,17 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Annotations + * @package Annotations */ -use Piwik\Plugin; +namespace Piwik\Plugins\Annotations; /** * Annotations plugins. Provides the ability to attach text notes to * dates for each sites. Notes can be viewed, modified, deleted or starred. * - * @package Piwik_Annotations + * @package Annotations */ -class Piwik_Annotations extends Plugin +class Annotations extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/Annotations/Controller.php b/plugins/Annotations/Controller.php index 739ec5deebb..00a927fe6db 100755 --- a/plugins/Annotations/Controller.php +++ b/plugins/Annotations/Controller.php @@ -6,19 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Annotations + * @package Annotations */ +namespace Piwik\Plugins\Annotations; + use Piwik\API\Request; use Piwik\Common; -use Piwik\Controller; +use Piwik\Plugins\Annotations\AnnotationList; +use Piwik\Plugins\Annotations\API; use Piwik\View; /** * Controller for the Annotations plugin. * - * @package Piwik_Annotations + * @package Annotations */ -class Piwik_Annotations_Controller extends Controller +class Controller extends \Piwik\Controller { /** * Controller action that returns HTML displaying annotations for a site and @@ -68,7 +71,7 @@ public function getAnnotationManager($fetch = false, $date = false, $period = fa $view->period = $period; $view->lastN = $lastN; - list($startDate, $endDate) = Piwik_Annotations_API::getDateRangeForPeriod($date, $period, $lastN); + list($startDate, $endDate) = API::getDateRangeForPeriod($date, $period, $lastN); $view->startDate = $startDate->toString(); $view->endDate = $endDate->toString(); @@ -76,7 +79,7 @@ public function getAnnotationManager($fetch = false, $date = false, $period = fa $view->startDatePretty = $startDate->getLocalized($dateFormat); $view->endDatePretty = $endDate->getLocalized($dateFormat); - $view->canUserAddNotes = Piwik_Annotations_AnnotationList::canUserAddNotesFor($idSite); + $view->canUserAddNotes = AnnotationList::canUserAddNotesFor($idSite); if ($fetch) { return $view->render(); diff --git a/plugins/AnonymizeIP/AnonymizeIP.php b/plugins/AnonymizeIP/AnonymizeIP.php index 79af7308a5e..ba0e2c22307 100644 --- a/plugins/AnonymizeIP/AnonymizeIP.php +++ b/plugins/AnonymizeIP/AnonymizeIP.php @@ -6,19 +6,20 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_AnonymizeIP + * @package AnonymizeIP */ +namespace Piwik\Plugins\AnonymizeIP; + use Piwik\Config; use Piwik\Common; use Piwik\Version; -use Piwik\Plugin; /** * Anonymize visitor IP addresses to comply with the privacy laws/guidelines in countries, such as Germany. * - * @package Piwik_AnonymizeIP + * @package AnonymizeIP */ -class Piwik_AnonymizeIP extends Plugin +class AnonymizeIP extends \Piwik\Plugin { /** * @see Piwik_Plugin::getInformation diff --git a/plugins/CoreAdminHome/API.php b/plugins/CoreAdminHome/API.php index 2768708ef57..71444288e38 100644 --- a/plugins/CoreAdminHome/API.php +++ b/plugins/CoreAdminHome/API.php @@ -6,8 +6,11 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ +namespace Piwik\Plugins\CoreAdminHome; + +use Exception; use Piwik\DataAccess\ArchiveTableCreator; use Piwik\Period; use Piwik\Period\Week; @@ -20,14 +23,14 @@ use Piwik\Db; /** - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ -class Piwik_CoreAdminHome_API +class API { static private $instance = null; /** - * @return Piwik_CoreAdminHome_API + * @return \Piwik\Plugins\CoreAdminHome\API */ static public function getInstance() { @@ -103,7 +106,6 @@ public function invalidateArchivedReports($idSites, $dates) } } - // If using the feature "Delete logs older than N days"... $logsAreDeletedBeforeThisDate = Config::getInstance()->Deletelogs['delete_logs_schedule_lowest_interval']; $logsDeleteEnabled = Config::getInstance()->Deletelogs['delete_logs_enable']; @@ -188,7 +190,7 @@ public function invalidateArchivedReports($idSites, $dates) Db::query($query, $bind); // Force to re-process data for these websites in the next archive.php cron run - $invalidatedIdSites = Piwik_CoreAdminHome_API::getWebsiteIdsToInvalidate(); + $invalidatedIdSites = self::getWebsiteIdsToInvalidate(); $invalidatedIdSites = array_merge($invalidatedIdSites, $idSites); $invalidatedIdSites = array_unique($invalidatedIdSites); $invalidatedIdSites = array_values($invalidatedIdSites); diff --git a/plugins/CoreAdminHome/Controller.php b/plugins/CoreAdminHome/Controller.php index 9e040b552cc..c70ad355014 100644 --- a/plugins/CoreAdminHome/Controller.php +++ b/plugins/CoreAdminHome/Controller.php @@ -6,12 +6,14 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ +namespace Piwik\Plugins\CoreAdminHome; + +use Exception; use Piwik\API\ResponseBuilder; use Piwik\ArchiveProcessor\Rules; use Piwik\Config; -use Piwik\Controller\Admin; use Piwik\Piwik; use Piwik\Common; use Piwik\Nonce; @@ -19,12 +21,15 @@ use Piwik\View; use Piwik\Url; use Piwik\Site; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Piwik\Plugins\LanguagesManager\API as LanguagesManagerAPI; +use Piwik\Plugins\SitesManager\API; /** * - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ -class Piwik_CoreAdminHome_Controller extends Admin +class Controller extends \Piwik\Controller\Admin { const LOGO_HEIGHT = 300; const LOGO_SMALL_HEIGHT = 100; @@ -66,7 +71,8 @@ public function generalSettings() $directoryWritable = is_writable(PIWIK_DOCUMENT_ROOT . '/misc/user/'); $logoFilesWriteable = is_writeable(PIWIK_DOCUMENT_ROOT . '/misc/user/logo.png') && is_writeable(PIWIK_DOCUMENT_ROOT . '/misc/user/logo.svg') - && is_writeable(PIWIK_DOCUMENT_ROOT . '/misc/user/logo-header.png');; + && is_writeable(PIWIK_DOCUMENT_ROOT . '/misc/user/logo-header.png'); + ; $view->logosWriteable = ($logoFilesWriteable || $directoryWritable) && ini_get('file_uploads') == 1; $trustedHosts = array(); @@ -76,7 +82,7 @@ public function generalSettings() $view->trustedHosts = $trustedHosts; } - $view->language = Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); + $view->language = LanguagesManager::getLanguageCodeForCurrentUser(); $this->setBasicVariablesView($view); echo $view->render(); } @@ -140,7 +146,7 @@ public function trackingCodeGenerator() $this->setBasicVariablesView($view); $view->topMenu = Piwik_GetTopMenu(); - $viewableIdSites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess(); + $viewableIdSites = API::getInstance()->getSitesIdWithAtLeastViewAccess(); $defaultIdSite = reset($viewableIdSites); $view->idSite = Common::getRequestVar('idSite', $defaultIdSite, 'int'); @@ -148,7 +154,7 @@ public function trackingCodeGenerator() $view->defaultReportSiteName = Site::getNameFor($view->idSite); $view->defaultSiteRevenue = Piwik::getCurrency($view->idSite); - $allUrls = Piwik_SitesManager_API::getInstance()->getSiteUrlsFromId($view->idSite); + $allUrls = API::getInstance()->getSiteUrlsFromId($view->idSite); if (isset($allUrls[1])) { $aliasUrl = $allUrls[1]; } else { @@ -160,9 +166,9 @@ public function trackingCodeGenerator() $view->defaultReportSiteDomain = @parse_url($mainUrl, PHP_URL_HOST); // get currencies for each viewable site - $view->currencySymbols = Piwik_SitesManager_API::getInstance()->getCurrencySymbols(); + $view->currencySymbols = API::getInstance()->getCurrencySymbols(); - $view->serverSideDoNotTrackEnabled = \Piwik_PrivacyManager_Controller::isDntSupported(); + $view->serverSideDoNotTrackEnabled = \Piwik\Plugins\PrivacyManager\Controller::isDntSupported(); echo $view->render(); } @@ -185,9 +191,9 @@ public function optOut() $view = new View('@CoreAdminHome/optOut'); $view->trackVisits = $trackVisits; $view->nonce = Nonce::getNonce('Piwik_OptOut', 3600); - $view->language = Piwik_LanguagesManager_API::getInstance()->isLanguageAvailable($language) + $view->language = LanguagesManagerAPI::getInstance()->isLanguageAvailable($language) ? $language - : Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); + : LanguagesManager::getLanguageCodeForCurrentUser(); echo $view->render(); } diff --git a/plugins/CoreAdminHome/CoreAdminHome.php b/plugins/CoreAdminHome/CoreAdminHome.php index c3517d88702..607df942467 100644 --- a/plugins/CoreAdminHome/CoreAdminHome.php +++ b/plugins/CoreAdminHome/CoreAdminHome.php @@ -6,22 +6,23 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ +namespace Piwik\Plugins\CoreAdminHome; + use Piwik\DataAccess\ArchiveSelector; use Piwik\DataAccess\ArchiveTableCreator; use Piwik\Piwik; use Piwik\Date; use Piwik\ScheduledTask; -use Piwik\Plugin; use Piwik\Db; use Piwik\ScheduledTime\Daily; /** * - * @package Piwik_CoreAdminHome + * @package CoreAdminHome */ -class Piwik_CoreAdminHome extends Plugin +class CoreAdminHome extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -91,7 +92,6 @@ function addMenu() array('module' => 'CoreAdminHome', 'action' => 'trackingCodeGenerator'), Piwik::isUserHasSomeAdminAccess(), $order = 4); - } function purgeOutdatedArchives() diff --git a/plugins/CoreHome/Controller.php b/plugins/CoreHome/Controller.php index 15ff5f7d48c..8af95e64490 100644 --- a/plugins/CoreHome/Controller.php +++ b/plugins/CoreHome/Controller.php @@ -6,26 +6,30 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreHome + * @package CoreHome */ +namespace Piwik\Plugins\CoreHome; + +use Exception; use Piwik\API\Request; use Piwik\Piwik; use Piwik\Common; use Piwik\Date; use Piwik\AssetManager; -use Piwik\Controller; use Piwik\FrontController; use Piwik\View; use Piwik\Url; use Piwik\UpdateCheck; use Piwik\Site; - +use Piwik_CoreHome_DataTableRowAction_MultiRowEvolution; +use Piwik_CoreHome_DataTableRowAction_RowEvolution; +use Piwik\Plugins\UsersManager\API; /** * - * @package Piwik_CoreHome + * @package CoreHome */ -class Piwik_CoreHome_Controller extends Controller +class Controller extends \Piwik\Controller { function getDefaultAction() { @@ -34,7 +38,7 @@ function getDefaultAction() function redirectToCoreHomeIndex() { - $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); + $defaultReport = API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), API::PREFERENCE_DEFAULT_REPORT); $module = 'CoreHome'; $action = 'index'; @@ -128,7 +132,6 @@ public function getJs() Piwik::serveStaticFile($jsMergedFile, "application/javascript; charset=UTF-8"); } - // -------------------------------------------------------- // ROW EVOLUTION // The following methods render the popover that shows the @@ -219,7 +222,7 @@ public function getPromoVideo() $view->promoVideoUrl = 'http://www.youtube.com/watch?v=OslfF_EH81g'; echo $view->render(); } - + /** * Redirects the user to a paypal so they can donate to Piwik. */ @@ -234,9 +237,9 @@ public function redirectToPaypal() unset($parameters[$name]); } } - - $url = "https://www.paypal.com/cgi-bin/webscr?".Url::getQueryStringFromParameters($parameters); - + + $url = "https://www.paypal.com/cgi-bin/webscr?" . Url::getQueryStringFromParameters($parameters); + header("Location: $url"); exit; } diff --git a/plugins/CoreHome/CoreHome.php b/plugins/CoreHome/CoreHome.php index 003cf6ee912..afb6744bf3c 100644 --- a/plugins/CoreHome/CoreHome.php +++ b/plugins/CoreHome/CoreHome.php @@ -6,16 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreHome + * @package CoreHome */ -use Piwik\Plugin; +namespace Piwik\Plugins\CoreHome; + use Piwik\WidgetsList; /** * - * @package Piwik_CoreHome + * @package CoreHome */ -class Piwik_CoreHome extends Plugin +class CoreHome extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -80,5 +81,4 @@ public function getJsFiles(&$jsFiles) $jsFiles[] = "plugins/CoreHome/javascripts/promo.js"; $jsFiles[] = "plugins/CoreHome/javascripts/color_manager.js"; } - } diff --git a/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php b/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php index 1bdf33debe2..c2a75061479 100644 --- a/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php +++ b/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php @@ -6,7 +6,7 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreHome + * @package CoreHome */ use Piwik\Common; use Piwik\ViewDataTable; @@ -14,7 +14,7 @@ /** * MULTI ROW EVOLUTION * The class handles the popover that shows the evolution of a multiple rows in a data table - * @package Piwik_CoreHome + * @package CoreHome */ class Piwik_CoreHome_DataTableRowAction_MultiRowEvolution extends Piwik_CoreHome_DataTableRowAction_RowEvolution diff --git a/plugins/CoreHome/DataTableRowAction/RowEvolution.php b/plugins/CoreHome/DataTableRowAction/RowEvolution.php index 63e76f04a98..37e6e524396 100644 --- a/plugins/CoreHome/DataTableRowAction/RowEvolution.php +++ b/plugins/CoreHome/DataTableRowAction/RowEvolution.php @@ -6,7 +6,7 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreHome + * @package CoreHome */ use Piwik\API\ResponseBuilder; use Piwik\API\Request; @@ -21,7 +21,7 @@ /** * ROW EVOLUTION * The class handles the popover that shows the evolution of a singe row in a data table - * @package Piwik_CoreHome + * @package CoreHome */ class Piwik_CoreHome_DataTableRowAction_RowEvolution { diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php index c1156cce999..0237c26a81c 100644 --- a/plugins/CorePluginsAdmin/Controller.php +++ b/plugins/CorePluginsAdmin/Controller.php @@ -6,9 +6,10 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CorePluginsAdmin + * @package CorePluginsAdmin */ -use Piwik\Controller\Admin; +namespace Piwik\Plugins\CorePluginsAdmin; + use Piwik\Piwik; use Piwik\Common; use Piwik\Config; @@ -17,9 +18,9 @@ /** * - * @package Piwik_CorePluginsAdmin + * @package CorePluginsAdmin */ -class Piwik_CorePluginsAdmin_Controller extends Admin +class Controller extends \Piwik\Controller\Admin { function extend() { @@ -141,7 +142,7 @@ public function uninstall($redirectAfter = true) { $pluginName = $this->initPluginModification(); $uninstalled = \Piwik\PluginsManager::getInstance()->uninstallPlugin($pluginName); - if(!$uninstalled) { + if (!$uninstalled) { $path = Common::getPathToPiwikRoot() . '/plugins/' . $pluginName . '/'; $messagePermissions = Piwik::getErrorMessageMissingPermissions($path); diff --git a/plugins/CorePluginsAdmin/CorePluginsAdmin.php b/plugins/CorePluginsAdmin/CorePluginsAdmin.php index fe4e9d87807..6116300ce20 100644 --- a/plugins/CorePluginsAdmin/CorePluginsAdmin.php +++ b/plugins/CorePluginsAdmin/CorePluginsAdmin.php @@ -6,16 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CorePluginsAdmin + * @package CorePluginsAdmin */ +namespace Piwik\Plugins\CorePluginsAdmin; + use Piwik\Piwik; -use Piwik\Plugin; /** * - * @package Piwik_CorePluginsAdmin + * @package CorePluginsAdmin */ -class Piwik_CorePluginsAdmin extends Plugin +class CorePluginsAdmin extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/CoreUpdater/Controller.php b/plugins/CoreUpdater/Controller.php index efc492417b7..7cb89e9e300 100644 --- a/plugins/CoreUpdater/Controller.php +++ b/plugins/CoreUpdater/Controller.php @@ -6,14 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreUpdater + * @package CoreUpdater */ +namespace Piwik\Plugins\CoreUpdater; + +use Exception; use Piwik\API\Request; use Piwik\ArchiveProcessor\Rules; use Piwik\Config; use Piwik\Piwik; use Piwik\Common; -use Piwik\Controller; use Piwik\Http; use Piwik\Updater; use Piwik\View; @@ -21,12 +23,15 @@ use Piwik\UpdateCheck; use Piwik\Unzip; use Piwik\View\OneClickDone; +use Piwik\Plugins\CoreUpdater\CoreUpdater; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Updater_UpdateErrorException; /** * - * @package Piwik_CoreUpdater + * @package CoreUpdater */ -class Piwik_CoreUpdater_Controller extends Controller +class Controller extends \Piwik\Controller { const CONFIG_FILE_BACKUP = '/config/global.ini.auto-backup-before-update.php'; const PATH_TO_EXTRACT_LATEST_VERSION = '/tmp/latest/'; @@ -232,7 +237,7 @@ public function index() { $language = Common::getRequestVar('language', ''); if (!empty($language)) { - Piwik_LanguagesManager::setLanguageForSession($language); + LanguagesManager::setLanguageForSession($language); } $this->runUpdaterAndExit(); } @@ -240,7 +245,7 @@ public function index() protected function runUpdaterAndExit() { $updater = new Updater(); - $componentsWithUpdateFile = Piwik_CoreUpdater::getComponentUpdates($updater); + $componentsWithUpdateFile = CoreUpdater::getComponentUpdates($updater); if (empty($componentsWithUpdateFile)) { Piwik::redirectToModule('CoreHome'); } diff --git a/plugins/CoreUpdater/CoreUpdater.php b/plugins/CoreUpdater/CoreUpdater.php index 7e4d2497a5e..20f3f5c0ae9 100644 --- a/plugins/CoreUpdater/CoreUpdater.php +++ b/plugins/CoreUpdater/CoreUpdater.php @@ -6,21 +6,23 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CoreUpdater + * @package CoreUpdater */ +namespace Piwik\Plugins\CoreUpdater; + +use Exception; use Piwik\Piwik; use Piwik\Common; use Piwik\FrontController; use Piwik\Updater; use Piwik\Version; use Piwik\UpdateCheck; -use Piwik\Plugin; /** * - * @package Piwik_CoreUpdater + * @package CoreUpdater */ -class Piwik_CoreUpdater extends Plugin +class CoreUpdater extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -69,7 +71,7 @@ public function dispatch() && $action == 'saveLanguage') ) { if (FrontController::shouldRethrowException()) { - throw new Exception("Piwik and/or some plugins have been upgraded to a new version. \n". + throw new Exception("Piwik and/or some plugins have been upgraded to a new version. \n" . "--> Please run the update process first. See documentation: http://piwik.org/docs/update/ \n"); } else { Piwik::redirectToModule('CoreUpdater'); diff --git a/plugins/CustomVariables/API.php b/plugins/CustomVariables/API.php index fb3e88456ee..21bdca1f55d 100644 --- a/plugins/CustomVariables/API.php +++ b/plugins/CustomVariables/API.php @@ -6,25 +6,28 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CustomVariables + * @package CustomVariables */ +namespace Piwik\Plugins\CustomVariables; + use Piwik\Archive; use Piwik\Metrics; use Piwik\Date; use Piwik\DataTable; use Piwik\Tracker\Action; +use Piwik\Plugins\CustomVariables\Archiver; /** * The Custom Variables API lets you access reports for your Custom Variables names and values. * - * @package Piwik_CustomVariables + * @package CustomVariables */ -class Piwik_CustomVariables_API +class API { static private $instance = null; /** - * @return Piwik_CustomVariables_API + * @return \Piwik\Plugins\CustomVariables\API */ static public function getInstance() { @@ -46,7 +49,7 @@ static public function getInstance() */ protected function getDataTable($idSite, $period, $date, $segment, $expanded, $idSubtable) { - $dataTable = Archive::getDataTableFromArchive(Piwik_CustomVariables_Archiver::CUSTOM_VARIABLE_RECORD_NAME, $idSite, $period, $date, $segment, $expanded, $idSubtable); + $dataTable = Archive::getDataTableFromArchive(Archiver::CUSTOM_VARIABLE_RECORD_NAME, $idSite, $period, $date, $segment, $expanded, $idSubtable); $dataTable->filter('Sort', array(Metrics::INDEX_NB_ACTIONS, 'desc', $naturalSort = false, $expanded)); $dataTable->queueFilter('ReplaceColumnNames'); $dataTable->queueFilter('ColumnDelete', 'nb_uniq_visitors'); @@ -111,7 +114,7 @@ public function getCustomVariablesValuesFromNameId($idSite, $period, $date, $idS $dataTable->renameColumn('price_viewed', 'price'); } $dataTable->queueFilter('ColumnCallbackReplace', array('label', create_function('$label', ' - return $label == Piwik_CustomVariables_Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED + return $label == \\Piwik\\Plugins\\CustomVariables\\Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED ? "' . Piwik_Translate('General_NotDefined', Piwik_Translate('CustomVariables_ColumnCustomVariableValue')) . '" : $label;'))); return $dataTable; diff --git a/plugins/CustomVariables/Archiver.php b/plugins/CustomVariables/Archiver.php index e26bb0a254b..d4d3cb7884b 100644 --- a/plugins/CustomVariables/Archiver.php +++ b/plugins/CustomVariables/Archiver.php @@ -1,24 +1,27 @@ getSelectAveragePrice() ); + if (in_array($slot, array(3, 4, 5))) { + $additionalSelects = array($this->getSelectAveragePrice()); } $query = $this->getLogAggregator()->queryActionsByDimension($dimensions, $where, $additionalSelects); $this->aggregateFromActions($query, $keyField, $valueField); @@ -106,7 +109,6 @@ protected function cleanCustomVarValue($value) return self::LABEL_CUSTOM_VALUE_NOT_DEFINED; } - protected function aggregateFromActions($query, $keyField, $valueField) { while ($row = $query->fetch()) { @@ -171,10 +173,9 @@ protected function aggregateActionByKeyAndValue($key, $value, $row) protected static function isReservedKey($key) { - return in_array($key, Piwik_CustomVariables_API::getReservedCustomVariableKeys()); + return in_array($key, API::getReservedCustomVariableKeys()); } - protected function aggregateFromConversions($query, $keyField, $valueField) { if ($query === false) { @@ -190,7 +191,7 @@ protected function aggregateFromConversions($query, $keyField, $valueField) protected function removeVisitsMetricsFromActionsAggregate() { - $dataArray = &$this->dataArray->getDataArray(); + $dataArray = & $this->dataArray->getDataArray(); foreach ($dataArray as $key => &$row) { if (!self::isReservedKey($key) && DataArray::isRowActions($row) diff --git a/plugins/CustomVariables/Controller.php b/plugins/CustomVariables/Controller.php index 5607e2c630e..da88d4e66e5 100644 --- a/plugins/CustomVariables/Controller.php +++ b/plugins/CustomVariables/Controller.php @@ -6,16 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CustomVariables + * @package CustomVariables */ -use Piwik\Controller; +namespace Piwik\Plugins\CustomVariables; + use Piwik\ViewDataTable; use Piwik\View; /** - * @package Piwik_CustomVariables + * @package CustomVariables */ -class Piwik_CustomVariables_Controller extends Controller +class Controller extends \Piwik\Controller { public function index($fetch = false) { diff --git a/plugins/CustomVariables/CustomVariables.php b/plugins/CustomVariables/CustomVariables.php index 30ebb6b5808..45bc3fa14b5 100644 --- a/plugins/CustomVariables/CustomVariables.php +++ b/plugins/CustomVariables/CustomVariables.php @@ -6,17 +6,19 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_CustomVariables + * @package CustomVariables */ +namespace Piwik\Plugins\CustomVariables; + use Piwik\ArchiveProcessor; +use Piwik\Plugins\CustomVariables\Archiver; use Piwik\Tracker; -use Piwik\Plugin; use Piwik\WidgetsList; /** - * @package Piwik_CustomVariables + * @package CustomVariables */ -class Piwik_CustomVariables extends Plugin +class CustomVariables extends \Piwik\Plugin { public function getInformation() { @@ -137,16 +139,16 @@ public function getReportsWithGoalMetrics(&$dimensions) */ public function archiveDay(ArchiveProcessor\Day $archiveProcessor) { - $archiving = new Piwik_CustomVariables_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archiveDay(); } } public function archivePeriod(ArchiveProcessor\Period $archiveProcessor) { - $archiving = new Piwik_CustomVariables_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archivePeriod(); } } @@ -164,26 +166,26 @@ private function getDisplayPropertiesForGetCustomVariables() array('', '')); return array( - 'columns_to_display' => array('label', 'nb_actions', 'nb_visits'), - 'filter_sort_column' => 'nb_actions', - 'filter_sort_order' => 'desc', - 'show_goals' => true, + 'columns_to_display' => array('label', 'nb_actions', 'nb_visits'), + 'filter_sort_column' => 'nb_actions', + 'filter_sort_order' => 'desc', + 'show_goals' => true, 'subtable_controller_action' => 'getCustomVariablesValuesFromNameId', - 'translations' => array('label' => Piwik_Translate('CustomVariables_ColumnCustomVariableName')), - 'show_footer_message' => $footerMessage + 'translations' => array('label' => Piwik_Translate('CustomVariables_ColumnCustomVariableName')), + 'show_footer_message' => $footerMessage ); } private function getDisplayPropertiesForGetCustomVariablesValuesFromNameId() { return array( - 'columns_to_display' => array('label', 'nb_actions', 'nb_visits'), - 'filter_sort_column' => 'nb_actions', - 'filter_sort_order' => 'desc', - 'show_goals' => true, - 'show_search' => false, + 'columns_to_display' => array('label', 'nb_actions', 'nb_visits'), + 'filter_sort_column' => 'nb_actions', + 'filter_sort_order' => 'desc', + 'show_goals' => true, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate('CustomVariables_ColumnCustomVariableValue')) + 'translations' => array('label' => Piwik_Translate('CustomVariables_ColumnCustomVariableValue')) ); } } diff --git a/plugins/DBStats/API.php b/plugins/DBStats/API.php index 46b3666c025..11788d19a11 100644 --- a/plugins/DBStats/API.php +++ b/plugins/DBStats/API.php @@ -6,11 +6,14 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DBStats + * @package DBStats */ +namespace Piwik\Plugins\DBStats; + use Piwik\Piwik; use Piwik\Common; use Piwik\DataTable; +use Piwik\Plugins\DBStats\MySQLMetadataProvider; /** * @see plugins/DBStats/MySQLMetadataProvider.php @@ -20,9 +23,9 @@ /** * DBStats API is used to request the overall status of the Mysql tables in use by Piwik. * - * @package Piwik_DBStats + * @package DBStats */ -class Piwik_DBStats_API +class API { /** Singleton instance of this class. */ static private $instance = null; @@ -48,7 +51,7 @@ static public function getInstance() */ public function __construct() { - $this->metadataProvider = new Piwik_DBStats_MySQLMetadataProvider(); + $this->metadataProvider = new MySQLMetadataProvider(); } /** @@ -57,7 +60,7 @@ public function __construct() public function resetTableStatuses() { Piwik::checkUserIsSuperUser(); - self::getInstance()->metadataProvider = new Piwik_DBStats_MySQLMetadataProvider(); + self::getInstance()->metadataProvider = new MySQLMetadataProvider(); } /** @@ -169,8 +172,7 @@ public function getMetricDataSummaryByYear() $dataTable = $this->getMetricDataSummary(); - $getTableYear = array('Piwik_DBStats_API', 'getArchiveTableYear'); - $dataTable->filter('GroupBy', array('label', $getTableYear)); + $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\API::getArchiveTableYear')); return $dataTable; } @@ -199,8 +201,7 @@ public function getReportDataSummaryByYear() $dataTable = $this->getReportDataSummary(); - $getTableYear = array('Piwik_DBStats_API', 'getArchiveTableYear'); - $dataTable->filter('GroupBy', array('label', $getTableYear)); + $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\API::getArchiveTableYear')); return $dataTable; } diff --git a/plugins/DBStats/Controller.php b/plugins/DBStats/Controller.php index 51f2a00ae6b..941b095f811 100644 --- a/plugins/DBStats/Controller.php +++ b/plugins/DBStats/Controller.php @@ -6,18 +6,19 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DBStats + * @package DBStats */ -use Piwik\Controller\Admin; +namespace Piwik\Plugins\DBStats; + use Piwik\Piwik; +use Piwik\Plugins\DBStats\API; use Piwik\ViewDataTable; use Piwik\View; /** - * - * @package Piwik_DBStats + * @package DBStats */ -class Piwik_DBStats_Controller extends Admin +class Controller extends \Piwik\Controller\Admin { /** * Returns the index for this plugin. Shows every other report defined by this plugin, @@ -38,7 +39,7 @@ public function index() $view->reportDataSummary = $this->getReportDataSummary(true); $view->adminDataSummary = $this->getAdminDataSummary(true); - list($siteCount, $userCount, $totalSpaceUsed) = Piwik_DBStats_API::getInstance()->getGeneralInformation(); + list($siteCount, $userCount, $totalSpaceUsed) = API::getInstance()->getGeneralInformation(); $view->siteCount = Piwik::getPrettyNumber($siteCount); $view->userCount = Piwik::getPrettyNumber($userCount); $view->totalSpaceUsed = Piwik::getPrettySizeFromBytes($totalSpaceUsed); diff --git a/plugins/DBStats/DBStats.php b/plugins/DBStats/DBStats.php index def12d84a44..433f682c9fe 100644 --- a/plugins/DBStats/DBStats.php +++ b/plugins/DBStats/DBStats.php @@ -6,20 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DBStats + * @package DBStats */ +namespace Piwik\Plugins\DBStats; + use Piwik\Piwik; use Piwik\Date; use Piwik\Common; +use Piwik\Plugins\DBStats\API; use Piwik\ScheduledTask; -use Piwik\Plugin; use Piwik\ScheduledTime\Weekly; /** * - * @package Piwik_DBStats + * @package DBStats */ -class Piwik_DBStats extends Plugin +class DBStats extends \Piwik\Plugin { const TIME_OF_LAST_TASK_RUN_OPTION = 'dbstats_time_of_last_cache_task_run'; @@ -65,7 +67,7 @@ public function getScheduledTasks(&$tasks) */ public function cacheDataByArchiveNameReports() { - $api = Piwik_DBStats_API::getInstance(); + $api = API::getInstance(); $api->getIndividualReportsSummary(true); $api->getIndividualMetricsSummary(true); @@ -147,7 +149,7 @@ private function getDisplayPropertiesForGetMetricDataSummary() $result['title'] = Piwik_Translate('DBStats_MetricTables'); $result['relatedReports'] = array( - 'DBStats.getMetricDataSummaryByYear' => Piwik_Translate('DBStats_MetricDataByYear') + 'DBStats.getMetricDataSummaryByYear' => Piwik_Translate('DBStats_MetricDataByYear') ); return $result; @@ -161,8 +163,8 @@ private function getDisplayPropertiesForGetMetricDataSummaryByYear() $result['translations']['label'] = Piwik_Translate('CoreHome_PeriodYear'); $result['title'] = Piwik_Translate('DBStats_MetricDataByYear'); - $result['relatedReports'] = array( - 'DBStats.getMetricDataSummary' => Piwik_Translate('DBStats_MetricTables') + $result['relatedReports'] = array( + 'DBStats.getMetricDataSummary' => Piwik_Translate('DBStats_MetricTables') ); return $result; @@ -191,7 +193,7 @@ private function getDisplayPropertiesForGetReportDataSummaryByYear() $result['translations']['label'] = Piwik_Translate('CoreHome_PeriodYear'); $result['title'] = Piwik_Translate('DBStats_ReportDataByYear'); $result['relatedReports'] = array( - 'DBStats.getReportDataSummary' => Piwik_Translate('DBStats_ReportTables') + 'DBStats.getReportDataSummary' => Piwik_Translate('DBStats_ReportTables') ); return $result; @@ -202,7 +204,7 @@ private function getDisplayPropertiesForGetIndividualReportsSummary() $result = array(); $this->addBaseDisplayProperties($result); $viewDataTable = $this->addPresentationFilters($result, $addTotalSizeColumn = false, $addPercentColumn = false, - $sizeColumns = array('estimated_size')); + $sizeColumns = array('estimated_size')); $result['filter_sort_order'] = 'asc'; $result['translations']['label'] = Piwik_Translate('General_Report'); @@ -222,7 +224,7 @@ private function getDisplayPropertiesForGetIndividualMetricsSummary() $result = array(); $this->addBaseDisplayProperties($result); $this->addPresentationFilters($result, $addTotalSizeColumn = false, $addPercentColumn = false, - $sizeColumns = array('estimated_size')); + $sizeColumns = array('estimated_size')); $result['filter_sort_order'] = 'asc'; $result['translations']['label'] = Piwik_Translate('General_Metric'); @@ -279,7 +281,7 @@ private function addPresentationFilters(&$properties, $addTotalSizeColumn = true }; $properties['filters'][] = array('ColumnCallbackAddColumn', - array(array('data_size', 'index_size'), 'total_size', $getTotalTableSize), $isPriority = true); + array(array('data_size', 'index_size'), 'total_size', $getTotalTableSize), $isPriority = true); $sizeColumns[] = 'total_size'; } @@ -299,9 +301,9 @@ private function addPresentationFilters(&$properties, $addTotalSizeColumn = true && $addTotalSizeColumn ) { $properties['filters'][] = array('ColumnCallbackAddColumnPercentage', - array('percent_total', 'total_size', 'total_size', $quotientPrecision = 0, - $shouldSkipRows = false, $getDivisorFromSummaryRow = true), - $isPriority = true + array('percent_total', 'total_size', 'total_size', $quotientPrecision = 0, + $shouldSkipRows = false, $getDivisorFromSummaryRow = true), + $isPriority = true ); $properties['filter_sort_column'] = 'percent_total'; diff --git a/plugins/DBStats/MySQLMetadataProvider.php b/plugins/DBStats/MySQLMetadataProvider.php index d47713cf301..4e39d508875 100755 --- a/plugins/DBStats/MySQLMetadataProvider.php +++ b/plugins/DBStats/MySQLMetadataProvider.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DBStats + * @package DBStats */ +namespace Piwik\Plugins\DBStats; + +use Exception; use Piwik\Piwik; use Piwik\Common; use Piwik\Config; use Piwik\DataTable; use Piwik\Db; - /** * Utility class that provides general information about databases, including the size of * the entire database, the size and row count of each table and the size and row count @@ -23,7 +25,7 @@ * This class will cache the table information it retrieves from the database. In order to * issue a new query instead of using this cache, you must create a new instance of this type. */ -class Piwik_DBStats_MySQLMetadataProvider +class MySQLMetadataProvider { /** * Cached MySQL table statuses. So we won't needlessly re-issue SHOW TABLE STATUS queries. diff --git a/plugins/Dashboard/API.php b/plugins/Dashboard/API.php index dd879797395..1330eacef6a 100644 --- a/plugins/Dashboard/API.php +++ b/plugins/Dashboard/API.php @@ -5,21 +5,22 @@ * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * @category Piwik_Plugins - * @package Piwik_Dashboard + * @package Dashboard */ +namespace Piwik\Plugins\Dashboard; + use Piwik\Piwik; use Piwik\WidgetsList; - /** * This API is the Dashboard API: it gives information about dashboards. * * @package Piwik_API */ -class Piwik_Dashboard_API +class API { /** - * @var Piwik_Dashboard_API + * @var \Piwik\Plugins\Dashboard\API */ static private $instance = null; @@ -27,11 +28,11 @@ class Piwik_Dashboard_API public function __construct() { - $this->dashboard = new Piwik_Dashboard(); + $this->dashboard = new Dashboard(); } /** - * @return Piwik_Dashboard_API + * @return \Piwik\Plugins\Dashboard\API */ static public function getInstance() { @@ -83,7 +84,7 @@ private function getDefaultDashboard() */ private function getUserDashboards() { - $userLogin = Piwik::getCurrentUserLogin(); + $userLogin = Piwik::getCurrentUserLogin(); $userDashboards = $this->dashboard->getAllDashboards($userLogin); $dashboards = array(); @@ -91,10 +92,9 @@ private function getUserDashboards() foreach ($userDashboards as $userDashboard) { if ($this->hasDashboardColumns($userDashboard)) { - $widgets = $this->getExistingWidgetsWithinDashboard($userDashboard); + $widgets = $this->getExistingWidgetsWithinDashboard($userDashboard); $dashboards[] = $this->buildDashboard($userDashboard, $widgets); } - } return $dashboards; @@ -111,8 +111,8 @@ private function getExistingWidgetsWithinDashboard($dashboard) foreach ($column as $widget) { if ($this->widgetIsNotHidden($widget) && $this->widgetExists($widget)) { - $module = $widget->parameters->module; - $action = $widget->parameters->action; + $module = $widget->parameters->module; + $action = $widget->parameters->action; $widgets[] = array('module' => $module, 'action' => $action); } diff --git a/plugins/Dashboard/Controller.php b/plugins/Dashboard/Controller.php index 7ffe0dc79e3..bded95b33e5 100644 --- a/plugins/Dashboard/Controller.php +++ b/plugins/Dashboard/Controller.php @@ -5,12 +5,14 @@ * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * @category Piwik_Plugins - * @package Piwik_Dashboard + * @package Dashboard */ +namespace Piwik\Plugins\Dashboard; + use Piwik\DataTable\Renderer\Json; use Piwik\Piwik; use Piwik\Common; -use Piwik\Controller; +use Piwik\Plugins\Dashboard\Dashboard; use Piwik\Session\SessionNamespace; use Piwik\View; use Piwik\Db; @@ -19,12 +21,12 @@ /** * Dashboard Controller * - * @package Piwik_Dashboard + * @package Dashboard */ -class Piwik_Dashboard_Controller extends Controller +class Controller extends \Piwik\Controller { /** - * @var Piwik_Dashboard + * @var Dashboard */ private $dashboard; @@ -32,7 +34,7 @@ protected function init() { parent::init(); - $this->dashboard = new Piwik_Dashboard(); + $this->dashboard = new Dashboard(); } protected function _getDashboardView($template) @@ -96,7 +98,7 @@ public function resetLayout() $layout = $this->dashboard->getDefaultLayout(); $idDashboard = Common::getRequestVar('idDashboard', 1, 'int'); if (Piwik::isUserIsAnonymous()) { - $session = new SessionNamespace("Piwik_Dashboard"); + $session = new SessionNamespace("Dashboard"); $session->dashboardLayout = $layout; $session->setExpirationSeconds(1800); } else { @@ -161,15 +163,15 @@ public function removeDashboard() public function getAllDashboards() { $this->checkTokenInUrl(); - + if (Piwik::isUserIsAnonymous()) { Json::sendHeaderJSON(); echo '[]'; - + return; } - $login = Piwik::getCurrentUserLogin(); + $login = Piwik::getCurrentUserLogin(); $dashboards = $this->dashboard->getAllDashboards($login); Json::sendHeaderJSON(); @@ -260,7 +262,7 @@ public function saveLayout() $idDashboard = Common::getRequestVar('idDashboard', 1, 'int'); $name = Common::getRequestVar('name', '', 'string'); if (Piwik::isUserIsAnonymous()) { - $session = new SessionNamespace("Piwik_Dashboard"); + $session = new SessionNamespace("Dashboard"); $session->dashboardLayout = $layout; $session->setExpirationSeconds(1800); } else { @@ -298,14 +300,13 @@ protected function getLayout($idDashboard) { if (Piwik::isUserIsAnonymous()) { - $session = new SessionNamespace("Piwik_Dashboard"); + $session = new SessionNamespace("Dashboard"); if (!isset($session->dashboardLayout)) { return $this->dashboard->getDefaultLayout(); } $layout = $session->dashboardLayout; - } else { $layout = $this->dashboard->getLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard); } @@ -335,7 +336,6 @@ protected function getAvailableLayouts() array(25, 25, 25, 25) ); } - } diff --git a/plugins/Dashboard/Dashboard.php b/plugins/Dashboard/Dashboard.php index 13d25ee9cbd..58618e05b4e 100644 --- a/plugins/Dashboard/Dashboard.php +++ b/plugins/Dashboard/Dashboard.php @@ -6,19 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Dashboard + * @package Dashboard */ +namespace Piwik\Plugins\Dashboard; + +use Exception; use Piwik\Piwik; use Piwik\Common; -use Piwik\Plugin; use Piwik\Site; use Piwik\Db; use Piwik\WidgetsList; +use Zend_Registry; /** - * @package Piwik_Dashboard + * @package Dashboard */ -class Piwik_Dashboard extends Plugin +class Dashboard extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/DevicesDetection/API.php b/plugins/DevicesDetection/API.php index 1800849fcf6..250919c5658 100644 --- a/plugins/DevicesDetection/API.php +++ b/plugins/DevicesDetection/API.php @@ -1,5 +1,4 @@ getDataTable('DevicesDetection_types', $idSite, $period, $date, $segment); - $dataTable->filter('ColumnCallbackReplace', array('label', 'Piwik_getDeviceTypeLabel')); + $dataTable->filter('ColumnCallbackReplace', array('label', __NAMESPACE__ . '\getDeviceTypeLabel')); $dataTable->filter('ColumnCallbackReplace', array('label', 'ucfirst')); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_getDeviceTypeLogo')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getDeviceTypeLogo')); return $dataTable; } @@ -81,8 +83,8 @@ public function getType($idSite, $period, $date, $segment = false) public function getBrand($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_brands', $idSite, $period, $date, $segment); - $dataTable->filter('ColumnCallbackReplace', array('label', 'Piwik_getDeviceBrandLabel')); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_GetBrandLogo')); + $dataTable->filter('ColumnCallbackReplace', array('label', __NAMESPACE__ . '\getDeviceBrandLabel')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getBrandLogo')); return $dataTable; } @@ -97,7 +99,7 @@ public function getBrand($idSite, $period, $date, $segment = false) public function getModel($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_models', $idSite, $period, $date, $segment); - $dataTable->filter('ColumnCallbackReplace', array('label', 'Piwik_getModelName')); + $dataTable->filter('ColumnCallbackReplace', array('label', __NAMESPACE__ . '\getModelName')); return $dataTable; } @@ -112,8 +114,8 @@ public function getModel($idSite, $period, $date, $segment = false) public function getOsFamilies($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_os', $idSite, $period, $date, $segment); - $dataTable->filter('GroupBy', array('label', 'Piwik_getOSFamilyFullNameExtended')); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_getOsFamilyLogoExtended')); + $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\getOSFamilyFullNameExtended')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getOsFamilyLogoExtended')); return $dataTable; } @@ -128,15 +130,15 @@ public function getOsFamilies($idSite, $period, $date, $segment = false) public function getOsVersions($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_osVersions', $idSite, $period, $date, $segment); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_getOsLogoExtended')); - $dataTable->filter('ColumnCallbackReplace', array('label', 'Piwik_getOsFullNameExtended')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getOsLogoExtended')); + $dataTable->filter('ColumnCallbackReplace', array('label', __NAMESPACE__ . '\getOsFullNameExtended')); return $dataTable; } /** * Gets datatable displaying number of visits by Browser family (eg. Firefox, InternetExplorer) - * @param int $idSite + * @param int $idSite * @param string $period * @param string $date * @param bool|string $segment @@ -145,8 +147,8 @@ public function getOsVersions($idSite, $period, $date, $segment = false) public function getBrowserFamilies($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_browsers', $idSite, $period, $date, $segment); - $dataTable->filter('GroupBy', array('label', 'Piwik_getBrowserFamilyFullNameExtended')); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_getBrowserFamilyLogoExtended')); + $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\getBrowserFamilyFullNameExtended')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getBrowserFamilyLogoExtended')); return $dataTable; } @@ -161,9 +163,8 @@ public function getBrowserFamilies($idSite, $period, $date, $segment = false) public function getBrowserVersions($idSite, $period, $date, $segment = false) { $dataTable = $this->getDataTable('DevicesDetection_browserVersions', $idSite, $period, $date, $segment); - $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', 'Piwik_getBrowserLogoExtended')); - $dataTable->filter('ColumnCallbackReplace', array('label', 'Piwik_getBrowserNameExtended')); + $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getBrowserLogoExtended')); + $dataTable->filter('ColumnCallbackReplace', array('label', __NAMESPACE__ . '\getBrowserNameExtended')); return $dataTable; } - } \ No newline at end of file diff --git a/plugins/DevicesDetection/Archiver.php b/plugins/DevicesDetection/Archiver.php index 73a66fb67d3..58b1df2cca9 100644 --- a/plugins/DevicesDetection/Archiver.php +++ b/plugins/DevicesDetection/Archiver.php @@ -6,13 +6,15 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DevicesDetection + * @package DevicesDetection */ +namespace Piwik\Plugins\DevicesDetection; + use Piwik\Metrics; use Piwik\PluginsArchiver; -class Piwik_DevicesDetection_Archiver extends PluginsArchiver +class Archiver extends PluginsArchiver { const DEVICE_TYPE_RECORD_NAME = 'DevicesDetection_types'; const DEVICE_BRAND_RECORD_NAME = 'DevicesDetection_brands'; @@ -32,16 +34,16 @@ class Piwik_DevicesDetection_Archiver extends PluginsArchiver public function archiveDay() { - $this->aggregateByLabel( self::DEVICE_TYPE_FIELD, self::DEVICE_TYPE_RECORD_NAME); - $this->aggregateByLabel( self::DEVICE_BRAND_FIELD, self::DEVICE_BRAND_RECORD_NAME); - $this->aggregateByLabel( self::DEVICE_MODEL_FIELD, self::DEVICE_MODEL_RECORD_NAME); - $this->aggregateByLabel( self::OS_FIELD, self::OS_RECORD_NAME); - $this->aggregateByLabel( self::OS_VERSION_FIELD, self::OS_VERSION_RECORD_NAME); - $this->aggregateByLabel( self::BROWSER_FIELD, self::BROWSER_RECORD_NAME); - $this->aggregateByLabel( self::BROWSER_VERSION_DIMENSION, self::BROWSER_VERSION_RECORD_NAME); + $this->aggregateByLabel(self::DEVICE_TYPE_FIELD, self::DEVICE_TYPE_RECORD_NAME); + $this->aggregateByLabel(self::DEVICE_BRAND_FIELD, self::DEVICE_BRAND_RECORD_NAME); + $this->aggregateByLabel(self::DEVICE_MODEL_FIELD, self::DEVICE_MODEL_RECORD_NAME); + $this->aggregateByLabel(self::OS_FIELD, self::OS_RECORD_NAME); + $this->aggregateByLabel(self::OS_VERSION_FIELD, self::OS_VERSION_RECORD_NAME); + $this->aggregateByLabel(self::BROWSER_FIELD, self::BROWSER_RECORD_NAME); + $this->aggregateByLabel(self::BROWSER_VERSION_DIMENSION, self::BROWSER_VERSION_RECORD_NAME); } - private function aggregateByLabel( $labelSQL, $recordName) + private function aggregateByLabel($labelSQL, $recordName) { $metrics = $this->getProcessor()->getMetricsForDimension($labelSQL); $table = $this->getProcessor()->getDataTableFromDataArray($metrics); diff --git a/plugins/DevicesDetection/Controller.php b/plugins/DevicesDetection/Controller.php index 189729e81e7..ac0beb50d48 100644 --- a/plugins/DevicesDetection/Controller.php +++ b/plugins/DevicesDetection/Controller.php @@ -1,12 +1,4 @@ "[Beta Plugin] " . Piwik_Translate("DevicesDetection_description"), - 'author' => 'Piwik and Clearcode.cc', + 'description' => "[Beta Plugin] " . Piwik_Translate("DevicesDetection_description"), + 'author' => 'Piwik and Clearcode.cc', 'author_homepage' => 'http://clearcode.cc', - 'version' => '1.12-b6', + 'version' => '1.12-b6', ); } - /** * @see Piwik_Plugin::getListHooksRegistered */ public function getListHooksRegistered() { return array( - 'ArchiveProcessing_Day.compute' => "archiveDay", - 'ArchiveProcessing_Period.compute' => 'archivePeriod', - 'Menu.add' => 'addMenu', - 'Tracker.newVisitorInformation' => 'parseMobileVisitData', - 'WidgetsList.add' => 'addWidgets', - 'API.getReportMetadata' => 'getReportMetadata', - 'API.getSegmentsMetadata' => 'getSegmentsMetadata', + 'ArchiveProcessing_Day.compute' => "archiveDay", + 'ArchiveProcessing_Period.compute' => 'archivePeriod', + 'Menu.add' => 'addMenu', + 'Tracker.newVisitorInformation' => 'parseMobileVisitData', + 'WidgetsList.add' => 'addWidgets', + 'API.getReportMetadata' => 'getReportMetadata', + 'API.getSegmentsMetadata' => 'getSegmentsMetadata', 'ViewDataTable.getReportDisplayProperties' => 'getReportDisplayProperties', ); } @@ -155,7 +158,6 @@ public function addWidgets() } } - /** * Get segments meta data */ @@ -187,12 +189,12 @@ public function getReportMetadata(&$reports) continue; $report = array( - 'category' => Piwik_Translate($category), - 'name' => Piwik_Translate($name), - 'module' => $apiModule, - 'action' => $apiAction, + 'category' => Piwik_Translate($category), + 'name' => Piwik_Translate($name), + 'module' => $apiModule, + 'action' => $apiAction, 'dimension' => Piwik_Translate($columnName), - 'order' => $i++ + 'order' => $i++ ); $translation = $name . 'Documentation'; @@ -201,7 +203,6 @@ public function getReportMetadata(&$reports) $report['documentation'] = $translated; } - $reports[] = $report; } } @@ -223,7 +224,7 @@ public function install() Db::exec($q2); } } catch (Exception $e) { - if (!Zend_Registry::get('db')->isErrNo($e, '1060')) { + if (!Zend_Registry::get('db')->isErrNo($e, '1060')) { throw $e; } } @@ -254,16 +255,16 @@ public function parseMobileVisitData(&$visitorInfo, $extraInfo) public function archiveDay(ArchiveProcessor\Day $archiveProcessor) { - $archiving = new Piwik_DevicesDetection_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archiveDay(); } } public function archivePeriod(ArchiveProcessor\Period $archiveProcessor) { - $archiving = new Piwik_DevicesDetection_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archivePeriod(); } } @@ -287,70 +288,70 @@ public function getReportDisplayProperties(&$properties) private function getDisplayPropertiesForGetType() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelTypes")) + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelTypes")) ); } private function getDisplayPropertiesForGetBrand() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrands")) + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrands")) ); } private function getDisplayPropertiesForGetModel() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelModels")) + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelModels")) ); } private function getDisplayPropertiesForGetOsFamilies() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelSystemFamily")), - 'title' => Piwik_Translate('DeviceDetection_OperatingSystemFamilies'), - 'relatedReports' => $this->getOsRelatedReports() + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelSystemFamily")), + 'title' => Piwik_Translate('DeviceDetection_OperatingSystemFamilies'), + 'relatedReports' => $this->getOsRelatedReports() ); } private function getDisplayPropertiesForGetOsVersions() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelSystemVersion")), - 'title' => Piwik_Translate('DeviceDetection_OperatingSystemVersions'), - 'relatedReports' => $this->getOsRelatedReports() + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelSystemVersion")), + 'title' => Piwik_Translate('DeviceDetection_OperatingSystemVersions'), + 'relatedReports' => $this->getOsRelatedReports() ); } private function getDisplayPropertiesForGetBrowserFamilies() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrowserFamily")), - 'title' => Piwik_Translate('DevicesDetection_BrowsersFamily'), - 'relatedReports' => $this->getBrowserRelatedReports() + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrowserFamily")), + 'title' => Piwik_Translate('DevicesDetection_BrowsersFamily'), + 'relatedReports' => $this->getBrowserRelatedReports() ); } private function getDisplayPropertiesForGetBrowserVersions() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrowserVersion")), - 'relatedReports' => $this->getBrowserRelatedReports() + 'translations' => array('label' => Piwik_Translate("DevicesDetection_dataTableLabelBrowserVersion")), + 'relatedReports' => $this->getBrowserRelatedReports() ); } diff --git a/plugins/DevicesDetection/UserAgentParserEnhanced/UserAgentParserEnhanced.php b/plugins/DevicesDetection/UserAgentParserEnhanced/UserAgentParserEnhanced.php index d078305d978..a8ec8e22042 100644 --- a/plugins/DevicesDetection/UserAgentParserEnhanced/UserAgentParserEnhanced.php +++ b/plugins/DevicesDetection/UserAgentParserEnhanced/UserAgentParserEnhanced.php @@ -7,7 +7,7 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DevicesDetection + * @package DevicesDetection */ //yml parser require_once(PIWIK_INCLUDE_PATH.'/libs/spyc.php'); diff --git a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/browsers.yml b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/browsers.yml index 9ab3bc4c1cf..351aa7f2681 100644 --- a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/browsers.yml +++ b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/browsers.yml @@ -5,7 +5,7 @@ # @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later # # @category Piwik_Plugins -# @package Piwik_DevicesDetection +# @package DevicesDetection ############### # SeaMonkey diff --git a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/mobiles.yml b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/mobiles.yml index d9a2a22f886..46ae6b9c975 100644 --- a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/mobiles.yml +++ b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/mobiles.yml @@ -5,7 +5,7 @@ # @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later # # @category Piwik_Plugins -# @package Piwik_DevicesDetection +# @package DevicesDetection ############### # HTC diff --git a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/oss.yml b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/oss.yml index 71b85f987f7..918a00487d3 100644 --- a/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/oss.yml +++ b/plugins/DevicesDetection/UserAgentParserEnhanced/regexes/oss.yml @@ -5,7 +5,7 @@ # @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later # # @category Piwik_Plugins -# @package Piwik_DevicesDetection +# @package DevicesDetection ############### ########## diff --git a/plugins/DevicesDetection/functions.php b/plugins/DevicesDetection/functions.php index 4819cd69742..92a4b3e84ee 100644 --- a/plugins/DevicesDetection/functions.php +++ b/plugins/DevicesDetection/functions.php @@ -1,5 +1,4 @@ $family) { if (in_array($label, $family)) { @@ -29,7 +33,7 @@ function Piwik_getBrowserFamilyFullNameExtended($label) return Piwik_Translate('General_Unknown'); } -function Piwik_getBrowserFamilyLogoExtended($label) +function getBrowserFamilyLogoExtended($label) { if (array_key_exists($label, UserAgentParserEnhanced::$browserFamilies)) { $path = 'plugins/UserSettings/images/browsers/' . UserAgentParserEnhanced::$browserFamilies[$label][0] . '.gif'; @@ -39,7 +43,7 @@ function Piwik_getBrowserFamilyLogoExtended($label) return $path; } -function Piwik_getBrowserNameExtended($label) +function getBrowserNameExtended($label) { $short = substr($label, 0, 2); $ver = substr($label, 3, 10); @@ -50,17 +54,17 @@ function Piwik_getBrowserNameExtended($label) } } -function Piwik_getBrowserLogoExtended($label) +function getBrowserLogoExtended($label) { $short = substr($label, 0, 2); - $familyName = Piwik_getBrowserFamilyFullNameExtended($short); - $path = Piwik_getBrowserFamilyLogoExtended($familyName); + $familyName = getBrowserFamilyFullNameExtended($short); + $path = getBrowserFamilyLogoExtended($familyName); return $path; } -function Piwik_getDeviceBrandLabel($label) +function getDeviceBrandLabel($label) { if (array_key_exists($label, UserAgentParserEnhanced::$deviceBrands)) { return ucfirst(UserAgentParserEnhanced::$deviceBrands[$label]); @@ -69,7 +73,7 @@ function Piwik_getDeviceBrandLabel($label) } } -function Piwik_getDeviceTypeLabel($label) +function getDeviceTypeLabel($label) { if (isset(UserAgentParserEnhanced::$deviceTypes[$label])) { return UserAgentParserEnhanced::$deviceTypes[$label]; @@ -78,7 +82,7 @@ function Piwik_getDeviceTypeLabel($label) } } -function Piwik_getDeviceTypeLogo($label) +function getDeviceTypeLogo($label) { $deviceTypeLogos = Array( "Desktop" => "normal.gif", @@ -97,7 +101,7 @@ function Piwik_getDeviceTypeLogo($label) return $path; } -function Piwik_getModelName($label) +function getModelName($label) { if (!$label) { return Piwik_Translate('General_Unknown'); @@ -105,7 +109,7 @@ function Piwik_getModelName($label) return $label; } -function Piwik_getOSFamilyFullNameExtended($label) +function getOSFamilyFullNameExtended($label) { foreach (UserAgentParserEnhanced::$osFamilies as $name => $family) { if (in_array($label, $family)) { @@ -115,7 +119,7 @@ function Piwik_getOSFamilyFullNameExtended($label) return Piwik_Translate('General_Unknown'); } -function Piwik_getOsFamilyLogoExtended($label) +function getOsFamilyLogoExtended($label) { if (array_key_exists($label, UserAgentParserEnhanced::$osFamilies)) { $path = 'plugins/UserSettings/images/os/' . UserAgentParserEnhanced::$osFamilies[$label][0] . ".gif"; @@ -125,7 +129,7 @@ function Piwik_getOsFamilyLogoExtended($label) return $path; } -function Piwik_getOsFullNameExtended($label) +function getOsFullNameExtended($label) { if (!empty($label) && $label != ";") { $os = substr($label, 0, 3); @@ -140,10 +144,10 @@ function Piwik_getOsFullNameExtended($label) -function Piwik_getOsLogoExtended($label) +function getOsLogoExtended($label) { $short = substr($label, 0, 3); - $familyName = Piwik_getOsFamilyFullNameExtended($short); - $path = Piwik_getOsFamilyLogoExtended($familyName); + $familyName = getOsFamilyFullNameExtended($short); + $path = getOsFamilyLogoExtended($familyName); return $path; } \ No newline at end of file diff --git a/plugins/DoNotTrack/DoNotTrack.php b/plugins/DoNotTrack/DoNotTrack.php index 8d9a3cf7002..1a02788a274 100644 --- a/plugins/DoNotTrack/DoNotTrack.php +++ b/plugins/DoNotTrack/DoNotTrack.php @@ -6,9 +6,10 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_DoNotTrack + * @package DoNotTrack */ -use Piwik\Plugin; +namespace Piwik\Plugins\DoNotTrack; + use Piwik\Common; use Piwik\Tracker\IgnoreCookie; use Piwik\Tracker\Request; @@ -18,9 +19,9 @@ * - X-Do-Not-Track header (used by AdBlockPlus and NoScript) * - DNT header (used by Mozilla) * - * @package Piwik_DoNotTrack + * @package DoNotTrack */ -class Piwik_DoNotTrack extends Plugin +class DoNotTrack extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/ExampleAPI/API.php b/plugins/ExampleAPI/API.php index 214d73eac55..a6c012a6440 100644 --- a/plugins/ExampleAPI/API.php +++ b/plugins/ExampleAPI/API.php @@ -8,9 +8,11 @@ * @category Piwik_Plugins * @package Piwik_ExampleAPI */ +namespace Piwik\Plugins\ExampleAPI; + +use Piwik\DataTable; use Piwik\DataTable\Row; use Piwik\Piwik; -use Piwik\DataTable; use Piwik\Version; /** @@ -19,7 +21,7 @@ * Please see the source code in in the file plugins/ExampleAPI/API.php for more documentation. * @package Piwik_ExampleAPI */ -class Piwik_ExampleAPI_API +class API { /** * * This is an example of a basic API file. Each plugin can have one public API. @@ -38,14 +40,14 @@ class Piwik_ExampleAPI_API * * It is highly recommended that all the plugin logic is done inside API implementations, and the * Controller and other objects would all call the API internally using, eg. - * Piwik_ExampleAPI_API::getInstance()->getSum(1, 2); + * API::getInstance()->getSum(1, 2); * */ static private $instance = null; /** * Singleton - * @return Piwik_ExampleAPI_API + * @return \Piwik\Plugins\ExampleAPI\API */ static public function getInstance() { @@ -80,11 +82,11 @@ public function getAnswerToLife() * If used internally, the data structure can be returned untouched by using * the API parameter 'format=original' * - * @return Piwik_MagicObject Will return a standard Piwik error when called from the Web APIs + * @return MagicObject Will return a standard Piwik error when called from the Web APIs */ public function getObject() { - return new Piwik_MagicObject(); + return new MagicObject(); } /** @@ -180,9 +182,9 @@ public function getMultiArray() /** * Magic Object * - * @package Piwik_ExamplePlugin + * @package ExamplePlugin */ -class Piwik_MagicObject +class MagicObject { function Incredible() { @@ -191,4 +193,4 @@ function Incredible() protected $wonderful = 'magnifique'; public $great = 'formidable'; -} +} \ No newline at end of file diff --git a/plugins/ExampleAPI/ExampleAPI.php b/plugins/ExampleAPI/ExampleAPI.php deleted file mode 100644 index da1c3f4c527..00000000000 --- a/plugins/ExampleAPI/ExampleAPI.php +++ /dev/null @@ -1,20 +0,0 @@ -WidgetsList::add( $widgetCategory, $widgetName, $controllerName, $controllerAction, $customParameters = array()); - Adds a widget that users can add in the dashboard, or export using the Widgets link at the top of the screen. See the example in the UserCountry Plugin file or any other plugin)
'; $out .= 'Common::prefixTable("site") = ' . Common::prefixTable("site") . '
'; - $out .= '

User access

'; $out .= 'Piwik::getCurrentUserLogin() = ' . Piwik::getCurrentUserLogin() . '
'; $out .= 'Piwik::isUserHasSomeAdminAccess() = ' . self::boolToString(Piwik::isUserHasSomeAdminAccess()) . '
'; @@ -112,19 +112,19 @@ public function index() $out .= 'At this point, we have: $fetched[\'token_auth\'] == ' . var_export($token_auth, true) . '
'; $out .= '

Example Sites information API

'; - $out .= 'Piwik_SitesManager_API::getInstance()->getSitesWithViewAccess() =
' . var_export(Piwik_SitesManager_API::getInstance()->getSitesWithViewAccess(), true) . '

'; - $out .= 'Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess() =
' . var_export(Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess(), true) . '

'; + $out .= 'API::getInstance()->getSitesWithViewAccess() =
' . var_export(API::getInstance()->getSitesWithViewAccess(), true) . '

'; + $out .= 'API::getInstance()->getSitesWithAdminAccess() =
' . var_export(API::getInstance()->getSitesWithAdminAccess(), true) . '

'; $out .= '

Example API Users information

'; $out .= 'View the list of API methods you can call on API reference
'; - $out .= 'For example you can try Piwik_UsersManager_API::getInstance()->getUsersSitesFromAccess("view"); or Piwik_UsersManager_API::getInstance()->deleteUser("userToDelete");
'; + $out .= 'For example you can try API::getInstance()->getUsersSitesFromAccess("view"); or API::getInstance()->deleteUser("userToDelete");
'; $out .= '

Javascript in Piwik

'; $out .= '

i18n internationalization

'; $out .= 'In order to translate strings within Javascript code, you can use the javascript function _pk_translate( token );. '; diff --git a/plugins/ExamplePlugin/ExamplePlugin.php b/plugins/ExamplePlugin/ExamplePlugin.php index 481c324b5d8..812898291d6 100644 --- a/plugins/ExamplePlugin/ExamplePlugin.php +++ b/plugins/ExamplePlugin/ExamplePlugin.php @@ -6,16 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExamplePlugin + * @package ExamplePlugin */ -use Piwik\Plugin; +namespace Piwik\Plugins\ExamplePlugin; + use Piwik\WidgetsList; /** * - * @package Piwik_ExamplePlugin + * @package ExamplePlugin */ -class Piwik_ExamplePlugin extends Plugin +class ExamplePlugin extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/ExamplePlugin/lang/en.php b/plugins/ExamplePlugin/lang/en.php index 9be43dddeac..eaec0c99401 100644 --- a/plugins/ExamplePlugin/lang/en.php +++ b/plugins/ExamplePlugin/lang/en.php @@ -6,7 +6,7 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExamplePlugin + * @package ExamplePlugin */ $translations = array( diff --git a/plugins/ExampleRssWidget/Controller.php b/plugins/ExampleRssWidget/Controller.php index aaa53a7ef16..45e5a44cdcd 100644 --- a/plugins/ExampleRssWidget/Controller.php +++ b/plugins/ExampleRssWidget/Controller.php @@ -6,20 +6,24 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ -use Piwik\Controller; + +namespace Piwik\Plugins\ExampleRssWidget; + +use Exception; +use Piwik\Plugins\ExampleRssWidget\RssRenderer; /** * - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ -class Piwik_ExampleRssWidget_Controller extends Controller +class Controller extends \Piwik\Controller { public function rssPiwik() { try { - $rss = new Piwik_ExampleRssWidget_Rss('http://feeds.feedburner.com/Piwik'); + $rss = new RssRenderer('http://feeds.feedburner.com/Piwik'); $rss->showDescription(true); echo $rss->get(); } catch (Exception $e) { @@ -30,7 +34,7 @@ public function rssPiwik() public function rssChangelog() { try { - $rss = new Piwik_ExampleRssWidget_Rss('http://feeds.feedburner.com/PiwikReleases'); + $rss = new RssRenderer('http://feeds.feedburner.com/PiwikReleases'); $rss->setCountPosts(1); $rss->showDescription(false); $rss->showContent(true); diff --git a/plugins/ExampleRssWidget/ExampleRssWidget.php b/plugins/ExampleRssWidget/ExampleRssWidget.php index a23daf88ee5..868913959ef 100644 --- a/plugins/ExampleRssWidget/ExampleRssWidget.php +++ b/plugins/ExampleRssWidget/ExampleRssWidget.php @@ -6,16 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ -use Piwik\Plugin; +namespace Piwik\Plugins\ExampleRssWidget; + use Piwik\WidgetsList; /** * - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ -class Piwik_ExampleRssWidget extends Plugin +class ExampleRssWidget extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/ExampleRssWidget/Rss.php b/plugins/ExampleRssWidget/RssRenderer.php similarity index 92% rename from plugins/ExampleRssWidget/Rss.php rename to plugins/ExampleRssWidget/RssRenderer.php index ee95a8a56dc..1b7baa1ba2b 100644 --- a/plugins/ExampleRssWidget/Rss.php +++ b/plugins/ExampleRssWidget/RssRenderer.php @@ -6,14 +6,19 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ +namespace Piwik\Plugins\ExampleRssWidget; + +use Zend_Feed; +use Zend_Feed_Exception; + /** * - * @package Piwik_ExampleRssWidget + * @package ExampleRssWidget */ -class Piwik_ExampleRssWidget_Rss +class RssRenderer { protected $url = null; protected $count = 3; diff --git a/plugins/ExampleUI/API.php b/plugins/ExampleUI/API.php index 4fc0c513f86..d2128fa296c 100644 --- a/plugins/ExampleUI/API.php +++ b/plugins/ExampleUI/API.php @@ -6,8 +6,10 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleUI + * @package ExampleUI */ +namespace Piwik\Plugins\ExampleUI; + use Piwik\Period\Range; use Piwik\DataTable; @@ -17,14 +19,14 @@ * The functions listed in this API are returning the data used in the Controller to draw graphs and * display tables. See also the ExampleAPI plugin for an introduction to Piwik APIs. * - * @package Piwik_ExampleUI + * @package ExampleUI */ -class Piwik_ExampleUI_API +class API { static private $instance = null; /** - * @return Piwik_ExampleUI_API + * @return \Piwik\Plugins\ExampleUI\API */ static public function getInstance() { diff --git a/plugins/ExampleUI/Controller.php b/plugins/ExampleUI/Controller.php index 5660190aaaf..201610f7e7b 100644 --- a/plugins/ExampleUI/Controller.php +++ b/plugins/ExampleUI/Controller.php @@ -6,17 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleUI + * @package ExampleUI */ +namespace Piwik\Plugins\ExampleUI; + use Piwik\Common; -use Piwik\Controller; use Piwik\ViewDataTable; use Piwik\View; /** - * @package Piwik_ExampleUI + * @package ExampleUI */ -class Piwik_ExampleUI_Controller extends Controller +class Controller extends \Piwik\Controller { public function dataTables() { @@ -122,7 +123,7 @@ public function generateSparkline() if ($serverRequested !== false) { $view->columns_to_display = array($serverRequested); } - + echo $view->render(); } diff --git a/plugins/ExampleUI/ExampleUI.php b/plugins/ExampleUI/ExampleUI.php index 4e1210cf14b..fcd6120cca4 100644 --- a/plugins/ExampleUI/ExampleUI.php +++ b/plugins/ExampleUI/ExampleUI.php @@ -6,7 +6,7 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ExampleUI + * @package ExampleUI */ /* @@ -18,13 +18,14 @@ - without all columns icon + update http://piwik.org/participate/user-interface */ -use Piwik\Plugin; +namespace Piwik\Plugins\ExampleUI; + /** * - * @package Piwik_ExampleUI + * @package ExampleUI */ -class Piwik_ExampleUI extends Plugin +class ExampleUI extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/Feedback/Controller.php b/plugins/Feedback/Controller.php index 3a43559d6f9..2b80b18ad28 100644 --- a/plugins/Feedback/Controller.php +++ b/plugins/Feedback/Controller.php @@ -6,12 +6,14 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Feedback + * @package Feedback */ +namespace Piwik\Plugins\Feedback; + +use Exception; use Piwik\Config; use Piwik\Piwik; use Piwik\Common; -use Piwik\Controller; use Piwik\IP; use Piwik\Mail; use Piwik\Nonce; @@ -21,14 +23,14 @@ /** * - * @package Piwik_Feedback + * @package Feedback */ -class Piwik_Feedback_Controller extends Controller +class Controller extends \Piwik\Controller { function index() { $view = new View('@Feedback/index'); - $view->nonce = Nonce::getNonce('Piwik_Feedback.sendFeedback', 3600); + $view->nonce = Nonce::getNonce('Feedback.sendFeedback', 3600); echo $view->render(); } @@ -60,10 +62,10 @@ function sendFeedback() if (preg_match('/https?:/i', $body)) { throw new Exception(Piwik_TranslateException('Feedback_ExceptionNoUrls')); } - if (!Nonce::verifyNonce('Piwik_Feedback.sendFeedback', $nonce)) { + if (!Nonce::verifyNonce('Feedback.sendFeedback', $nonce)) { throw new Exception(Piwik_TranslateException('General_ExceptionNonceMismatch')); } - Nonce::discardNonce('Piwik_Feedback.sendFeedback'); + Nonce::discardNonce('Feedback.sendFeedback'); $mail = new Mail(); $mail->setFrom(Common::unsanitizeInputValue($email)); diff --git a/plugins/Feedback/Feedback.php b/plugins/Feedback/Feedback.php index 522c09fe96d..48f8d297f40 100644 --- a/plugins/Feedback/Feedback.php +++ b/plugins/Feedback/Feedback.php @@ -6,15 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Feedback + * @package Feedback */ -use Piwik\Plugin; +namespace Piwik\Plugins\Feedback; + /** * - * @package Piwik_Feedback + * @package Feedback */ -class Piwik_Feedback extends Plugin +class Feedback extends \Piwik\Plugin { /** diff --git a/plugins/Goals/API.php b/plugins/Goals/API.php index 3eb1a62e281..c80ade9ac35 100644 --- a/plugins/Goals/API.php +++ b/plugins/Goals/API.php @@ -6,8 +6,11 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Goals + * @package Goals */ +namespace Piwik\Plugins\Goals; + +use Exception; use Piwik\Archive; use Piwik\Metrics; use Piwik\Piwik; @@ -17,6 +20,8 @@ use Piwik\Db; use Piwik\Tracker\Cache; use Piwik\Tracker\GoalManager; +use Piwik\Plugins\Goals\Goals; +use Piwik\Plugins\Goals\Archiver; /** * Goals API lets you Manage existing goals, via "updateGoal" and "deleteGoal", create new Goals via "addGoal", @@ -36,14 +41,14 @@ * * See also the documentation about Tracking Goals in Piwik. * - * @package Piwik_Goals + * @package Goals */ -class Piwik_Goals_API +class API { static private $instance = null; /** - * @return Piwik_Goals_API + * @return \Piwik\Plugins\Goals\API */ static public function getInstance() { @@ -199,7 +204,7 @@ public function deleteGoal($idSite, $idGoal) Piwik::checkUserHasAdminAccess($idSite); Db::query("UPDATE " . Common::prefixTable('goal') . " SET deleted = 1 - WHERE idsite = ? + WHERE idsite = ? AND idgoal = ?", array($idSite, $idGoal)); Db::deleteAllRows(Common::prefixTable("log_conversion"), "WHERE idgoal = ?", 100000, array($idGoal)); @@ -215,11 +220,11 @@ protected function getItems($recordName, $idSite, $period, $date, $abandonedCart Piwik::checkUserHasViewAccess($idSite); $recordNameFinal = $recordName; if ($abandonedCarts) { - $recordNameFinal = Piwik_Goals_Archiver::getItemRecordNameAbandonedCart($recordName); + $recordNameFinal = Archiver::getItemRecordNameAbandonedCart($recordName); } $archive = Archive::build($idSite, $period, $date); $dataTable = $archive->getDataTable($recordNameFinal); - + $dataTable->filter('Sort', array(Metrics::INDEX_ECOMMERCE_ITEM_REVENUE)); $dataTable->queueFilter('ReplaceColumnNames'); $dataTable->queueFilter('ReplaceSummaryRowLabel'); @@ -238,7 +243,8 @@ protected function getItems($recordName, $idSite, $period, $date, $abandonedCart $dataTable->queueFilter('ColumnDelete', array('price')); // Enrich the datatable with Product/Categories views, and conversion rates - $customVariables = Piwik_CustomVariables_API::getInstance()->getCustomVariables($idSite, $period, $date, $segment = false, $expanded = false, $_leavePiwikCoreVariables = true); + $customVariables = \Piwik\Plugins\CustomVariables\API::getInstance()->getCustomVariables($idSite, $period, $date, $segment = false, $expanded = false, + $_leavePiwikCoreVariables = true); $mapping = array( 'Goals_ItemsSku' => '_pks', 'Goals_ItemsName' => '_pkn', @@ -295,16 +301,15 @@ protected function renameNotDefinedRow($dataTable, $notDefinedStringPretty) } return; } - $rowNotDefined = $dataTable->getRowFromLabel(Piwik_CustomVariables_Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED); + $rowNotDefined = $dataTable->getRowFromLabel(\Piwik\Plugins\CustomVariables\Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED); if ($rowNotDefined) { $rowNotDefined->setColumn('label', $notDefinedStringPretty); } } - protected function enrichItemsDataTableWithItemsViewMetrics($dataTable, $idSite, $period, $date, $idSubtable) { - $ecommerceViews = Piwik_CustomVariables_API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment = false, $_leavePriceViewedColumn = true); + $ecommerceViews = \Piwik\Plugins\CustomVariables\API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment = false, $_leavePriceViewedColumn = true); // For Product names and SKU reports, and for Category report // Use the Price (tracked on page views) @@ -385,7 +390,7 @@ public function get($idSite, $period, $date, $segment = false, $idGoal = false, $idGoal = self::convertSpecialGoalIds($idGoal); if (empty($columns)) { - $columns = Piwik_Goals::getGoalColumns($idGoal); + $columns = Goals::getGoalColumns($idGoal); if ($idGoal == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) { $columns[] = 'avg_order_revenue'; } @@ -399,7 +404,7 @@ public function get($idSite, $period, $date, $segment = false, $idGoal = false, } $columnsToSelect = array(); foreach ($columns as &$columnName) { - $columnsToSelect[] = Piwik_Goals_Archiver::getRecordName($columnName, $idGoal); + $columnsToSelect[] = Archiver::getRecordName($columnName, $idGoal); } $dataTable = $archive->getDataTableFromNumeric($columnsToSelect); @@ -447,7 +452,7 @@ protected function getNumeric($idSite, $period, $date, $segment, $toFetch) */ public function getConversions($idSite, $period, $date, $segment = false, $idGoal = false) { - return $this->getNumeric($idSite, $period, $date, $segment, Piwik_Goals_Archiver::getRecordName('nb_conversions', $idGoal)); + return $this->getNumeric($idSite, $period, $date, $segment, Archiver::getRecordName('nb_conversions', $idGoal)); } /** @@ -455,7 +460,7 @@ public function getConversions($idSite, $period, $date, $segment = false, $idGoa */ public function getNbVisitsConverted($idSite, $period, $date, $segment = false, $idGoal = false) { - return $this->getNumeric($idSite, $period, $date, $segment, Piwik_Goals_Archiver::getRecordName('nb_visits_converted', $idGoal)); + return $this->getNumeric($idSite, $period, $date, $segment, Archiver::getRecordName('nb_visits_converted', $idGoal)); } /** @@ -463,7 +468,7 @@ public function getNbVisitsConverted($idSite, $period, $date, $segment = false, */ public function getConversionRate($idSite, $period, $date, $segment = false, $idGoal = false) { - return $this->getNumeric($idSite, $period, $date, $segment, Piwik_Goals_Archiver::getRecordName('conversion_rate', $idGoal)); + return $this->getNumeric($idSite, $period, $date, $segment, Archiver::getRecordName('conversion_rate', $idGoal)); } /** @@ -471,7 +476,7 @@ public function getConversionRate($idSite, $period, $date, $segment = false, $id */ public function getRevenue($idSite, $period, $date, $segment = false, $idGoal = false) { - return $this->getNumeric($idSite, $period, $date, $segment, Piwik_Goals_Archiver::getRecordName('revenue', $idGoal)); + return $this->getNumeric($idSite, $period, $date, $segment, Archiver::getRecordName('revenue', $idGoal)); } /** @@ -498,7 +503,7 @@ protected function getGoalSpecificDataTable($recordName, $idSite, $period, $date $realGoalId = $idGoal != true ? false : self::convertSpecialGoalIds($idGoal); // get the data table - $dataTable = $archive->getDataTable(Piwik_Goals_Archiver::getRecordName($recordName, $realGoalId), $idSubtable = null); + $dataTable = $archive->getDataTable(Archiver::getRecordName($recordName, $realGoalId), $idSubtable = null); $dataTable->queueFilter('ReplaceColumnNames'); return $dataTable; @@ -519,7 +524,7 @@ protected function getGoalSpecificDataTable($recordName, $idSite, $period, $date public function getDaysToConversion($idSite, $period, $date, $segment = false, $idGoal = false) { $dataTable = $this->getGoalSpecificDataTable( - Piwik_Goals_Archiver::DAYS_UNTIL_CONV_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); + Archiver::DAYS_UNTIL_CONV_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); $dataTable->queueFilter('Sort', array('label', 'asc', true)); $dataTable->queueFilter( @@ -543,7 +548,7 @@ public function getDaysToConversion($idSite, $period, $date, $segment = false, $ public function getVisitsUntilConversion($idSite, $period, $date, $segment = false, $idGoal = false) { $dataTable = $this->getGoalSpecificDataTable( - Piwik_Goals_Archiver::VISITS_UNTIL_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); + Archiver::VISITS_UNTIL_RECORD_NAME, $idSite, $period, $date, $segment, $idGoal); $dataTable->queueFilter('Sort', array('label', 'asc', true)); $dataTable->queueFilter( diff --git a/plugins/Goals/Archiver.php b/plugins/Goals/Archiver.php index cad582453aa..ae0cbf3b079 100644 --- a/plugins/Goals/Archiver.php +++ b/plugins/Goals/Archiver.php @@ -6,17 +6,20 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Goals + * @package Goals */ +namespace Piwik\Plugins\Goals; + use Piwik\DataAccess\LogAggregator; use Piwik\Metrics; use Piwik\DataTable; use Piwik\DataArray; use Piwik\PluginsArchiver; use Piwik\Tracker\GoalManager; +use Piwik\Plugins\Goals\Goals; -class Piwik_Goals_Archiver extends PluginsArchiver +class Archiver extends PluginsArchiver { const VISITS_UNTIL_RECORD_NAME = 'visits_until_conv'; const DAYS_UNTIL_CONV_RECORD_NAME = 'days_until_conv'; @@ -120,7 +123,7 @@ protected function archiveGeneralGoalMetrics() unset($row['label']); $values = array(); - foreach($conversionMetrics as $field => $statement) { + foreach ($conversionMetrics as $field => $statement) { $values[$field] = $row[$field]; } $goals->sumMetrics($idGoal, $values); @@ -173,7 +176,7 @@ protected function getConversionsNumericMetrics(DataArray $goals) $recordName = self::getRecordName($metricName, $idGoal); $numericRecords[$recordName] = $value; } - if(!empty($array[Metrics::INDEX_GOAL_NB_VISITS_CONVERTED])) { + if (!empty($array[Metrics::INDEX_GOAL_NB_VISITS_CONVERTED])) { $conversion_rate = $this->getConversionRate($array[Metrics::INDEX_GOAL_NB_VISITS_CONVERTED]); $recordName = self::getRecordName('conversion_rate', $idGoal); $numericRecords[$recordName] = $conversion_rate; @@ -330,8 +333,9 @@ protected function cleanupRowGetLabel(&$row, $currentField) } $label = "Value not defined"; // Product Name/Category not defined" - if (class_exists('Piwik_CustomVariables')) { - $label = Piwik_CustomVariables_Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED; + //TODOA : working? + if (class_exists('Piwik\Plugins\CustomVariables\CustomVariables')) { + $label = \Piwik\Plugins\CustomVariables\Archiver::LABEL_CUSTOM_VALUE_NOT_DEFINED; } } @@ -403,7 +407,7 @@ public function archivePeriod() $fieldsToSum = array(); foreach ($goalIdsToSum as $goalId) { - $metricsToSum = Piwik_Goals::getGoalColumns($goalId); + $metricsToSum = Goals::getGoalColumns($goalId); unset($metricsToSum[array_search('conversion_rate', $metricsToSum)]); foreach ($metricsToSum as $metricName) { $fieldsToSum[] = self::getRecordName($metricName, $goalId); @@ -419,13 +423,13 @@ public function archivePeriod() // sum up the visits to conversion data table & the days to conversion data table $this->getProcessor()->aggregateDataTableReports(array( - self::getRecordName(self::VISITS_UNTIL_RECORD_NAME, $goalId), - self::getRecordName(self::DAYS_UNTIL_CONV_RECORD_NAME, $goalId))); + self::getRecordName(self::VISITS_UNTIL_RECORD_NAME, $goalId), + self::getRecordName(self::DAYS_UNTIL_CONV_RECORD_NAME, $goalId))); } // sum up goal overview reports $this->getProcessor()->aggregateDataTableReports(array( - self::getRecordName(self::VISITS_UNTIL_RECORD_NAME), - self::getRecordName(self::DAYS_UNTIL_CONV_RECORD_NAME))); + self::getRecordName(self::VISITS_UNTIL_RECORD_NAME), + self::getRecordName(self::DAYS_UNTIL_CONV_RECORD_NAME))); } } \ No newline at end of file diff --git a/plugins/Goals/Controller.php b/plugins/Goals/Controller.php index 17a5e38fae1..c9e10f40747 100644 --- a/plugins/Goals/Controller.php +++ b/plugins/Goals/Controller.php @@ -6,24 +6,28 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Goals + * @package Goals */ +namespace Piwik\Plugins\Goals; + +use Exception; use Piwik\API\Request; use Piwik\DataTable\Filter\AddColumnsProcessedMetricsGoal; use Piwik\Piwik; use Piwik\Common; use Piwik\DataTable; -use Piwik\Controller; use Piwik\FrontController; use Piwik\View\ReportsByDimension; use Piwik\ViewDataTable; use Piwik\View; +use Piwik\Plugins\Goals\Goals; +use Piwik\Plugins\Referers\API as ReferersAPI; /** * - * @package Piwik_Goals + * @package Goals */ -class Piwik_Goals_Controller extends Controller +class Controller extends \Piwik\Controller { const CONVERSION_RATE_PRECISION = 1; @@ -58,7 +62,7 @@ public function __construct() { parent::__construct(); $this->idSite = Common::getRequestVar('idSite', null, 'int'); - $this->goals = Piwik_Goals_API::getInstance()->getGoals($this->idSite); + $this->goals = API::getInstance()->getGoals($this->idSite); foreach ($this->goals as &$goal) { $goal['name'] = Common::sanitizeInputValue($goal['name']); if (isset($goal['pattern'])) { @@ -137,10 +141,10 @@ protected function getGoalReportView($idGoal = false) // conversion rate for new and returning visitors $segment = 'visitorType==returning,visitorType==returningCustomer'; - $conversionRateReturning = Piwik_Goals_API::getInstance()->getConversionRate($this->idSite, Common::getRequestVar('period'), Common::getRequestVar('date'), $segment, $idGoal); + $conversionRateReturning = API::getInstance()->getConversionRate($this->idSite, Common::getRequestVar('period'), Common::getRequestVar('date'), $segment, $idGoal); $view->conversion_rate_returning = $this->formatConversionRate($conversionRateReturning); $segment = 'visitorType==new'; - $conversionRateNew = Piwik_Goals_API::getInstance()->getConversionRate($this->idSite, Common::getRequestVar('period'), Common::getRequestVar('date'), $segment, $idGoal); + $conversionRateNew = API::getInstance()->getConversionRate($this->idSite, Common::getRequestVar('period'), Common::getRequestVar('date'), $segment, $idGoal); $view->conversion_rate_new = $this->formatConversionRate($conversionRateNew); $view->goalReportsByDimension = $this->getGoalReportsByDimensionTable( $view->nb_conversions, isset($ecommerce), !empty($view->cart_nb_conversions)); @@ -150,7 +154,7 @@ protected function getGoalReportView($idGoal = false) public function index() { $view = $this->getOverviewView(); - + // unsanitize goal names and other text data (not done in API so as not to break // any other code/cause security issues) $goals = $this->goals; @@ -161,7 +165,7 @@ public function index() } } $view->goalsJSON = Common::json_encode($goals); - + $view->userCanEditGoals = Piwik::isUserHasAdminAccess($this->idSite); $view->ecommerceEnabled = $this->site->isEcommerceEnabled(); $view->displayFullReport = true; @@ -294,7 +298,6 @@ public function getEvolutionGraph($fetch = false, array $columns = array(), $idG return $this->renderView($view, $fetch); } - protected function getTopDimensions($idGoal) { $columnNbConversions = 'goal_' . $idGoal . '_nb_conversions'; @@ -310,7 +313,7 @@ protected function getTopDimensions($idGoal) $keywordNotDefinedString = ''; if (\Piwik\PluginsManager::getInstance()->isPluginActivated('Referers')) { - $keywordNotDefinedString = Piwik_Referers_API::getKeywordNotDefinedString(); + $keywordNotDefinedString = ReferersAPI::getKeywordNotDefinedString(); $topDimensionsToLoad += array( 'keyword' => 'Referers.getKeywords', 'website' => 'Referers.getWebsites', @@ -436,12 +439,12 @@ private function getGoalReportsByDimensionTable($conversions, $ecommerce = false $customParams['idGoal'] = '0'; // NOTE: Must be string! Otherwise Piwik_View_HtmlTable_Goals fails. } - $allReports = Piwik_Goals::getReportsWithGoalMetrics(); + $allReports = Goals::getReportsWithGoalMetrics(); foreach ($allReports as $category => $reports) { $categoryText = Piwik_Translate('Goals_ViewGoalsBy', $category); foreach ($reports as $report) { $customParams['viewDataTable'] = 'tableGoals'; - if(in_array($report['action'], array('getVisitsUntilConversion', 'getDaysToConversion'))) { + if (in_array($report['action'], array('getVisitsUntilConversion', 'getDaysToConversion'))) { $customParams['viewDataTable'] = 'table'; } @@ -453,16 +456,16 @@ private function getGoalReportsByDimensionTable($conversions, $ecommerce = false return $goalReportsByDimension->render(); } - - // + + // // Report rendering actions - // + // public function getItemsSku($fetch = false) { return ViewDataTable::renderReport($this->pluginName, __FUNCTION__, $fetch); } - + public function getItemsName($fetch = false) { return ViewDataTable::renderReport($this->pluginName, __FUNCTION__, $fetch); diff --git a/plugins/Goals/Goals.php b/plugins/Goals/Goals.php index 4dc4685c59a..2d3bd0de27d 100644 --- a/plugins/Goals/Goals.php +++ b/plugins/Goals/Goals.php @@ -6,23 +6,26 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Goals + * @package Goals */ +namespace Piwik\Plugins\Goals; + use Piwik\ArchiveProcessor; use Piwik\Piwik; use Piwik\Common; +use Piwik\Plugins\Goals\API; +use Piwik\Plugins\Goals\Archiver; use Piwik\Tracker\GoalManager; use Piwik\TranslationWriter; -use Piwik\Plugin; use Piwik\Site; use Piwik\WidgetsList; use Piwik\Db; /** * - * @package Piwik_Goals + * @package Goals */ -class Piwik_Goals extends Plugin +class Goals extends \Piwik\Plugin { protected $ecommerceReports = array( array('Goals_ProductSKU', 'Goals', 'getItemsSku'), @@ -85,17 +88,17 @@ public function getInformation() public function getListHooksRegistered() { $hooks = array( - 'AssetManager.getJsFiles' => 'getJsFiles', - 'AssetManager.getCssFiles' => 'getCssFiles', - 'Common.fetchWebsiteAttributes' => 'fetchGoalsFromDb', - 'ArchiveProcessing_Day.compute' => 'archiveDay', - 'ArchiveProcessing_Period.compute' => 'archivePeriod', - 'API.getReportMetadata.end' => 'getReportMetadata', - 'API.getSegmentsMetadata' => 'getSegmentsMetadata', - 'WidgetsList.add' => 'addWidgets', - 'Menu.add' => 'addMenus', - 'SitesManager.deleteSite' => 'deleteSiteGoals', - 'Goals.getReportsWithGoalMetrics' => 'getActualReportsWithGoalMetrics', + 'AssetManager.getJsFiles' => 'getJsFiles', + 'AssetManager.getCssFiles' => 'getCssFiles', + 'Common.fetchWebsiteAttributes' => 'fetchGoalsFromDb', + 'ArchiveProcessing_Day.compute' => 'archiveDay', + 'ArchiveProcessing_Period.compute' => 'archivePeriod', + 'API.getReportMetadata.end' => 'getReportMetadata', + 'API.getSegmentsMetadata' => 'getSegmentsMetadata', + 'WidgetsList.add' => 'addWidgets', + 'Menu.add' => 'addMenus', + 'SitesManager.deleteSite' => 'deleteSiteGoals', + 'Goals.getReportsWithGoalMetrics' => 'getActualReportsWithGoalMetrics', 'ViewDataTable.getReportDisplayProperties' => 'getReportDisplayProperties', // TODO: ViewDataTable should get ALL once ); return $hooks; @@ -153,7 +156,7 @@ public function getReportMetadata(&$reports, $info) // If only one website is selected, we add the Goal metrics if (count($idSites) == 1) { $idSite = reset($idSites); - $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); + $goals = API::getInstance()->getGoals($idSite); // Add overall visits to conversion report $reports[] = array( @@ -350,7 +353,6 @@ public function getReportMetadata(&$reports, $info) } } } - } static public function getProductReportColumns() @@ -412,7 +414,7 @@ public function getCssFiles(&$cssFiles) public function fetchGoalsFromDb(&$array, $idSite) { // add the 'goal' entry in the website array - $array['goals'] = Piwik_Goals_API::getInstance()->getGoals($idSite); + $array['goals'] = API::getInstance()->getGoals($idSite); } public function addWidgets() @@ -431,7 +433,7 @@ public function addWidgets() // Goals widgets WidgetsList::add('Goals_Goals', 'Goals_GoalsOverview', 'Goals', 'widgetGoalsOverview'); - $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); + $goals = API::getInstance()->getGoals($idSite); if (count($goals) > 0) { foreach ($goals as $goal) { WidgetsList::add('Goals_Goals', Common::sanitizeInputValue($goal['name']), 'Goals', 'widgetGoalReport', array('idGoal' => $goal['idgoal'])); @@ -442,7 +444,7 @@ public function addWidgets() function addMenus() { $idSite = Common::getRequestVar('idSite', null, 'int'); - $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); + $goals = API::getInstance()->getGoals($idSite); $mainGoalMenu = $this->getGoalCategoryName($idSite); $site = new Site($idSite); if (count($goals) == 0) { @@ -487,8 +489,8 @@ protected function getGoalCategoryName($idSite) */ public function archiveDay(ArchiveProcessor\Day $archiveProcessor) { - $archiving = new Piwik_Goals_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archiveDay(); } } @@ -499,12 +501,12 @@ public function archiveDay(ArchiveProcessor\Day $archiveProcessor) */ public function archivePeriod(ArchiveProcessor\Period $archiveProcessor) { - $archiving = new Piwik_Goals_Archiver($archiveProcessor); - if($archiving->shouldArchive()) { + $archiving = new Archiver($archiveProcessor); + if ($archiving->shouldArchive()) { $archiving->archivePeriod(); } } - + public function getReportDisplayProperties(&$properties) { $properties['Goals.getItemsSku'] = $this->getDisplayPropertiesForGetItemsSku(); @@ -513,86 +515,86 @@ public function getReportDisplayProperties(&$properties) $properties['Goals.getVisitsUntilConversion'] = $this->getDisplayPropertiesForGetVisitsUntilConversion(); $properties['Goals.getDaysToConversion'] = $this->getDisplayPropertiesForGetDaysToConversion(); } - + private function getDisplayPropertiesForGetItemsSku() { return $this->getDisplayPropertiesForItemsReport(Piwik_Translate('Goals_ProductSKU')); } - + private function getDisplayPropertiesForGetItemsName() { return $this->getDisplayPropertiesForItemsReport(Piwik_Translate('Goals_ProductName')); } - + private function getDisplayPropertiesForGetItemsCategory() { return $this->getDisplayPropertiesForItemsReport(Piwik_Translate('Goals_ProductCategory')); } - + private function getDisplayPropertiesForGetVisitsUntilConversion() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'show_table_all_columns' => false, - 'columns_to_display' => array('label', 'nb_conversions'), - 'filter_sort_column' => 'label', - 'filter_sort_order' => 'asc', - 'translations' => array( - 'label' => Piwik_Translate('Goals_VisitsUntilConv'), + 'show_table_all_columns' => false, + 'columns_to_display' => array('label', 'nb_conversions'), + 'filter_sort_column' => 'label', + 'filter_sort_order' => 'asc', + 'translations' => array( + 'label' => Piwik_Translate('Goals_VisitsUntilConv'), 'nb_conversions' => Piwik_Translate('Goals_ColumnConversions'), ), - 'filter_limit' => count(Piwik_Goals_Archiver::$visitCountRanges), - 'show_offset_information' => false, - 'show_pagination_control' => false, - 'show_all_views_icons' => false + 'filter_limit' => count(Archiver::$visitCountRanges), + 'show_offset_information' => false, + 'show_pagination_control' => false, + 'show_all_views_icons' => false ); } - + private function getDisplayPropertiesForGetDaysToConversion() { return array( - 'show_search' => false, + 'show_search' => false, 'show_exclude_low_population' => false, - 'show_table_all_columns' => false, - 'columns_to_display' => array('label', 'nb_conversions'), - 'filter_sort_column' => 'label', - 'filter_sort_order' => 'asc', - 'translations' => array( - 'label' => Piwik_Translate('Goals_DaysToConv'), + 'show_table_all_columns' => false, + 'columns_to_display' => array('label', 'nb_conversions'), + 'filter_sort_column' => 'label', + 'filter_sort_order' => 'asc', + 'translations' => array( + 'label' => Piwik_Translate('Goals_DaysToConv'), 'nb_conversions' => Piwik_Translate('Goals_ColumnConversions'), ), - 'filter_limit' => count(Piwik_Goals_Archiver::$daysToConvRanges), - 'show_all_views_icons' => false, - 'show_offset_information' => false, - 'show_pagination_control' => false, + 'filter_limit' => count(Archiver::$daysToConvRanges), + 'show_all_views_icons' => false, + 'show_offset_information' => false, + 'show_pagination_control' => false, ); } - + private function getDisplayPropertiesForItemsReport($label) { $idSite = Common::getRequestVar('idSite'); - + $moneyColumns = array('revenue', 'avg_price'); $prettifyMoneyColumns = array( 'ColumnCallbackReplace', array($moneyColumns, '\Piwik\Piwik::getPrettyMoney', array($idSite))); - + $result = array( - 'show_ecommerce' => true, - 'show_all_views_icons' => false, - 'show_table' => false, + 'show_ecommerce' => true, + 'show_all_views_icons' => false, + 'show_table' => false, 'show_exclude_low_population' => false, - 'show_table_all_columns' => false, - 'filter_limit' => 10, - 'translations' => array('label' => $label), - 'filter_sort_column' => 'revenue', - 'filter_sort_order' => 'desc', - 'filters' => array($prettifyMoneyColumns) + 'show_table_all_columns' => false, + 'filter_limit' => 10, + 'translations' => array('label' => $label), + 'filter_sort_column' => 'revenue', + 'filter_sort_order' => 'desc', + 'filters' => array($prettifyMoneyColumns) ); - + // set columns/translations which differ based on viewDataTable TODO: shouldn't have to do this check... amount of reports should be dynamic, but metadata should be static - $columns = Piwik_Goals::getProductReportColumns(); - + $columns = Goals::getProductReportColumns(); + $abandonedCart = Common::getRequestVar('viewDataTable', 'ecommerceOrder', 'string') == 'ecommerceAbandonedCart'; if ($abandonedCart) { $columns['abandoned_carts'] = Piwik_Translate('General_AbandonedCarts'); @@ -601,13 +603,13 @@ private function getDisplayPropertiesForItemsReport($label) $columns['avg_quantity'] = Piwik_Translate('Goals_LeftInCart', Piwik_Translate('General_AverageQuantity')); unset($columns['orders']); unset($columns['conversion_rate']); - + $result['request_parameters_to_modify'] = array('abandonedCarts' => '1'); } - + $result['translations'] = array_merge(array('label' => $label), $columns); $result['columns_to_display'] = array_keys($result['translations']); - + // set metrics documentation in normal ecommerce report if (!$abandonedCart) { $result['metrics_documentation'] = array( @@ -621,10 +623,10 @@ private function getDisplayPropertiesForItemsReport($label) 'conversion_rate' => Piwik_Translate('Goals_ColumnConversionRateProductDocumentation', $label), ); } - + $result['custom_parameters']['viewDataTable'] = $abandonedCart ? Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART : Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER; - + return $result; } } diff --git a/plugins/ImageGraph/API.php b/plugins/ImageGraph/API.php index dafd9d93998..17c9c760c7a 100644 --- a/plugins/ImageGraph/API.php +++ b/plugins/ImageGraph/API.php @@ -6,12 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph + * @package ImageGraph */ +namespace Piwik\Plugins\ImageGraph; + use Piwik\Period; use Piwik\Piwik; use Piwik\Common; use Piwik\Translate; +use Piwik\Plugins\API\API as MetaAPI; +use Piwik\Plugins\ImageGraph\StaticGraph; /** * The ImageGraph.get API call lets you generate beautiful static PNG Graphs for any existing Piwik report. @@ -24,9 +28,9 @@ * * See also How to embed static Image Graphs? for more information. * - * @package Piwik_ImageGraph + * @package ImageGraph */ -class Piwik_ImageGraph_API +class API { const FILENAME_KEY = 'filename'; const TRUNCATE_KEY = 'truncate'; @@ -36,31 +40,31 @@ class Piwik_ImageGraph_API const MAX_HEIGHT = 2048; static private $DEFAULT_PARAMETERS = array( - Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE => array( + StaticGraph::GRAPH_TYPE_BASIC_LINE => array( self::FILENAME_KEY => 'BasicLine', self::TRUNCATE_KEY => 6, self::WIDTH_KEY => 1044, self::HEIGHT_KEY => 290, ), - Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR => array( + StaticGraph::GRAPH_TYPE_VERTICAL_BAR => array( self::FILENAME_KEY => 'BasicBar', self::TRUNCATE_KEY => 6, self::WIDTH_KEY => 1044, self::HEIGHT_KEY => 290, ), - Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR => array( + StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR => array( self::FILENAME_KEY => 'HorizontalBar', self::TRUNCATE_KEY => null, // horizontal bar graphs are dynamically truncated self::WIDTH_KEY => 800, self::HEIGHT_KEY => 290, ), - Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_3D_PIE => array( + StaticGraph::GRAPH_TYPE_3D_PIE => array( self::FILENAME_KEY => '3DPie', self::TRUNCATE_KEY => 5, self::WIDTH_KEY => 1044, self::HEIGHT_KEY => 290, ), - Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_PIE => array( + StaticGraph::GRAPH_TYPE_BASIC_PIE => array( self::FILENAME_KEY => 'BasicPie', self::TRUNCATE_KEY => 5, self::WIDTH_KEY => 1044, @@ -71,11 +75,11 @@ class Piwik_ImageGraph_API static private $DEFAULT_GRAPH_TYPE_OVERRIDE = array( 'UserSettings_getPlugin' => array( false // override if !$isMultiplePeriod - => Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR, + => StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR, ), 'Referers_getRefererType' => array( false // override if !$isMultiplePeriod - => Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR, + => StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR, ), ); @@ -100,7 +104,7 @@ class Piwik_ImageGraph_API static private $instance = null; /** - * @return Piwik_ImageGraph_API + * @return \Piwik\Plugins\ImageGraph\API */ static public function getInstance() { @@ -118,29 +122,31 @@ public function get( $apiModule, $apiAction, $graphType = false, - $outputType = Piwik_ImageGraph_API::GRAPH_OUTPUT_INLINE, + $outputType = API::GRAPH_OUTPUT_INLINE, $columns = false, $labels = false, $showLegend = true, $width = false, $height = false, - $fontSize = Piwik_ImageGraph_API::DEFAULT_FONT_SIZE, + $fontSize = API::DEFAULT_FONT_SIZE, $legendFontSize = false, $aliasedGraph = true, $idGoal = false, $colors = false, - $textColor = Piwik_ImageGraph_API::DEFAULT_TEXT_COLOR, - $backgroundColor = Piwik_ImageGraph_API::DEFAULT_BACKGROUND_COLOR, - $gridColor = Piwik_ImageGraph_API::DEFAULT_GRID_COLOR, + $textColor = API::DEFAULT_TEXT_COLOR, + $backgroundColor = API::DEFAULT_BACKGROUND_COLOR, + $gridColor = API::DEFAULT_GRID_COLOR, $idSubtable = false, $legendAppendMetric = true, $segment = false - ) { + ) + { Piwik::checkUserHasViewAccess($idSite); // Health check - should we also test for GD2 only? if (!Piwik::isGdExtensionEnabled()) { - throw new Exception('Error: To create graphs in Piwik, please enable GD php extension (with Freetype support) in php.ini, and restart your web server.'); + throw new \Exception('Error: To create graphs in Piwik, please enable GD php extension (with Freetype support) in php.ini, + and restart your web server.'); } $useUnicodeFont = array( @@ -162,7 +168,7 @@ public function get( $apiParameters = array('idGoal' => $idGoal); } // Fetch the metadata for given api-action - $metadata = Piwik_API_API::getInstance()->getMetadata( + $metadata = MetaAPI::getInstance()->getMetadata( $idSite, $apiModule, $apiAction, $apiParameters, $languageLoaded, $period, $date, $hideMetricsDoc = false, $showSubtableReports = true); if (!$metadata) { @@ -184,12 +190,12 @@ public function get( if (empty($graphType)) { if ($isMultiplePeriod) { - $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE; + $graphType = StaticGraph::GRAPH_TYPE_BASIC_LINE; } else { if ($constantRowsCount) { - $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR; + $graphType = StaticGraph::GRAPH_TYPE_VERTICAL_BAR; } else { - $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR; + $graphType = StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR; } } @@ -198,7 +204,7 @@ public function get( $graphType = self::$DEFAULT_GRAPH_TYPE_OVERRIDE[$reportUniqueId][$isMultiplePeriod]; } } else { - $availableGraphTypes = Piwik_ImageGraph_StaticGraph::getAvailableStaticGraphTypes(); + $availableGraphTypes = StaticGraph::getAvailableStaticGraphTypes(); if (!in_array($graphType, $availableGraphTypes)) { throw new Exception( Piwik_TranslateException( @@ -255,8 +261,8 @@ public function get( // sort and truncate filters $defaultFilterTruncate = self::$DEFAULT_PARAMETERS[$graphType][self::TRUNCATE_KEY]; switch ($graphType) { - case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_3D_PIE: - case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_PIE: + case StaticGraph::GRAPH_TYPE_3D_PIE: + case StaticGraph::GRAPH_TYPE_BASIC_PIE: if (count($ordinateColumns) > 1) { // pChart doesn't support multiple series on pie charts @@ -267,8 +273,8 @@ public function get( $this->setFilterTruncate($defaultFilterTruncate); break; - case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR: - case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE: + case StaticGraph::GRAPH_TYPE_VERTICAL_BAR: + case StaticGraph::GRAPH_TYPE_BASIC_LINE: if (!$isMultiplePeriod && !$constantRowsCount) { $this->setFilterTruncate($defaultFilterTruncate); @@ -294,7 +300,7 @@ public function get( } } - $processedReport = Piwik_API_API::getInstance()->getRowEvolution( + $processedReport = MetaAPI::getInstance()->getRowEvolution( $idSite, $period, $date, @@ -351,7 +357,7 @@ public function get( $ordinateLabels[$plottedMetric] = $processedReport['label'] . ' (' . $metrics[$plottedMetric]['name'] . ')'; } } else { - $processedReport = Piwik_API_API::getInstance()->getProcessedReport( + $processedReport = MetaAPI::getInstance()->getProcessedReport( $idSite, $period, $date, @@ -436,7 +442,6 @@ public function get( $ordinateSeries[$column][] = $parsedOrdinateValue; } - } else { foreach ($ordinateColumns as $column) { $ordinateSeries[$column][] = 0; @@ -453,7 +458,7 @@ public function get( } //Setup the graph - $graph = Piwik_ImageGraph_StaticGraph::factory($graphType); + $graph = StaticGraph::factory($graphType); $graph->setWidth($width); $graph->setHeight($height); $graph->setFont($font); @@ -479,10 +484,9 @@ public function get( // render graph $graph->renderGraph(); - } catch (Exception $e) { - $graph = new Piwik_ImageGraph_StaticGraph_Exception(); + $graph = new \Piwik\Plugins\ImageGraph\StaticGraph\Exception(); $graph->setWidth($width); $graph->setHeight($height); $graph->setFont($font); diff --git a/plugins/ImageGraph/Controller.php b/plugins/ImageGraph/Controller.php index a36d520b8ed..19925fdc41c 100644 --- a/plugins/ImageGraph/Controller.php +++ b/plugins/ImageGraph/Controller.php @@ -1,9 +1,4 @@ getReportMetadata($idSite, $period, $date); + $reports = API::getInstance()->getReportMetadata($idSite, $period, $date); $plot = array(); foreach ($reports as $report) { if (!empty($report['imageGraphUrl'])) { @@ -53,7 +54,7 @@ public function testAllSizes() $date = Common::getRequestVar('date', 'today', 'string'); $_GET['token_auth'] = Piwik::getCurrentUserTokenAuth(); - $availableReports = Piwik_API_API::getInstance()->getReportMetadata($this->idSite, $period, $date); + $availableReports = API::getInstance()->getReportMetadata($this->idSite, $period, $date); $view->availableReports = $availableReports; $view->graphTypes = array( '', // default graph type @@ -73,5 +74,4 @@ public function testAllSizes() ); echo $view->render(); } - } diff --git a/plugins/ImageGraph/ImageGraph.php b/plugins/ImageGraph/ImageGraph.php index 6181877fb7e..fc992a34251 100644 --- a/plugins/ImageGraph/ImageGraph.php +++ b/plugins/ImageGraph/ImageGraph.php @@ -1,12 +1,4 @@ 'Piwik_ImageGraph_StaticGraph_Evolution', - self::GRAPH_TYPE_VERTICAL_BAR => 'Piwik_ImageGraph_StaticGraph_VerticalBar', - self::GRAPH_TYPE_HORIZONTAL_BAR => 'Piwik_ImageGraph_StaticGraph_HorizontalBar', - self::GRAPH_TYPE_BASIC_PIE => 'Piwik_ImageGraph_StaticGraph_Pie', - self::GRAPH_TYPE_3D_PIE => 'Piwik_ImageGraph_StaticGraph_3DPie', + self::GRAPH_TYPE_BASIC_LINE => 'Evolution', + self::GRAPH_TYPE_VERTICAL_BAR => 'VerticalBar', + self::GRAPH_TYPE_HORIZONTAL_BAR => 'HorizontalBar', + self::GRAPH_TYPE_BASIC_PIE => 'Pie', + self::GRAPH_TYPE_3D_PIE => 'Pie3D', ); const ABSCISSA_SERIE_NAME = 'ABSCISSA'; @@ -70,9 +76,9 @@ abstract public function renderGraph(); /** * Return the StaticGraph according to the static graph type $graphType * - * @throws exception If the static graph type is unknown + * @throws Exception If the static graph type is unknown * @param string $graphType - * @return Piwik_ImageGraph_StaticGraph + * @return \Piwik\Plugins\ImageGraph\StaticGraph */ public static function factory($graphType) { @@ -138,7 +144,7 @@ public function setHeight($height) public function setFontSize($fontSize) { if (!is_numeric($fontSize)) { - $fontSize = Piwik_ImageGraph_API::DEFAULT_FONT_SIZE; + $fontSize = API::DEFAULT_FONT_SIZE; } $this->fontSize = $fontSize; } @@ -263,8 +269,8 @@ protected function initpImage() $this->pImage->setFontProperties( array_merge( array( - 'FontName' => $this->font, - 'FontSize' => $this->fontSize, + 'FontName' => $this->font, + 'FontSize' => $this->fontSize, ), $this->textColor ) diff --git a/plugins/ImageGraph/StaticGraph/3DPie.php b/plugins/ImageGraph/StaticGraph/3DPie.php index 62252c0059e..4a7ab3ef06c 100644 --- a/plugins/ImageGraph/StaticGraph/3DPie.php +++ b/plugins/ImageGraph/StaticGraph/3DPie.php @@ -6,14 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; + /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_3DPie extends Piwik_ImageGraph_StaticGraph_PieGraph +class Pie3D extends PieGraph { public function renderGraph() { diff --git a/plugins/ImageGraph/StaticGraph/Evolution.php b/plugins/ImageGraph/StaticGraph/Evolution.php index a4851afaa4a..3bc870b9b63 100644 --- a/plugins/ImageGraph/StaticGraph/Evolution.php +++ b/plugins/ImageGraph/StaticGraph/Evolution.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; +use Piwik\Plugins\ImageGraph\StaticGraph\GridGraph; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_Evolution extends Piwik_ImageGraph_StaticGraph_GridGraph +class Evolution extends GridGraph { public function renderGraph() diff --git a/plugins/ImageGraph/StaticGraph/Exception.php b/plugins/ImageGraph/StaticGraph/Exception.php index 5140c73eb69..0772e603cf7 100644 --- a/plugins/ImageGraph/StaticGraph/Exception.php +++ b/plugins/ImageGraph/StaticGraph/Exception.php @@ -6,15 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; +use Piwik\Plugins\ImageGraph\StaticGraph; +use pData; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_Exception extends Piwik_ImageGraph_StaticGraph +class Exception extends StaticGraph { const MESSAGE_RIGHT_MARGIN = 5; @@ -30,7 +33,6 @@ protected function getDefaultColors() return array(); } - public function setWidth($width) { if (empty($width)) { diff --git a/plugins/ImageGraph/StaticGraph/GridGraph.php b/plugins/ImageGraph/StaticGraph/GridGraph.php index 3efd36bc1ac..026c2952bcd 100644 --- a/plugins/ImageGraph/StaticGraph/GridGraph.php +++ b/plugins/ImageGraph/StaticGraph/GridGraph.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; +use Piwik\Plugins\ImageGraph\StaticGraph; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -abstract class Piwik_ImageGraph_StaticGraph_GridGraph extends Piwik_ImageGraph_StaticGraph +abstract class GridGraph extends StaticGraph { const GRAPHIC_COLOR_KEY = 'GRAPHIC_COLOR'; @@ -413,7 +415,6 @@ protected function truncateLabel($label, $labelWidthLimit, $fontSize = false) } return $label; } - // display min & max values // can not currently be used because pChart's label design is not flexible enough // e.g: it is not possible to remove the box border & the square icon diff --git a/plugins/ImageGraph/StaticGraph/HorizontalBar.php b/plugins/ImageGraph/StaticGraph/HorizontalBar.php index fe4cf5b3b48..64ebf2d4e55 100644 --- a/plugins/ImageGraph/StaticGraph/HorizontalBar.php +++ b/plugins/ImageGraph/StaticGraph/HorizontalBar.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; +use Piwik\Plugins\ImageGraph\StaticGraph\GridGraph; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_HorizontalBar extends Piwik_ImageGraph_StaticGraph_GridGraph +class HorizontalBar extends GridGraph { const INTERLEAVE = 0.30; const PADDING_CHARS = ' '; @@ -173,7 +175,7 @@ public function renderGraph() - $logoHeight / 2 + 1; - if(method_exists($this->pImage, $drawingFunction)) { + if (method_exists($this->pImage, $drawingFunction)) { $this->pImage->$drawingFunction( $gridLeftMarginBeforePadding, $logoYPosition, diff --git a/plugins/ImageGraph/StaticGraph/Pie.php b/plugins/ImageGraph/StaticGraph/Pie.php index bdfbdef9ab4..1626ebd3fc7 100644 --- a/plugins/ImageGraph/StaticGraph/Pie.php +++ b/plugins/ImageGraph/StaticGraph/Pie.php @@ -6,14 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; + +use Piwik\Plugins\ImageGraph\StaticGraph\PieGraph; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_Pie extends Piwik_ImageGraph_StaticGraph_PieGraph +class Pie extends PieGraph { public function renderGraph() { diff --git a/plugins/ImageGraph/StaticGraph/PieGraph.php b/plugins/ImageGraph/StaticGraph/PieGraph.php index a44bf79418d..02e8d6ccecb 100644 --- a/plugins/ImageGraph/StaticGraph/PieGraph.php +++ b/plugins/ImageGraph/StaticGraph/PieGraph.php @@ -6,16 +6,21 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; + +use Piwik\Plugins\ImageGraph\StaticGraph; +use pPie; + require_once PIWIK_INCLUDE_PATH . "/libs/pChart2.1.3/class/pPie.class.php"; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -abstract class Piwik_ImageGraph_StaticGraph_PieGraph extends Piwik_ImageGraph_StaticGraph +abstract class PieGraph extends StaticGraph { const RADIUS_MARGIN = 40; const PIE_RIGHT_MARGIN = 20; diff --git a/plugins/ImageGraph/StaticGraph/VerticalBar.php b/plugins/ImageGraph/StaticGraph/VerticalBar.php index 5bf40df7f81..add00e64234 100644 --- a/plugins/ImageGraph/StaticGraph/VerticalBar.php +++ b/plugins/ImageGraph/StaticGraph/VerticalBar.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ +namespace Piwik\Plugins\ImageGraph\StaticGraph; +use Piwik\Plugins\ImageGraph\StaticGraph\GridGraph; /** * - * @package Piwik_ImageGraph_StaticGraph + * @package StaticGraph */ -class Piwik_ImageGraph_StaticGraph_VerticalBar extends Piwik_ImageGraph_StaticGraph_GridGraph +class VerticalBar extends GridGraph { const INTERLEAVE = 0.10; diff --git a/plugins/Installation/Controller.php b/plugins/Installation/Controller.php index d0207e1ffa5..9160ca4c632 100644 --- a/plugins/Installation/Controller.php +++ b/plugins/Installation/Controller.php @@ -6,10 +6,12 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ +namespace Piwik\Plugins\Installation; + +use Exception; use Piwik\API\Request; -use Piwik\Controller\Admin; use Piwik\DataAccess\ArchiveTableCreator; use Piwik\Db\Adapter; use Piwik\Piwik; @@ -24,32 +26,39 @@ use Piwik\Url; use Piwik\ProxyHeaders; use Piwik\Db; +use Piwik\Plugins\Installation\FormDatabaseSetup; +use Piwik\Plugins\Installation\FormFirstWebsiteSetup; +use Piwik\Plugins\Installation\FormGeneralSetup; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Piwik\Plugins\SitesManager\API as SitesManagerAPI; +use Piwik\Plugins\UsersManager\API as UsersManagerAPI; +use Zend_Db_Adapter_Exception; /** * Installation controller * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_Controller extends Admin +class Controller extends \Piwik\Controller\Admin { // public so plugins can add/delete installation steps public $steps = array( - 'welcome' => 'Installation_Welcome', - 'systemCheck' => 'Installation_SystemCheck', - 'databaseSetup' => 'Installation_DatabaseSetup', - 'databaseCheck' => 'Installation_DatabaseCheck', - 'tablesCreation' => 'Installation_Tables', - 'generalSetup' => 'Installation_SuperUser', - 'firstWebsiteSetup' => 'Installation_SetupWebsite', - 'trackingCode' => 'Installation_JsTag', - 'finished' => 'Installation_Congratulations', + 'welcome' => 'Installation_Welcome', + 'systemCheck' => 'Installation_SystemCheck', + 'databaseSetup' => 'Installation_DatabaseSetup', + 'databaseCheck' => 'Installation_DatabaseCheck', + 'tablesCreation' => 'Installation_Tables', + 'generalSetup' => 'Installation_SuperUser', + 'firstWebsiteSetup' => 'Installation_SetupWebsite', + 'trackingCode' => 'Installation_JsTag', + 'finished' => 'Installation_Congratulations', ); protected $session; public function __construct() { - $this->session = new SessionNamespace('Piwik_Installation'); + $this->session = new SessionNamespace('Installation'); if (!isset($this->session->currentStepDone)) { $this->session->currentStepDone = ''; $this->session->skipThisStep = array(); @@ -87,7 +96,7 @@ function welcome($message = false) // Delete merged js/css files to force regenerations based on updated activated plugin list Piwik::deleteAllCacheOnUpdate(); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/welcome', $this->getInstallationSteps(), __FUNCTION__ @@ -107,7 +116,7 @@ function systemCheck() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/systemCheck', $this->getInstallationSteps(), __FUNCTION__ @@ -147,11 +156,11 @@ function databaseSetup() // case the user hits the back button $this->session->skipThisStep = array( - 'firstWebsiteSetup' => false, - 'trackingCode' => false, + 'firstWebsiteSetup' => false, + 'trackingCode' => false, ); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/databaseSetup', $this->getInstallationSteps(), __FUNCTION__ @@ -160,7 +169,7 @@ function databaseSetup() $view->showNextStep = false; - $form = new Piwik_Installation_FormDatabaseSetup(); + $form = new FormDatabaseSetup(); if ($form->validate()) { try { @@ -187,7 +196,7 @@ function databaseSetup() function databaseCheck() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/databaseCheck', $this->getInstallationSteps(), __FUNCTION__ @@ -246,7 +255,7 @@ function tablesCreation() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/tablesCreation', $this->getInstallationSteps(), __FUNCTION__ @@ -281,8 +290,8 @@ function tablesCreation() Access::getInstance(); Piwik::setUserIsSuperUser(); if ($baseTablesInstalled >= $minimumCountPiwikTables && - count(Piwik_SitesManager_API::getInstance()->getAllSitesId()) > 0 && - count(Piwik_UsersManager_API::getInstance()->getUsers()) > 0 + count(SitesManagerAPI::getInstance()->getAllSitesId()) > 0 && + count(SitesManagerAPI::getInstance()->getUsers()) > 0 ) { $view->showReuseExistingTables = true; // when the user reuses the same tables we skip the website creation step @@ -313,14 +322,14 @@ function generalSetup() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/generalSetup', $this->getInstallationSteps(), __FUNCTION__ ); $this->skipThisStep(__FUNCTION__); - $form = new Piwik_Installation_FormGeneralSetup(); + $form = new FormGeneralSetup(); if ($form->validate()) { $superUserInfos = array( @@ -370,14 +379,14 @@ public function firstWebsiteSetup() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/firstWebsiteSetup', $this->getInstallationSteps(), __FUNCTION__ ); $this->skipThisStep(__FUNCTION__); - $form = new Piwik_Installation_FormFirstWebsiteSetup(); + $form = new FormFirstWebsiteSetup(); if (!isset($this->session->generalSetupSuccessMessage)) { $view->displayGeneralSetupSuccess = true; $this->session->generalSetupSuccessMessage = true; @@ -407,7 +416,6 @@ public function firstWebsiteSetup() } catch (Exception $e) { $view->errorMessage = $e->getMessage(); } - } $view->addForm($form); echo $view->render(); @@ -420,7 +428,7 @@ public function trackingCode() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/trackingCode', $this->getInstallationSteps(), __FUNCTION__ @@ -458,7 +466,7 @@ public function finished() { $this->checkPreviousStepIsValid(__FUNCTION__); - $view = new Piwik_Installation_View( + $view = new View( '@Installation/finished', $this->getInstallationSteps(), __FUNCTION__ @@ -562,7 +570,7 @@ protected function writeConfigFileFromSession() public function saveLanguage() { $language = Common::getRequestVar('language'); - Piwik_LanguagesManager::setLanguageForSession($language); + LanguagesManager::setLanguageForSession($language); Url::redirectToReferer(); } @@ -601,7 +609,7 @@ protected function checkPreviousStepIsValid($currentStep) } } if ($error) { - Piwik_Login_Controller::clearSession(); + \Piwik\Plugins\Login\Controller::clearSession(); $message = Piwik_Translate('Installation_ErrorInvalidState', array('
', '', @@ -693,20 +701,20 @@ public static function getSystemInformation() $directoriesToCheck = array(); - if(!Piwik::isInstalled()) { + if (!Piwik::isInstalled()) { // at install, need /config to be writable (so we can create config.ini.php) $directoriesToCheck[] = '/config/'; } $directoriesToCheck = array_merge($directoriesToCheck, array( - '/tmp/', - '/tmp/templates_c/', - '/tmp/cache/', - '/tmp/assets/', - '/tmp/latest/', - '/tmp/tcpdf/', - '/tmp/sessions/', - )); + '/tmp/', + '/tmp/templates_c/', + '/tmp/cache/', + '/tmp/assets/', + '/tmp/latest/', + '/tmp/tcpdf/', + '/tmp/sessions/', + )); $infos['directories'] = Piwik::checkDirectoriesWritable($directoriesToCheck); @@ -905,7 +913,6 @@ public static function functionExists($functionName) $blacklistFunctions = array_map('strtolower', array_map('trim', explode(',', $blacklist))); return $exists && !in_array($functionName, $blacklistFunctions); } - } return $exists; } diff --git a/plugins/Installation/FormDatabaseSetup.php b/plugins/Installation/FormDatabaseSetup.php index f4d1f992478..a1f58c6c78b 100644 --- a/plugins/Installation/FormDatabaseSetup.php +++ b/plugins/Installation/FormDatabaseSetup.php @@ -6,18 +6,24 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ +namespace Piwik\Plugins\Installation; + use Piwik\Db\Adapter; use Piwik\Piwik; use Piwik\Common; use Piwik\QuickForm2; +use Exception; +use HTML_QuickForm2_DataSource_Array; +use HTML_QuickForm2_Factory; +use Zend_Db_Adapter_Exception; /** * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormDatabaseSetup extends QuickForm2 +class FormDatabaseSetup extends QuickForm2 { function __construct($id = 'databasesetupform', $method = 'post', $attributes = null, $trackSubmit = false) { @@ -26,9 +32,9 @@ function __construct($id = 'databasesetupform', $method = 'post', $attributes = function init() { - HTML_QuickForm2_Factory::registerRule('checkValidFilename', 'Piwik_Installation_FormDatabaseSetup_Rule_checkValidFilename'); + HTML_QuickForm2_Factory::registerRule('checkValidFilename', 'FormDatabaseSetup_Rule_checkValidFilename'); - $checkUserPrivilegesClass = 'Piwik_Installation_FormDatabaseSetup_Rule_checkUserPrivileges'; + $checkUserPrivilegesClass = 'Rule_checkUserPrivileges'; HTML_QuickForm2_Factory::registerRule('checkUserPrivileges', $checkUserPrivilegesClass); $availableAdapters = Adapter::getAdapters(); @@ -44,7 +50,7 @@ function init() $user = $this->addElement('text', 'username') ->setLabel(Piwik_Translate('Installation_DatabaseSetupLogin')); $user->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_DatabaseSetupLogin'))); - $requiredPrivileges = Piwik_Installation_FormDatabaseSetup_Rule_checkUserPrivileges::getRequiredPrivilegesPretty(); + $requiredPrivileges = Rule_checkUserPrivileges::getRequiredPrivilegesPretty(); $user->addRule('checkUserPrivileges', Piwik_Translate('Installation_InsufficientPrivileges', $requiredPrivileges . '

') . Piwik_Translate('Installation_InsufficientPrivilegesHelp')); @@ -148,9 +154,9 @@ public function createDatabaseObject() * - DROP * - CREATE TEMPORARY TABLES * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormDatabaseSetup_Rule_checkUserPrivileges extends HTML_QuickForm2_Rule +class Rule_checkUserPrivileges extends HTML_QuickForm2_Rule { const TEST_TABLE_NAME = 'piwik_test_table'; const TEST_TEMP_TABLE_NAME = 'piwik_test_table_temp'; @@ -228,22 +234,22 @@ public static function getRequiredPrivileges() { return array( 'CREATE' => 'CREATE TABLE ' . self::TEST_TABLE_NAME . ' ( - id INT AUTO_INCREMENT, - value INT, - PRIMARY KEY (id), - KEY index_value (value) - )', + id INT AUTO_INCREMENT, + value INT, + PRIMARY KEY (id), + KEY index_value (value) + )', 'ALTER' => 'ALTER TABLE ' . self::TEST_TABLE_NAME . ' - ADD COLUMN other_value INT DEFAULT 0', + ADD COLUMN other_value INT DEFAULT 0', 'SELECT' => 'SELECT * FROM ' . self::TEST_TABLE_NAME, 'INSERT' => 'INSERT INTO ' . self::TEST_TABLE_NAME . ' (value) VALUES (123)', 'UPDATE' => 'UPDATE ' . self::TEST_TABLE_NAME . ' SET value = 456 WHERE id = 1', 'DELETE' => 'DELETE FROM ' . self::TEST_TABLE_NAME . ' WHERE id = 1', 'DROP' => 'DROP TABLE ' . self::TEST_TABLE_NAME, 'CREATE TEMPORARY TABLES' => 'CREATE TEMPORARY TABLE ' . self::TEST_TEMP_TABLE_NAME . ' ( - id INT AUTO_INCREMENT, - PRIMARY KEY (id) - )', + id INT AUTO_INCREMENT, + PRIMARY KEY (id) + )', ); } @@ -294,9 +300,9 @@ private function dropExtraTables($db) /** * Filename check for prefix/DB name * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormDatabaseSetup_Rule_checkValidFilename extends HTML_QuickForm2_Rule +class FormDatabaseSetup_Rule_checkValidFilename extends HTML_QuickForm2_Rule { function validateOwner() { diff --git a/plugins/Installation/FormFirstWebsiteSetup.php b/plugins/Installation/FormFirstWebsiteSetup.php index 31c3e4cf4a1..2f8a810b1fa 100644 --- a/plugins/Installation/FormFirstWebsiteSetup.php +++ b/plugins/Installation/FormFirstWebsiteSetup.php @@ -6,15 +6,20 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ + +namespace Piwik\Plugins\Installation; +use HTML_QuickForm2_DataSource_Array; +use HTML_QuickForm2_Factory; use Piwik\QuickForm2; +use Piwik\Plugins\SitesManager\API; /** * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormFirstWebsiteSetup extends QuickForm2 +class FormFirstWebsiteSetup extends QuickForm2 { function __construct($id = 'websitesetupform', $method = 'post', $attributes = null, $trackSubmit = false) { @@ -23,12 +28,12 @@ function __construct($id = 'websitesetupform', $method = 'post', $attributes = n function init() { - HTML_QuickForm2_Factory::registerRule('checkTimezone', 'Piwik_Installation_FormFirstWebsiteSetup_Rule_isValidTimezone'); + HTML_QuickForm2_Factory::registerRule('checkTimezone', 'Rule_isValidTimezone'); $urlExample = 'http://example.org'; $javascriptOnClickUrlExample = "javascript:if(this.value=='$urlExample'){this.value='http://';} this.style.color='black';"; - $timezones = Piwik_SitesManager_API::getInstance()->getTimezonesList(); + $timezones = API::getInstance()->getTimezonesList(); $timezones = array_merge(array('No timezone' => Piwik_Translate('SitesManager_SelectACity')), $timezones); $this->addElement('text', 'siteName') @@ -66,20 +71,20 @@ function init() /** * Timezone validation rule * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormFirstWebsiteSetup_Rule_isValidTimezone extends HTML_QuickForm2_Rule +class Rule_isValidTimezone extends HTML_QuickForm2_Rule { function validateOwner() { try { $timezone = $this->owner->getValue(); if (!empty($timezone)) { - Piwik_SitesManager_API::getInstance()->setDefaultTimezone($timezone); + API::getInstance()->setDefaultTimezone($timezone); } } catch (Exception $e) { return false; } return true; } -} +} \ No newline at end of file diff --git a/plugins/Installation/FormGeneralSetup.php b/plugins/Installation/FormGeneralSetup.php index bd2504588a6..cfa4ce3c8b0 100644 --- a/plugins/Installation/FormGeneralSetup.php +++ b/plugins/Installation/FormGeneralSetup.php @@ -6,16 +6,20 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ -use Piwik\Piwik; +namespace Piwik\Plugins\Installation; + +use HTML_QuickForm2_DataSource_Array; +use HTML_QuickForm2_Factory; use Piwik\QuickForm2; +use Piwik\Piwik; /** * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormGeneralSetup extends QuickForm2 +class FormGeneralSetup extends QuickForm2 { function __construct($id = 'generalsetupform', $method = 'post', $attributes = null, $trackSubmit = false) { @@ -24,8 +28,8 @@ function __construct($id = 'generalsetupform', $method = 'post', $attributes = n function init() { - HTML_QuickForm2_Factory::registerRule('checkLogin', 'Piwik_Installation_FormGeneralSetup_Rule_isValidLoginString'); - HTML_QuickForm2_Factory::registerRule('checkEmail', 'Piwik_Installation_FormGeneralSetup_Rule_isValidEmailString'); + HTML_QuickForm2_Factory::registerRule('checkLogin', 'Rule_isValidLoginString'); + HTML_QuickForm2_Factory::registerRule('checkEmail', 'Rule_isValidEmailString'); $login = $this->addElement('text', 'login') ->setLabel(Piwik_Translate('Installation_SuperUserLogin')); @@ -67,9 +71,9 @@ function init() /** * Login id validation rule * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormGeneralSetup_Rule_isValidLoginString extends HTML_QuickForm2_Rule +class Rule_isValidLoginString extends HTML_QuickForm2_Rule { function validateOwner() { @@ -89,12 +93,12 @@ function validateOwner() /** * Email address validation rule * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_FormGeneralSetup_Rule_isValidEmailString extends HTML_QuickForm2_Rule +class Rule_isValidEmailString extends HTML_QuickForm2_Rule { function validateOwner() { return Piwik::isValidEmailString($this->owner->getValue()); } -} +} \ No newline at end of file diff --git a/plugins/Installation/Installation.php b/plugins/Installation/Installation.php index 8017e4e5352..1fb9a565f99 100644 --- a/plugins/Installation/Installation.php +++ b/plugins/Installation/Installation.php @@ -6,20 +6,20 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ +namespace Piwik\Plugins\Installation; + use Piwik\Piwik; use Piwik\Common; -use Piwik\Plugin; -use Piwik\Translate; /** * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation extends Plugin +class Installation extends \Piwik\Plugin { - protected $installationControllerName = 'Piwik_Installation_Controller'; + protected $installationControllerName = 'Controller'; /** * @see Piwik_Plugin::getListHooksRegistered diff --git a/plugins/Installation/View.php b/plugins/Installation/View.php index 84a8d631cf4..d5599bed53b 100644 --- a/plugins/Installation/View.php +++ b/plugins/Installation/View.php @@ -6,15 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Installation + * @package Installation */ -use Piwik\View; +namespace Piwik\Plugins\Installation; + /** * - * @package Piwik_Installation + * @package Installation */ -class Piwik_Installation_View extends View +class View extends \Piwik\View { public function __construct($subtemplatePath, $installationSteps, $currentStepName) { diff --git a/plugins/LanguagesManager/API.php b/plugins/LanguagesManager/API.php index ee6dd2aaa93..332b68cc9cc 100644 --- a/plugins/LanguagesManager/API.php +++ b/plugins/LanguagesManager/API.php @@ -6,9 +6,11 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_LanguagesManager + * @package LanguagesManager * */ +namespace Piwik\Plugins\LanguagesManager; + use Piwik\Piwik; use Piwik\Common; use Piwik\Db; @@ -23,14 +25,14 @@ * You can also request the default language to load for a user via "getLanguageForUser", * or update it via "setLanguageForUser". * - * @package Piwik_LanguagesManager + * @package LanguagesManager */ -class Piwik_LanguagesManager_API +class API { static private $instance = null; /** - * @return Piwik_LanguagesManager_API + * @return \Piwik\Plugins\LanguagesManager\API */ static public function getInstance() { diff --git a/plugins/LanguagesManager/Controller.php b/plugins/LanguagesManager/Controller.php index 212293ce790..3eba8c5097d 100644 --- a/plugins/LanguagesManager/Controller.php +++ b/plugins/LanguagesManager/Controller.php @@ -6,18 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_LanguagesManager + * @package LanguagesManager * */ +namespace Piwik\Plugins\LanguagesManager; + use Piwik\Piwik; use Piwik\Common; -use Piwik\Controller; +use Piwik\Plugins\LanguagesManager\API; use Piwik\Url; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Zend_Registry; /** - * @package Piwik_LanguagesManager + * @package LanguagesManager */ -class Piwik_LanguagesManager_Controller extends Controller +class Controller extends \Piwik\Controller { /** * anonymous = in the session @@ -31,11 +35,11 @@ public function saveLanguage() if (Piwik::isInstalled()) { $this->checkTokenInUrl(); } - Piwik_LanguagesManager::setLanguageForSession($language); + LanguagesManager::setLanguageForSession($language); if (Zend_Registry::isRegistered('access')) { $currentUser = Piwik::getCurrentUserLogin(); if ($currentUser && $currentUser !== 'anonymous') { - Piwik_LanguagesManager_API::getInstance()->setLanguageForUser($currentUser, $language); + API::getInstance()->setLanguageForUser($currentUser, $language); } } Url::redirectToReferer(); diff --git a/plugins/LanguagesManager/LanguagesManager.php b/plugins/LanguagesManager/LanguagesManager.php index 6bd1bf553c1..004d82ade6b 100644 --- a/plugins/LanguagesManager/LanguagesManager.php +++ b/plugins/LanguagesManager/LanguagesManager.php @@ -6,23 +6,27 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_LanguagesManager + * @package LanguagesManager * */ +namespace Piwik\Plugins\LanguagesManager; + +use Exception; use Piwik\Config; use Piwik\Piwik; use Piwik\Common; use Piwik\Cookie; +use Piwik\Plugins\LanguagesManager\API; use Piwik\View; -use Piwik\Plugin; use Piwik\Db; use Piwik\Translate; +use Zend_Registry; /** * - * @package Piwik_LanguagesManager + * @package LanguagesManager */ -class Piwik_LanguagesManager extends Plugin +class LanguagesManager extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -75,7 +79,7 @@ public function addLanguagesManagerToOtherTopBar(&$str) private function getLanguagesSelector() { $view = new View("@LanguagesManager/getLanguagesSelector"); - $view->languages = Piwik_LanguagesManager_API::getInstance()->getAvailableLanguageNames(); + $view->languages = API::getInstance()->getAvailableLanguageNames(); $view->currentLanguageCode = self::getLanguageCodeForCurrentUser(); $view->currentLanguageName = self::getLanguageNameForCurrentUser(); return $view->render(); @@ -86,7 +90,7 @@ function getLanguageToLoad(&$language) if (empty($language)) { $language = self::getLanguageCodeForCurrentUser(); } - if (!Piwik_LanguagesManager_API::getInstance()->isLanguageAvailable($language)) { + if (!API::getInstance()->isLanguageAvailable($language)) { $language = Translate::getInstance()->getLanguageDefault(); } } @@ -132,10 +136,10 @@ public function uninstall() static public function getLanguageCodeForCurrentUser() { $languageCode = self::getLanguageFromPreferences(); - if (!Piwik_LanguagesManager_API::getInstance()->isLanguageAvailable($languageCode)) { - $languageCode = Common::extractLanguageCodeFromBrowserLanguage(Common::getBrowserLanguage(), Piwik_LanguagesManager_API::getInstance()->getAvailableLanguages()); + if (!API::getInstance()->isLanguageAvailable($languageCode)) { + $languageCode = Common::extractLanguageCodeFromBrowserLanguage(Common::getBrowserLanguage(), API::getInstance()->getAvailableLanguages()); } - if (!Piwik_LanguagesManager_API::getInstance()->isLanguageAvailable($languageCode)) { + if (!API::getInstance()->isLanguageAvailable($languageCode)) { $languageCode = Translate::getInstance()->getLanguageDefault(); } return $languageCode; @@ -147,7 +151,7 @@ static public function getLanguageCodeForCurrentUser() static public function getLanguageNameForCurrentUser() { $languageCode = self::getLanguageCodeForCurrentUser(); - $languages = Piwik_LanguagesManager_API::getInstance()->getAvailableLanguageNames(); + $languages = API::getInstance()->getAvailableLanguageNames(); foreach ($languages as $language) { if ($language['code'] === $languageCode) { return $language['name']; @@ -166,13 +170,12 @@ static protected function getLanguageFromPreferences() try { $currentUser = Piwik::getCurrentUserLogin(); - return Piwik_LanguagesManager_API::getInstance()->getLanguageForUser($currentUser); + return API::getInstance()->getLanguageForUser($currentUser); } catch (Exception $e) { return false; } } - /** * Returns the language for the session * @@ -196,7 +199,7 @@ static public function getLanguageForSession() */ static public function setLanguageForSession($languageCode) { - if (!Piwik_LanguagesManager_API::getInstance()->isLanguageAvailable($languageCode)) { + if (!API::getInstance()->isLanguageAvailable($languageCode)) { return false; } diff --git a/plugins/Live/API.php b/plugins/Live/API.php index 3354c67335d..a1d2b9248f6 100644 --- a/plugins/Live/API.php +++ b/plugins/Live/API.php @@ -6,8 +6,11 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Live + * @package Live */ +namespace Piwik\Plugins\Live; + +use Exception; use Piwik\Config; use Piwik\DataAccess\LogAggregator; use Piwik\DataTable\Filter\ColumnDelete; @@ -24,6 +27,8 @@ use Piwik\Db; use Piwik\Tracker\Action; use Piwik\Tracker\GoalManager; +use Piwik\Plugins\Live\Visitor; +use Piwik\Plugins\SitesManager\API as SitesManagerAPI; /** * @see plugins/Referers/functions.php @@ -49,14 +54,14 @@ * The method "getCounters" is used to return a simple counter: visits, number of actions, number of converted visits, in the last N minutes. * * See also the documentation about Real time widget and visitor level reports in Piwik. - * @package Piwik_Live + * @package Live */ -class Piwik_Live_API +class API { static private $instance = null; /** - * @return Piwik_Live_API + * @return \Piwik\Plugins\Live\API */ static public function getInstance() { @@ -181,10 +186,10 @@ private function getCleanedVisitorsFromDetails($visitorDetails, $idSite, $flat = $site = new Site($idSite); $timezone = $site->getTimezone(); - $currencies = Piwik_SitesManager_API::getInstance()->getCurrencySymbols(); + $currencies = SitesManagerAPI::getInstance()->getCurrencySymbols(); foreach ($visitorDetails as $visitorDetail) { $this->cleanVisitorDetails($visitorDetail, $idSite); - $visitor = new Piwik_Live_Visitor($visitorDetail); + $visitor = new Visitor($visitorDetail); $visitorDetailsArray = $visitor->getAllVisitorDetails(); $visitorDetailsArray['siteCurrency'] = $site->getCurrency(); @@ -199,11 +204,11 @@ private function getCleanedVisitorsFromDetails($visitorDetails, $idSite, $flat = $visitorDetailsArray['serverTimePrettyFirstAction'] = $dateTimeVisitFirstAction->getLocalized('%time%'); $visitorDetailsArray['actionDetails'] = array(); - if(!$doNotFetchActions) { + if (!$doNotFetchActions) { $visitorDetailsArray = $this->enrichVisitorArrayWithActions($visitorDetailsArray, $actionsLimit, $timezone); } - if($flat) { + if ($flat) { $visitorDetailsArray = $this->flattenVisitorDetailsArray($visitorDetailsArray); } $table->addRowFromArray(array(Row::COLUMNS => $visitorDetailsArray)); @@ -223,7 +228,6 @@ private function getCustomVariablePrettyKey($key) return $key; } - /** * The &flat=1 feature is used by API.getSuggestedValuesForSegment * @@ -259,8 +263,8 @@ private function flattenVisitorDetailsArray($visitorDetailsArray) // Flatten Goals $count = 1; - foreach($visitorDetailsArray['actionDetails'] as $action) { - if(!empty($action['goalId'])) { + foreach ($visitorDetailsArray['actionDetails'] as $action) { + if (!empty($action['goalId'])) { $flattenedKeyName = 'visitConvertedGoalId' . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP . $count; $visitorDetailsArray[$flattenedKeyName] = $action['goalId']; $count++; @@ -269,18 +273,18 @@ private function flattenVisitorDetailsArray($visitorDetailsArray) // Flatten Page Titles/URLs $count = 1; - foreach($visitorDetailsArray['actionDetails'] as $action) { - if(!empty($action['url'])) { + foreach ($visitorDetailsArray['actionDetails'] as $action) { + if (!empty($action['url'])) { $flattenedKeyName = 'pageUrl' . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP . $count; $visitorDetailsArray[$flattenedKeyName] = $action['url']; } - if(!empty($action['pageTitle'])) { + if (!empty($action['pageTitle'])) { $flattenedKeyName = 'pageTitle' . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP . $count; $visitorDetailsArray[$flattenedKeyName] = $action['pageTitle']; } - if(!empty($action['siteSearchKeyword'])) { + if (!empty($action['siteSearchKeyword'])) { $flattenedKeyName = 'siteSearchKeyword' . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP . $count; $visitorDetailsArray[$flattenedKeyName] = $action['siteSearchKeyword']; } @@ -289,25 +293,25 @@ private function flattenVisitorDetailsArray($visitorDetailsArray) // Entry/exit pages $firstAction = $lastAction = false; - foreach($visitorDetailsArray['actionDetails'] as $action) { - if($action['type'] == 'action') { - if(empty($firstAction)) { + foreach ($visitorDetailsArray['actionDetails'] as $action) { + if ($action['type'] == 'action') { + if (empty($firstAction)) { $firstAction = $action; } $lastAction = $action; } } - if(!empty($firstAction['pageTitle'])) { + if (!empty($firstAction['pageTitle'])) { $visitorDetailsArray['entryPageTitle'] = $firstAction['pageTitle']; } - if(!empty($firstAction['url'])) { + if (!empty($firstAction['url'])) { $visitorDetailsArray['entryPageUrl'] = $firstAction['url']; } - if(!empty($lastAction['pageTitle'])) { + if (!empty($lastAction['pageTitle'])) { $visitorDetailsArray['exitPageTitle'] = $lastAction['pageTitle']; } - if(!empty($lastAction['url'])) { + if (!empty($lastAction['url'])) { $visitorDetailsArray['exitPageUrl'] = $lastAction['url']; } @@ -411,8 +415,8 @@ private function loadLastVisitorDetailsFromDatabase($idSite, $period = false, $d // 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 @@ -517,7 +521,6 @@ private function enrichVisitorArrayWithActions($visitorDetailsArray, $actionsLim if (isset($actionDetails[$actionIdx + 1])) { $actionDetail['timeSpent'] = $actionDetails[$actionIdx + 1]['timeSpentRef']; $actionDetail['timeSpentPretty'] = Piwik::getPrettyTimeFromSeconds($actionDetail['timeSpent']); - } unset($actionDetails[$actionIdx]['timeSpentRef']); // not needed after timeSpent is added @@ -663,7 +666,6 @@ private function enrichVisitorArrayWithActions($visitorDetailsArray, $actionsLim // Convert datetimes to the site timezone $dateTimeVisit = Date::factory($details['serverTimePretty'], $timezone); $details['serverTimePretty'] = $dateTimeVisit->getLocalized(Piwik_Translate('CoreHome_ShortDateFormat') . ' %time%'); - } $visitorDetailsArray['goalConversions'] = count($goalDetails); return $visitorDetailsArray; diff --git a/plugins/Live/Controller.php b/plugins/Live/Controller.php index 3e708d4d798..fd961c923ff 100644 --- a/plugins/Live/Controller.php +++ b/plugins/Live/Controller.php @@ -6,20 +6,22 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Live + * @package Live */ +namespace Piwik\Plugins\Live; + use Piwik\API\Request; use Piwik\Common; use Piwik\Piwik; use Piwik\Config; -use Piwik\Controller; +use Piwik\Plugins\Live\API; use Piwik\ViewDataTable; use Piwik\View; /** - * @package Piwik_Live + * @package Live */ -class Piwik_Live_Controller extends Controller +class Controller extends \Piwik\Controller { const SIMPLE_VISIT_COUNT_WIDGET_LAST_MINUTES_CONFIG_KEY = 'live_widget_visitor_count_last_minutes'; @@ -80,7 +82,7 @@ private function render(View $view, $fetch) } echo $rendered; } - + public function indexVisitorLog() { $view = new View('@Live/indexVisitorLog.twig'); @@ -120,9 +122,9 @@ public function getLastVisitsStart($fetch = false) private function setCounters($view) { $segment = Request::getRawSegmentFromRequest(); - $last30min = Piwik_Live_API::getInstance()->getCounters($this->idSite, $lastMinutes = 30, $segment); + $last30min = API::getInstance()->getCounters($this->idSite, $lastMinutes = 30, $segment); $last30min = $last30min[0]; - $today = Piwik_Live_API::getInstance()->getCounters($this->idSite, $lastMinutes = 24 * 60, $segment); + $today = API::getInstance()->getCounters($this->idSite, $lastMinutes = 24 * 60, $segment); $today = $today[0]; $view->visitorsCountHalfHour = $last30min['visits']; $view->visitorsCountToday = $today['visits']; diff --git a/plugins/Live/Live.php b/plugins/Live/Live.php index dfa08ce8c58..7ef67b56b56 100644 --- a/plugins/Live/Live.php +++ b/plugins/Live/Live.php @@ -6,17 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Live + * @package Live */ -use Piwik\Plugin; +namespace Piwik\Plugins\Live; + use Piwik\Common; use Piwik\WidgetsList; /** * - * @package Piwik_Live + * @package Live */ -class Piwik_Live extends Plugin +class Live extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -24,10 +25,10 @@ class Piwik_Live extends Plugin public function getListHooksRegistered() { return array( - 'AssetManager.getJsFiles' => 'getJsFiles', - 'AssetManager.getCssFiles' => 'getCssFiles', - 'WidgetsList.add' => 'addWidget', - 'Menu.add' => 'addMenu', + 'AssetManager.getJsFiles' => 'getJsFiles', + 'AssetManager.getCssFiles' => 'getCssFiles', + 'WidgetsList.add' => 'addWidget', + 'Menu.add' => 'addMenu', 'ViewDataTable.getReportDisplayProperties' => 'getReportDisplayProperties', ); } @@ -62,25 +63,25 @@ public function getReportDisplayProperties(&$properties) private function getDisplayPropertiesForGetLastVisitsDetails() { return array( - 'datatable_template' => "@Live/getVisitorLog.twig", - 'disable_generic_filters' => true, - 'enable_sort' => false, - 'filter_sort_column' => 'idVisit', - 'filter_sort_order' => 'asc', - 'show_search' => false, - 'filter_limit' => 20, - 'show_offset_information' => false, + 'datatable_template' => "@Live/getVisitorLog.twig", + 'disable_generic_filters' => true, + 'enable_sort' => false, + 'filter_sort_column' => 'idVisit', + 'filter_sort_order' => 'asc', + 'show_search' => false, + 'filter_limit' => 20, + 'show_offset_information' => false, 'show_exclude_low_population' => false, - 'show_all_views_icons' => false, - 'show_table_all_columns' => false, - 'show_export_as_rss_feed' => false, - 'disable_row_actions' => true, - 'documentation' => Piwik_Translate('Live_VisitorLogDocumentation', array('
', '
')), - 'custom_parameters' => array( + 'show_all_views_icons' => false, + 'show_table_all_columns' => false, + 'show_export_as_rss_feed' => false, + 'disable_row_actions' => true, + 'documentation' => Piwik_Translate('Live_VisitorLogDocumentation', array('
', '
')), + 'custom_parameters' => array( // set a very high row count so that the next link in the footer of the data table is always shown - 'totalRows' => 10000000, + 'totalRows' => 10000000, - 'filterEcommerce' => Common::getRequestVar('filterEcommerce', 0, 'int'), + 'filterEcommerce' => Common::getRequestVar('filterEcommerce', 0, 'int'), 'pageUrlNotDefined' => Piwik_Translate('General_NotDefined', Piwik_Translate('Actions_ColumnPageURL')) ), ); diff --git a/plugins/Live/Visitor.php b/plugins/Live/Visitor.php index 5d7441fc38e..849521ba3d0 100644 --- a/plugins/Live/Visitor.php +++ b/plugins/Live/Visitor.php @@ -6,13 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Live + * @package Live */ +namespace Piwik\Plugins\Live; + use Piwik\Piwik; use Piwik\Common; use Piwik\IP; use Piwik\Tracker; use Piwik\Tracker\Visit; +use Piwik\Plugins\API\API as MetaAPI; +use Piwik\Plugins\Referers\API as ReferersAPI; +use Piwik\Plugins\UserCountry\LocationProvider\GeoIp; /** * @see plugins/Referers/functions.php @@ -27,10 +32,9 @@ require_once PIWIK_INCLUDE_PATH . '/plugins/Provider/functions.php'; /** - * - * @package Piwik_Live + * @package Live */ -class Piwik_Live_Visitor +class Visitor { const DELIMITER_PLUGIN_NAME = ", "; @@ -102,7 +106,7 @@ function getAllVisitorDetails() 'referrerSearchEngineUrl' => $this->getSearchEngineUrl(), 'referrerSearchEngineIcon' => $this->getSearchEngineIcon(), 'operatingSystem' => $this->getOperatingSystem(), - 'operatingSystemCode' => $this->getOperatingSystemCode(), + 'operatingSystemCode' => $this->getOperatingSystemCode(), 'operatingSystemShortName' => $this->getOperatingSystemShortName(), 'operatingSystemIcon' => $this->getOperatingSystemIcon(), 'browserFamily' => $this->getBrowserFamily(), @@ -244,17 +248,17 @@ function getCountryCode() function getCountryName() { - return Piwik_CountryTranslate($this->getCountryCode()); + return \Piwik\Plugins\UserCountry\countryTranslate($this->getCountryCode()); } function getCountryFlag() { - return Piwik_getFlagFromCode($this->getCountryCode()); + return \Piwik\Plugins\UserCountry\getFlagFromCode($this->getCountryCode()); } function getContinent() { - return Piwik_ContinentTranslate($this->getContinentCode()); + return \Piwik\Plugins\UserCountry\continentTranslate($this->getContinentCode()); } function getContinentCode() @@ -274,7 +278,7 @@ public function getRegionName() { $region = $this->getRegionCode(); if ($region != '' && $region != Visit::UNKNOWN_CODE) { - return Piwik_UserCountry_LocationProvider_GeoIp::getRegionNameFromCodes( + return GeoIp::getRegionNameFromCodes( $this->details['location_country'], $region); } return null; @@ -335,12 +339,12 @@ function getCustomVariables() function getRefererType() { - return Piwik_getRefererTypeFromShortName($this->details['referer_type']); + return \Piwik\Plugins\Referers\getRefererTypeFromShortName($this->details['referer_type']); } function getRefererTypeName() { - return Piwik_getRefererTypeLabel($this->details['referer_type']); + return \Piwik\Plugins\Referers\getRefererTypeLabel($this->details['referer_type']); } function getKeyword() @@ -349,7 +353,7 @@ function getKeyword() if (\Piwik\PluginsManager::getInstance()->isPluginActivated('Referers') && $this->getRefererType() == 'search' ) { - $keyword = Piwik_Referers_API::getCleanKeyword($keyword); + $keyword = \Piwik\Plugins\Referers\API::getCleanKeyword($keyword); } return urldecode($keyword); } @@ -358,7 +362,7 @@ function getRefererUrl() { if ($this->getRefererType() == 'search') { if (\Piwik\PluginsManager::getInstance()->isPluginActivated('Referers') - && $this->details['referer_keyword'] == Piwik_Referers_API::LABEL_KEYWORD_NOT_DEFINED + && $this->details['referer_keyword'] == ReferersAPI::LABEL_KEYWORD_NOT_DEFINED ) { return 'http://piwik.org/faq/general/#faq_144'; } // Case URL is google.XX/url.... then we rewrite to the search result page url @@ -367,7 +371,7 @@ function getRefererUrl() ) { $refUrl = @parse_url($this->details['referer_url']); if (isset($refUrl['host'])) { - $url = Piwik_getSearchEngineUrlFromUrlAndKeyword('http://google.com', $this->getKeyword()); + $url = \Piwik\Plugins\Referers\getSearchEngineUrlFromUrlAndKeyword('http://google.com', $this->getKeyword()); $url = str_replace('google.com', $refUrl['host'], $url); return $url; } @@ -406,7 +410,7 @@ function getSearchEngineUrl() if ($this->getRefererType() == 'search' && !empty($this->details['referer_name']) ) { - return Piwik_getSearchEngineUrlFromName($this->details['referer_name']); + return \Piwik\Plugins\Referers\getSearchEngineUrlFromName($this->details['referer_name']); } return null; } @@ -415,7 +419,7 @@ function getSearchEngineIcon() { $searchEngineUrl = $this->getSearchEngineUrl(); if (!is_null($searchEngineUrl)) { - return Piwik_getSearchEngineLogoFromUrl($searchEngineUrl); + return \Piwik\Plugins\Referers\getSearchEngineLogoFromUrl($searchEngineUrl); } return null; } @@ -451,7 +455,7 @@ function getPluginIcons() $pluginIcons = array(); foreach ($pluginNames as $plugin) { - $pluginIcons[] = array("pluginIcon" => Piwik_getPluginsLogo($plugin), "pluginName" => $plugin); + $pluginIcons[] = array("pluginIcon" => \Piwik\Plugins\UserSettings\getPluginsLogo($plugin), "pluginName" => $plugin); } return $pluginIcons; } @@ -465,27 +469,27 @@ function getOperatingSystemCode() function getOperatingSystem() { - return Piwik_getOSLabel($this->details['config_os']); + return \Piwik\Plugins\UserSettings\getOSLabel($this->details['config_os']); } function getOperatingSystemShortName() { - return Piwik_getOSShortLabel($this->details['config_os']); + return \Piwik\Plugins\UserSettings\getOSShortLabel($this->details['config_os']); } function getOperatingSystemIcon() { - return Piwik_getOSLogo($this->details['config_os']); + return \Piwik\Plugins\UserSettings\getOSLogo($this->details['config_os']); } function getBrowserFamilyDescription() { - return Piwik_getBrowserTypeLabel($this->getBrowserFamily()); + return \Piwik\Plugins\UserSettings\getBrowserTypeLabel($this->getBrowserFamily()); } function getBrowserFamily() { - return Piwik_getBrowserFamily($this->details['config_browser_name']); + return \Piwik\Plugins\UserSettings\getBrowserFamily($this->details['config_browser_name']); } function getBrowserCode() @@ -500,23 +504,23 @@ function getBrowserVersion() function getBrowser() { - return Piwik_getBrowserLabel($this->details['config_browser_name'] . ";" . $this->details['config_browser_version']); + return \Piwik\Plugins\UserSettings\getBrowserLabel($this->details['config_browser_name'] . ";" . $this->details['config_browser_version']); } function getBrowserIcon() { - return Piwik_getBrowsersLogo($this->details['config_browser_name'] . ";" . $this->details['config_browser_version']); + return \Piwik\Plugins\UserSettings\getBrowsersLogo($this->details['config_browser_name'] . ";" . $this->details['config_browser_version']); } function getScreenType() { - return Piwik_getScreenTypeFromResolution($this->details['config_resolution']); + return \Piwik\Plugins\UserSettings\getScreenTypeFromResolution($this->details['config_resolution']); } function getDeviceType() { - if(\Piwik\PluginsManager::getInstance()->isPluginActivated('DevicesDetection')) { - return Piwik_getDeviceTypeLabel($this->details['config_device_type']); + if (\Piwik\PluginsManager::getInstance()->isPluginActivated('DevicesDetection')) { + return \Piwik\Plugins\DevicesDetection\getDeviceTypeLabel($this->details['config_device_type']); } return false; } @@ -528,9 +532,9 @@ function getResolution() function getScreenTypeIcon() { - return Piwik_getScreensLogo($this->getScreenType()); + return \Piwik\Plugins\UserSettings\getScreensLogo($this->getScreenType()); } - + function getProvider() { if (isset($this->details['location_provider'])) { @@ -542,12 +546,12 @@ function getProvider() function getProviderName() { - return Piwik_Provider_getPrettyProviderName($this->getProvider()); + return \Piwik\Plugins\Provider\getPrettyProviderName($this->getProvider()); } function getProviderUrl() { - return Piwik_getHostnameUrl(@$this->details['location_provider']); + return \Piwik\Plugins\Provider\getHostnameUrl(@$this->details['location_provider']); } function getDateTimeLastAction() @@ -569,7 +573,7 @@ function getVisitEcommerceStatusIcon() function getVisitEcommerceStatus() { - return Piwik_API_API::getVisitEcommerceStatusFromId($this->details['visit_goal_buyer']); + return MetaAPI::getVisitEcommerceStatusFromId($this->details['visit_goal_buyer']); } function getVisitorGoalConvertedIcon() diff --git a/plugins/Login/Auth.php b/plugins/Login/Auth.php index 251369e9762..10bad0d0ac6 100644 --- a/plugins/Login/Auth.php +++ b/plugins/Login/Auth.php @@ -6,19 +6,21 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Login + * @package Login */ +namespace Piwik\Plugins\Login; + use Piwik\Config; use Piwik\Common; -use Piwik\Auth; use Piwik\AuthResult; use Piwik\Db; +use Piwik\Plugins\UsersManager\API; /** * - * @package Piwik_Login + * @package Login */ -class Piwik_Login_Auth implements Auth +class Auth implements \Piwik\Auth { protected $login = null; protected $token_auth = null; @@ -42,7 +44,7 @@ public function authenticate() { $rootLogin = Config::getInstance()->superuser['login']; $rootPassword = Config::getInstance()->superuser['password']; - $rootToken = Piwik_UsersManager_API::getInstance()->getTokenAuth($rootLogin, $rootPassword); + $rootToken = API::getInstance()->getTokenAuth($rootLogin, $rootPassword); if (is_null($this->login)) { if ($this->token_auth === $rootToken) { diff --git a/plugins/Login/Controller.php b/plugins/Login/Controller.php index 4aebcd3a86f..1e440de915b 100644 --- a/plugins/Login/Controller.php +++ b/plugins/Login/Controller.php @@ -6,12 +6,14 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Login + * @package Login */ +namespace Piwik\Plugins\Login; + +use Exception; use Piwik\Config; use Piwik\Piwik; use Piwik\Common; -use Piwik\Controller; use Piwik\Cookie; use Piwik\IP; use Piwik\Mail; @@ -20,15 +22,20 @@ use Piwik\Url; use Piwik\QuickForm2; use Piwik\Session; +use Piwik\Plugins\Login\Login; +use Piwik\Plugins\Login\FormLogin; +use Piwik\Plugins\Login\FormResetPassword; +use Piwik\Plugins\UsersManager\UsersManager; +use Piwik\Plugins\UsersManager\API; require_once PIWIK_INCLUDE_PATH . '/core/Config.php'; /** * Login controller * - * @package Piwik_Login + * @package Login */ -class Piwik_Login_Controller extends Controller +class Controller extends \Piwik\Controller { /** * Generate hash on user info and password @@ -71,10 +78,10 @@ function login($messageNoAccess = null, $infoMessage = false) { self::checkForceSslLogin(); - $form = new Piwik_Login_FormLogin(); + $form = new FormLogin(); if ($form->validate()) { $nonce = $form->getSubmitValue('form_nonce'); - if (Nonce::verifyNonce('Piwik_Login.login', $nonce)) { + if (Nonce::verifyNonce('Login.login', $nonce)) { $login = $form->getSubmitValue('form_login'); $password = $form->getSubmitValue('form_password'); $rememberMe = $form->getSubmitValue('form_rememberme') == '1'; @@ -112,7 +119,7 @@ private function configureView($view) $view->forceSslLogin = Config::getInstance()->General['force_ssl_login']; // crsf token: don't trust the submitted value; generate/fetch it from session data - $view->nonce = Nonce::getNonce('Piwik_Login.login'); + $view->nonce = Nonce::getNonce('Login.login'); } /** @@ -162,7 +169,7 @@ protected function authenticateAndRedirect($login, $md5Password, $rememberMe, $u 'md5Password' => $md5Password, 'rememberMe' => $rememberMe, ); - Nonce::discardNonce('Piwik_Login.login'); + Nonce::discardNonce('Login.login'); Piwik_PostEvent('Login.initSession', array(&$info)); Url::redirectToUrl($urlToRedirect); } @@ -188,10 +195,10 @@ function resetPassword() $infoMessage = null; $formErrors = null; - $form = new Piwik_Login_FormResetPassword(); + $form = new FormResetPassword(); if ($form->validate()) { $nonce = $form->getSubmitValue('form_nonce'); - if (Nonce::verifyNonce('Piwik_Login.login', $nonce)) { + if (Nonce::verifyNonce('Login.login', $nonce)) { $formErrors = $this->resetPasswordFirstStep($form); if (empty($formErrors)) { $infoMessage = Piwik_Translate('Login_ConfirmationLinkSent'); @@ -225,7 +232,7 @@ private function resetPasswordFirstStep($form) // check the password try { - Piwik_UsersManager::checkPassword($password); + UsersManager::checkPassword($password); } catch (Exception $ex) { return array($ex->getMessage()); } @@ -243,14 +250,14 @@ private function resetPasswordFirstStep($form) $login = $user['login']; // if valid, store password information in options table, then... - Piwik_Login::savePasswordResetInfo($login, $password); + Login::savePasswordResetInfo($login, $password); // ... send email with confirmation link try { $this->sendEmailConfirmationLink($user); } catch (Exception $ex) { // remove password reset info - Piwik_Login::removePasswordResetInfo($login); + Login::removePasswordResetInfo($login); return array($ex->getMessage() . '
' . Piwik_Translate('Login_ContactAdmin')); } @@ -312,7 +319,7 @@ public function confirmResetPassword() } // check that the reset token is valid - $resetPassword = Piwik_Login::getPasswordToResetTo($login); + $resetPassword = Login::getPasswordToResetTo($login); if ($resetPassword === false || !self::isValidToken($resetToken, $user)) { throw new Exception(Piwik_Translate('Login_InvalidOrExpiredToken')); } @@ -356,7 +363,7 @@ private function setNewUserPassword($user, $passwordHash) Config::getInstance()->superuser = $user; Config::getInstance()->forceSave(); } else { - Piwik_UsersManager_API::getInstance()->updateUser( + API::getInstance()->updateUser( $user['login'], $passwordHash, $email = false, $alias = false, $isPasswordHashed = true); } } @@ -390,10 +397,10 @@ protected function getUserInformation($loginMail) 'email' => Piwik::getSuperUserEmail(), 'password' => Config::getInstance()->superuser['password'], ); - } else if (Piwik_UsersManager_API::getInstance()->userExists($loginMail)) { - $user = Piwik_UsersManager_API::getInstance()->getUser($loginMail); - } else if (Piwik_UsersManager_API::getInstance()->userEmailExists($loginMail)) { - $user = Piwik_UsersManager_API::getInstance()->getUserByEmail($loginMail); + } else if (API::getInstance()->userExists($loginMail)) { + $user = API::getInstance()->getUser($loginMail); + } else if (API::getInstance()->userEmailExists($loginMail)) { + $user = API::getInstance()->getUserByEmail($loginMail); } return $user; diff --git a/plugins/Login/FormLogin.php b/plugins/Login/FormLogin.php index 229288e713f..f0f5596fe55 100644 --- a/plugins/Login/FormLogin.php +++ b/plugins/Login/FormLogin.php @@ -6,15 +6,18 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Login + * @package Login */ +namespace Piwik\Plugins\Login; + +use HTML_QuickForm2_DataSource_Array; use Piwik\QuickForm2; /** * - * @package Piwik_Login + * @package Login */ -class Piwik_Login_FormLogin extends QuickForm2 +class FormLogin extends QuickForm2 { function __construct($id = 'login_form', $method = 'post', $attributes = null, $trackSubmit = false) { diff --git a/plugins/Login/FormResetPassword.php b/plugins/Login/FormResetPassword.php index abbe1bd4a1b..0f02aaedcf5 100644 --- a/plugins/Login/FormResetPassword.php +++ b/plugins/Login/FormResetPassword.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Login + * @package Login */ +namespace Piwik\Plugins\Login; + use Piwik\QuickForm2; /** * - * @package Piwik_Login + * @package Login */ -class Piwik_Login_FormResetPassword extends QuickForm2 +class FormResetPassword extends QuickForm2 { function __construct($id = 'resetpasswordform', $method = 'post', $attributes = null, $trackSubmit = false) { diff --git a/plugins/Login/Login.php b/plugins/Login/Login.php index b1da0954ad3..2e511b0a5ba 100644 --- a/plugins/Login/Login.php +++ b/plugins/Login/Login.php @@ -6,20 +6,26 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_Login + * @package Login */ +namespace Piwik\Plugins\Login; + +use Exception; use Piwik\Config; use Piwik\Piwik; use Piwik\Cookie; use Piwik\Option; +use Piwik\Plugins\Login\Auth; +use Piwik\Plugins\Login\Controller; use Piwik\Session; -use Piwik\Plugin; +use Piwik\Plugins\UsersManager\UsersManager; +use Piwik\Plugins\UsersManager\API; /** * - * @package Piwik_Login + * @package Login */ -class Piwik_Login extends Plugin +class Login extends \Piwik\Plugin { /** * @see Piwik_Plugin::getListHooksRegistered @@ -43,7 +49,7 @@ public function noAccess(Exception $exception) { $exceptionMessage = $exception->getMessage(); - $controller = new Piwik_Login_Controller(); + $controller = new Controller(); $controller->login($exceptionMessage, '' /* $exception->getTraceAsString() */); } @@ -63,7 +69,7 @@ public function ApiRequestAuthenticate($tokenAuth) */ function initAuthenticationObject($allowCookieAuthentication = false) { - $auth = new Piwik_Login_Auth(); + $auth = new Auth(); \Zend_Registry::set('auth', $auth); $action = Piwik::getAction(); @@ -91,7 +97,7 @@ function initAuthenticationObject($allowCookieAuthentication = false) /** * Authenticate user and initializes the session. * Listens to Login.initSession hook. - * + * * @throws Exception */ public function initSession($info) @@ -100,7 +106,7 @@ public function initSession($info) $md5Password = $info['md5Password']; $rememberMe = $info['rememberMe']; - $tokenAuth = Piwik_UsersManager_API::getInstance()->getTokenAuth($login, $md5Password); + $tokenAuth = API::getInstance()->getTokenAuth($login, $md5Password); $auth = \Zend_Registry::get('auth'); $auth->setLogin($login); @@ -137,7 +143,7 @@ public function initSession($info) public static function savePasswordResetInfo($login, $password) { $optionName = self::getPasswordResetInfoOptionName($login); - $optionData = Piwik_UsersManager::getPasswordHash($password); + $optionData = UsersManager::getPasswordHash($password); Piwik_SetOption($optionName, $optionData); } diff --git a/plugins/MobileMessaging/API.php b/plugins/MobileMessaging/API.php index 491bb46f860..bb2664ffffd 100644 --- a/plugins/MobileMessaging/API.php +++ b/plugins/MobileMessaging/API.php @@ -6,10 +6,15 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + use Piwik\Piwik; use Piwik\Common; +use Piwik\Plugins\MobileMessaging\MobileMessaging; +use Piwik\Plugins\MobileMessaging\SMSProvider; +use Piwik\Plugins\PDFReports\API as PDFReportsAPI; /** * The MobileMessaging API lets you manage and access all the MobileMessaging plugin features including : @@ -17,9 +22,9 @@ * - activate phone numbers * - check remaining credits * - send SMS - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging_API +class API { const VERIFICATION_CODE_LENGTH = 5; const SMS_FROM = 'Piwik'; @@ -27,7 +32,7 @@ class Piwik_MobileMessaging_API static private $instance = null; /** - * @return Piwik_MobileMessaging_API + * @return \Piwik\Plugins\MobileMessaging\API */ static public function getInstance() { @@ -39,11 +44,11 @@ static public function getInstance() /** * @param string $provider - * @return Piwik_MobileMessaging_SMSProvider + * @return SMSProvider */ static private function getSMSProviderInstance($provider) { - return Piwik_MobileMessaging_SMSProvider::factory($provider); + return SMSProvider::factory($provider); } /** @@ -56,17 +61,17 @@ public function areSMSAPICredentialProvided() Piwik::checkUserHasSomeViewAccess(); $credential = $this->getSMSAPICredential(); - return isset($credential[Piwik_MobileMessaging::API_KEY_OPTION]); + return isset($credential[MobileMessaging::API_KEY_OPTION]); } private function getSMSAPICredential() { $settings = $this->getCredentialManagerSettings(); return array( - Piwik_MobileMessaging::PROVIDER_OPTION => - isset($settings[Piwik_MobileMessaging::PROVIDER_OPTION]) ? $settings[Piwik_MobileMessaging::PROVIDER_OPTION] : null, - Piwik_MobileMessaging::API_KEY_OPTION => - isset($settings[Piwik_MobileMessaging::API_KEY_OPTION]) ? $settings[Piwik_MobileMessaging::API_KEY_OPTION] : null, + MobileMessaging::PROVIDER_OPTION => + isset($settings[MobileMessaging::PROVIDER_OPTION]) ? $settings[MobileMessaging::PROVIDER_OPTION] : null, + MobileMessaging::API_KEY_OPTION => + isset($settings[MobileMessaging::API_KEY_OPTION]) ? $settings[MobileMessaging::API_KEY_OPTION] : null, ); } @@ -79,7 +84,7 @@ public function getSMSProvider() { $this->checkCredentialManagementRights(); $credential = $this->getSMSAPICredential(); - return $credential[Piwik_MobileMessaging::PROVIDER_OPTION]; + return $credential[MobileMessaging::PROVIDER_OPTION]; } /** @@ -99,8 +104,8 @@ public function setSMSAPICredential($provider, $apiKey) $settings = $this->getCredentialManagerSettings(); - $settings[Piwik_MobileMessaging::PROVIDER_OPTION] = $provider; - $settings[Piwik_MobileMessaging::API_KEY_OPTION] = $apiKey; + $settings[MobileMessaging::PROVIDER_OPTION] = $provider; + $settings[MobileMessaging::API_KEY_OPTION] = $apiKey; $this->setCredentialManagerSettings($settings); @@ -140,7 +145,7 @@ public function addPhoneNumber($phoneNumber) $phoneNumbers[$phoneNumber] = $verificationCode; $this->savePhoneNumbers($phoneNumbers); - $this->increaseCount(Piwik_MobileMessaging::PHONE_NUMBER_VALIDATION_REQUEST_COUNT_OPTION, $phoneNumber); + $this->increaseCount(MobileMessaging::PHONE_NUMBER_VALIDATION_REQUEST_COUNT_OPTION, $phoneNumber); return true; } @@ -171,15 +176,15 @@ public function sendSMS($content, $phoneNumber, $from) Piwik::checkUserIsNotAnonymous(); $credential = $this->getSMSAPICredential(); - $SMSProvider = self::getSMSProviderInstance($credential[Piwik_MobileMessaging::PROVIDER_OPTION]); + $SMSProvider = self::getSMSProviderInstance($credential[MobileMessaging::PROVIDER_OPTION]); $SMSProvider->sendSMS( - $credential[Piwik_MobileMessaging::API_KEY_OPTION], + $credential[MobileMessaging::API_KEY_OPTION], $content, $phoneNumber, $from ); - $this->increaseCount(Piwik_MobileMessaging::SMS_SENT_COUNT_OPTION, $phoneNumber); + $this->increaseCount(MobileMessaging::SMS_SENT_COUNT_OPTION, $phoneNumber); return true; } @@ -194,9 +199,9 @@ public function getCreditLeft() $this->checkCredentialManagementRights(); $credential = $this->getSMSAPICredential(); - $SMSProvider = self::getSMSProviderInstance($credential[Piwik_MobileMessaging::PROVIDER_OPTION]); + $SMSProvider = self::getSMSProviderInstance($credential[MobileMessaging::PROVIDER_OPTION]); return $SMSProvider->getCreditLeft( - $credential[Piwik_MobileMessaging::API_KEY_OPTION] + $credential[MobileMessaging::API_KEY_OPTION] ); } @@ -216,7 +221,7 @@ public function removePhoneNumber($phoneNumber) $this->savePhoneNumbers($phoneNumbers); // remove phone number from reports - $pdfReportsAPIInstance = Piwik_PDFReports_API::getInstance(); + $pdfReportsAPIInstance = PDFReportsAPI::getInstance(); $reports = $pdfReportsAPIInstance->getReports( $idSite = false, $period = false, @@ -225,9 +230,9 @@ public function removePhoneNumber($phoneNumber) ); foreach ($reports as $report) { - if ($report['type'] == Piwik_MobileMessaging::MOBILE_TYPE) { + if ($report['type'] == MobileMessaging::MOBILE_TYPE) { $reportParameters = $report['parameters']; - $reportPhoneNumbers = $reportParameters[Piwik_MobileMessaging::PHONE_NUMBERS_PARAMETER]; + $reportPhoneNumbers = $reportParameters[MobileMessaging::PHONE_NUMBERS_PARAMETER]; $updatedPhoneNumbers = array(); foreach ($reportPhoneNumbers as $reportPhoneNumber) { if ($reportPhoneNumber != $phoneNumber) { @@ -236,7 +241,7 @@ public function removePhoneNumber($phoneNumber) } if (count($updatedPhoneNumbers) != count($reportPhoneNumbers)) { - $reportParameters[Piwik_MobileMessaging::PHONE_NUMBERS_PARAMETER] = $updatedPhoneNumbers; + $reportParameters[MobileMessaging::PHONE_NUMBERS_PARAMETER] = $updatedPhoneNumbers; // note: reports can end up without any recipients $pdfReportsAPIInstance->updateReport( @@ -262,8 +267,8 @@ private function retrievePhoneNumbers() $settings = $this->getCurrentUserSettings(); $phoneNumbers = array(); - if (isset($settings[Piwik_MobileMessaging::PHONE_NUMBERS_OPTION])) { - $phoneNumbers = $settings[Piwik_MobileMessaging::PHONE_NUMBERS_OPTION]; + if (isset($settings[MobileMessaging::PHONE_NUMBERS_OPTION])) { + $phoneNumbers = $settings[MobileMessaging::PHONE_NUMBERS_OPTION]; } return $phoneNumbers; @@ -273,7 +278,7 @@ private function savePhoneNumbers($phoneNumbers) { $settings = $this->getCurrentUserSettings(); - $settings[Piwik_MobileMessaging::PHONE_NUMBERS_OPTION] = $phoneNumbers; + $settings[MobileMessaging::PHONE_NUMBERS_OPTION] = $phoneNumbers; $this->setCurrentUserSettings($settings); } @@ -383,7 +388,7 @@ public function deleteSMSAPICredential() $settings = $this->getCredentialManagerSettings(); - $settings[Piwik_MobileMessaging::API_KEY_OPTION] = null; + $settings[MobileMessaging::API_KEY_OPTION] = null; $this->setCredentialManagerSettings($settings); @@ -398,7 +403,7 @@ private function checkCredentialManagementRights() private function setUserSettings($user, $settings) { Piwik_SetOption( - $user . Piwik_MobileMessaging::USER_SETTINGS_POSTFIX_OPTION, + $user . MobileMessaging::USER_SETTINGS_POSTFIX_OPTION, Common::json_encode($settings) ); } @@ -420,7 +425,7 @@ private function getCredentialManagerLogin() private function getUserSettings($user) { - $optionIndex = $user . Piwik_MobileMessaging::USER_SETTINGS_POSTFIX_OPTION; + $optionIndex = $user . MobileMessaging::USER_SETTINGS_POSTFIX_OPTION; $userSettings = Piwik_GetOption($optionIndex); if (empty($userSettings)) { @@ -450,7 +455,7 @@ private function getCurrentUserSettings() public function setDelegatedManagement($delegatedManagement) { Piwik::checkUserIsSuperUser(); - Piwik_SetOption(Piwik_MobileMessaging::DELEGATED_MANAGEMENT_OPTION, $delegatedManagement); + Piwik_SetOption(MobileMessaging::DELEGATED_MANAGEMENT_OPTION, $delegatedManagement); } /** @@ -461,6 +466,6 @@ public function setDelegatedManagement($delegatedManagement) public function getDelegatedManagement() { Piwik::checkUserHasSomeViewAccess(); - return Piwik_GetOption(Piwik_MobileMessaging::DELEGATED_MANAGEMENT_OPTION) == 'true'; + return Piwik_GetOption(MobileMessaging::DELEGATED_MANAGEMENT_OPTION) == 'true'; } } diff --git a/plugins/MobileMessaging/APIException.php b/plugins/MobileMessaging/APIException.php index d48bb0520ae..515d872bf0d 100644 --- a/plugins/MobileMessaging/APIException.php +++ b/plugins/MobileMessaging/APIException.php @@ -6,13 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + +use Exception; + /** - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging_APIException extends Exception +class APIException extends Exception { } diff --git a/plugins/MobileMessaging/Controller.php b/plugins/MobileMessaging/Controller.php index 0054d62912b..7cbf2d3bf22 100644 --- a/plugins/MobileMessaging/Controller.php +++ b/plugins/MobileMessaging/Controller.php @@ -6,22 +6,27 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -use Piwik\Controller\Admin; +namespace Piwik\Plugins\MobileMessaging; + use Piwik\Piwik; use Piwik\Common; use Piwik\IP; +use Piwik\Plugins\LanguagesManager\LanguagesManager; +use Piwik\Plugins\MobileMessaging\API; use Piwik\View; +use Piwik\Plugins\MobileMessaging\CountryCallingCodes; +use Piwik\Plugins\MobileMessaging\SMSProvider; require_once PIWIK_INCLUDE_PATH . '/plugins/UserCountry/functions.php'; /** * - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging_Controller extends Admin +class Controller extends \Piwik\Controller\Admin { /* * Mobile Messaging Settings tab : @@ -38,7 +43,7 @@ public function index() $view->isSuperUser = Piwik::isUserIsSuperUser(); - $mobileMessagingAPI = Piwik_MobileMessaging_API::getInstance(); + $mobileMessagingAPI = API::getInstance(); $view->delegatedManagement = $mobileMessagingAPI->getDelegatedManagement(); $view->credentialSupplied = $mobileMessagingAPI->areSMSAPICredentialProvided(); $view->accountManagedByCurrentUser = $view->isSuperUser || $view->delegatedManagement; @@ -48,23 +53,23 @@ public function index() $view->creditLeft = $mobileMessagingAPI->getCreditLeft(); } - $view->smsProviders = Piwik_MobileMessaging_SMSProvider::$availableSMSProviders; + $view->smsProviders = SMSProvider::$availableSMSProviders; // construct the list of countries from the lang files $countries = array(); foreach (Common::getCountriesList() as $countryCode => $continentCode) { - if (isset(Piwik_MobileMessaging_CountryCallingCodes::$countryCallingCodes[$countryCode])) { + if (isset(CountryCallingCodes::$countryCallingCodes[$countryCode])) { $countries[$countryCode] = array( - 'countryName' => Piwik_CountryTranslate($countryCode), - 'countryCallingCode' => Piwik_MobileMessaging_CountryCallingCodes::$countryCallingCodes[$countryCode], + 'countryName' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode), + 'countryCallingCode' => CountryCallingCodes::$countryCallingCodes[$countryCode], ); } } $view->countries = $countries; $view->defaultCountry = Common::getCountry( - Piwik_LanguagesManager::getLanguageCodeForCurrentUser(), + LanguagesManager::getLanguageCodeForCurrentUser(), true, IP::getIpFromHeader() ); diff --git a/plugins/MobileMessaging/CountryCallingCodes.php b/plugins/MobileMessaging/CountryCallingCodes.php index b1097220f8c..b98aa180ad4 100644 --- a/plugins/MobileMessaging/CountryCallingCodes.php +++ b/plugins/MobileMessaging/CountryCallingCodes.php @@ -6,14 +6,16 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + /** * - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging_CountryCallingCodes +class CountryCallingCodes { // list taken from core/DataFiles/Countries.php public static $countryCallingCodes = array( diff --git a/plugins/MobileMessaging/GSMCharset.php b/plugins/MobileMessaging/GSMCharset.php index 4d58c965802..3a8da082901 100644 --- a/plugins/MobileMessaging/GSMCharset.php +++ b/plugins/MobileMessaging/GSMCharset.php @@ -6,15 +6,17 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + /** * GSM 03.38 Charset * - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging_GSMCharset +class GSMCharset { public static $GSMCharset = array( diff --git a/plugins/MobileMessaging/MobileMessaging.php b/plugins/MobileMessaging/MobileMessaging.php index 532e511d731..a7e845a0c24 100644 --- a/plugins/MobileMessaging/MobileMessaging.php +++ b/plugins/MobileMessaging/MobileMessaging.php @@ -6,17 +6,23 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + use Piwik\Piwik; +use Piwik\Plugins\MobileMessaging\API as MobileMessagingAPI; use Piwik\View; -use Piwik\Plugin; +use Piwik\Plugins\API\API; +use Piwik_MobileMessaging_ReportRenderer_Exception; +use Piwik_MobileMessaging_ReportRenderer_Sms; +use Piwik\Plugins\PDFReports\API as PDFReportsAPI; /** * - * @package Piwik_MobileMessaging + * @package MobileMessaging */ -class Piwik_MobileMessaging extends Plugin +class MobileMessaging extends \Piwik\Plugin { const DELEGATED_MANAGEMENT_OPTION = 'MobileMessaging_DelegatedManagement'; const PROVIDER_OPTION = 'Provider'; @@ -98,12 +104,12 @@ public function getCssFiles($cssFiles) { $cssFiles[] = "plugins/MobileMessaging/stylesheets/MobileMessagingSettings.less"; } - + public function validateReportParameters(&$parameters, $info) { if (self::manageEvent($info)) { // phone number validation - $availablePhoneNumbers = Piwik_MobileMessaging_API::getInstance()->getActivatedPhoneNumbers(); + $availablePhoneNumbers = MobileMessagingAPI::getInstance()->getActivatedPhoneNumbers(); $phoneNumbers = $parameters[self::PHONE_NUMBERS_PARAMETER]; foreach ($phoneNumbers as $key => $phoneNumber) { @@ -121,10 +127,10 @@ public function validateReportParameters(&$parameters, $info) public function getReportMetadata(&$availableReportMetadata, $notificationInfo) { if (self::manageEvent($notificationInfo)) { - $idSite = $notificationInfo[Piwik_PDFReports_API::ID_SITE_INFO_KEY]; + $idSite = $notificationInfo[PDFReportsAPI::ID_SITE_INFO_KEY]; foreach (self::$availableReports as $availableReport) { - $reportMetadata = Piwik_API_API::getInstance()->getMetadata( + $reportMetadata = API::getInstance()->getMetadata( $idSite, $availableReport['module'], $availableReport['action'] @@ -180,7 +186,7 @@ public function allowMultipleReports(&$allowMultipleReports, $info) public function getReportRecipients(&$recipients, $notificationInfo) { if (self::manageEvent($notificationInfo)) { - $report = $notificationInfo[Piwik_PDFReports_API::REPORT_KEY]; + $report = $notificationInfo[PDFReportsAPI::REPORT_KEY]; $recipients = $report['parameters'][self::PHONE_NUMBERS_PARAMETER]; } } @@ -188,9 +194,9 @@ public function getReportRecipients(&$recipients, $notificationInfo) public function sendReport($notificationInfo) { if (self::manageEvent($notificationInfo)) { - $report = $notificationInfo[Piwik_PDFReports_API::REPORT_KEY]; - $contents = $notificationInfo[Piwik_PDFReports_API::REPORT_CONTENT_KEY]; - $reportSubject = $notificationInfo[Piwik_PDFReports_API::REPORT_SUBJECT_KEY]; + $report = $notificationInfo[PDFReportsAPI::REPORT_KEY]; + $contents = $notificationInfo[PDFReportsAPI::REPORT_CONTENT_KEY]; + $reportSubject = $notificationInfo[PDFReportsAPI::REPORT_SUBJECT_KEY]; $parameters = $report['parameters']; $phoneNumbers = $parameters[self::PHONE_NUMBERS_PARAMETER]; @@ -200,7 +206,7 @@ public function sendReport($notificationInfo) $reportSubject = Piwik_Translate('General_Reports'); } - $mobileMessagingAPI = Piwik_MobileMessaging_API::getInstance(); + $mobileMessagingAPI = MobileMessagingAPI::getInstance(); foreach ($phoneNumbers as $phoneNumber) { $mobileMessagingAPI->sendSMS( $contents, @@ -219,13 +225,13 @@ static public function template_reportParametersPDFReports(&$out) $view = new View('@MobileMessaging/reportParametersPDFReports'); $view->reportType = self::MOBILE_TYPE; - $view->phoneNumbers = Piwik_MobileMessaging_API::getInstance()->getActivatedPhoneNumbers(); + $view->phoneNumbers = MobileMessagingAPI::getInstance()->getActivatedPhoneNumbers(); $out .= $view->render(); } private static function manageEvent($notificationInfo) { - return in_array($notificationInfo[Piwik_PDFReports_API::REPORT_TYPE_INFO_KEY], array_keys(self::$managedReportTypes)); + return in_array($notificationInfo[PDFReportsAPI::REPORT_TYPE_INFO_KEY], array_keys(self::$managedReportTypes)); } function install() @@ -239,11 +245,11 @@ function install() function deactivate() { // delete all mobile reports - $pdfReportsAPIInstance = Piwik_PDFReports_API::getInstance(); + $pdfReportsAPIInstance = PDFReportsAPI::getInstance(); $reports = $pdfReportsAPIInstance->getReports(); foreach ($reports as $report) { - if ($report['type'] == Piwik_MobileMessaging::MOBILE_TYPE) { + if ($report['type'] == MobileMessaging::MOBILE_TYPE) { $pdfReportsAPIInstance->deleteReport($report['idreport']); } } diff --git a/plugins/MobileMessaging/ReportRenderer/Sms.php b/plugins/MobileMessaging/ReportRenderer/Sms.php index 5c89166ea25..2bd3239bdb1 100644 --- a/plugins/MobileMessaging/ReportRenderer/Sms.php +++ b/plugins/MobileMessaging/ReportRenderer/Sms.php @@ -9,6 +9,7 @@ * @package Piwik_MobileMessaging_ReportRenderer */ use Piwik\Common; +use Piwik\Plugins\MultiSites\API; use Piwik\View; use Piwik\ReportRenderer; use Piwik\Site; @@ -62,9 +63,9 @@ public function renderReport($processedReport) $reportData = $processedReport['reportData']; $evolutionMetrics = array(); - $multiSitesAPIMetrics = Piwik_MultiSites_API::getApiMetrics($enhanced = true); + $multiSitesAPIMetrics = API::getApiMetrics($enhanced = true); foreach ($multiSitesAPIMetrics as $metricSettings) { - $evolutionMetrics[] = $metricSettings[Piwik_MultiSites_API::METRIC_EVOLUTION_COL_NAME_KEY]; + $evolutionMetrics[] = $metricSettings[API::METRIC_EVOLUTION_COL_NAME_KEY]; } // no decimal for all metrics to shorten SMS content (keeps the monetary sign for revenue metrics) diff --git a/plugins/MobileMessaging/SMSProvider.php b/plugins/MobileMessaging/SMSProvider.php index 402c135b48f..7a9c36bb771 100644 --- a/plugins/MobileMessaging/SMSProvider.php +++ b/plugins/MobileMessaging/SMSProvider.php @@ -6,17 +6,21 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * * @category Piwik_Plugins - * @package Piwik_MobileMessaging + * @package MobileMessaging */ +namespace Piwik\Plugins\MobileMessaging; + +use Exception; use Piwik\Loader; +use Piwik\Plugins\MobileMessaging\GSMCharset; /** - * The Piwik_MobileMessaging_SMSProvider abstract class is used as a base class for SMS provider implementations. + * The SMSProvider abstract class is used as a base class for SMS provider implementations. * - * @package Piwik_MobileMessaging - * @subpackage Piwik_MobileMessaging_SMSProvider + * @package MobileMessaging + * @subpackage SMSProvider */ -abstract class Piwik_MobileMessaging_SMSProvider +abstract class SMSProvider { const MAX_GSM_CHARS_IN_ONE_UNIQUE_SMS = 160; const MAX_GSM_CHARS_IN_ONE_CONCATENATED_SMS = 153; @@ -26,11 +30,11 @@ abstract class Piwik_MobileMessaging_SMSProvider static public $availableSMSProviders = array( 'Clockwork' => 'You can use to send SMS Reports from Piwik.

About Clockwork: