factory() public static method

Creates a new Date instance using a string datetime value. The timezone of the Date result will be in UTC.
public static factory ( string | integer $dateString, string $timezone = null ) : Date
$dateString string | integer `'today'`, `'yesterday'`, `'now'`, `'yesterdaySameTime'`, a string with `'YYYY-MM-DD HH:MM:SS'` format or a unix timestamp.
$timezone string The timezone of the result. If specified, `$dateString` will be converted from UTC to this timezone before being used in the Date return value.
return Date
 public static function getArchiveIdAndVisits(ArchiveProcessor\Parameters $params, $minDatetimeArchiveProcessedUTC)
 {
     $idSite = $params->getSite()->getId();
     $period = $params->getPeriod()->getId();
     $dateStart = $params->getPeriod()->getDateStart();
     $dateStartIso = $dateStart->toString('Y-m-d');
     $dateEndIso = $params->getPeriod()->getDateEnd()->toString('Y-m-d');
     $numericTable = ArchiveTableCreator::getNumericTable($dateStart);
     $minDatetimeIsoArchiveProcessedUTC = null;
     if ($minDatetimeArchiveProcessedUTC) {
         $minDatetimeIsoArchiveProcessedUTC = Date::factory($minDatetimeArchiveProcessedUTC)->getDatetime();
     }
     $requestedPlugin = $params->getRequestedPlugin();
     $segment = $params->getSegment();
     $plugins = array("VisitsSummary", $requestedPlugin);
     $doneFlags = Rules::getDoneFlags($plugins, $segment);
     $doneFlagValues = Rules::getSelectableDoneFlagValues();
     $results = self::getModel()->getArchiveIdAndVisits($numericTable, $idSite, $period, $dateStartIso, $dateEndIso, $minDatetimeIsoArchiveProcessedUTC, $doneFlags, $doneFlagValues);
     if (empty($results)) {
         return false;
     }
     $idArchive = self::getMostRecentIdArchiveFromResults($segment, $requestedPlugin, $results);
     $idArchiveVisitsSummary = self::getMostRecentIdArchiveFromResults($segment, "VisitsSummary", $results);
     list($visits, $visitsConverted) = self::getVisitsMetricsFromResults($idArchive, $idArchiveVisitsSummary, $results);
     if (false === $visits && false === $idArchive) {
         return false;
     }
     return array($idArchive, $visits, $visitsConverted);
 }
Beispiel #2
0
 /**
  * Computes the output for the given data table
  *
  * @param DataTable $table
  * @return string
  * @throws Exception
  */
 protected function renderTable($table)
 {
     if (!$table instanceof DataTable\Map || $table->getKeyName() != 'date') {
         throw new Exception("RSS feeds can be generated for one specific website &idSite=X." . "\nPlease specify only one idSite or consider using &format=XML instead.");
     }
     $idSite = Common::getRequestVar('idSite', 1, 'int');
     $period = Common::getRequestVar('period');
     $piwikUrl = SettingsPiwik::getPiwikUrl() . "?module=CoreHome&action=index&idSite=" . $idSite . "&period=" . $period;
     $out = "";
     $moreRecentFirst = array_reverse($table->getDataTables(), true);
     foreach ($moreRecentFirst as $date => $subtable) {
         /** @var DataTable $subtable */
         $timestamp = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_PERIOD_INDEX)->getDateStart()->getTimestamp();
         $site = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_SITE_INDEX);
         $pudDate = date('r', $timestamp);
         $dateInSiteTimezone = Date::factory($timestamp);
         if ($site) {
             $dateInSiteTimezone = $dateInSiteTimezone->setTimezone($site->getTimezone());
         }
         $dateInSiteTimezone = $dateInSiteTimezone->toString('Y-m-d');
         $thisPiwikUrl = Common::sanitizeInputValue($piwikUrl . "&date={$dateInSiteTimezone}");
         $siteName = $site ? $site->getName() : '';
         $title = $siteName . " on " . $date;
         $out .= "\t<item>\n\t\t<pubDate>{$pudDate}</pubDate>\n\t\t<guid>{$thisPiwikUrl}</guid>\n\t\t<link>{$thisPiwikUrl}</link>\n\t\t<title>{$title}</title>\n\t\t<author>http://piwik.org</author>\n\t\t<description>";
         $out .= Common::sanitizeInputValue($this->renderDataTable($subtable));
         $out .= "</description>\n\t</item>\n";
     }
     $header = $this->getRssHeader();
     $footer = $this->getRssFooter();
     return $header . $out . $footer;
 }
