diff options
author | mattab <matthieu.aubry@gmail.com> | 2013-09-14 07:23:23 +0400 |
---|---|---|
committer | mattab <matthieu.aubry@gmail.com> | 2013-09-14 07:23:23 +0400 |
commit | e3bd0c0b9e8bd34efd27d31fe310602fcfc3a894 (patch) | |
tree | 9e8873a2410dedb65b3e725bf537d4781047b7b7 /core | |
parent | 8d11a25fa7f41212584a58998c59884a4b9836d4 (diff) |
Moving piwik settings specific getters to SettingsPiwik class
Adding MetricsFormatter class which knows how to format/display metrics (time, money, size, etc)
Diffstat (limited to 'core')
-rw-r--r-- | core/ArchiveProcessor/Period.php | 9 | ||||
-rw-r--r-- | core/ArchiveProcessor/Rules.php | 3 | ||||
-rw-r--r-- | core/AssetManager.php | 2 | ||||
-rw-r--r-- | core/Common.php | 14 | ||||
-rw-r--r-- | core/Controller.php | 15 | ||||
-rw-r--r-- | core/Cookie.php | 6 | ||||
-rw-r--r-- | core/DataAccess/ArchiveWriter.php | 3 | ||||
-rw-r--r-- | core/Filesystem.php | 12 | ||||
-rw-r--r-- | core/FrontController.php | 4 | ||||
-rw-r--r-- | core/Mail.php | 5 | ||||
-rw-r--r-- | core/Metrics.php | 3 | ||||
-rw-r--r-- | core/MetricsFormatter.php | 217 | ||||
-rw-r--r-- | core/Nonce.php | 4 | ||||
-rw-r--r-- | core/Piwik.php | 372 | ||||
-rw-r--r-- | core/PluginsManager.php | 4 | ||||
-rw-r--r-- | core/ReportRenderer/Html.php | 8 | ||||
-rw-r--r-- | core/Segment.php | 5 | ||||
-rw-r--r-- | core/SettingsPiwik.php | 180 | ||||
-rw-r--r-- | core/Timer.php | 4 | ||||
-rw-r--r-- | core/Twig.php | 10 | ||||
-rw-r--r-- | core/View.php | 2 | ||||
-rw-r--r-- | core/ViewDataTable.php | 16 |
22 files changed, 445 insertions, 453 deletions
diff --git a/core/ArchiveProcessor/Period.php b/core/ArchiveProcessor/Period.php index 778b41f075..02d1af72db 100644 --- a/core/ArchiveProcessor/Period.php +++ b/core/ArchiveProcessor/Period.php @@ -13,13 +13,12 @@ namespace Piwik\ArchiveProcessor; use Exception; use Piwik\Archive; -use Piwik\Metrics; -use Piwik\Piwik; -use Piwik\Common; use Piwik\ArchiveProcessor; +use Piwik\Common; use Piwik\DataTable; -use Piwik\DataTable\Map; use Piwik\DataTable\Manager; +use Piwik\Metrics; +use Piwik\SettingsPiwik; /** * This class provides generic methods to archive data for a period (week / month / year). @@ -266,7 +265,7 @@ class Period extends ArchiveProcessor protected function enrichWithUniqueVisitorsMetric(&$results) { if (array_key_exists('nb_uniq_visitors', $results)) { - if (Piwik::isUniqueVisitorsEnabled($this->getPeriod()->getLabel())) { + if (SettingsPiwik::isUniqueVisitorsEnabled($this->getPeriod()->getLabel())) { $results['nb_uniq_visitors'] = (float)$this->computeNbUniqVisitors(); } else { unset($results['nb_uniq_visitors']); diff --git a/core/ArchiveProcessor/Rules.php b/core/ArchiveProcessor/Rules.php index eadb6ad244..9b40be42bc 100644 --- a/core/ArchiveProcessor/Rules.php +++ b/core/ArchiveProcessor/Rules.php @@ -15,6 +15,7 @@ use Piwik\Config; use Piwik\Date; use Piwik\Piwik; use Piwik\Segment; +use Piwik\SettingsPiwik; use Piwik\SettingsServer; use Piwik\Site; use Piwik\Tracker\Cache; @@ -59,7 +60,7 @@ class Rules return true; } - $segmentsToProcess = Piwik::getKnownSegmentsToArchive(); + $segmentsToProcess = SettingsPiwik::getKnownSegmentsToArchive(); if (!empty($segmentsToProcess)) { // If the requested segment is one of the segments to pre-process // we ensure that any call to the API will trigger archiving of all reports for this segment diff --git a/core/AssetManager.php b/core/AssetManager.php index 1f4a190475..b5ae6a6a5f 100644 --- a/core/AssetManager.php +++ b/core/AssetManager.php @@ -86,7 +86,7 @@ class AssetManager public static function generateAssetsCacheBuster() { $pluginList = md5(implode(",", PluginsManager::getInstance()->getLoadedPluginsName())); - $cacheBuster = md5(Common::getSalt() . $pluginList . PHP_VERSION . Version::VERSION); + $cacheBuster = md5(SettingsPiwik::getSalt() . $pluginList . PHP_VERSION . Version::VERSION); return $cacheBuster; } diff --git a/core/Common.php b/core/Common.php index d115cc53ed..36ff82061e 100644 --- a/core/Common.php +++ b/core/Common.php @@ -587,20 +587,6 @@ class Common } /** - * Get salt from [superuser] section - * - * @return string - */ - public static function getSalt() - { - static $salt = null; - if (is_null($salt)) { - $salt = @Config::getInstance()->superuser['salt']; - } - return $salt; - } - - /** * Configureable hash() algorithm (defaults to md5) * * @param string $str String to be hashed diff --git a/core/Controller.php b/core/Controller.php index b1d394430d..c241085848 100644 --- a/core/Controller.php +++ b/core/Controller.php @@ -11,23 +11,14 @@ namespace Piwik; use Exception; -use Piwik\Config; +use Piwik\API\Request; use Piwik\DataTable\Filter\CalculateEvolutionFilter; -use Piwik\Period; use Piwik\Period\Month; +use Piwik\Period; use Piwik\Period\Range; -use Piwik\Piwik; -use Piwik\Common; -use Piwik\Access; -use Piwik\NoAccessException; -use Piwik\Date; -use Piwik\Site; use Piwik\Plugins\API\API; -use Piwik\API\Request; -use Piwik\FrontController; use Piwik\Plugins\LanguagesManager\LanguagesManager; use Piwik\Plugins\SitesManager\API as SitesManagerAPI; -use Piwik\Url; use Piwik\Plugins\UsersManager\API as UsersManagerAPI; use Piwik\View; use Piwik\ViewDataTable; @@ -549,7 +540,7 @@ abstract class Controller } $currentPeriod = Common::getRequestVar('period'); - $view->displayUniqueVisitors = Piwik::isUniqueVisitorsEnabled($currentPeriod); + $view->displayUniqueVisitors = SettingsPiwik::isUniqueVisitorsEnabled($currentPeriod); $availablePeriods = array('day', 'week', 'month', 'year', 'range'); if (!in_array($currentPeriod, $availablePeriods)) { throw new Exception("Period must be one of: " . implode(",", $availablePeriods)); diff --git a/core/Cookie.php b/core/Cookie.php index 84246569af..4492fffb72 100644 --- a/core/Cookie.php +++ b/core/Cookie.php @@ -10,8 +10,6 @@ */ namespace Piwik; -use Piwik\Common; - /** * Simple class to handle the cookies: * - read a cookie values @@ -206,7 +204,7 @@ class Cookie { $signature = substr($content, -40); if (substr($content, -43, 3) == self::VALUE_SEPARATOR . '_=' && - $signature == sha1(substr($content, 0, -40) . Common::getSalt()) + $signature == sha1(substr($content, 0, -40) . SettingsPiwik::getSalt()) ) { // strip trailing: VALUE_SEPARATOR '_=' signature" return substr($content, 0, -43); @@ -272,7 +270,7 @@ class Cookie $cookieStr .= '_='; // sign cookie - $signature = sha1($cookieStr . Common::getSalt()); + $signature = sha1($cookieStr . SettingsPiwik::getSalt()); return $cookieStr . $signature; } diff --git a/core/DataAccess/ArchiveWriter.php b/core/DataAccess/ArchiveWriter.php index 18bc227d74..45027c5bd3 100644 --- a/core/DataAccess/ArchiveWriter.php +++ b/core/DataAccess/ArchiveWriter.php @@ -20,6 +20,7 @@ use Piwik\Db\BatchInsert; use Piwik\Period; use Piwik\Piwik; use Piwik\Segment; +use Piwik\SettingsPiwik; /** * This class is used to create a new Archive. @@ -134,7 +135,7 @@ class ArchiveWriter . $period->getId() . '/' . $period->getDateStart()->toString('Y-m-d') . ',' . $period->getDateEnd()->toString('Y-m-d'); - return $lockName . '/' . md5($lockName . Common::getSalt()); + return $lockName . '/' . md5($lockName . SettingsPiwik::getSalt()); } public function finalizeArchive() diff --git a/core/Filesystem.php b/core/Filesystem.php index 45877e6763..34b66ed777 100644 --- a/core/Filesystem.php +++ b/core/Filesystem.php @@ -11,10 +11,22 @@ namespace Piwik; use Exception; +use Piwik\Tracker\Cache; class Filesystem { /** + * Called on Core install, update, plugin enable/disable + * Will clear all cache that could be affected by the change in configuration being made + */ + public static function deleteAllCacheOnUpdate() + { + AssetManager::removeMergedAssets(); + View::clearCompiledTemplates(); + Cache::deleteTrackerCache(); + } + + /** * ending WITHOUT slash * * @return string diff --git a/core/FrontController.php b/core/FrontController.php index 693d5bd5ae..e3db4927d8 100644 --- a/core/FrontController.php +++ b/core/FrontController.php @@ -276,8 +276,8 @@ class FrontController PluginsManager::getInstance()->installLoadedPlugins(); // ensure the current Piwik URL is known for later use - if (method_exists('Piwik\Piwik', 'getPiwikUrl')) { - $host = Piwik::getPiwikUrl(); + if (method_exists('Piwik\SettingsPiwik', 'getPiwikUrl')) { + $host = SettingsPiwik::getPiwikUrl(); } Piwik_PostEvent('FrontController.initAuthenticationObject'); diff --git a/core/Mail.php b/core/Mail.php index 1ffbc5d2e4..27ccf629ef 100644 --- a/core/Mail.php +++ b/core/Mail.php @@ -10,9 +10,6 @@ */ namespace Piwik; -use Piwik\Config; -use Piwik\Piwik; -use Piwik\Url; use Zend_Mail; /** @@ -48,7 +45,7 @@ class Mail extends Zend_Mail $piwikHost = Url::getCurrentHost($hostname); // If known Piwik URL, use it instead of "localhost" - $piwikUrl = Piwik::getPiwikUrl(); + $piwikUrl = SettingsPiwik::getPiwikUrl(); $url = parse_url($piwikUrl); if (isset($url['host']) && $url['host'] != 'localhost' diff --git a/core/Metrics.php b/core/Metrics.php index 3d6bc17c48..ada20a7646 100644 --- a/core/Metrics.php +++ b/core/Metrics.php @@ -9,7 +9,6 @@ * @package Piwik */ namespace Piwik; -use Piwik\Piwik; /** * This class holds the various mappings we use to internally store and manipulate metrics. @@ -194,7 +193,7 @@ class Metrics { $nameToUnit = array( '_rate' => '%', - 'revenue' => Piwik::getCurrency($idSite), + 'revenue' => MetricsFormatter::getCurrencySymbol($idSite), '_time_' => 's' ); diff --git a/core/MetricsFormatter.php b/core/MetricsFormatter.php new file mode 100644 index 0000000000..63794f3c81 --- /dev/null +++ b/core/MetricsFormatter.php @@ -0,0 +1,217 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * @category Piwik + * @package Piwik + */ +namespace Piwik; + +use Piwik\Tracker\GoalManager; + +class MetricsFormatter +{ + /** + * Gets a prettified string representation of a number. The result will have + * thousands separators and a decimal point specific to the current locale. + * + * @param number $value + * @return string + */ + public static function getPrettyNumber($value) + { + $locale = localeconv(); + + $decimalPoint = $locale['decimal_point']; + $thousandsSeparator = $locale['thousands_sep']; + + return number_format($value, 0, $decimalPoint, $thousandsSeparator); + } + + /** + * Pretty format a time + * + * @param int $numberOfSeconds + * @param bool $displayTimeAsSentence If set to true, will output "5min 17s", if false "00:05:17" + * @param bool $isHtml + * @param bool $round to the full seconds + * @return string + */ + public static function getPrettyTimeFromSeconds($numberOfSeconds, $displayTimeAsSentence = true, $isHtml = true, $round = false) + { + $numberOfSeconds = $round ? (int)$numberOfSeconds : (float)$numberOfSeconds; + + // Display 01:45:17 time format + if ($displayTimeAsSentence === false) { + $hours = floor($numberOfSeconds / 3600); + $minutes = floor(($reminder = ($numberOfSeconds - $hours * 3600)) / 60); + $seconds = floor($reminder - $minutes * 60); + $time = sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes) . ':' . sprintf("%02s", $seconds); + $centiSeconds = ($numberOfSeconds * 100) % 100; + if ($centiSeconds) { + $time .= '.' . sprintf("%02s", $centiSeconds); + } + return $time; + } + $secondsInYear = 86400 * 365.25; + $years = floor($numberOfSeconds / $secondsInYear); + $minusYears = $numberOfSeconds - $years * $secondsInYear; + $days = floor($minusYears / 86400); + + $minusDays = $numberOfSeconds - $days * 86400; + $hours = floor($minusDays / 3600); + + $minusDaysAndHours = $minusDays - $hours * 3600; + $minutes = floor($minusDaysAndHours / 60); + + $seconds = $minusDaysAndHours - $minutes * 60; + $precision = ($seconds > 0 && $seconds < 0.01 ? 3 : 2); + $seconds = round($seconds, $precision); + + if ($years > 0) { + $return = sprintf(Piwik_Translate('General_YearsDays'), $years, $days); + } elseif ($days > 0) { + $return = sprintf(Piwik_Translate('General_DaysHours'), $days, $hours); + } elseif ($hours > 0) { + $return = sprintf(Piwik_Translate('General_HoursMinutes'), $hours, $minutes); + } elseif ($minutes > 0) { + $return = sprintf(Piwik_Translate('General_MinutesSeconds'), $minutes, $seconds); + } else { + $return = sprintf(Piwik_Translate('General_Seconds'), $seconds); + } + if ($isHtml) { + return str_replace(' ', ' ', $return); + } + return $return; + } + + /** + * Pretty format a memory size value + * + * @param number $size size in bytes + * @param string $unit The specific unit to use, if any. If null, the unit is determined by $size. + * @param int $precision The precision to use when rounding. + * @return string + */ + public static function getPrettySizeFromBytes($size, $unit = null, $precision = 1) + { + if ($size == 0) { + return '0 M'; + } + + $units = array('B', 'K', 'M', 'G', 'T'); + foreach ($units as $currentUnit) { + if ($size >= 1024 && $unit != $currentUnit) { + $size = $size / 1024; + } else { + break; + } + } + return round($size, $precision) . " " . $currentUnit; + } + + /** + * Pretty format monetary value for a site + * + * @param int|string $value + * @param int $idSite + * @param bool $htmlAllowed + * @return string + */ + public static function getPrettyMoney($value, $idSite, $htmlAllowed = true) + { + $currencyBefore = MetricsFormatter::getCurrencySymbol($idSite); + + $space = ' '; + if ($htmlAllowed) { + $space = ' '; + } + + $currencyAfter = ''; + // manually put the currency symbol after the amount for euro + // (maybe more currencies prefer this notation?) + if (in_array($currencyBefore, array('€', 'kr'))) { + $currencyAfter = $space . $currencyBefore; + $currencyBefore = ''; + } + + // if the input is a number (it could be a string or INPUT form), + // and if this number is not an int, we round to precision 2 + if (is_numeric($value)) { + if ($value == round($value)) { + // 0.0 => 0 + $value = round($value); + } else { + $precision = GoalManager::REVENUE_PRECISION; + $value = sprintf("%01." . $precision . "f", $value); + } + } + $prettyMoney = $currencyBefore . $space . $value . $currencyAfter; + return $prettyMoney; + } + + /** + * For the given value, based on the column name, will apply: pretty time, pretty money + * @param int $idSite + * @param string $columnName + * @param mixed $value + * @param bool $htmlAllowed + * @return string + */ + public static function getPrettyValue($idSite, $columnName, $value, $htmlAllowed) + { + // Display time in human readable + if (strpos($columnName, 'time') !== false) { + // Little hack: Display 15s rather than 00:00:15, only for "(avg|min|max)_generation_time" + $timeAsSentence = (substr($columnName, -16) == '_time_generation'); + return self::getPrettyTimeFromSeconds($value, $timeAsSentence); + } + // Add revenue symbol to revenues + if (strpos($columnName, 'revenue') !== false && strpos($columnName, 'evolution') === false) { + return self::getPrettyMoney($value, $idSite, $htmlAllowed); + } + // Add % symbol to rates + if (strpos($columnName, '_rate') !== false) { + if (strpos($value, "%") === false) { + return $value . "%"; + } + } + return $value; + } + + /** + * Get currency symbol for a site + * + * @param int $idSite + * @return string + */ + public static function getCurrencySymbol($idSite) + { + $symbols = MetricsFormatter::getCurrencyList(); + $site = new Site($idSite); + $currency = $site->getCurrency(); + if (isset($symbols[$currency])) { + return $symbols[$currency][0]; + } + + return ''; + } + + /** + * Returns a list of currency symbols + * + * @return array array( currencyCode => symbol, ... ) + */ + public static function getCurrencyList() + { + static $currenciesList = null; + if (is_null($currenciesList)) { + require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Currencies.php'; + $currenciesList = $GLOBALS['Piwik_CurrencyList']; + } + return $currenciesList; + } +}
\ No newline at end of file diff --git a/core/Nonce.php b/core/Nonce.php index d7606854f9..136db339af 100644 --- a/core/Nonce.php +++ b/core/Nonce.php @@ -10,9 +10,7 @@ */ namespace Piwik; -use Piwik\Common; use Piwik\Session\SessionNamespace; -use Piwik\Url; /** * Nonce class. @@ -46,7 +44,7 @@ class Nonce // to handle browser pre-fetch or double fetch caused by some browser add-ons/extensions if (empty($nonce)) { // generate a new nonce - $nonce = md5(Common::getSalt() . time() . Common::generateUniqId()); + $nonce = md5(SettingsPiwik::getSalt() . time() . Common::generateUniqId()); $ns->nonce = $nonce; $ns->setExpirationSeconds($ttl, 'nonce'); } diff --git a/core/Piwik.php b/core/Piwik.php index 926393a531..75f37139b9 100644 --- a/core/Piwik.php +++ b/core/Piwik.php @@ -18,9 +18,7 @@ use Piwik\Log\ScreenFormatter; use Piwik\Plugin; use Piwik\Plugins\UsersManager\API; use Piwik\Session; -use Piwik\Tracker\Cache; use Piwik\Tracker; -use Piwik\Tracker\GoalManager; use Piwik\View; use Zend_Registry; @@ -62,42 +60,6 @@ class Piwik const LABEL_ID_GOAL_IS_ECOMMERCE_ORDER = 'ecommerceOrder'; /** - * Should we process and display Unique Visitors? - * -> Always process for day/week/month periods - * For Year and Range, only process if it was enabled in the config file, - * - * @param string $periodLabel Period label (e.g., 'day') - * @return bool - */ - static public function isUniqueVisitorsEnabled($periodLabel) - { - $generalSettings = Config::getInstance()->General; - - $settingName = "enable_processing_unique_visitors_$periodLabel"; - $result = !empty($generalSettings[$settingName]) && $generalSettings[$settingName] == 1; - - // check enable_processing_unique_visitors_year_and_range for backwards compatibility - if (($periodLabel == 'year' || $periodLabel == 'range') - && isset($generalSettings['enable_processing_unique_visitors_year_and_range']) - ) { - $result |= $generalSettings['enable_processing_unique_visitors_year_and_range'] == 1; - } - - return $result; - } - - /** - * Returns true if Segmentation is allowed for this user - * - * @return bool - */ - public static function isSegmentationEnabled() - { - return !Piwik::isUserIsAnonymous() - || Config::getInstance()->General['anonymous_user_enable_use_segments_API']; - } - - /** * Uninstallation helper */ static public function uninstall() @@ -122,69 +84,6 @@ class Piwik } /** - * Called on Core install, update, plugin enable/disable - * Will clear all cache that could be affected by the change in configuration being made - */ - static public function deleteAllCacheOnUpdate() - { - AssetManager::removeMergedAssets(); - View::clearCompiledTemplates(); - Cache::deleteTrackerCache(); - } - - /** - * Cache for result of getPiwikUrl. - * Can be overwritten for testing purposes only. - * - * @var string - */ - static public $piwikUrlCache = null; - - /** - * Returns the cached the Piwik URL, eg. http://demo.piwik.org/ or http://example.org/piwik/ - * If not found, then tries to cache it and returns the value. - * - * If the Piwik URL changes (eg. Piwik moved to new server), the value will automatically be refreshed in the cache. - * - * @return string - */ - static public function getPiwikUrl() - { - // Only set in tests - if (self::$piwikUrlCache !== null) { - return self::$piwikUrlCache; - } - - $key = 'piwikUrl'; - $url = Piwik_GetOption($key); - if (SettingsServer::isPhpCliMode() - // in case archive.php is triggered with domain localhost - || SettingsServer::isArchivePhpTriggered() - || defined('PIWIK_MODE_ARCHIVE') - ) { - return $url; - } - - $currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName()); - - if (empty($url) - // if URL changes, always update the cache - || $currentUrl != $url - ) { - if (strlen($currentUrl) >= strlen('http://a/')) { - Piwik_SetOption($key, $currentUrl, $autoLoad = true); - } - $url = $currentUrl; - } - return $url; - } - - - /* - * PHP environment settings - */ - - /** * Logging and error handling * * @var bool|null @@ -199,7 +98,7 @@ class Piwik static public function log($message = '') { if (is_null(self::$shouldLog)) { - self::$shouldLog = self::shouldLoggerLog(); + self::$shouldLog = SettingsPiwik::shouldLoggerLog(); // It is possible that the logger is not setup: // - Tracker request, and debug disabled, // - and some scheduled tasks call code that tries and log something @@ -215,24 +114,6 @@ class Piwik } /** - * Returns if logging should work - * @return bool - */ - static public function shouldLoggerLog() - { - try { - $shouldLog = (SettingsServer::isPhpCliMode() - || Config::getInstance()->log['log_only_when_cli'] == 0) - && - (Config::getInstance()->log['log_only_when_debug_parameter'] == 0 - || isset($_REQUEST['debug'])); - } catch (Exception $e) { - $shouldLog = false; - } - return $shouldLog; - } - - /** * Trigger E_USER_ERROR with optional message * * @param string $message @@ -264,21 +145,6 @@ class Piwik */ /** - * Returns a list of currency symbols - * - * @return array array( currencyCode => symbol, ... ) - */ - static public function getCurrencyList() - { - static $currenciesList = null; - if (is_null($currenciesList)) { - require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Currencies.php'; - $currenciesList = $GLOBALS['Piwik_CurrencyList']; - } - return $currenciesList; - } - - /** * Computes the division of i1 by i2. If either i1 or i2 are not number, or if i2 has a value of zero * we return 0 to avoid the division by zero. * @@ -311,192 +177,6 @@ class Piwik } /** - * Get currency symbol for a site - * - * @param int $idSite - * @return string - */ - static public function getCurrency($idSite) - { - $symbols = self::getCurrencyList(); - $site = new Site($idSite); - $currency = $site->getCurrency(); - if (isset($symbols[$currency])) { - return $symbols[$currency][0]; - } - - return ''; - } - - /** - * For the given value, based on the column name, will apply: pretty time, pretty money - * @param int $idSite - * @param string $columnName - * @param mixed $value - * @param bool $htmlAllowed - * @return string - */ - static public function getPrettyValue($idSite, $columnName, $value, $htmlAllowed) - { - // Display time in human readable - if (strpos($columnName, 'time') !== false) { - // Little hack: Display 15s rather than 00:00:15, only for "(avg|min|max)_generation_time" - $timeAsSentence = (substr($columnName, -16) == '_time_generation'); - return Piwik::getPrettyTimeFromSeconds($value, $timeAsSentence); - } - // Add revenue symbol to revenues - if (strpos($columnName, 'revenue') !== false && strpos($columnName, 'evolution') === false) { - return Piwik::getPrettyMoney($value, $idSite, $htmlAllowed); - } - // Add % symbol to rates - if (strpos($columnName, '_rate') !== false) { - if (strpos($value, "%") === false) { - return $value . "%"; - } - } - return $value; - } - - /** - * Pretty format monetary value for a site - * - * @param int|string $value - * @param int $idSite - * @param bool $htmlAllowed - * @return string - */ - static public function getPrettyMoney($value, $idSite, $htmlAllowed = true) - { - $currencyBefore = self::getCurrency($idSite); - - $space = ' '; - if ($htmlAllowed) { - $space = ' '; - } - - $currencyAfter = ''; - // manually put the currency symbol after the amount for euro - // (maybe more currencies prefer this notation?) - if (in_array($currencyBefore, array('€', 'kr'))) { - $currencyAfter = $space . $currencyBefore; - $currencyBefore = ''; - } - - // if the input is a number (it could be a string or INPUT form), - // and if this number is not an int, we round to precision 2 - if (is_numeric($value)) { - if ($value == round($value)) { - // 0.0 => 0 - $value = round($value); - } else { - $precision = GoalManager::REVENUE_PRECISION; - $value = sprintf("%01." . $precision . "f", $value); - } - } - $prettyMoney = $currencyBefore . $space . $value . $currencyAfter; - return $prettyMoney; - } - - /** - * Pretty format a memory size value - * - * @param number $size size in bytes - * @param string $unit The specific unit to use, if any. If null, the unit is determined by $size. - * @param int $precision The precision to use when rounding. - * @return string - */ - static public function getPrettySizeFromBytes($size, $unit = null, $precision = 1) - { - if ($size == 0) { - return '0 M'; - } - - $units = array('B', 'K', 'M', 'G', 'T'); - foreach ($units as $currentUnit) { - if ($size >= 1024 && $unit != $currentUnit) { - $size = $size / 1024; - } else { - break; - } - } - return round($size, $precision) . " " . $currentUnit; - } - - /** - * Pretty format a time - * - * @param int $numberOfSeconds - * @param bool $displayTimeAsSentence If set to true, will output "5min 17s", if false "00:05:17" - * @param bool $isHtml - * @param bool $round to the full seconds - * @return string - */ - static public function getPrettyTimeFromSeconds($numberOfSeconds, $displayTimeAsSentence = true, $isHtml = true, $round = false) - { - $numberOfSeconds = $round ? (int)$numberOfSeconds : (float)$numberOfSeconds; - - // Display 01:45:17 time format - if ($displayTimeAsSentence === false) { - $hours = floor($numberOfSeconds / 3600); - $minutes = floor(($reminder = ($numberOfSeconds - $hours * 3600)) / 60); - $seconds = floor($reminder - $minutes * 60); - $time = sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes) . ':' . sprintf("%02s", $seconds); - $centiSeconds = ($numberOfSeconds * 100) % 100; - if ($centiSeconds) { - $time .= '.' . sprintf("%02s", $centiSeconds); - } - return $time; - } - $secondsInYear = 86400 * 365.25; - $years = floor($numberOfSeconds / $secondsInYear); - $minusYears = $numberOfSeconds - $years * $secondsInYear; - $days = floor($minusYears / 86400); - - $minusDays = $numberOfSeconds - $days * 86400; - $hours = floor($minusDays / 3600); - - $minusDaysAndHours = $minusDays - $hours * 3600; - $minutes = floor($minusDaysAndHours / 60); - - $seconds = $minusDaysAndHours - $minutes * 60; - $precision = ($seconds > 0 && $seconds < 0.01 ? 3 : 2); - $seconds = round($seconds, $precision); - - if ($years > 0) { - $return = sprintf(Piwik_Translate('General_YearsDays'), $years, $days); - } elseif ($days > 0) { - $return = sprintf(Piwik_Translate('General_DaysHours'), $days, $hours); - } elseif ($hours > 0) { - $return = sprintf(Piwik_Translate('General_HoursMinutes'), $hours, $minutes); - } elseif ($minutes > 0) { - $return = sprintf(Piwik_Translate('General_MinutesSeconds'), $minutes, $seconds); - } else { - $return = sprintf(Piwik_Translate('General_Seconds'), $seconds); - } - if ($isHtml) { - return str_replace(' ', ' ', $return); - } - return $return; - } - - /** - * Gets a prettified string representation of a number. The result will have - * thousands separators and a decimal point specific to the current locale. - * - * @param number $value - * @return string - */ - static public function getPrettyNumber($value) - { - $locale = localeconv(); - - $decimalPoint = $locale['decimal_point']; - $thousandsSeparator = $locale['thousands_sep']; - - return number_format($value, 0, $decimalPoint, $thousandsSeparator); - } - - /** * Returns the Javascript code to be inserted on every page to track * * @param int $idSite @@ -538,44 +218,6 @@ class Piwik return $title; } - /** - * Number of websites to show in the Website selector - * - * @return int - */ - static public function getWebsitesCountToDisplay() - { - $count = max(Config::getInstance()->General['site_selector_max_sites'], - Config::getInstance()->General['autocomplete_min_sites']); - return (int)$count; - } - - /** - * Segments to pre-process - * - * @return string - */ - static public function getKnownSegmentsToArchive() - { - if (self::$cachedKnownSegmentsToArchive === null) { - $segments = Config::getInstance()->Segments; - $cachedResult = isset($segments['Segments']) ? $segments['Segments'] : array(); - - Piwik_PostEvent('Piwik.getKnownSegmentsToArchiveAllSites', array(&$cachedResult)); - - self::$cachedKnownSegmentsToArchive = array_unique($cachedResult); - } - - return self::$cachedKnownSegmentsToArchive; - } - - static public function getKnownSegmentsToArchiveForSite($idSite) - { - $segments = array(); - Piwik_PostEvent('Piwik.getKnownSegmentsToArchiveForSite', array(&$segments, $idSite)); - return $segments; - } - /* * Access */ @@ -1006,7 +648,7 @@ class Piwik */ static public function checkValidLoginString($userLogin) { - if (!self::isChecksEnabled() + if (!SettingsPiwik::isUserCredentialsSanityCheckEnabled() && !empty($userLogin) ) { return; @@ -1022,16 +664,6 @@ class Piwik } } - /** - * Should Piwik check that the login & password have minimum length and valid characters? - * - * @return bool True if checks enabled; false otherwise - */ - static public function isChecksEnabled() - { - return Config::getInstance()->General['disable_checks_usernames_attributes'] == 0; - } - /* * Database and table definition methods */ diff --git a/core/PluginsManager.php b/core/PluginsManager.php index 2df4707994..b56f4a4e43 100644 --- a/core/PluginsManager.php +++ b/core/PluginsManager.php @@ -243,7 +243,7 @@ class PluginsManager } Config::getInstance()->forceSave(); - Piwik::deleteAllCacheOnUpdate(); + Filesystem::deleteAllCacheOnUpdate(); return $plugins; } @@ -310,7 +310,7 @@ class PluginsManager $this->updatePluginsConfig($plugins); Config::getInstance()->forceSave(); - Piwik::deleteAllCacheOnUpdate(); + Filesystem::deleteAllCacheOnUpdate(); } protected function isPluginInFilesystem($pluginName) diff --git a/core/ReportRenderer/Html.php b/core/ReportRenderer/Html.php index 40055bbaa6..4e8a2c53cf 100644 --- a/core/ReportRenderer/Html.php +++ b/core/ReportRenderer/Html.php @@ -10,10 +10,10 @@ */ namespace Piwik\ReportRenderer; -use Piwik\Piwik; -use Piwik\View; -use Piwik\ReportRenderer; use Piwik\Plugins\API\API; +use Piwik\ReportRenderer; +use Piwik\SettingsPiwik; +use Piwik\View; /** * @@ -119,7 +119,7 @@ class Html extends ReportRenderer $view->assign("reportTableHeaderTextSize", self::REPORT_TABLE_HEADER_TEXT_SIZE); $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("currentPath", SettingsPiwik::getPiwikUrl()); $view->assign("logoHeader", API::getInstance()->getHeaderLogoUrl()); } diff --git a/core/Segment.php b/core/Segment.php index 8687362a56..508afbdd11 100644 --- a/core/Segment.php +++ b/core/Segment.php @@ -10,10 +10,7 @@ */ namespace Piwik; use Exception; -use Piwik\Piwik; -use Piwik\Common; use Piwik\Plugins\API\API; -use Piwik\SegmentExpression; /** * @@ -34,7 +31,7 @@ class Segment public function __construct($string, $idSites) { $string = trim($string); - if (!Piwik::isSegmentationEnabled() + if (!SettingsPiwik::isSegmentationEnabled() && !empty($string) ) { throw new Exception("The Super User has disabled the Segmentation feature."); diff --git a/core/SettingsPiwik.php b/core/SettingsPiwik.php new file mode 100644 index 0000000000..8067c8a215 --- /dev/null +++ b/core/SettingsPiwik.php @@ -0,0 +1,180 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * @category Piwik + * @package Piwik + */ +namespace Piwik; + +use Exception; + +class SettingsPiwik +{ + /** + * Get salt from [superuser] section + * + * @return string + */ + public static function getSalt() + { + static $salt = null; + if (is_null($salt)) { + $salt = @Config::getInstance()->superuser['salt']; + } + return $salt; + } + + /** + * Should Piwik check that the login & password have minimum length and valid characters? + * + * @return bool True if checks enabled; false otherwise + */ + public static function isUserCredentialsSanityCheckEnabled() + { + return Config::getInstance()->General['disable_checks_usernames_attributes'] == 0; + } + + /** + * Segments to pre-process + * + * @return string + */ + static public function getKnownSegmentsToArchive() + { + if (self::$cachedKnownSegmentsToArchive === null) { + $segments = Config::getInstance()->Segments; + $cachedResult = isset($segments['Segments']) ? $segments['Segments'] : array(); + + Piwik_PostEvent('Piwik.getKnownSegmentsToArchiveAllSites', array(&$cachedResult)); + + self::$cachedKnownSegmentsToArchive = array_unique($cachedResult); + } + + return self::$cachedKnownSegmentsToArchive; + } + + + public static function getKnownSegmentsToArchiveForSite($idSite) + { + $segments = array(); + Piwik_PostEvent('Piwik.getKnownSegmentsToArchiveForSite', array(&$segments, $idSite)); + return $segments; + } + + /** + * Number of websites to show in the Website selector + * + * @return int + */ + public static function getWebsitesCountToDisplay() + { + $count = max(Config::getInstance()->General['site_selector_max_sites'], + Config::getInstance()->General['autocomplete_min_sites']); + return (int)$count; + } + + /** + * Returns if logging should work + * @return bool + */ + public static function shouldLoggerLog() + { + try { + $shouldLog = (SettingsServer::isPhpCliMode() + || Config::getInstance()->log['log_only_when_cli'] == 0) + && + (Config::getInstance()->log['log_only_when_debug_parameter'] == 0 + || isset($_REQUEST['debug'])); + } catch (Exception $e) { + $shouldLog = false; + } + return $shouldLog; + } + + /** + * Cache for result of getPiwikUrl. + * Can be overwritten for testing purposes only. + * + * @var string + */ + static public $piwikUrlCache = null; + + /** + * Returns the cached the Piwik URL, eg. http://demo.piwik.org/ or http://example.org/piwik/ + * If not found, then tries to cache it and returns the value. + * + * If the Piwik URL changes (eg. Piwik moved to new server), the value will automatically be refreshed in the cache. + * + * @return string + */ + public static function getPiwikUrl() + { + // Only set in tests + if (Piwik::$piwikUrlCache !== null) { + return Piwik::$piwikUrlCache; + } + + $key = 'piwikUrl'; + $url = Piwik_GetOption($key); + if (SettingsServer::isPhpCliMode() + // in case archive.php is triggered with domain localhost + || SettingsServer::isArchivePhpTriggered() + || defined('PIWIK_MODE_ARCHIVE') + ) { + return $url; + } + + $currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName()); + + if (empty($url) + // if URL changes, always update the cache + || $currentUrl != $url + ) { + if (strlen($currentUrl) >= strlen('http://a/')) { + Piwik_SetOption($key, $currentUrl, $autoLoad = true); + } + $url = $currentUrl; + } + return $url; + } + + /** + * Returns true if Segmentation is allowed for this user + * + * @return bool + */ + public static function isSegmentationEnabled() + { + return !Piwik::isUserIsAnonymous() + || Config::getInstance()->General['anonymous_user_enable_use_segments_API']; + } + + /** + * Should we process and display Unique Visitors? + * -> Always process for day/week/month periods + * For Year and Range, only process if it was enabled in the config file, + * + * @param string $periodLabel Period label (e.g., 'day') + * @return bool + */ + public static function isUniqueVisitorsEnabled($periodLabel) + { + $generalSettings = Config::getInstance()->General; + + $settingName = "enable_processing_unique_visitors_$periodLabel"; + $result = !empty($generalSettings[$settingName]) && $generalSettings[$settingName] == 1; + + // check enable_processing_unique_visitors_year_and_range for backwards compatibility + if (($periodLabel == 'year' || $periodLabel == 'range') + && isset($generalSettings['enable_processing_unique_visitors_year_and_range']) + ) { + $result |= $generalSettings['enable_processing_unique_visitors_year_and_range'] == 1; + } + + return $result; + } +} diff --git a/core/Timer.php b/core/Timer.php index c1d17a8020..cddb7cb93f 100644 --- a/core/Timer.php +++ b/core/Timer.php @@ -10,8 +10,6 @@ */ namespace Piwik; -use Piwik\Piwik; - /** * * @package Piwik @@ -61,7 +59,7 @@ class Timer */ public function getMemoryLeak() { - return "Memory delta: " . Piwik::getPrettySizeFromBytes($this->getMemoryUsage() - $this->memoryStart); + return "Memory delta: " . MetricsFormatter::getPrettySizeFromBytes($this->getMemoryUsage() - $this->memoryStart); } /** diff --git a/core/Twig.php b/core/Twig.php index 09dbe27940..59fabb8a2e 100644 --- a/core/Twig.php +++ b/core/Twig.php @@ -11,13 +11,7 @@ namespace Piwik; use Exception; -use Piwik\API\Request; -use Piwik\Piwik; -use Piwik\Common; -use Piwik\AssetManager; use Piwik\Translate; -use Piwik\Url; -use Piwik\PluginsManager; use Piwik\Visualization\Sparkline; use Twig_Environment; use Twig_Extension_Debug; @@ -170,7 +164,7 @@ class Twig } $idSite = func_get_args(); $idSite = $idSite[1]; - return Piwik::getPrettyMoney($amount, $idSite); + return MetricsFormatter::getPrettyMoney($amount, $idSite); }); $this->twig->addFilter($moneyFilter); } @@ -178,7 +172,7 @@ class Twig protected function addFilter_sumTime() { $sumtimeFilter = new Twig_SimpleFilter('sumtime', function ($numberOfSeconds) { - return Piwik::getPrettyTimeFromSeconds($numberOfSeconds); + return MetricsFormatter::getPrettyTimeFromSeconds($numberOfSeconds); }); $this->twig->addFilter($sumtimeFilter); } diff --git a/core/View.php b/core/View.php index 910e5b1397..98406e30cc 100644 --- a/core/View.php +++ b/core/View.php @@ -99,7 +99,7 @@ class View implements ViewInterface $userLogin = Piwik::getCurrentUserLogin(); $this->userLogin = $userLogin; - $count = Piwik::getWebsitesCountToDisplay(); + $count = SettingsPiwik::getWebsitesCountToDisplay(); $sites = SitesManagerAPI::getInstance()->getSitesWithAtLeastViewAccess($count); usort($sites, function($site1, $site2) { diff --git a/core/ViewDataTable.php b/core/ViewDataTable.php index fd4d171615..5fdd36c32a 100644 --- a/core/ViewDataTable.php +++ b/core/ViewDataTable.php @@ -10,21 +10,13 @@ */ namespace Piwik; -use Piwik\Config; -use Piwik\Metrics; -use Piwik\Period; use Piwik\API\Request; -use Piwik\Period\Range; -use Piwik\Piwik; -use Piwik\NoAccessException; -use Piwik\Common; -use Piwik\Date; use Piwik\DataTable; -use Piwik\Url; -use Piwik\Site; +use Piwik\Period; +use Piwik\Period\Range; +use Piwik\Plugins\API\API; use Piwik\ViewDataTable\Properties; use Piwik\ViewDataTable\VisualizationPropertiesProxy; -use Piwik\Plugins\API\API; /** * This class is used to load (from the API) and customize the output of a given DataTable. @@ -645,7 +637,7 @@ class ViewDataTable $today = mktime(0, 0, 0); if ($date->getTimestamp() > $today) { $elapsedSeconds = time() - $date->getTimestamp(); - $timeAgo = Piwik::getPrettyTimeFromSeconds($elapsedSeconds); + $timeAgo = MetricsFormatter::getPrettyTimeFromSeconds($elapsedSeconds); return Piwik_Translate('CoreHome_ReportGeneratedXAgo', $timeAgo); } |