Example #1
0
 public function outputResponse(Tracker $tracker)
 {
     if (!$tracker->shouldRecordStatistics()) {
         $this->outputApiResponse($tracker);
         Common::printDebug("Logging disabled, display transparent logo");
     } elseif (!$tracker->hasLoggedRequests()) {
         if (!$this->isHttpGetRequest() || !empty($_GET) || !empty($_POST)) {
             Common::sendResponseCode(400);
         }
         Common::printDebug("Empty request => Piwik page");
         echo "<a href='/'>Piwik</a> is a free/libre web <a href='http://piwik.org'>analytics</a> that lets you keep control of your data.";
     } else {
         $this->outputApiResponse($tracker);
         Common::printDebug("Nothing to notice => default behaviour");
     }
     Common::printDebug("End of the page.");
     if ($tracker->isDebugModeEnabled() && $tracker->isDatabaseConnected() && TrackerDb::isProfilingEnabled()) {
         $db = Tracker::getDatabase();
         $db->recordProfiling();
         Profiler::displayDbTrackerProfile($db);
     }
     if ($tracker->isDebugModeEnabled()) {
         Common::printDebug($_COOKIE);
         Common::printDebug((string) $this->timer);
     }
 }
Example #2
0
 public function outputResponse(Tracker $tracker)
 {
     if (!$tracker->shouldRecordStatistics()) {
         $this->outputApiResponse($tracker);
         Common::printDebug("Logging disabled, display transparent logo");
     } elseif (!$tracker->hasLoggedRequests()) {
         if (!$this->isHttpGetRequest() || !empty($_GET) || !empty($_POST)) {
             Common::sendResponseCode(400);
         }
         Common::printDebug("Empty request => Piwik page");
         echo "This resource is part of Piwik. Keep full control of your data with the leading free and open source <a href='https://piwik.org' target='_blank'>digital analytics platform</a> for web and mobile.";
     } else {
         $this->outputApiResponse($tracker);
         Common::printDebug("Nothing to notice => default behaviour");
     }
     Common::printDebug("End of the page.");
     if ($tracker->isDebugModeEnabled() && $tracker->isDatabaseConnected() && TrackerDb::isProfilingEnabled()) {
         $db = Tracker::getDatabase();
         $db->recordProfiling();
         Profiler::displayDbTrackerProfile($db);
     }
     if ($tracker->isDebugModeEnabled()) {
         Common::printDebug($_COOKIE);
         Common::printDebug((string) $this->timer);
     }
 }
Example #3
0
 public function outputResponse(Tracker $tracker)
 {
     if (!$tracker->shouldRecordStatistics()) {
         $this->outputApiResponse($tracker);
         Common::printDebug("Logging disabled, display transparent logo");
     } elseif (!$tracker->hasLoggedRequests()) {
         if (!$this->isHttpGetRequest() || !empty($_GET) || !empty($_POST)) {
             Common::sendResponseCode(400);
         }
         Common::printDebug("Empty request => Piwik page");
         //echo date('Y-m-d H:i:s');
     } else {
         $this->outputApiResponse($tracker);
         Common::printDebug("Nothing to notice => default behaviour");
     }
     Common::printDebug("End of the page.");
     if ($tracker->isDebugModeEnabled() && $tracker->isDatabaseConnected() && TrackerDb::isProfilingEnabled()) {
         $db = Tracker::getDatabase();
         $db->recordProfiling();
         Profiler::displayDbTrackerProfile($db);
     }
     if ($tracker->isDebugModeEnabled()) {
         Common::printDebug($_COOKIE);
         Common::printDebug((string) $this->timer);
     }
 }