Beispiel #3
0
 /**
  * @group Core
  */
 public function testGetPrettyString()
 {
     Translate::loadEnglishTranslation();
     $year = new Year(Date::factory('2024-10-09'));
     $shouldBe = '2024';
     $this->assertEquals($shouldBe, $year->getPrettyString());
 }
 protected static function beforeTableDataCached()
 {
     $date = Date::factory('2010-03-01');
     $archiveTableCreator = new ArchiveTableCreator();
     $archiveTableCreator->getBlobTable($date);
     $archiveTableCreator->getNumericTable($date);
 }
Beispiel #5
0
 /**
  * Constructor.
  */
 public function __construct()
 {
     $date = $this->month . '-01';
     $classes = get_declared_classes();
     sort($classes);
     foreach ($classes as $className) {
         if (is_subclass_of($className, 'Fixture') && !is_subclass_of($className, __CLASS__) && $className != __CLASS__ && $className != "Piwik_Test_Fixture_SqlDump" && $className != "Piwik\\Tests\\Fixtures\\UpdaterTestFixture") {
             $klassReflect = new ReflectionClass($className);
             if (!strpos($klassReflect->getFilename(), "tests/PHPUnit/Fixtures") && $className != "Test_Piwik_Fixture_CustomAlerts" && $className != "Piwik\\Plugins\\Insights\\tests\\Fixtures\\SomeVisitsDifferentPathsOnTwoDays") {
                 continue;
             }
             $fixture = new $className();
             if (!property_exists($fixture, 'dateTime')) {
                 continue;
             }
             $fixture->dateTime = $this->adjustDateTime($fixture->dateTime, $date);
             $this->fixtures[$className] = $fixture;
             $date = Date::factory($date)->addDay(1)->toString();
         }
     }
     $this->now = $this->fixtures['Test_Piwik_Fixture_ManySitesImportedLogsWithXssAttempts']->now;
     // make sure Test_Piwik_Fixture_ManySitesImportedLogsWithXssAttempts is the first fixture
     $fixture = $this->fixtures['Test_Piwik_Fixture_ManySitesImportedLogsWithXssAttempts'];
     unset($this->fixtures['Test_Piwik_Fixture_ManySitesImportedLogsWithXssAttempts']);
     $this->fixtures = array_merge(array('Test_Piwik_Fixture_ManySitesImportedLogsWithXssAttempts' => $fixture), $this->fixtures);
 }
 public function index()
 {
     Piwik::checkUserHasSuperUserAccess();
     $view = new View('@TasksTimetable/index.twig');
     $this->setGeneralVariablesView($view);
     $tasks = Option::get('TaskScheduler.timetable');
     if (!empty($tasks)) {
         $tasks = unserialize($tasks);
     }
     if (empty($tasks)) {
         $tasks = array();
     } else {
         asort($tasks);
     }
     $tsNow = Date::now()->getTimestamp();
     $dateFormat = Piwik::translate(Date::DATE_FORMAT_LONG) . ' h:mm:ss';
     $formatter = new Formatter();
     $tasksFormatted = array();
     foreach ($tasks as $name => $timestamp) {
         $tasksFormatted[] = array('name' => $name, 'executionDate' => Date::factory($timestamp)->getLocalized($dateFormat), 'ts_difference' => $formatter->getPrettyTimeFromSeconds($timestamp - $tsNow));
     }
     $view->currentTime = Date::now()->getLocalized($dateFormat);
     $view->tasks = $tasksFormatted;
     return $view->render();
 }
 private function trackVisits()
 {
     $dateTime = $this->dateTime;
     $idSite = 1;
     $idGoal_OneConversionPerVisit = $this->idGoal_OneConversionPerVisit;
     $idGoal_MultipleConversionPerVisit = $this->idGoal_MultipleConversionPerVisit;
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     // Record 1st goal, should only have 1 conversion
     $t->setUrl('http://example.org/index.htm');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.3)->getDatetime());
     self::checkResponse($t->doTrackPageView('Thank you mate'));
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
     self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 10000000));
     // Record 2nd goal, should record both conversions
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.5)->getDatetime());
     self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 300));
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.6)->getDatetime());
     self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 366));
     // Update & set to not allow multiple
     $goals = API::getInstance()->getGoals($idSite);
     $goal = $goals[$idGoal_OneConversionPerVisit];
     self::assertTrue($goal['allow_multiple'] == 0);
     API::getInstance()->updateGoal($idSite, $idGoal_OneConversionPerVisit, $goal['name'], @$goal['match_attribute'], @$goal['pattern'], @$goal['pattern_type'], @$goal['case_sensitive'], $goal['revenue'], $goal['allow_multiple'] = 1);
     self::assertTrue($goal['allow_multiple'] == 1);
     // 1st goal should Now be tracked
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.61)->getDatetime());
     self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 656));
     // few minutes later, create a new_visit
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.7)->getDatetime());
     $t->setTokenAuth($this->getTokenAuth());
     $t->setForceNewVisit();
     $t->doTrackPageView('This is tracked in a new visit.');
 }
 public function setUp()
 {
     parent::setUp();
     $this->archiveTableDao = self::$fixture->piwikEnvironment->getContainer()->get('Piwik\\DataAccess\\ArchiveTableDao');
     ArchiveTableCreator::getBlobTable(Date::factory('2015-01-01'));
     ArchiveTableCreator::getNumericTable(Date::factory('2015-01-01'));
 }
 private function trackVisits()
 {
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     $t->setUrlReferrer('http://www.google.com/search?q=piwik');
     $t->setUrl('http://example.org/foo/bar.html');
     self::checkResponse($t->doTrackPageView('http://incredible.title/'));
     $t->setUrl('https://example.org/foo/bar.html');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.2)->getDatetime());
     self::checkResponse($t->doTrackPageView('https://incredible.title/'));
     $t->setUrl('https://wWw.example.org/foo/bar2.html');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.3)->getDatetime());
     self::checkResponse($t->doTrackPageView('http://www.incredible.title/'));
     $t->setUrl('http://WwW.example.org/foo/bar2.html');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
     self::checkResponse($t->doTrackPageView('https://www.incredible.title/'));
     $t->setUrl('http://www.example.org/foo/bar3.html');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.5)->getDatetime());
     self::checkResponse($t->doTrackPageView('incredible.title/'));
     $t->setUrl('http://www.my.url/ꟽ碌㒧䊶亄ﶆⅅขκもኸόσशμεޖृ');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.7)->getDatetime());
     self::checkResponse($t->doTrackPageView('Valid URL, although strange looking'));
     $t->setUrl('https://make.wordpress.org/?emoji=😎l&param=test');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.8)->getDatetime());
     self::checkResponse($t->doTrackPageView('Emoji here: %F0%9F%98%8E'));
     // this pageview should be last
     $t->setUrl('https://example.org/foo/bar4.html');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.6)->getDatetime());
     self::checkResponse($t->doTrackPageView('incredible.title/'));
 }
 private function trackVisits()
 {
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1);
     $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja');
     $t->setUrl('http://example.org/%C3%A9%C3%A9%C3%A9%22%27...%20%3Cthis%20is%20cool%3E!');
     $t->setGenerationTime(523);
     self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
     $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.2)->getDatetime());
     $t->setGenerationTime(123);
     self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
     $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.3)->getDatetime());
     $t->setGenerationTime(153);
     self::checkResponse($t->doTrackPageView('incredible parent title! <>,; / subtitle <>,;'));
     $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.31)->getDatetime());
     $t->setGenerationTime(153);
     self::checkResponse($t->doTrackEvent('Category', 'Action', 'Name', 11111));
     $t->setUrl('http://example.org/dir2/file.php?foo=bar&foo2=bar');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
     $t->setGenerationTime(1233);
     self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
     $t->setUrl('http://example.org/dir2/sub/0/file.php');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
     // Very high Generation time should be ignored
     $t->setGenerationTime(6350000);
     self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
     $t->setUrl('http://example.org/0');
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
     $t->setGenerationTime(635);
     self::checkResponse($t->doTrackPageView('I am URL zero!'));
 }
