This API lets you create websites via "addSite", update existing websites via "updateSite" and delete websites via "deleteSite". When creating websites, it can be useful to access internal codes used by Piwik for currencies via "getCurrencyList", or timezones via "getTimezonesList". There are also many ways to request a list of websites: from the website ID via "getSiteFromId" or the site URL via "getSitesIdFromSiteUrl". Often, the most useful technique is to list all websites that are known to a current user, based on the token_auth, via "getSitesWithAdminAccess", "getSitesWithViewAccess" or "getSitesWithAtLeastViewAccess" (which returns both). Some methods will affect all websites globally: "setGlobalExcludedIps" will set the list of IPs to be excluded on all websites, "setGlobalExcludedQueryParameters" will set the list of URL parameters to remove from URLs for all websites. The existing values can be fetched via "getExcludedIpsGlobal" and "getExcludedQueryParametersGlobal". See also the documentation about Managing Websites in Piwik.
Inheritance: extends Piwik\Plugin\API
 /**
  * Check for a newer version
  *
  * @param bool $force Force check
  * @param int $interval Interval used for update checks
  */
 public static function check($force = false, $interval = null)
 {
     if (!self::isAutoUpdateEnabled()) {
         return;
     }
     if ($interval === null) {
         $interval = self::CHECK_INTERVAL;
     }
     $lastTimeChecked = Option::get(self::LAST_TIME_CHECKED);
     if ($force || $lastTimeChecked === false || time() - $interval > $lastTimeChecked) {
         // set the time checked first, so that parallel Piwik requests don't all trigger the http requests
         Option::set(self::LAST_TIME_CHECKED, time(), $autoLoad = 1);
         $parameters = array('piwik_version' => Version::VERSION, 'php_version' => PHP_VERSION, 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), 'timezone' => API::getInstance()->getDefaultTimezone());
         $url = Config::getInstance()->General['api_service_url'] . '/1.0/getLatestVersion/' . '?' . http_build_query($parameters, '', '&');
         $timeout = self::SOCKET_TIMEOUT;
         if (@Config::getInstance()->Debug['allow_upgrades_to_beta']) {
             $url = 'http://builds.piwik.org/LATEST_BETA';
         }
         try {
             $latestVersion = Http::sendHttpRequest($url, $timeout);
             if (!preg_match('~^[0-9][0-9a-zA-Z_.-]*$~D', $latestVersion)) {
                 $latestVersion = '';
             }
         } catch (Exception $e) {
             // e.g., disable_functions = fsockopen; allow_url_open = Off
             $latestVersion = '';
         }
         Option::set(self::LATEST_VERSION, $latestVersion);
     }
 }