Example #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $options = $input->getOption('options');
     $groups = $input->getArgument('group');
     $groups = explode(",", $groups);
     $groups = array_filter($groups, 'strlen');
     $command = '../../vendor/phpunit/phpunit/phpunit';
     if (!$this->isCoverageEnabled($options) && $this->isXdebugLoaded()) {
         $output->writeln('<comment>Did you know? You can run tests faster by disabling xdebug</comment>');
     }
     // force xdebug usage for coverage options
     if ($this->isCoverageEnabled($options) && !$this->isXdebugLoaded()) {
         $output->writeln('<info>xdebug extension required for code coverage.</info>');
         $output->writeln('<info>searching for xdebug extension...</info>');
         $extensionDir = shell_exec('php-config --extension-dir');
         $xdebugFile = trim($extensionDir) . DIRECTORY_SEPARATOR . 'xdebug.so';
         if (!file_exists($xdebugFile)) {
             $dialog = $this->getHelperSet()->get('dialog');
             $xdebugFile = $dialog->askAndValidate($output, 'xdebug not found. Please provide path to xdebug.so', function ($xdebugFile) {
                 return file_exists($xdebugFile);
             });
         } else {
             $output->writeln('<info>xdebug extension found in extension path.</info>');
         }
         $output->writeln("<info>using {$xdebugFile} as xdebug extension.</info>");
         $phpunitPath = trim(shell_exec('which phpunit'));
         $command = sprintf('php -d zend_extension=%s %s', $xdebugFile, $phpunitPath);
     }
     if ($input->getOption('xhprof')) {
         Profiler::setupProfilerXHProf($isMainRun = true);
         putenv('PIWIK_USE_XHPROF=1');
     }
     $testFile = $input->getOption('file');
     if (!empty($testFile)) {
         $this->executeTestFile($testFile, $options, $command, $output);
     } else {
         $suite = $this->getTestsuite($input);
         $this->executeTestGroups($suite, $groups, $options, $command, $output);
     }
     return $this->returnVar;
 }
Example #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $options = $input->getOption('options');
     $groups = $input->getArgument('group');
     $groups = explode(",", $groups);
     $groups = array_map('ucfirst', $groups);
     $groups = array_filter($groups, 'strlen');
     $command = '../../vendor/phpunit/phpunit/phpunit';
     // force xdebug usage for coverage options
     if (false !== strpos($options, '--coverage') && !extension_loaded('xdebug')) {
         $output->writeln('<info>xdebug extension required for code coverage.</info>');
         $output->writeln('<info>searching for xdebug extension...</info>');
         $extensionDir = shell_exec('php-config --extension-dir');
         $xdebugFile = trim($extensionDir) . DIRECTORY_SEPARATOR . 'xdebug.so';
         if (!file_exists($xdebugFile)) {
             $dialog = $this->getHelperSet()->get('dialog');
             $xdebugFile = $dialog->askAndValidate($output, 'xdebug not found. Please provide path to xdebug.so', function ($xdebugFile) {
                 return file_exists($xdebugFile);
             });
         } else {
             $output->writeln('<info>xdebug extension found in extension path.</info>');
         }
         $output->writeln("<info>using {$xdebugFile} as xdebug extension.</info>");
         $phpunitPath = trim(shell_exec('which phpunit'));
         $command = sprintf('php -d zend_extension=%s %s', $xdebugFile, $phpunitPath);
     }
     if (empty($groups)) {
         $groups = $this->getTestsGroups();
     }
     if ($input->getOption('xhprof')) {
         Profiler::setupProfilerXHProf($isMainRun = true);
         putenv('PIWIK_USE_XHPROF=1');
     }
     foreach ($groups as $group) {
         $params = '--group ' . $group . ' ' . str_replace('%group%', $group, $options);
         $cmd = sprintf('cd %s/tests/PHPUnit && %s %s', PIWIK_DOCUMENT_ROOT, $command, $params);
         $output->writeln('Executing command: <info>' . $cmd . '</info>');
         passthru($cmd);
         $output->writeln("");
     }
 }
 public function beforeContainerCreated()
 {
     $this->vars->reload();
     if ($this->vars->queryParamOverride) {
         foreach ($this->vars->queryParamOverride as $key => $value) {
             $_GET[$key] = $value;
         }
     }
     if ($this->vars->globalsOverride) {
         foreach ($this->vars->globalsOverride as $key => $value) {
             $GLOBALS[$key] = $value;
         }
     }
     if ($this->vars->hostOverride) {
         \Piwik\Url::setHost($this->vars->hostOverride);
     }
     if ($this->vars->useXhprof) {
         \Piwik\Profiler::setupProfilerXHProf($mainRun = false, $setupDuringTracking = true);
     }
     \Piwik\Cache\Backend\File::$invalidateOpCacheBeforeRead = true;
 }