Beispiel #11
0
 /**
  * @return bool `true` if the purge was executed, `false` if it was skipped.
  * @throws \Exception
  */
 public function purgeOutdatedArchives()
 {
     if ($this->willPurgingCausePotentialProblemInUI()) {
         $this->logger->info("Purging temporary archives: skipped (browser triggered archiving not enabled & not running after core:archive)");
         return false;
     }
     $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled();
     $this->logger->info("Purging archives in {tableCount} archive tables.", array('tableCount' => count($archiveTables)));
     // keep track of dates we purge for, since getTablesArchivesInstalled() will return numeric & blob
     // tables (so dates will appear two times, and we should only purge once per date)
     $datesPurged = array();
     foreach ($archiveTables as $table) {
         $date = ArchiveTableCreator::getDateFromTableName($table);
         list($year, $month) = explode('_', $date);
         // Somehow we may have archive tables created with older dates, prevent exception from being thrown
         if ($year > 1990) {
             if (empty($datesPurged[$date])) {
                 $dateObj = Date::factory("{$year}-{$month}-15");
                 $this->archivePurger->purgeOutdatedArchives($dateObj);
                 $this->archivePurger->purgeArchivesWithPeriodRange($dateObj);
                 $datesPurged[$date] = true;
             } else {
                 $this->logger->debug("Date {date} already purged.", array('date' => $date));
             }
         } else {
             $this->logger->info("Skipping purging of archive tables *_{year}_{month}, year <= 1990.", array('year' => $year, 'month' => $month));
         }
     }
     return true;
 }
 public function setUp()
 {
     // add one thousand sites
     $allIdSites = array();
     for ($i = 0; $i < 1000; ++$i) {
         $allIdSites[] = Fixture::createWebsite($this->date, $ecommerce = 1, $siteName = "Site #{$i}");
     }
     $urls = array();
     for ($i = 0; $i != 3; ++$i) {
         $url = "http://whatever.com/" . ($i - 1) . "/" . ($i + 1);
         $title = "page view " . ($i - 1) . " / " . ($i + 1);
         $urls[$url] = $title;
     }
     $visitTimes = array();
     $date = Date::factory($this->date);
     for ($i = 0; $i != 4; ++$i) {
         $visitTimes[] = $date->addHour($i)->getDatetime();
     }
     // add 12000 visits (3 visitors with 4 visits each for each site) w/ 3 pageviews each on one day
     foreach ($visitTimes as $visitTime) {
         foreach ($allIdSites as $idSite) {
             for ($visitor = 0; $visitor != 3; ++$visitor) {
                 $t = BenchmarkTestCase::getLocalTracker($idSite);
                 $ip = "157.5.6." . ($visitor + 1);
                 $t->setIp($ip);
                 $t->setNewVisitorId();
                 $t->setForceVisitDateTime($visitTime);
                 foreach ($urls as $url => $title) {
                     $t->setUrl($url);
                     $t->doTrackPageView($title);
                 }
             }
         }
     }
 }
 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;
     }
 }
 private function trackVisits()
 {
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     for ($referrerSite = 1; $referrerSite < 4; $referrerSite++) {
         for ($referrerPage = 1; $referrerPage < 3; $referrerPage++) {
             $offset = $referrerSite * 3 + $referrerPage;
             $t = self::getTracker($idSite, Date::factory($dateTime)->addHour($offset)->getDatetime());
             $t->setUrlReferrer('http://www.referrer' . $referrerSite . '.com/sub/dir/page' . $referrerPage . '.html');
             $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue' . $referrerPage, 'visit');
             for ($page = 0; $page < 3; $page++) {
                 $t->setUrl('http://example.org/dir' . $referrerSite . '/sub/dir/page' . $page . '.html');
                 $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue' . $page, 'page');
                 $t->setGenerationTime($referrerPage * $referrerSite * ($page + 1) * 100);
                 self::checkResponse($t->doTrackPageView('title'));
             }
         }
     }
     $t = self::getTracker($idSite, Date::factory($dateTime)->addHour(24)->getDatetime());
     $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue1', 'visit');
     $t->setUrl('http://example.org/sub/dir/dir1/page1.html');
     $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue1', 'page');
     self::checkResponse($t->doTrackPageView('title'));
     $t = self::getTracker($idSite, Date::factory($dateTime)->addHour(24)->getDatetime());
     $t->setUrl('http://example.org/page1.html');
     self::checkResponse($t->doTrackPageView('title'));
 }
 private function trackVisits()
 {
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     // two visits to site 1 & 3
     $visitor1 = self::getTracker($idSite, $dateTime, $defaultInit = true);
     $visitor1->setForceVisitDateTime(Date::factory($this->dateTime)->getDatetime());
     $visitor1->setUrl('http://helios.org/alpha');
     $visitor1->doTrackPageView("page title");
     $visitor1->setIdSite($this->idSite2);
     $visitor1->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(1)->getDatetime());
     $visitor1->setUrl('http://taura.org/');
     $visitor1->doTrackPageView("page title");
     // one visit to site 1
     $visitor2 = self::getTracker($idSite, $dateTime, $defaultInit = true);
     $visitor2->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(2)->getDatetime());
     $visitor2->setUrl('http://helios.org/beta');
     $visitor2->doTrackPageView("page title 2");
     // two visits to site 2 and 3
     $visitor3 = self::getTracker($this->idSite1, $dateTime, $defaultInit = true);
     $visitor3->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(3)->getDatetime());
     $visitor3->setUrl('http://virgon.org/');
     $visitor3->doTrackPageView("page title 2");
     $visitor3->setIdSite($this->idSite2);
     $visitor3->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(4)->getDatetime());
     $visitor3->setUrl('http://taura.org/');
     $visitor3->doTrackPageView("page title");
 }
 public function setUp()
 {
     // add one site
     Fixture::createWebsite($this->date, $ecommerce = 1, $siteName = "Site #0", $siteUrl = "http://whatever.com/");
     // add two goals
     $goals = API::getInstance();
     $goals->addGoal($this->idSite, 'all', 'url', 'http', 'contains', false, 5);
     $goals->addGoal($this->idSite, 'all', 'url', 'thing2', 'contains');
     $start = Date::factory($this->date);
     $dates = array();
     for ($day = 0; $day != 31; ++$day) {
         $dates[] = $start->addDay($day);
     }
     $t = BenchmarkTestCase::getLocalTracker($this->idSite);
     $actionNum = 0;
     foreach ($dates as $date) {
         for ($visitNum = 0; $visitNum != 1000; ++$visitNum) {
             if ($visitNum % 2 == 0) {
                 $url = "http://whatever.com/{$actionNum}/0/1/2/3/4/5/6/7/8/9";
                 $referrerUrl = "http://google.com/?q={$actionNum}";
             } else {
                 $url = "http://whatever.com/thing2/{$actionNum}/0/1/2/3/4/5/6/7/8/9";
                 $referrerUrl = "http://";
             }
             $title = "A page title / {$actionNum} / 0 / 1 / 2 / 3 / 4 / 5 / 6 / 7 / 8 /9";
             $t->setNewVisitorId();
             $t->setForceVisitDateTime($date);
             $t->setUrl($url);
             $t->setUrlReferrer($referrerUrl);
             Fixture::checkResponse($t->doTrackPageView($title));
             ++$actionNum;
         }
     }
 }
 private function trackVisits()
 {
     // tests run in UTC, the Tracker in UTC
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     // Also testing to record this as a bot while specifically allowing bots
     $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
     $t->DEBUG_APPEND_URL .= '&bots=1';
     $t->DEBUG_APPEND_URL .= '&forceIpAnonymization=1';
     // VISIT 1 = Referrer is "Keyword not defined"
     // Alsotrigger goal to check that attribution goes to this keyword
     $t->setUrlReferrer('http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC&url=http%3A%2F%2Fpiwik.org%2F&ei=&usg=');
     $t->setUrl('http://example.org/this%20is%20cool!?filter=<script>alert(1);</script>{"place":{"place":"0c5b2444-70a0-4932-980c-b4dc0d3f02b5"}}');
     self::checkResponse($t->doTrackPageView('incredible title! (Page URL contains a HTML entity)'));
     $idGoal = 1;
     if (!self::goalExists($idSite, $idGoal)) {
         $idGoal = API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', '');
     }
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.3)->getDatetime());
     self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42));
     // VISIT 2 = Referrer has keyword, but the URL should be rewritten
     // in Live Output to point to google search result page
     $t->setForceVisitDateTime(Date::factory($dateTime)->addHour(2)->getDatetime());
     $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja');
     // Test with empty title, that the output of Live is valid
     self::checkResponse($t->doTrackPageView(''));
 }
 public function getApiForTesting()
 {
     $idSite = self::$fixture->idSite;
     $dateTime = self::$fixture->dateTime;
     $dateString = Date::factory($dateTime)->toString();
     // Note: we must set  'UserCountry.getLocationFromIP' since it's "excluded" by default in setApiNotToCall
     $apiToCall = array('UserCountry');
     $apiToTest = array(array($apiToCall, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'))), array($apiToCall, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_region', 'segment' => 'regionCode==P3;countryCode==gb')), array($apiToCall, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_city', 'segment' => 'city==Stratford-upon-Avon;regionCode==P3;countryCode==gb')), array($apiToCall, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_lat_long', 'segment' => 'latitude>45;latitude<49.3;longitude>-125;longitude<-122')), array('UserCountry.getCountry', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_continent', 'segment' => 'continentCode==eur')), array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'Actions', 'apiAction' => 'getPageUrls', 'testSuffix' => '_sortByProcessedMetric', 'otherRequestParameters' => array('filter_sort_column' => 'nb_actions_per_visit'))), array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'VisitTime', 'apiAction' => 'getVisitInformationPerServerTime', 'testSuffix' => '_sortByProcessedMetric_constantRowsCountShouldKeepEmptyRows', 'otherRequestParameters' => array('filter_sort_column' => 'nb_actions_per_visit'))), array(array('UserCountry.getLocationFromIP', 'Live.getLastVisitsDetails'), array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('month'), 'otherRequestParameters' => array('ip' => '194.57.91.215'))), array(array('UserCountry.getLocationFromIP'), array('otherRequestParameters' => array('ip' => '194.57.91.215'))), array(array('UserCountry.getLocationFromIP'), array('testSuffix' => '_IPv6', 'otherRequestParameters' => array('ip' => '2001:db8:85a3:0:0:8a2e:370:7334'))));
     // Randomly fails on 5.3
     if (!self::isPhpVersion53()) {
         $apiToTest[] = array('Live.getLastVisitsDetails', array('idSite' => $idSite, 'date' => $dateString, 'periods' => 'month', 'testSuffix' => '_Live.getLastVisitsDetails_sortDesc', 'otherRequestParameters' => array('filter_sort_order' => 'desc', 'filter_limit' => 7)));
         // #5950
         $apiToTest[] = array('Live.getLastVisitsDetails', array('idSite' => $idSite, 'date' => $dateString, 'periods' => 'month', 'testSuffix' => '_Live.getLastVisitsDetails_sortByIdVisit', 'otherRequestParameters' => array('filter_sort_order' => 'desc', 'filter_sort_column' => 'idVisit', 'filter_limit' => 7)));
         // #7458
         $apiToTest[] = array('Live.getLastVisitsDetails', array('idSite' => $idSite, 'date' => $dateString, 'periods' => 'month', 'testSuffix' => '_Live.getLastVisitsDetails_offsetAndLimit_1', 'otherRequestParameters' => array('filter_offset' => '1', 'filter_limit' => 3)));
         $apiToTest[] = array('Live.getLastVisitsDetails', array('idSite' => $idSite, 'date' => $dateString, 'periods' => 'month', 'testSuffix' => '_Live.getLastVisitsDetails_offsetAndLimit_2', 'otherRequestParameters' => array('filter_offset' => '4', 'filter_limit' => 3)));
     }
     // this also fails on all PHP versions, it seems randomly.
     //            $apiToTest[] = array('Live.getLastVisitsDetails', array(
     //                'idSite'                 => $idSite,
     //                'date'                   => $dateString,
     //                'periods'                => 'month',
     //                'testSuffix'             => '_Live.getLastVisitsDetails_sortAsc',
     //                'otherRequestParameters' => array('filter_sort_order' => 'asc', 'filter_limit' => 7)
     //            ));
     return $apiToTest;
 }
 private function trackVisits()
 {
     $dateTimes = $this->dateTimes;
     $days = 0;
     $ridx = 0;
     foreach ($dateTimes as $dateTime) {
         $days++;
         // Fake the visit count cookie
         $debugStringAppend = "&_idvc={$days}";
         $visitor = $this->makeTracker($this->idSite, $dateTime, $debugStringAppend);
         // FIRST VISIT THIS DAY
         $visitor->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.1)->getDatetime());
         $visitor->setUrl('http://example.org/homepage');
         $visitor->setUrlReferrer($this->referrerUrls[$ridx++]);
         self::checkResponse($visitor->doTrackPageView('ou pas'));
         // Test change the IP, the visit should not be split but recorded to the same idvisitor
         $visitor->setIp('200.1.15.22');
         $visitor->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.2)->getDatetime());
         $urlWithThreeSubdirectories = 'http://example.org/sub1/sub2/sub3/news';
         $visitor->setUrl($urlWithThreeSubdirectories);
         self::checkResponse($visitor->doTrackPageView('ou pas'));
         // SECOND VISIT THIS DAY
         $visitor->setForceVisitDateTime(Date::factory($dateTime)->addHour(1)->getDatetime());
         $visitor->setUrl('http://example.org/news');
         $visitor->setUrlReferrer($this->referrerUrls[$ridx++]);
         self::checkResponse($visitor->doTrackPageView('ou pas'));
         if ($days <= 3) {
             $visitor = $this->makeTracker($this->idSite2, $dateTime);
             $visitor->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.1)->getDatetime());
             $visitor->setUrl('http://example.org/homepage');
             $visitor->setUrlReferrer($this->referrerUrls[$ridx - 1]);
             self::checkResponse($visitor->doTrackPageView('Second website'));
         }
     }
 }