Example #2
0
 /**
  * Records Global settings when user submit changes
  */
 public function setGlobalSettings()
 {
     $response = new ResponseBuilder(Common::getRequestVar('format'));
     try {
         $this->checkTokenInUrl();
         $timezone = Common::getRequestVar('timezone', false);
         $excludedIps = Common::getRequestVar('excludedIps', false);
         $excludedQueryParameters = Common::getRequestVar('excludedQueryParameters', false);
         $excludedUserAgents = Common::getRequestVar('excludedUserAgents', false);
         $currency = Common::getRequestVar('currency', false);
         $searchKeywordParameters = Common::getRequestVar('searchKeywordParameters', $default = "");
         $searchCategoryParameters = Common::getRequestVar('searchCategoryParameters', $default = "");
         $enableSiteUserAgentExclude = Common::getRequestVar('enableSiteUserAgentExclude', $default = 0);
         $keepURLFragments = Common::getRequestVar('keepURLFragments', $default = 0);
         $api = API::getInstance();
         $api->setDefaultTimezone($timezone);
         $api->setDefaultCurrency($currency);
         $api->setGlobalExcludedQueryParameters($excludedQueryParameters);
         $api->setGlobalExcludedIps($excludedIps);
         $api->setGlobalExcludedUserAgents($excludedUserAgents);
         $api->setGlobalSearchParameters($searchKeywordParameters, $searchCategoryParameters);
         $api->setSiteSpecificUserAgentExcludeEnabled($enableSiteUserAgentExclude == 1);
         $api->setKeepURLFragmentsGlobal($keepURLFragments);
         $toReturn = $response->getResponse();
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
Example #3
0
 static function update($schema = 'Myisam')
 {
     // force regeneration of cache files following #648
     Piwik::setUserIsSuperUser();
     $allSiteIds = API::getInstance()->getAllSitesId();
     Cache::regenerateCacheWebsiteAttributes($allSiteIds);
 }
 /**
  * One site with custom search parameters,
  * One site using default search parameters,
  * One site with disabled site search
  */
 private function setUpWebsites()
 {
     API::getInstance()->setGlobalSearchParameters($searchKeywordParameters = 'gkwd', $searchCategoryParameters = 'gcat');
     if (!self::siteCreated($idSite = 1)) {
         self::createWebsite(Date::factory($this->dateTime)->getDatetime(), 0, "Site 1 - Site search", $siteurl = false, $search = 1, $searchKwd = 'q,mykwd,p', $searchCat = 'cats');
     }
 }
 private function setUpWebsitesAndGoals()
 {
     $ecommerce = $this->allowConversions ? 1 : 0;
     // tests run in UTC, the Tracker in UTC
     if (!self::siteCreated($idSite = 1)) {
         self::createWebsite($this->dateTime, $ecommerce, "Site 1");
     }
     if (!self::siteCreated($idSite = 2)) {
         self::createWebsite($this->dateTime, 0, "Site 2");
     }
     if ($this->allowConversions) {
         if (!self::goalExists($idSite = 1, $idGoal = 1)) {
             APIGoals::getInstance()->addGoal($this->idSite1, 'all', 'url', 'http', 'contains', false, 5);
         }
         if (!self::goalExists($idSite = 1, $idGoal = 2)) {
             APIGoals::getInstance()->addGoal($this->idSite2, 'all', 'url', 'http', 'contains');
         }
         if (!self::goalExists($idSite = 1, $idGoal = 3)) {
             APIGoals::getInstance()->addGoal($this->idSite1, 'matching URL with campaign parameter', 'url', self::URL_IS_GOAL_WITH_CAMPAIGN_PARAMETERS, 'contains');
         }
     }
     APISitesManager::getInstance()->updateSite($this->idSite1, "Site 1", $urls = null, $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 2);
     // KEEP_URL_FRAGMENT_NO No for idSite 1
     APISitesManager::getInstance()->updateSite($this->idSite2, "Site 2", $urls = null, $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1);
     // KEEP_URL_FRAGMENT_YES Yes for idSite 2
 }
Example #6
0
 private function setSiteManagerApiMock()
 {
     $sitesInfo = $this->sitesInfo;
     $mock = $this->getMock('stdClass', array('getSiteFromId'));
     $mock->expects($this->any())->method('getSiteFromId')->willReturnCallback(function ($idSite) use($sitesInfo) {
         return $sitesInfo[$idSite];
     });
     SitesManagerAPI::setSingletonInstance($mock);
 }
 public function setUp()
 {
     parent::setUp();
     // setup the access layer
     FakeAccess::$superUser = true;
     $this->idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test");
     \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging', 'MultiSites'));
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
 }
Example #8
0
 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();
 }
Example #9
0
 public function index()
 {
     $view = new View('@ScheduledReports/index');
     $this->setGeneralVariablesView($view);
     $view->countWebsites = count(APISitesManager::getInstance()->getSitesIdWithAtLeastViewAccess());
     // get report types
     $reportTypes = API::getReportTypes();
     $view->reportTypes = $reportTypes;
     $view->defaultReportType = self::DEFAULT_REPORT_TYPE;
     $view->defaultReportFormat = ScheduledReports::DEFAULT_REPORT_FORMAT;
     $view->displayFormats = ScheduledReports::getDisplayFormats();
     $reportsByCategoryByType = array();
     $reportFormatsByReportType = array();
     $allowMultipleReportsByReportType = array();
     foreach ($reportTypes as $reportType => $reportTypeIcon) {
         // get report formats
         $reportFormatsByReportType[$reportType] = API::getReportFormats($reportType);
         $allowMultipleReportsByReportType[$reportType] = API::allowMultipleReports($reportType);
         // get report metadata
         $reportsByCategory = array();
         $availableReportMetadata = API::getReportMetadata($this->idSite, $reportType);
         foreach ($availableReportMetadata as $reportMetadata) {
             $reportsByCategory[$reportMetadata['category']][] = $reportMetadata;
         }
         $reportsByCategoryByType[$reportType] = $reportsByCategory;
     }
     $view->reportsByCategoryByReportType = $reportsByCategoryByType;
     $view->reportFormatsByReportType = $reportFormatsByReportType;
     $view->allowMultipleReportsByReportType = $allowMultipleReportsByReportType;
     $reports = array();
     $reportsById = array();
     if (!Piwik::isUserIsAnonymous()) {
         $reports = API::getInstance()->getReports($this->idSite, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = true);
         foreach ($reports as &$report) {
             $report['recipients'] = API::getReportRecipients($report);
             $reportsById[$report['idreport']] = $report;
         }
     }
     $view->reports = $reports;
     $view->reportsJSON = Common::json_encode($reportsById);
     $view->downloadOutputType = API::OUTPUT_INLINE;
     $view->periods = ScheduledReports::getPeriodToFrequency();
     $view->defaultPeriod = ScheduledReports::DEFAULT_PERIOD;
     $view->defaultHour = ScheduledReports::DEFAULT_HOUR;
     $view->language = LanguagesManager::getLanguageCodeForCurrentUser();
     $view->segmentEditorActivated = false;
     if (API::isSegmentEditorActivated()) {
         $savedSegmentsById = array();
         foreach (APISegmentEditor::getInstance()->getAll($this->idSite) as $savedSegment) {
             $savedSegmentsById[$savedSegment['idsegment']] = $savedSegment['name'];
         }
         $view->savedSegmentsById = $savedSegmentsById;
         $view->segmentEditorActivated = true;
     }
     return $view->render();
 }
Example #10
0
 private function trackVisits()
 {
     if (!$this->trackInvalidRequests) {
         return;
     }
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(true);
     API::getInstance()->setGlobalExcludedUserAgents('globalexcludeduseragent');
     // Trigger empty request
     $trackerUrl = self::getTrackerUrl();
     $response = Http::fetchRemoteFile($trackerUrl);
     self::assertTrue(strpos($response, 'is a free open source web') !== false, 'Piwik empty request response not correct: ' . $response);
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     // test GoogleBot UA visitor
     $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
     self::checkResponse($t->doTrackPageView('bot visit, please do not record'));
     // Test IP Exclusion works with or without IP exclusion
     foreach (array(false, true) as $enable) {
         $excludedIp = '154.1.12.34';
         API::getInstance()->updateSite($idSite, 'new site name', $url = array('http://site.com'), $ecommerce = 0, $ss = 1, $ss_kwd = '', $ss_cat = '', $excludedIp . ',1.2.3.4', $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = 'excludeduseragentstring');
         // Enable IP Anonymization
         $t->DEBUG_APPEND_URL = '&forceIpAnonymization=' . (int) $enable;
         // test with excluded User Agent
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (excludeduseragentstring)');
         $t->setIp('211.1.2.3');
         self::checkResponse($t->doTrackPageView('visit from excluded User Agent'));
         $t->setUserAgent('Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0 Google (+https://developers.google.com/+/web/snippet/)');
         self::checkResponse($t->doTrackPageView('visit from excluded User Agent'));
         // test w/ global excluded User Agent
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (globalexcludeduseragent)');
         $t->setIp('211.1.2.3');
         self::checkResponse($t->doTrackPageView('visit from global excluded User Agent'));
         // test with excluded IP
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)');
         // restore normal user agent
         $t->setIp($excludedIp);
         self::checkResponse($t->doTrackPageView('visit from IP excluded'));
         // test with global list of excluded IPs
         $excludedIpBis = '145.5.3.4';
         API::getInstance()->setGlobalExcludedIps($excludedIpBis);
         $t->setIp($excludedIpBis);
         self::checkResponse($t->doTrackPageView('visit from IP globally excluded'));
     }
     try {
         @$t->setAttributionInfo(array());
         self::fail();
     } catch (Exception $e) {
     }
     try {
         $t->setAttributionInfo(json_encode('test'));
         self::fail();
     } catch (Exception $e) {
     }
     $t->setAttributionInfo(json_encode(array()));
 }
 private function makeVisitorAndAction($lastActionTimestamp, $currentActionTime, $isVisitorKnown = false)
 {
     $idsite = API::getInstance()->addSite("name", "http://piwik.net/");
     /** @var Request $request */
     list($visit, $request) = $this->prepareVisitWithRequest(array('idsite' => $idsite), $currentActionTime);
     $visitProperties = new VisitProperties();
     $visitProperties->setProperty('visit_last_action_time', Date::factory($lastActionTimestamp)->getTimestamp());
     $request->setMetadata('CoreHome', 'isVisitorKnown', $isVisitorKnown);
     return array($visit, $visitProperties, $request);
 }
