Returns true if the current request is a Tracker request.
public static isTrackerApiRequest ( ) : boolean | ||
Résultat | boolean | true if the current request is a Tracking API Request (ie. piwik.php) |
public function validate() { $inTrackerRequest = SettingsServer::isTrackerApiRequest(); $inConsole = Common::isPhpCliMode(); $this->checkConfigFileExists($this->settingsProvider->getPathGlobal()); $this->checkConfigFileExists($this->settingsProvider->getPathLocal(), $startInstaller = !$inTrackerRequest && !$inConsole); }
public static function make($pluginName) { if (SettingsServer::isTrackerApiRequest()) { $storage = new SettingsStorage($pluginName); } else { $storage = new Storage($pluginName); } return $storage; }
/** * Returns the database connection and creates it if it hasn't been already. * * @return \Piwik\Tracker\Db|\Piwik\Db\AdapterInterface|\Piwik\Db */ public static function get() { if (SettingsServer::isTrackerApiRequest()) { return Tracker::getDatabase(); } if (!self::hasDatabaseObject()) { self::createDatabaseObject(); } return self::$connection; }
public function validate() { $this->checkConfigFileExists($this->settingsProvider->getPathGlobal()); if (SettingsPiwik::isPiwikInstalled()) { $this->checkConfigFileExists($this->settingsProvider->getPathLocal(), $startInstaller = false); return; } $startInstaller = true; if (SettingsServer::isTrackerApiRequest()) { // if Piwik is not installed yet, the piwik.php should do nothing and not return an error throw new NotYetInstalledException("As Piwik is not installed yet, the Tracking API cannot proceed and will exit without error."); } if (Common::isPhpCliMode()) { // in CLI, do not start/redirect to installer, simply output the exception at the top $startInstaller = false; } // Start the installation when config file not found $this->checkConfigFileExists($this->settingsProvider->getPathLocal(), $startInstaller); }
/** * Load translation * * @param Plugin $plugin * @param string $langCode * @throws \Exception * @return bool whether the translation was found and loaded */ private function loadTranslation($plugin, $langCode) { // we are in Tracker mode if Loader is not (yet) loaded if (SettingsServer::isTrackerApiRequest()) { return false; } if (is_string($plugin)) { $pluginName = $plugin; } else { $pluginName = $plugin->getPluginName(); } $path = self::getPluginsDirectory() . $pluginName . '/lang/%s.json'; $defaultLangPath = sprintf($path, $langCode); $defaultEnglishLangPath = sprintf($path, 'en'); $translationsLoaded = false; // merge in english translations as default first if (file_exists($defaultEnglishLangPath)) { $translations = $this->getTranslationsFromFile($defaultEnglishLangPath); $translationsLoaded = true; if (isset($translations[$pluginName])) { // only merge translations of plugin - prevents overwritten strings Translate::mergeTranslationArray(array($pluginName => $translations[$pluginName])); } } // merge in specific language translations (to overwrite english defaults) if (!empty($langCode) && $defaultEnglishLangPath != $defaultLangPath && file_exists($defaultLangPath)) { $translations = $this->getTranslationsFromFile($defaultLangPath); $translationsLoaded = true; if (isset($translations[$pluginName])) { // only merge translations of plugin - prevents overwritten strings Translate::mergeTranslationArray(array($pluginName => $translations[$pluginName])); } } return $translationsLoaded; }
public function test_loadTrackerEnvironment_shouldNotThrow_whenConfigNotFound() { $this->assertTrue(!array_key_exists('PIWIK_TRACKER_DEBUG', $GLOBALS)); $this->assertFalse(SettingsServer::isTrackerApiRequest()); $this->assertTrue(is_readable(Config::getInstance()->getLocalPath())); $this->removeConfigFile(); $this->assertFalse(is_readable(Config::getInstance()->getLocalPath())); Tracker::loadTrackerEnvironment(); $this->assertTrue(SettingsServer::isTrackerApiRequest()); //always reset on the test itself $this->restoreConfigFile(); }
/** * @ignore */ public static function persistCache() { if (self::$isDirty) { if (SettingsServer::isTrackerApiRequest()) { $mode = '-tracker'; } else { $mode = '-ui'; } self::getStorage()->set(self::getCacheFilename() . $mode, self::$content); } }
/** * @param $setting * @throws \Exception */ private function checkHasEnoughReadPermission(Setting $setting) { // When the request is a Tracker request, allow plugins to read settings if (SettingsServer::isTrackerApiRequest()) { return; } if (!$setting->isReadableByCurrentUser()) { $errorMsg = Piwik::translate('CoreAdminHome_PluginSettingReadNotAllowed', array($setting->getName(), $this->pluginName)); throw new \Exception($errorMsg); } }
/** * Initializes Profiling via XHProf. * See: https://github.com/piwik/piwik/blob/master/tests/README.xhprof.md */ public static function setupProfilerXHProf($mainRun = false, $setupDuringTracking = false) { if (!$setupDuringTracking && SettingsServer::isTrackerApiRequest()) { // do not profile Tracker return; } if (self::$isXhprofSetup) { return; } $xhProfPath = PIWIK_INCLUDE_PATH . '/vendor/facebook/xhprof/extension/modules/xhprof.so'; if (!file_exists($xhProfPath)) { throw new Exception("Cannot find xhprof, run 'composer install --dev' and build the extension."); } if (!function_exists('xhprof_enable')) { throw new Exception("Cannot find xhprof_enable, make sure to add 'extension={$xhProfPath}' to your php.ini."); } $outputDir = ini_get("xhprof.output_dir"); if (empty($outputDir)) { throw new Exception("The profiler output dir is not set. Add 'xhprof.output_dir=...' to your php.ini."); } if (!is_writable($outputDir)) { throw new Exception("The profiler output dir '" . ini_get("xhprof.output_dir") . "' should exist and be writable."); } if (!function_exists('xhprof_error')) { function xhprof_error($out) { echo substr($out, 0, 300) . '...'; } } $currentGitBranch = SettingsPiwik::getCurrentGitBranch(); $profilerNamespace = "piwik"; if ($currentGitBranch != 'master') { $profilerNamespace .= "-" . $currentGitBranch; } if ($mainRun) { self::setProfilingRunIds(array()); } xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY); register_shutdown_function(function () use($profilerNamespace, $mainRun) { $xhprofData = xhprof_disable(); $xhprofRuns = new XHProfRuns_Default(); $runId = $xhprofRuns->save_run($xhprofData, $profilerNamespace); if (empty($runId)) { die('could not write profiler run'); } $runs = Profiler::getProfilingRunIds(); array_unshift($runs, $runId); if ($mainRun) { Profiler::aggregateXhprofRuns($runs, $profilerNamespace, $saveTo = $runId); $baseUrlStored = SettingsPiwik::getPiwikUrl(); $out = "\n\n"; $baseUrl = "http://" . @$_SERVER['HTTP_HOST'] . "/" . @$_SERVER['REQUEST_URI']; if (strlen($baseUrlStored) > strlen($baseUrl)) { $baseUrl = $baseUrlStored; } $baseUrl = $baseUrlStored . "vendor/facebook/xhprof/xhprof_html/?source={$profilerNamespace}&run={$runId}"; $out .= "Profiler report is available at:\n"; $out .= "<a href='{$baseUrl}'>{$baseUrl}</a>"; $out .= "\n\n"; if (Development::isEnabled()) { $out .= "WARNING: Development mode is enabled. Many runtime optimizations are not applied in development mode. "; $out .= "Unless you intend to profile Piwik in development mode, your profile may not be accurate."; $out .= "\n\n"; } echo $out; } else { Profiler::setProfilingRunIds($runs); } }); self::$isXhprofSetup = true; }
/** * Reloads config data from disk. * * @throws \Exception if the global config file is not found and this is a tracker request, or * if the local config file is not found and this is NOT a tracker request. */ public function reload() { $this->initialized = true; $inTrackerRequest = SettingsServer::isTrackerApiRequest(); // read defaults from global.ini.php if (!is_readable($this->pathGlobal) && $inTrackerRequest) { throw new Exception(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal))); } try { $this->settings->reload(array($this->pathGlobal, $this->pathCommon), $this->pathLocal); } catch (IniReadingException $e) { if ($inTrackerRequest) { throw $e; } } // Check config.ini.php last if (!$inTrackerRequest) { $this->checkLocalConfigFound(); } }
/** * Read configuration from files into memory * * @throws Exception if local config file is not readable; exits for other errors */ public function init() { $this->initialized = true; $reportError = SettingsServer::isTrackerApiRequest(); // read defaults from global.ini.php if (!is_readable($this->pathGlobal) && $reportError) { Piwik_ExitWithMessage(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal))); } $this->configGlobal = _parse_ini_file($this->pathGlobal, true); if (empty($this->configGlobal) && $reportError) { Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()"))); } $this->configCommon = _parse_ini_file($this->pathCommon, true); // Check config.ini.php last $this->checkLocalConfigFound(); $this->configLocal = _parse_ini_file($this->pathLocal, true); if (empty($this->configLocal) && $reportError) { Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()"))); } }
use Piwik\Cache\Eager; use Piwik\SettingsServer; return array('path.root' => PIWIK_USER_PATH, 'path.tmp' => function (ContainerInterface $c) { $root = $c->get('path.root'); // TODO remove that special case and instead have plugins override 'path.tmp' to add the instance id if ($c->has('ini.General.instance_id')) { $instanceId = $c->get('ini.General.instance_id'); $instanceId = $instanceId ? '/' . $instanceId : ''; } else { $instanceId = ''; } return $root . '/tmp' . $instanceId; }, 'path.cache' => DI\string('{path.tmp}/cache/tracker/'), 'Piwik\\Cache\\Eager' => function (ContainerInterface $c) { $backend = $c->get('Piwik\\Cache\\Backend'); $cacheId = $c->get('cache.eager.cache_id'); if (SettingsServer::isTrackerApiRequest()) { $eventToPersist = 'Tracker.end'; $cacheId .= 'tracker'; } else { $eventToPersist = 'Request.dispatch.end'; $cacheId .= 'ui'; } $cache = new Eager($backend, $cacheId); \Piwik\Piwik::addAction($eventToPersist, function () use($cache) { $cache->persistCacheIfNeeded(43200); }); return $cache; }, 'Piwik\\Cache\\Backend' => function (ContainerInterface $c) { try { $backend = $c->get('ini.Cache.backend'); } catch (NotFoundException $ex) {
private function makeStorage(BackendInterface $backend) { if (SettingsServer::isTrackerApiRequest()) { $backend = new Backend\Cache($backend); } return new Storage($backend); }
/** * Called at the end of the page generation */ public function __destruct() { try { if (class_exists('Piwik\\Profiler') && !SettingsServer::isTrackerApiRequest()) { // in tracker mode Piwik\Tracker\Db\Pdo\Mysql does currently not implement profiling Profiler::displayDbProfileReport(); Profiler::printQueryCount(); } } catch (Exception $e) { Log::debug($e); } }
public static function restoreTrackerPlugins() { if (SettingsServer::isTrackerApiRequest() && Tracker::$initTrackerMode) { Plugin\Manager::getInstance()->loadTrackerPlugins(); } }
/** * Used to initialize core Piwik components on a piwik.php request * Eg. when cache is missed and we will be calling some APIs to generate cache */ public static function initCorePiwikInTrackerMode() { if (SettingsServer::isTrackerApiRequest() && self::$initTrackerMode === false) { self::$initTrackerMode = true; require_once PIWIK_INCLUDE_PATH . '/core/Option.php'; Access::getInstance(); Config::getInstance(); try { Db::get(); } catch (Exception $e) { Db::createDatabaseObject(); } \Piwik\Plugin\Manager::getInstance()->loadCorePluginsDuringTracker(); } }
/** * Triggers an error if the development mode is enabled. Depending on the current environment / mode it will either * log the given message or throw an exception to make sure it will be displayed in the Piwik UI. * * @param string $message * @throws Exception */ public static function error($message) { if (!self::isEnabled()) { return; } $message .= ' (This error is only shown in development mode)'; if (SettingsServer::isTrackerApiRequest() || Common::isPhpCliMode()) { Log::error($message); } else { throw new Exception($message); } }