Beispiel #20
0
 protected static function deleteArchivesWithPeriodRange(Date $date)
 {
     $numericTable = ArchiveTableCreator::getNumericTable($date);
     $blobTable = ArchiveTableCreator::getBlobTable($date);
     $yesterday = Date::factory('yesterday')->getDateTime();
     Log::debug("Purging Custom Range archives: done [ purged archives older than %s from %s / blob ]", $yesterday, $numericTable);
     self::getModel()->deleteArchivesWithPeriodRange($numericTable, $blobTable, Piwik::$idPeriods['range'], $yesterday);
 }
Beispiel #21
0
 private function createManyLogEntries($numLogEntries)
 {
     $date = Date::factory('2014-01-01 01:00:00');
     for ($i = 1; $i <= $numLogEntries; $i++) {
         $date->subSeconds(1);
         $this->createLogEntry("DEBUG Piwik\\Common[2015-08-19 12:39:02] [93d35] Test Message " . $i, $date->getDatetime());
     }
 }
 private function getSiteCreatedTime($idSite)
 {
     $attributes = Cache::getCacheWebsiteAttributes($idSite);
     if (!isset($attributes['ts_created'])) {
         return null;
     }
     return Date::factory($attributes['ts_created']);
 }
 public function setUp()
 {
     parent::setUp();
     self::updateDatabase();
     self::createWebsite("2012-01-01 00:00:00");
     $fakeTasks = array('Piwik\\Plugins\\ExamplePlugin\\Tasks.myTask' => Date::factory("2012-01-02 02:33:45")->getTimestampUTC(), 'Piwik\\Plugins\\CoreUpdater\\Tasks.sendNotificationIfUpdateAvailable' => Date::factory("2012-03-04 13:45:56")->getTimestampUTC(), 'Piwik\\Plugins\\CorePluginsAdmin\\Tasks.sendNotificationIfUpdatesAvailable' => Date::factory("2012-02-12 15:12:10")->getTimestampUTC());
     Option::set('TaskScheduler.timetable', serialize($fakeTasks));
 }
 private function buildTracker()
 {
     $t = Fixture::getTracker($this->idSite, Date::factory('2014-01-05 00:01:01')->getDatetime());
     $t->setDebugStringAppend('debug=1');
     $t->setTokenAuth(Fixture::getTokenAuth());
     $t->setUrl('http://example.org/index1.htm');
     return $t;
 }