Example #12
0
 public function setUp()
 {
     parent::setUp();
     // setup the access layer
     self::setSuperUser();
     \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('API', 'UserCountry', 'ScheduledReports', 'MobileMessaging', 'VisitsSummary', 'Referrers'));
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
     APISitesManager::getInstance()->addSite("Test", array("http://piwik.net"));
     APISitesManager::getInstance()->addSite("Test", array("http://piwik.net"));
     FakeAccess::setIdSitesView(array($this->idSite, 2));
     APIScheduledReports::$cache = array();
 }
 function validateOwner()
 {
     try {
         $timezone = $this->owner->getValue();
         if (!empty($timezone)) {
             API::getInstance()->setDefaultTimezone($timezone);
         }
     } catch (\Exception $e) {
         return false;
     }
     return true;
 }
Example #14
0
 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();
 }
 /**
  * Returns default site ID that Piwik should load.
  *
  * _Note: This value is a Piwik setting set by each user._
  *
  * @return bool|int
  * @api
  */
 public function getDefaultWebsiteId()
 {
     $defaultReport = $this->getDefaultReport();
     if (is_numeric($defaultReport) && Piwik::isUserHasViewAccess($defaultReport)) {
         return $defaultReport;
     }
     $sitesId = APISitesManager::getInstance()->getSitesIdWithAtLeastViewAccess();
     if (!empty($sitesId)) {
         return $sitesId[0];
     }
     return false;
 }