Example #7
0
 public function doRun(InputInterface $input, OutputInterface $output)
 {
     if ($input->hasParameterOption('--xhprof')) {
         Profiler::setupProfilerXHProf(true, true);
     }
     $this->initPiwikHost($input);
     $this->initEnvironment($output);
     $this->initLoggerOutput($output);
     try {
         self::initPlugins();
     } catch (ConfigNotFoundException $e) {
         // Piwik not installed yet, no config file?
         Log::warning($e->getMessage());
     }
     $commands = $this->getAvailableCommands();
     foreach ($commands as $command) {
         $this->addCommandIfExists($command);
     }
     $self = $this;
     return Access::doAsSuperUser(function () use($input, $output, $self) {
         return call_user_func(array($self, 'Symfony\\Component\\Console\\Application::doRun'), $input, $output);
     });
 }
Example #8
0
 /**
  * Cleanup
  */
 protected function end()
 {
     if ($this->usingBulkTracking) {
         $result = array('status' => 'success', 'tracked' => $this->countOfLoggedRequests);
         Common::sendHeader('Content-Type: application/json');
         echo Common::json_encode($result);
         exit;
     }
     switch ($this->getState()) {
         case self::STATE_LOGGING_DISABLE:
             $this->outputTransparentGif();
             Common::printDebug("Logging disabled, display transparent logo");
             break;
         case self::STATE_EMPTY_REQUEST:
             Common::printDebug("Empty request => Piwik page");
             echo "<a href='/'>Piwik</a> is a free/libre web <a href='http://piwik.org'>analytics</a> that lets you keep control of your data.";
             break;
         case self::STATE_NOSCRIPT_REQUEST:
         case self::STATE_NOTHING_TO_NOTICE:
         default:
             $this->outputTransparentGif();
             Common::printDebug("Nothing to notice => default behaviour");
             break;
     }
     Common::printDebug("End of the page.");
     if ($GLOBALS['PIWIK_TRACKER_DEBUG'] === true) {
         if (isset(self::$db)) {
             self::$db->recordProfiling();
             Profiler::displayDbTrackerProfile(self::$db);
         }
     }
     self::disconnectDatabase();
 }