Beispiel #25
0
 public function test_UpdateCommand_ReturnsCorrectExitCode_WhenErrorOccurs()
 {
     // create a blob table, then drop it manually so update 2.10.0-b10 will fail
     $tableName = ArchiveTableCreator::getBlobTable(Date::factory('2015-01-01'));
     Db::exec("DROP TABLE {$tableName}");
     $result = $this->applicationTester->run(array('command' => 'core:update', '--yes' => true));
     $this->assertEquals(1, $result, $this->getCommandDisplayOutputErrorMessage());
     $this->assertContains("Piwik could not be updated! See above for more information.", $this->applicationTester->getDisplay());
 }
 private function trackVisits()
 {
     $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true);
     // Record 1st page view
     $t->setUrl('http://example.org/index.htm');
     self::checkResponse($t->doTrackPageView('0'));
     $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.3)->getDatetime());
     self::checkResponse($t->doTrackGoal($this->idGoal3, $revenue = 42.256));
 }
 /**
  * This method takes the websites timezone into consideration when scheduling a task.
  * @param int $idSite
  * @param string $period  Eg 'day', 'week', 'month'
  * @return Daily|Monthly|Weekly
  * @throws \Exception
  * @ignore
  */
 public static function getScheduledTimeForSite($idSite, $period)
 {
     $arbitraryDateInUTC = Date::factory('2011-01-01');
     $midnightInSiteTimezone = date('H', Date::factory($arbitraryDateInUTC, Site::getTimezoneFor($idSite))->getTimestamp());
     $hourInUTC = (24 - $midnightInSiteTimezone) % 24;
     $schedule = self::getScheduledTimeForPeriod($period);
     $schedule->setHour($hourInUTC);
     return $schedule;
 }
 public function getApiForTesting()
 {
     $dateTime = self::$fixture->dateTime;
     $periods = array('day', 'week', 'month', 'year');
     $dateStart = \Piwik\Date::factory($dateTime)->subDay(10)->toString();
     $dateEnd = \Piwik\Date::factory($dateTime)->addDay(15)->toString();
     $dateRange = $dateStart . "," . $dateEnd;
     return array(array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => true, 'testSuffix' => '_disabledBefore')), array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => false, 'testSuffix' => '_enabled')), array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => true, 'testSuffix' => '_disabledAfter')), array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateRange, 'periods' => array('range'), 'disableArchiving' => false, 'testSuffix' => '_enabledBefore_isDateRange')), array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateRange, 'periods' => array('range'), 'disableArchiving' => true, 'testSuffix' => '_disabledBefore_isDateRange')));
 }
 private function trackVisits()
 {
     $dateTime = Date::factory($this->date)->addHour(27);
     // tracking a visit that is tomorrow in New York time
     $idSite = $this->idSite;
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     // visit that is 'tomorrow' in UTC
     $t->setUrl('http://example.org/index.htm');
     self::checkResponse($t->doTrackPageView('incredible title!'));
 }
 /**
  * @group        Benchmarks
  */
 public function testArchivingProcess()
 {
     if ($this->archivingLaunched) {
         echo "NOTE: Had to archive data, memory results will not be accurate. Run again for better results.";
     }
     Rules::$archivingDisabledByTests = true;
     $period = Period\Factory::build(self::$fixture->period, Date::factory(self::$fixture->date));
     $dateRange = $period->getDateStart() . ',' . $period->getDateEnd();
     API::getInstance()->get(self::$fixture->idSite, 'day', $dateRange);
 }