Example #16
0
 public function setUp()
 {
     parent::setUp();
     self::updateDatabase();
     // make sure site has an early enough creation date (for period selector tests)
     Db::get()->update(Common::prefixTable("site"), array('ts_created' => '2011-01-01'), "idsite = 1");
     $this->addOverlayVisits();
     $this->addNewSitesForSiteSelector();
     DbHelper::createAnonymousUser();
     UsersManagerAPI::getInstance()->setSuperUserAccess('superUserLogin', true);
     SitesManagerAPI::getInstance()->updateSite(1, null, null, true);
 }
Example #17
0
 /**
  * Adds a new entry to the menu.
  *
  * @param string $menuName The menu's category name. Can be a translation token.
  * @param string $subMenuName The menu item's name. Can be a translation token.
  * @param string|array $url The URL the admin menu entry should link to, or an array of query parameters
  *                          that can be used to build the URL.
  * @param boolean $displayedForCurrentUser Whether this menu entry should be displayed for the
  *                                         current user. If false, the entry will not be added.
  * @param int $order The order hint.
  * @param bool|string $tooltip An optional tooltip to display or false to display the tooltip.
  * @api
  */
 public function add($menuName, $subMenuName, $url, $displayedForCurrentUser = true, $order = 50, $tooltip = false)
 {
     if (!$displayedForCurrentUser) {
         return;
     }
     // make sure the idSite value used is numeric (hack-y fix for #3426)
     if (!is_numeric(Common::getRequestVar('idSite', false))) {
         $idSites = API::getInstance()->getSitesIdWithAtLeastViewAccess();
         $url['idSite'] = reset($idSites);
     }
     $this->menuEntries[] = array($menuName, $subMenuName, $url, $order, $tooltip);
 }
 /**
  * One site with custom search parameters,
  * One site using default search parameters,
  * One site with disabled site search
  */
 protected function setUpWebsites()
 {
     API::getInstance()->setGlobalSearchParameters($searchKeywordParameters = 'gkwd', $searchCategoryParameters = 'gcat');
     if (!self::siteCreated($idSite = 1)) {
         self::createWebsite(Date::factory($this->dateTime)->subHour(200)->getDatetime(), 0, "Site 1 - Site search", $siteurl = false, $search = 1, $searchKwd = 'q,mykwd,p', $searchCat = 'cats');
     }
     if (!self::siteCreated($idSite = 2)) {
         self::createWebsite(Date::factory($this->dateTime)->subHour(400)->getDatetime(), 0, "Site 2 - Site search use default", $siteurl = false, $search = 1, $searchKwd = '', $searchCat = '');
     }
     if (!self::siteCreated($idSite = 3)) {
         self::createWebsite(Date::factory($this->dateTime)->subHour(600)->getDatetime(), 0, "Site 3 - No site search", $siteurl = false, $search = 0);
     }
 }
 /**
  * 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));
 }
Example #20
0
 public function test_TrackingOldVisit_ThatIsExcluded_DoesNotResetCreatedTime()
 {
     Fixture::createWebsite('2015-01-01 00:00:00');
     SitesManager\API::getInstance()->setGlobalExcludedIps('123.44.67.43');
     $createdTime = $this->getSiteCreatedTime($idSite = 1);
     $this->assertEquals('2014-12-31 00:00:00', $createdTime);
     $t = $this->getLocalTracker();
     $t->setForceVisitDateTime('2014-05-05 05:05:05');
     $t->setIp('123.44.67.43');
     Fixture::checkResponse($t->doTrackPageView('page view'));
     $createdTime = $this->getSiteCreatedTime($idSite = 1);
     $this->assertEquals('2014-12-31 00:00:00', $createdTime);
 }
 public function setUp()
 {
     parent::setUp();
     \Piwik\Plugin\Manager::getInstance()->loadPlugin('SegmentEditor');
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
     // setup the access layer
     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 = '******';
     APISitesManager::getInstance()->addSite('test', 'http://example.org');
 }
Example #22
0
 /**
  * Get excluded query parameters for a site.
  * This information is used for client side url normalization.
  */
 public function getExcludedQueryParameters($idSite)
 {
     $this->authenticate($idSite);
     $sitesManager = APISitesManager::getInstance();
     $site = $sitesManager->getSiteFromId($idSite);
     try {
         return SitesManager::getTrackerExcludedQueryParameters($site);
     } catch (Exception $e) {
         // an exception is thrown when the user has no view access.
         // do not throw the exception to the outside.
         return array();
     }
 }
