private function assertAccessReloadedAndRestored($expectedTokenToBeReloaded) { $this->access->expects($this->exactly(2))->method('reloadAccess'); // verify access reloaded $this->auth->expects($this->at(0))->method('setLogin')->with($this->equalTo(null)); $this->auth->expects($this->at(1))->method('setTokenAuth')->with($this->equalTo($expectedTokenToBeReloaded)); $this->auth->expects($this->at(2))->method('authenticate')->will($this->returnValue(new AuthResult(AuthResult::SUCCESS, 'login1', $expectedTokenToBeReloaded))); // verify access restored $this->auth->expects($this->at(3))->method('setLogin')->with($this->equalTo(null)); $this->auth->expects($this->at(4))->method('setTokenAuth')->with($this->equalTo($tokenRestored = $this->userAuthToken)); $this->auth->expects($this->at(5))->method('authenticate')->will($this->returnValue(new AuthResult(AuthResult::SUCCESS, 'login', $this->userAuthToken))); }
private function addAnnotations() { // create fake access for fake username $access = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($access); // add two annotations per week for three months, starring every third annotation // first month in 2011, second two in 2012 $count = 0; $dateStart = Date::factory('2011-12-01'); $dateEnd = Date::factory('2012-03-01'); while ($dateStart->getTimestamp() < $dateEnd->getTimestamp()) { $starred = $count % 3 == 0 ? 1 : 0; $site1Text = "{$count}: Site 1 annotation for " . $dateStart->toString(); $site2Text = "{$count}: Site 2 annotation for " . $dateStart->toString(); API::getInstance()->add($this->idSite1, $dateStart->toString(), $site1Text, $starred); API::getInstance()->add($this->idSite2, $dateStart->toString(), $site2Text, $starred); $nextDay = $dateStart->addDay(1); ++$count; $starred = $count % 3 == 0 ? 1 : 0; $site1Text = "{$count}: Site 1 annotation for " . $nextDay->toString(); $site2Text = "{$count}: Site 2 annotation for " . $nextDay->toString(); API::getInstance()->add($this->idSite1, $nextDay->toString(), $site1Text, $starred); API::getInstance()->add($this->idSite2, $nextDay->toString(), $site2Text, $starred); $dateStart = $dateStart->addPeriod(1, 'WEEK'); ++$count; } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->recreateContainerWithWebEnvironment(); $this->initHostAndQueryString($input); if ($this->isTestModeEnabled()) { $indexFile = '/tests/PHPUnit/proxy/'; $this->resetDatabase(); } else { $indexFile = '/'; } $indexFile .= 'index.php'; if (!empty($_GET['pid'])) { $process = new Process($_GET['pid']); if ($process->hasFinished()) { return; } $process->startProcess(); } if ($input->getOption('superuser')) { StaticContainer::addDefinitions(array('observers.global' => \DI\add(array(array('Environment.bootstrapped', function () { Access::getInstance()->setSuperUserAccess(true); }))))); } require_once PIWIK_INCLUDE_PATH . $indexFile; if (!empty($process)) { $process->finishProcess(); } }
public function setUp() { parent::setUp(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); }
public function setUp() { parent::setUp(); // setup the access layer (required in Segment contrustor testing if anonymous is allowed to use segments) $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); }
public function setUp() { parent::setUp(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('SitesManager')); }
private function makeSureTestRunsInContextOfAnonymousUser() { Piwik::postEvent('Request.initAuthenticationObject'); $access = Access::getInstance(); $this->hasSuperUserAccess = $access->hasSuperUserAccess(); $access->setSuperUserAccess(false); $access->reloadAccess(StaticContainer::get('Piwik\\Auth')); Request::reloadAuthUsingTokenAuth(array('token_auth' => 'anonymous')); }
private function migratePluginEmailUpdateSetting() { $isEnabled = Option::get('enableUpdateCommunicationPlugins'); Access::doAsSuperUser(function () use($isEnabled) { $settings = StaticContainer::get('Piwik\\Plugins\\CoreUpdater\\SystemSettings'); $settings->sendPluginUpdateEmail->setValue(!empty($isEnabled)); $settings->save(); }); }
public function setUp() { parent::setUp(); $access = Access::getInstance(); $access->setSuperUserAccess(true); $this->idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('MultiSites', 'VisitsSummary', 'Actions')); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); }
/** * @dataProvider getUnitColumns * @group Core */ public function testGetUnit($column, $expected) { \Piwik\Site::setSites(array(1 => array('name' => 'TestSite', 'currency' => 'EUR'))); $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); $actual = Metrics::getUnit($column, 1); $this->assertEquals($expected, $actual); }
public function setUp() { parent::setUp(); $pseudoMockAccess = new \FakeAccess(); \FakeAccess::setSuperUserAccess(true); Access::setSingletonInstance($pseudoMockAccess); $idSite = Fixture::createWebsite('2014-01-01 00:00:00'); $this->builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'idSite' => $idSite)); }
private function hasAccessToSameSite($login) { // users is allowed to see other users having view or admin access to these sites if (!isset($this->idSitesWithAdmin)) { $this->idSitesWithAdmin = $this->access->getSitesIdWithAdminAccess(); $this->usersWithAdminAccess = $this->model->getUsersSitesFromAccess('admin'); $this->usersWithViewAccess = $this->model->getUsersSitesFromAccess('view'); } return isset($this->usersWithViewAccess[$login]) && array_intersect($this->idSitesWithAdmin, $this->usersWithViewAccess[$login]) || isset($this->usersWithAdminAccess[$login]) && array_intersect($this->idSitesWithAdmin, $this->usersWithAdminAccess[$login]); }
public function setUp() { parent::setUp(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; //finally we set the user as a Super User by default Access::setSingletonInstance($pseudoMockAccess); $this->idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging', 'MultiSites')); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); }
public function setUp() { parent::setUp(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::setIdSitesView(array(1, 2)); FakeAccess::setIdSitesAdmin(array(3, 4)); //finally we set the user as a Super User by default FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); $this->auth = new Auth(); }
public function setUp() { parent::setUp(); $this->api = API::getInstance(); $pseudoMockAccess = new FakeAccess(); FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); Fixture::createWebsite('2014-01-01 00:00:00'); Fixture::createWebsite('2014-01-01 00:00:00'); Fixture::createWebsite('2014-01-01 00:00:00'); $this->api->addUser('userLogin', 'password', '*****@*****.**'); }
/** * NOTE: This test must be last since the new sites that get added are added in * random order. */ public function testDynamicResolverSitesCreated() { self::$fixture->logVisitsWithDynamicResolver(); // reload access so new sites are viewable Access::getInstance()->setSuperUserAccess(true); // make sure sites aren't created twice $piwikDotNet = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); $this->assertEquals(1, count($piwikDotNet)); $anothersiteDotCom = API::getInstance()->getSitesIdFromSiteUrl('http://anothersite.com'); $this->assertEquals(1, count($anothersiteDotCom)); $whateverDotCom = API::getInstance()->getSitesIdFromSiteUrl('http://whatever.com'); $this->assertEquals(1, count($whateverDotCom)); }
public function setUp() { parent::setUp(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::setIdSitesView(array(1, 2)); FakeAccess::setIdSitesAdmin(array(3, 4)); //finally we set the user as a Super User by default FakeAccess::$superUser = true; Access::setSingletonInstance($pseudoMockAccess); $user_agents = array('Mozilla/6.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4', 'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/18.6.872.0 Safari/535.2 UNTRUSTED/1.0 3gpp-gba UNTRUSTED/1.0', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'); $_SERVER['HTTP_USER_AGENT'] = $user_agents[mt_rand(0, count($user_agents) - 1)]; }
public function setUp() { // drop all tables Db::dropAllTables(); // download data dump if url supplied if (is_file($this->dumpUrl)) { $dumpPath = $this->dumpUrl; } else { $dumpPath = PIWIK_INCLUDE_PATH . '/tmp/logdump.sql.gz'; $bufferSize = 1024 * 1024; $dump = fopen($this->dumpUrl, 'rb'); $outfile = fopen($dumpPath, 'wb'); $bytesRead = 0; while (!feof($dump)) { fwrite($outfile, fread($dump, $bufferSize), $bufferSize); $bytesRead += $bufferSize; } fclose($dump); fclose($outfile); if ($bytesRead <= 40 * 1024 * 1024) { // sanity check throw new Exception("Could not download sql dump!"); } } // unzip the dump if (substr($dumpPath, -3) === ".gz") { $deflatedDumpPath = PIWIK_INCLUDE_PATH . '/tmp/logdump.sql'; // TODO: should depend on name of URL exec("gunzip -c \"" . $dumpPath . "\" > \"{$deflatedDumpPath}\"", $output, $return); if ($return !== 0) { throw new Exception("gunzip failed: " . implode("\n", $output)); } } else { $deflatedDumpPath = $dumpPath; } // load the data into the correct database $user = Config::getInstance()->database['username']; $password = Config::getInstance()->database['password']; Config::getInstance()->database['tables_prefix'] = $this->tablesPrefix; $cmd = "mysql -u \"{$user}\" \"--password={$password}\" {$this->dbName} < \"" . $deflatedDumpPath . "\" 2>&1"; exec($cmd, $output, $return); if ($return !== 0) { throw new Exception("Failed to load sql dump: " . implode("\n", $output)); } // make sure archiving will be called Rules::setBrowserTriggerArchiving(true); // reload access Access::getInstance()->reloadAccess(); $this->getTestEnvironment()->configOverride = array('database' => array('tables_prefix' => $this->tablesPrefix)); $this->getTestEnvironment()->save(); }
function validateOwner() { try { $timezone = $this->owner->getValue(); if (!empty($timezone)) { Access::doAsSuperUser(function () use($timezone) { API::getInstance()->setDefaultTimezone($timezone); }); } } catch (\Exception $e) { return false; } return true; }
public function setUserDefaultReportPreference() { // We initialize the default report user preference for each user (if it hasn't been inited before) for performance, // doing this lets us avoid loading all siteIds (which can be 50k or more) when this preference is requested. // getting the user preference can be called quite often when generating links etc (to get defaultWebsiteId). $usersModel = $this->usersModel; $usersManagerApi = $this->usersManagerApi; Access::getInstance()->doAsSuperUser(function () use($usersModel, $usersManagerApi) { $allUsers = $usersModel->getUsers(array()); foreach ($allUsers as $user) { $usersManagerApi->initUserPreferenceWithDefault($user['login'], API::PREFERENCE_DEFAULT_REPORT); } }); }
/** * Setup the database and create the base tables for all tests */ public function setUp() { parent::setUp(); static::$fixture->extraDefinitions = array_merge(static::provideContainerConfigBeforeClass(), $this->provideContainerConfig()); static::$fixture->createEnvironmentInstance(); Db::createDatabaseObject(); Fixture::loadAllPlugins(new TestingEnvironmentVariables(), get_class($this), self::$fixture->extraPluginsToLoad); Access::getInstance()->setSuperUserAccess(true); if (!empty(self::$tableData)) { self::restoreDbTables(self::$tableData); } PiwikCache::getEagerCache()->flushAll(); PiwikCache::getTransientCache()->flushAll(); MenuAbstract::clearMenus(); }
public function setUp() { parent::setUp(); \Piwik\Plugin\Manager::getInstance()->loadPlugin('SegmentEditor'); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::setIdSitesView(array(1, 2)); FakeAccess::setIdSitesAdmin(array(3, 4)); //finally we set the user as a Super User by default FakeAccess::$superUser = true; FakeAccess::$superUserLogin = '******'; Access::setSingletonInstance($pseudoMockAccess); APISitesManager::getInstance()->addSite('test', 'http://example.org'); }
public function setUp() { parent::setUp(); \Piwik\Plugin\Manager::getInstance()->loadPlugin('UsersManager'); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); // setup the access layer $pseudoMockAccess = new FakeAccess(); FakeAccess::setIdSitesView(array(1, 2)); FakeAccess::setIdSitesAdmin(array(3, 4)); //finally we set the user as a Super User by default FakeAccess::$superUser = true; FakeAccess::$superUserLogin = '******'; Access::setSingletonInstance($pseudoMockAccess); $this->api = API::getInstance(); $this->model = new Model(); }
/** * NOTE: This test must be last since the new sites that get added are added in * random order. * NOTE: This test combines two tests in order to avoid executing the log importer another time. * If the log importer were refactored, the invalid requests test could be a unit test in * python. */ public function test_LogImporter_CreatesSitesWhenDynamicResolverUsed_AndReportsOnInvalidRequests() { $this->simulateInvalidTrackerRequest(); $output = self::$fixture->logVisitsWithDynamicResolver($maxPayloadSize = 3); // reload access so new sites are viewable Access::getInstance()->setSuperUserAccess(true); // make sure sites aren't created twice $piwikDotNet = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); $this->assertEquals(1, count($piwikDotNet)); $anothersiteDotCom = API::getInstance()->getSitesIdFromSiteUrl('http://anothersite.com'); $this->assertEquals(1, count($anothersiteDotCom)); $whateverDotCom = API::getInstance()->getSitesIdFromSiteUrl('http://whatever.com'); $this->assertEquals(1, count($whateverDotCom)); // make sure invalid requests are reported correctly $this->assertContains('The Piwik tracker identified 2 invalid requests on lines: 10, 11', $output); $this->assertContains("The following lines were not tracked by Piwik, either due to a malformed tracker request or error in the tracker:\n\n10, 11", $output); }
/** * Returns array containing data about the website: goals, URLs, etc. * * @param int $idSite * @return array */ static function getCacheWebsiteAttributes($idSite) { if ('all' == $idSite) { return array(); } $idSite = (int) $idSite; if ($idSite <= 0) { return array(); } $cache = self::getInstance(); $cacheContent = $cache->get($idSite); if (false !== $cacheContent) { return $cacheContent; } Tracker::initCorePiwikInTrackerMode(); $content = array(); Access::doAsSuperUser(function () use(&$content, $idSite) { /** * Triggered to get the attributes of a site entity that might be used by the * Tracker. * * Plugins add new site attributes for use in other tracking events must * use this event to put those attributes in the Tracker Cache. * * **Example** * * public function getSiteAttributes($content, $idSite) * { * $sql = "SELECT info FROM " . Common::prefixTable('myplugin_extra_site_info') . " WHERE idsite = ?"; * $content['myplugin_site_data'] = Db::fetchOne($sql, array($idSite)); * } * * @param array &$content Array mapping of site attribute names with values. * @param int $idSite The site ID to get attributes for. */ Piwik::postEvent('Tracker.Cache.getSiteAttributes', array(&$content, $idSite)); Common::printDebug("Website {$idSite} tracker cache was re-created."); }); // if nothing is returned from the plugins, we don't save the content // this is not expected: all websites are expected to have at least one URL if (!empty($content)) { $cache->set($idSite, $content); } return $content; }
public function setUp() { // drop all tables Db::dropAllTables(); // download data dump if url supplied if (is_file($this->dumpUrl)) { $dumpPath = $this->dumpUrl; } else { $dumpPath = PIWIK_INCLUDE_PATH . '/tmp/logdump.sql.gz'; $bytesRead = $this->downloadDumpInPath($dumpPath); // sanity check if ($bytesRead <= 40 * 1024 * 1024) { $str = "Could not download sql dump! You can manually download %s into %s"; throw new Exception(sprintf($str, $this->dumpUrl, $dumpPath)); } } // unzip the dump if (substr($dumpPath, -3) === ".gz") { $deflatedDumpPath = PIWIK_INCLUDE_PATH . '/tmp/logdump.sql'; // TODO: should depend on name of URL exec("gunzip -c \"" . $dumpPath . "\" > \"{$deflatedDumpPath}\"", $output, $return); if ($return !== 0) { throw new Exception("gunzip failed: " . implode("\n", $output)); } } else { $deflatedDumpPath = $dumpPath; } // load the data into the correct database $user = Config::getInstance()->database['username']; $password = Config::getInstance()->database['password']; $host = Config::getInstance()->database['host']; Config::getInstance()->database['tables_prefix'] = $this->tablesPrefix; $cmd = "mysql -h \"{$host}\" -u \"{$user}\" \"--password={$password}\" {$this->dbName} < \"" . $deflatedDumpPath . "\" 2>&1"; exec($cmd, $output, $return); if ($return !== 0) { throw new Exception("Failed to load sql dump: " . implode("\n", $output)); } // make sure archiving will be called Rules::setBrowserTriggerArchiving(true); // reload access Access::getInstance()->reloadAccess(); $testVars = new TestingEnvironmentVariables(); $testVars->configOverride = array('database' => array('tables_prefix' => $this->tablesPrefix)); $testVars->save(); }
public function doRun(InputInterface $input, OutputInterface $output) { $this->initPiwikHost($input); $this->initConfig($output); try { self::initPlugins(); } catch (\Exception $e) { // Piwik not installed yet, no config file? } Translate::reloadLanguage('en'); $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); }); }
public static function updateComponents(Updater $updater, $componentsWithUpdateFile) { $warnings = array(); $errors = array(); $deactivatedPlugins = array(); $coreError = false; if (!empty($componentsWithUpdateFile)) { $currentAccess = Access::getInstance(); $hasSuperUserAccess = $currentAccess->hasSuperUserAccess(); if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(true); } // if error in any core update, show message + help message + EXIT // if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE // if warning in any core update or in any plugins update, show message + CONTINUE // if no error or warning, success message + CONTINUE foreach ($componentsWithUpdateFile as $name => $filenames) { try { $warnings = array_merge($warnings, $updater->update($name)); } catch (UpdaterErrorException $e) { $errors[] = $e->getMessage(); if ($name == 'core') { $coreError = true; break; } elseif (\Piwik\Plugin\Manager::getInstance()->isPluginActivated($name)) { \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($name); $deactivatedPlugins[] = $name; } } } if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(false); } } Filesystem::deleteAllCacheOnUpdate(); $result = array('warnings' => $warnings, 'errors' => $errors, 'coreError' => $coreError, 'deactivatedPlugins' => $deactivatedPlugins); /** * Triggered after Piwik has been updated. */ Piwik::postEvent('CoreUpdater.update.end'); return $result; }
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); }); }
/** * Returns the list of websites ID associated with a URL. * * @param string $login * @param array $urls * @return array list of websites ID */ public function getSitesIdFromSiteUrlHavingAccess($login, $urls) { $siteUrlTable = Common::prefixTable('site_url'); $sqlAccessSite = Access::getSqlAccessSite('idsite'); $ids = $this->db->fetchAll('SELECT idsite FROM ' . $this->table . ' WHERE main_url IN ( ' . Common::getSqlStringFieldsArray($urls) . ')' . 'AND idsite IN (' . $sqlAccessSite . ') ' . 'UNION SELECT idsite FROM ' . $siteUrlTable . ' WHERE url IN ( ' . Common::getSqlStringFieldsArray($urls) . ')' . 'AND idsite IN (' . $sqlAccessSite . ')', array_merge($urls, array($login), $urls, array($login))); return $ids; }