Example #9
0
@date_default_timezone_set('UTC');
require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';
\Piwik\Loader::init();
\Piwik\Loader::registerTestNamespace();
require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php';
require_once PIWIK_INCLUDE_PATH . '/core/testMinimumPhpVersion.php';
require_once PIWIK_INCLUDE_PATH . '/core/FrontController.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/Fixture.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/DatabaseTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/IntegrationTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/ConsoleCommandTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/BenchmarkTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/FakeAccess.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/TestingEnvironment.php';
if (getenv('PIWIK_USE_XHPROF') == 1) {
    \Piwik\Profiler::setupProfilerXHProf();
}
// require test fixtures
$fixturesToLoad = array('/tests/PHPUnit/Fixtures/*.php', '/tests/PHPUnit/UI/Fixtures/*.php', '/plugins/*/tests/Fixtures/*.php', '/plugins/*/Test/Fixtures/*.php');
foreach ($fixturesToLoad as $fixturePath) {
    foreach (glob(PIWIK_INCLUDE_PATH . $fixturePath) as $file) {
        require_once $file;
    }
}
// General requirement checks & help: a webserver must be running for tests to work!
checkPiwikSetupForTests();
function checkPiwikSetupForTests()
{
    if (empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '@REQUEST_URI@') {
        echo "WARNING: for tests to pass, you must first:\n1) Install webserver on localhost, eg. apache\n2) Make these Piwik files available on the webserver, at eg. http://localhost/dev/piwik/\n3) Install Piwik by going through the installation process\n4) Copy phpunit.xml.dist to phpunit.xml\n5) Edit in phpunit.xml the @REQUEST_URI@ and replace with the webserver path to Piwik, eg. '/dev/piwik/'\n\nTry again.\n-> If you still get this message, you can work around it by specifying Host + Request_Uri at the top of this file tests/PHPUnit/bootstrap.php. <-";
        exit(1);
 private function handleProfiler()
 {
     if (!empty($_GET['xhprof'])) {
         $mainRun = $_GET['xhprof'] == 1;
         // core:archive command sets xhprof=2
         Profiler::setupProfilerXHProf($mainRun);
     }
 }
Example #11
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $options = $input->getOption('options');
     $groups = $input->getOption('group');
     $magics = $input->getArgument('variables');
     $groups = $this->getGroupsFromString($groups);
     // bin is the composer executeable directory, where all vendors (should) place their executables
     $command = PIWIK_VENDOR_PATH . '/bin/phpunit';
     if (version_compare(PHP_VERSION, '5.4.0', '<')) {
         $command = 'php -dzend.enable_gc=0 ' . $command;
     }
     if (!$this->isCoverageEnabled($options) && $this->isXdebugLoaded()) {
         $message = 'Did you know? You can run tests faster by disabling xdebug';
         if ($this->isXdebugCodeCoverageEnabled()) {
             $message .= ' (if you need xdebug, speed up tests by setting xdebug.coverage_enable=0)</comment>';
         }
         $output->writeln('<comment>' . $message . '</comment>');
     }
     // force xdebug usage for coverage options
     if ($this->isCoverageEnabled($options) && !$this->isXdebugLoaded()) {
         $output->writeln('<info>xdebug extension required for code coverage.</info>');
         $output->writeln('<info>searching for xdebug extension...</info>');
         $extensionDir = shell_exec('php-config --extension-dir');
         $xdebugFile = trim($extensionDir) . DIRECTORY_SEPARATOR . 'xdebug.so';
         if (!file_exists($xdebugFile)) {
             $dialog = $this->getHelperSet()->get('dialog');
             $xdebugFile = $dialog->askAndValidate($output, 'xdebug not found. Please provide path to xdebug.so', function ($xdebugFile) {
                 return file_exists($xdebugFile);
             });
         } else {
             $output->writeln('<info>xdebug extension found in extension path.</info>');
         }
         $output->writeln("<info>using {$xdebugFile} as xdebug extension.</info>");
         $phpunitPath = trim(shell_exec('which phpunit'));
         $command = sprintf('php -d zend_extension=%s %s', $xdebugFile, $phpunitPath);
     }
     if ($input->getOption('xhprof')) {
         Profiler::setupProfilerXHProf($isMainRun = true);
         putenv('PIWIK_USE_XHPROF=1');
     }
     $suite = $this->getTestsuite($input);
     $testFile = $this->getTestFile($input);
     if (!empty($magics)) {
         foreach ($magics as $magic) {
             if (empty($suite) && in_array($magic, $this->getTestsSuites())) {
                 $suite = $this->buildTestSuiteName($magic);
             } elseif (empty($testFile) && 'core' === $magic) {
                 $testFile = $this->fixPathToTestFileOrDirectory('tests/PHPUnit');
             } elseif (empty($testFile) && 'plugins' === $magic) {
                 $testFile = $this->fixPathToTestFileOrDirectory('plugins');
             } elseif (empty($testFile) && file_exists($magic)) {
                 $testFile = $this->fixPathToTestFileOrDirectory($magic);
             } elseif (empty($testFile) && $this->getPluginTestFolderName($magic)) {
                 $testFile = $this->getPluginTestFolderName($magic);
             } elseif (empty($groups)) {
                 $groups = $this->getGroupsFromString($magic);
             } else {
                 $groups[] = $magic;
             }
         }
     }
     $this->executeTests($suite, $testFile, $groups, $options, $command, $output);
     return $this->returnVar;
 }
Example #12
0
 public static function addHooks()
 {
     $testingEnvironment = new Piwik_TestingEnvironment();
     if ($testingEnvironment->queryParamOverride) {
         foreach ($testingEnvironment->queryParamOverride as $key => $value) {
             $_GET[$key] = $value;
         }
     }
     if ($testingEnvironment->globalsOverride) {
         foreach ($testingEnvironment->globalsOverride as $key => $value) {
             $GLOBALS[$key] = $value;
         }
     }
     if ($testingEnvironment->useXhprof) {
         \Piwik\Profiler::setupProfilerXHProf($mainRun = false, $setupDuringTracking = true);
     }
     Config::setSingletonInstance(new Config($testingEnvironment->configFileGlobal, $testingEnvironment->configFileLocal, $testingEnvironment->configFileCommon));
     \Piwik\CacheFile::$invalidateOpCacheBeforeRead = true;
     Piwik::addAction('Access.createAccessSingleton', function ($access) use($testingEnvironment) {
         if (!$testingEnvironment->testUseRegularAuth) {
             $access = new Piwik_MockAccess($access);
             \Piwik\Access::setSingletonInstance($access);
         }
     });
     if (!$testingEnvironment->dontUseTestConfig) {
         Piwik::addAction('Config.createConfigSingleton', function (Config $config, &$cache, &$local) use($testingEnvironment) {
             $config->setTestEnvironment($testingEnvironment->configFileLocal, $testingEnvironment->configFileGlobal, $testingEnvironment->configFileCommon);
             if ($testingEnvironment->configFileLocal) {
                 $local['General']['session_save_handler'] = 'dbtable';
             }
             $manager = \Piwik\Plugin\Manager::getInstance();
             $pluginsToLoad = $testingEnvironment->getCoreAndSupportedPlugins();
             if (!empty($testingEnvironment->pluginsToLoad)) {
                 $pluginsToLoad = array_unique(array_merge($pluginsToLoad, $testingEnvironment->pluginsToLoad));
             }
             sort($pluginsToLoad);
             $local['Plugins'] = array('Plugins' => $pluginsToLoad);
             $local['log']['log_writers'] = array('file');
             $manager->unloadPlugins();
             // TODO: replace this and below w/ configOverride use
             if ($testingEnvironment->tablesPrefix) {
                 $cache['database']['tables_prefix'] = $testingEnvironment->tablesPrefix;
             }
             if ($testingEnvironment->dbName) {
                 $cache['database']['dbname'] = $testingEnvironment->dbName;
             }
             if ($testingEnvironment->configOverride) {
                 $cache = $testingEnvironment->arrayMergeRecursiveDistinct($cache, $testingEnvironment->configOverride);
             }
         });
     }
     Piwik::addAction('Request.dispatch', function () use($testingEnvironment) {
         if (empty($_GET['ignoreClearAllViewDataTableParameters'])) {
             // TODO: should use testingEnvironment variable, not query param
             \Piwik\ViewDataTable\Manager::clearAllViewDataTableParameters();
         }
         if ($testingEnvironment->optionsOverride) {
             foreach ($testingEnvironment->optionsOverride as $name => $value) {
                 Option::set($name, $value);
             }
         }
         \Piwik\Plugins\CoreVisualizations\Visualizations\Cloud::$debugDisableShuffle = true;
         \Piwik\Visualization\Sparkline::$enableSparklineImages = false;
         \Piwik\Plugins\ExampleUI\API::$disableRandomness = true;
     });
     Piwik::addAction('AssetManager.getStylesheetFiles', function (&$stylesheets) {
         $stylesheets[] = 'tests/resources/screenshot-override/override.css';
     });
     Piwik::addAction('AssetManager.getJavaScriptFiles', function (&$jsFiles) {
         $jsFiles[] = 'tests/resources/screenshot-override/override.js';
     });
     self::addSendMailHook();
     Piwik::addAction('Updater.checkForUpdates', function () {
         try {
             @\Piwik\Filesystem::deleteAllCacheOnUpdate();
         } catch (Exception $ex) {
             // pass
         }
     });
     $testingEnvironment->logVariables();
     $testingEnvironment->executeSetupTestEnvHook();
 }
Example #13
0
 /**
  * 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;
 }
Example #14
0
 /**
  * Renders the current view. Also sends the stored 'Content-Type' HTML header.
  * See {@link setContentType()}.
  *
  * @return string Generated template.
  */
 public function render()
 {
     try {
         $this->currentModule = Piwik::getModule();
         $this->currentAction = Piwik::getAction();
         $this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
         $this->token_auth = Piwik::getCurrentUserTokenAuth();
         $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
         $this->userIsSuperUser = Piwik::hasUserSuperUserAccess();
         $this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
         $this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
         $this->isWidget = Common::getRequestVar('widget', 0, 'int');
         $this->cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster();
         $this->loginModule = Piwik::getLoginPluginName();
         $user = APIUsersManager::getInstance()->getUser($this->userLogin);
         $this->userAlias = $user['alias'];
     } catch (Exception $e) {
         // can fail, for example at installation (no plugin loaded yet)
     }
     try {
         $this->totalTimeGeneration = Registry::get('timer')->getTime();
         $this->totalNumberOfQueries = Profiler::getQueryCount();
     } catch (Exception $e) {
         $this->totalNumberOfQueries = 0;
     }
     ProxyHttp::overrideCacheControlHeaders('no-store');
     @header('Content-Type: ' . $this->contentType);
     // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail)
     @header('X-Frame-Options: ' . (string) $this->xFrameOptions);
     return $this->renderTwigTemplate();
 }
Example #15
0
@set_include_path(PIWIK_INCLUDE_SEARCH_PATH);
@ini_set('memory_limit', -1);
error_reporting(E_ALL | E_NOTICE);
@date_default_timezone_set('UTC');
require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php';
require_once PIWIK_INCLUDE_PATH . '/core/testMinimumPhpVersion.php';
require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';
require_once PIWIK_INCLUDE_PATH . '/core/FrontController.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/DatabaseTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/IntegrationTestCase.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/FakeAccess.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/MockPiwikOption.php';
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/TestingEnvironment.php';
require_once file_exists(PIWIK_INCLUDE_PATH . '/vendor/autoload.php') ? PIWIK_INCLUDE_PATH . '/vendor/autoload.php' : PIWIK_INCLUDE_PATH . '/../../autoload.php';
// Piwik is installed as a dependency
\Piwik\Profiler::setupProfilerXHProf($mainRun = true);
// require test fixtures
require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/Fixture.php';
$fixturesToLoad = array('/tests/PHPUnit/Fixtures/*.php', '/tests/PHPUnit/UI/Fixtures/*.php', '/plugins/*/tests/Fixtures/*.php', '/plugins/*/Test/Fixtures/*.php');
foreach ($fixturesToLoad as $fixturePath) {
    foreach (glob(PIWIK_INCLUDE_PATH . $fixturePath) as $file) {
        require_once $file;
    }
}
// General requirement checks & help: a webserver must be running for tests to work!
checkPiwikSetupForTests();
function checkPiwikSetupForTests()
{
    if (empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '@REQUEST_URI@') {
        echo "WARNING: for tests to pass, you must first:\n1) Install webserver on localhost, eg. apache\n2) Make these Piwik files available on the webserver, at eg. http://localhost/dev/piwik/\n3) Install Piwik by going through the installation process\n4) Copy phpunit.xml.dist to phpunit.xml\n5) Edit in phpunit.xml the @REQUEST_URI@ and replace with the webserver path to Piwik, eg. '/dev/piwik/'\n\nTry again.\n-> If you still get this message, you can work around it by specifying Host + Request_Uri at the top of this file tests/PHPUnit/bootstrap.php. <-";
        exit(1);
Example #16
0
 public function init()
 {
     // Note: the order of methods call matters here.
     $this->initCore();
     $this->initTokenAuth();
     $this->initCheckCli();
     $this->initStateFromParameters();
     Piwik::setUserHasSuperUserAccess(true);
     $this->logInitInfo();
     $this->checkPiwikUrlIsValid();
     $this->logArchiveTimeoutInfo();
     // record archiving start time
     Option::set(self::OPTION_ARCHIVING_STARTED_TS, time());
     $this->segments = $this->initSegmentsToArchive();
     $this->allWebsites = APISitesManager::getInstance()->getAllSitesId();
     if (!empty($this->shouldArchiveOnlySpecificPeriods)) {
         $this->log("- Will process the following periods: " . implode(", ", $this->shouldArchiveOnlySpecificPeriods) . " (--force-periods)");
     }
     $websitesIds = $this->initWebsiteIds();
     $this->filterWebsiteIds($websitesIds);
     if (!empty($this->shouldArchiveSpecifiedSites) || !empty($this->shouldArchiveAllSites) || !SharedSiteIds::isSupported()) {
         $this->websites = new FixedSiteIds($websitesIds);
     } else {
         $this->websites = new SharedSiteIds($websitesIds);
         if ($this->websites->getInitialSiteIds() != $websitesIds) {
             $this->log('Will ignore websites and help finish a previous started queue instead. IDs: ' . implode(', ', $this->websites->getInitialSiteIds()));
         }
     }
     if ($this->shouldStartProfiler) {
         \Piwik\Profiler::setupProfilerXHProf($mainRun = true);
         $this->log("XHProf profiling is enabled.");
     }
     /**
      * This event is triggered after a CronArchive instance is initialized.
      *
      * @param array $websiteIds The list of website IDs this CronArchive instance is processing.
      *                          This will be the entire list of IDs regardless of whether some have
      *                          already been processed.
      */
     Piwik::postEvent('CronArchive.init.finish', array($this->websites->getInitialSiteIds()));
 }
Example #17
0
 /**
  * Renders the current view. Also sends the stored 'Content-Type' HTML header.
  * See {@link setContentType()}.
  *
  * @return string Generated template.
  */
 public function render()
 {
     try {
         $this->currentModule = Piwik::getModule();
         $this->currentAction = Piwik::getAction();
         $userLogin = Piwik::getCurrentUserLogin();
         $this->userLogin = $userLogin;
         $count = SettingsPiwik::getWebsitesCountToDisplay();
         $sites = APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($count);
         usort($sites, function ($site1, $site2) {
             return strcasecmp($site1["name"], $site2["name"]);
         });
         $this->sites = $sites;
         $this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
         $this->token_auth = Piwik::getCurrentUserTokenAuth();
         $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
         $this->userIsSuperUser = Piwik::isUserIsSuperUser();
         $this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
         $this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
         $this->isWidget = Common::getRequestVar('widget', 0, 'int');
         if (Config::getInstance()->General['autocomplete_min_sites'] <= count($sites)) {
             $this->show_autocompleter = true;
         } else {
             $this->show_autocompleter = false;
         }
         $this->loginModule = Piwik::getLoginPluginName();
         $user = APIUsersManager::getInstance()->getUser($userLogin);
         $this->userAlias = $user['alias'];
     } catch (Exception $e) {
         // can fail, for example at installation (no plugin loaded yet)
     }
     try {
         $this->totalTimeGeneration = Registry::get('timer')->getTime();
         $this->totalNumberOfQueries = Profiler::getQueryCount();
     } catch (Exception $e) {
         $this->totalNumberOfQueries = 0;
     }
     ProxyHttp::overrideCacheControlHeaders('no-store');
     @header('Content-Type: ' . $this->contentType);
     // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail)
     @header('X-Frame-Options: ' . (string) $this->xFrameOptions);
     return $this->renderTwigTemplate();
 }
 public function init()
 {
     // Note: the order of methods call matters here.
     $this->displayHelp();
     $this->initPiwikHost();
     $this->initLog();
     $this->initCore();
     $this->initTokenAuth();
     $this->initCheckCli();
     $this->initStateFromParameters();
     Piwik::setUserIsSuperUser(true);
     $this->logInitInfo();
     $this->checkPiwikUrlIsValid();
     $this->logArchiveTimeoutInfo();
     $this->segments = $this->initSegmentsToArchive();
     $this->allWebsites = APISitesManager::getInstance()->getAllSitesId();
     $websitesIds = $this->initWebsiteIds();
     $this->filterWebsiteIds($websitesIds);
     $this->websites = $websitesIds;
     if ($this->shouldStartProfiler) {
         \Piwik\Profiler::setupProfilerXHProf($mainRun = true);
         $this->log("XHProf profiling is enabled.");
     }
 }