Example #23
0
 /**
  * Adds a new entry to the menu.
  *
  * @param string $menuName The menu's category name. Can be a translation token.
  * @param string $subMenuName The menu item's name. Can be a translation token.
  * @param string|array $url The URL the admin menu entry should link to, or an array of query parameters
  *                          that can be used to build the URL.
  * @param boolean $displayedForCurrentUser Whether this menu entry should be displayed for the
  *                                         current user. If false, the entry will not be added.
  * @param int $order The order hint.
  * @param bool|string $tooltip An optional tooltip to display or false to display the tooltip.
  * @api
  */
 public function add($menuName, $subMenuName, $url, $displayedForCurrentUser = true, $order = 50, $tooltip = false)
 {
     if (!$displayedForCurrentUser) {
         // TODO this parameter should be removed and instead menu items should be only added if it is supposed to be
         // displayed. Won't do it now to stay backward compatible. For Piwik 3.0 we should do it.
         return;
     }
     // make sure the idSite value used is numeric (hack-y fix for #3426)
     if (!is_numeric(Common::getRequestVar('idSite', false))) {
         $idSites = API::getInstance()->getSitesIdWithAtLeastViewAccess();
         $url['idSite'] = reset($idSites);
     }
     $this->menuEntries[] = array($menuName, $subMenuName, $url, $order, $tooltip);
 }
 private function setLastRunArchiveOptions()
 {
     $periodTypes = array('day', 'periods');
     $idSites = API::getInstance()->getAllSitesId();
     $daysAgoArchiveRanSuccessfully = 1500;
     $this->assertTrue($daysAgoArchiveRanSuccessfully > \Piwik\CronArchive::ARCHIVE_SITES_WITH_TRAFFIC_SINCE / 86400);
     $time = Date::factory(self::$fixture->dateTime)->subDay($daysAgoArchiveRanSuccessfully)->getTimestamp();
     foreach ($periodTypes as $period) {
         foreach ($idSites as $idSite) {
             // lastRunKey() function inlined
             $lastRunArchiveOption = "lastRunArchive" . $period . "_" . $idSite;
             \Piwik\Option::set($lastRunArchiveOption, $time);
         }
     }
 }
 private function getSitesToInvalidateFor(InputInterface $input)
 {
     $sites = $input->getOption('sites');
     $siteIds = Site::getIdSitesFromIdSitesString($sites);
     if (empty($siteIds)) {
         throw new \InvalidArgumentException("Invalid --sites value: '{$sites}'.");
     }
     $allSiteIds = SitesManagerAPI::getInstance()->getAllSitesId();
     foreach ($siteIds as $idSite) {
         if (!in_array($idSite, $allSiteIds)) {
             throw new \InvalidArgumentException("Invalid --sites value: '{$sites}', there are no sites with IDs = {$idSite}");
         }
     }
     return $siteIds;
 }
 /**
  * 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);
 }
Example #27
0
 /**
  * Main Plugin Index
  *
  * @return mixed
  * @throws \Exception
  */
 public function index()
 {
     Piwik::checkUserHasSomeAdminAccess();
     if (isset($_SERVER['REQUEST_METHOD']) && 'POST' == $_SERVER['REQUEST_METHOD']) {
         // Cannot use Common::getRequestVar, because the function remove whitespaces and newline breaks
         $postedSiteData = isset($_POST['site']) ? $_POST['site'] : null;
         if (is_array($postedSiteData) && count($postedSiteData) > 0) {
             foreach ($postedSiteData as $id => $site) {
                 if (!isset($site['css'], $site['file'])) {
                     continue;
                 }
                 // Check URL
                 if (!UrlHelper::isLookLikeUrl($site['file'])) {
                     $site['file'] = null;
                 }
                 API::getInstance()->saveSite($id, $site['css'], $site['file']);
             }
             // Redirect to, clear POST vars
             $this->redirectToIndex('CustomOptOut', 'index');
             return;
         }
     }
     $view = new View('@CustomOptOut/index.twig');
     Site::clearCache();
     if (Piwik::hasUserSuperUserAccess()) {
         $sitesRaw = APISiteManager::getInstance()->getAllSites();
     } else {
         $sitesRaw = APISiteManager::getInstance()->getSitesWithAdminAccess();
     }
     // Gets sites after Site.setSite hook was called
     $sites = array_values(Site::getSites());
     if (count($sites) != count($sitesRaw)) {
         throw new \Exception("One or more website are missing or invalid.");
     }
     foreach ($sites as &$site) {
         $site['alias_urls'] = APISiteManager::getInstance()->getSiteUrlsFromId($site['idsite']);
     }
     $view->adminSites = $sites;
     $view->adminSitesCount = count($sites);
     $view->language = LanguagesManager::getLanguageCodeForCurrentUser();
     $view->isEditorEnabled = API::getInstance()->isCssEditorEnabled();
     $view->editorTheme = API::getInstance()->getEditorTheme();
     $view->showOldLinks = false;
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Example #28
0
 /**
  * Returns default site ID that Piwik should load.
  *
  * _Note: This value is a Piwik setting set by each user._
  *
  * @return bool|int
  * @api
  */
 public function getDefaultWebsiteId()
 {
     $defaultWebsiteId = false;
     // User preference: default website ID to load
     $defaultReport = APIUsersManager::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), APIUsersManager::PREFERENCE_DEFAULT_REPORT);
     if (is_numeric($defaultReport)) {
         $defaultWebsiteId = $defaultReport;
     }
     if ($defaultWebsiteId && Piwik::isUserHasViewAccess($defaultWebsiteId)) {
         return $defaultWebsiteId;
     }
     $sitesId = APISitesManager::getInstance()->getSitesIdWithAtLeastViewAccess();
     if (!empty($sitesId)) {
         return $sitesId[0];
     }
     return false;
 }
Example #29
0
 public function setUp()
 {
     self::downloadGeoIpDbs();
     parent::setUp();
     self::updateDatabase();
     // make sure site has an early enough creation date (for period selector tests)
     Db::get()->update(Common::prefixTable("site"), array('ts_created' => '2011-01-01'), "idsite = 1");
     // for proper geolocation
     LocationProvider::setCurrentProvider(LocationProvider\GeoIp\Php::ID);
     IPAnonymizer::deactivate();
     $this->addOverlayVisits();
     $this->addNewSitesForSiteSelector();
     DbHelper::createAnonymousUser();
     UsersManagerAPI::getInstance()->setSuperUserAccess('superUserLogin', true);
     SitesManagerAPI::getInstance()->updateSite(1, null, null, true);
     // create non super user
     UsersManagerAPI::getInstance()->addUser('oliverqueen', 'smartypants', '*****@*****.**');
     UsersManagerAPI::getInstance()->setUserAccess('oliverqueen', 'view', array(1));
 }
Example #30
0
 static function update()
 {
     $obsoleteFiles = array(PIWIK_INCLUDE_PATH . '/core/Db/Mysqli.php');
     foreach ($obsoleteFiles as $obsoleteFile) {
         if (file_exists($obsoleteFile)) {
             @unlink($obsoleteFile);
         }
     }
     $obsoleteDirectories = array(PIWIK_INCLUDE_PATH . '/core/Db/Pdo');
     foreach ($obsoleteDirectories as $dir) {
         if (file_exists($dir)) {
             Filesystem::unlinkRecursive($dir, true);
         }
     }
     // force regeneration of cache files
     Piwik::setUserHasSuperUserAccess();
     $allSiteIds = API::getInstance()->getAllSitesId();
     Cache::regenerateCacheWebsiteAttributes($allSiteIds);
 }