Esempio n. 1
0
 /**
  * Prepares the archive. Gets the idarchive from the ArchiveProcessing.
  * 
  * This will possibly launch the archiving process if the archive was not available.
  * 
  * @return void
  */
 public function prepareArchive()
 {
     $archiveJustProcessed = false;
     if (!$this->alreadyChecked) {
         $this->isThereSomeVisits = false;
         $this->alreadyChecked = true;
         // if the END of the period is BEFORE the website creation date
         // we already know there are no stats for this period
         // we add one day to make sure we don't miss the day of the website creation
         if ($this->period->getDateEnd()->addDay(2)->isEarlier($this->site->getCreationDate())) {
             return;
         }
         // if the starting date is in the future we know there is no visit
         if ($this->period->getDateStart()->subDay(1)->isLater(Piwik_Date::today())) {
             return;
         }
         // we make sure the archive is available for the given date
         $periodLabel = $this->period->getLabel();
         $archiveProcessing = Piwik_ArchiveProcessing::factory($periodLabel);
         $archiveProcessing->setSite($this->site);
         $archiveProcessing->setPeriod($this->period);
         $idArchive = $archiveProcessing->loadArchive();
         if ($idArchive === null) {
             $archiveJustProcessed = true;
             $archiveProcessing->launchArchiving();
             $idArchive = $archiveProcessing->getIdArchive();
         }
         $this->isThereSomeVisits = $archiveProcessing->isThereSomeVisits;
         $this->idArchive = $idArchive;
         $this->archiveProcessing = $archiveProcessing;
     }
     return $archiveJustProcessed;
 }
Esempio n. 2
0
 /**
  * Prepares the archive. Gets the idarchive from the ArchiveProcessing.
  * 
  * This will possibly launch the archiving process if the archive was not available.
  */
 public function prepareArchive()
 {
     $archiveJustProcessed = false;
     $periodString = $this->period->getLabel();
     $plugin = Piwik_ArchiveProcessing::getPluginBeingProcessed($this->getRequestedReport());
     $cacheKey = 'all';
     if ($periodString == 'range') {
         $cacheKey = $plugin;
     }
     if (!isset($this->alreadyChecked[$cacheKey])) {
         $this->isThereSomeVisits = false;
         $this->alreadyChecked[$cacheKey] = true;
         $dayString = $this->period->getPrettyString();
         $logMessage = "Preparing archive: " . $periodString . "(" . $dayString . "), plugin {$plugin} ";
         // if the END of the period is BEFORE the website creation date
         // we already know there are no stats for this period
         // we add one day to make sure we don't miss the day of the website creation
         if ($this->period->getDateEnd()->addDay(2)->isEarlier($this->site->getCreationDate())) {
             Piwik::log("{$logMessage} skipped, archive is before the website was created.");
             return;
         }
         // if the starting date is in the future we know there is no visit
         if ($this->period->getDateStart()->subDay(2)->isLater(Piwik_Date::today())) {
             Piwik::log("{$logMessage} skipped, archive is after today.");
             return;
         }
         // we make sure the archive is available for the given date
         $periodLabel = $this->period->getLabel();
         $this->archiveProcessing = Piwik_ArchiveProcessing::factory($periodLabel);
         $this->archiveProcessing->setSite($this->site);
         $this->archiveProcessing->setPeriod($this->period);
         $this->archiveProcessing->setSegment($this->segment);
         $this->archiveProcessing->init();
         $this->archiveProcessing->setRequestedReport($this->getRequestedReport());
         $archivingDisabledArchiveNotProcessed = false;
         $idArchive = $this->archiveProcessing->loadArchive();
         if (empty($idArchive)) {
             if ($this->archiveProcessing->isArchivingDisabled()) {
                 $archivingDisabledArchiveNotProcessed = true;
                 $logMessage = "* ARCHIVING DISABLED, for {$logMessage}";
             } else {
                 Piwik::log("* PROCESSING {$logMessage}, not archived yet...");
                 $archiveJustProcessed = true;
                 // Process the reports
                 $this->archiveProcessing->launchArchiving();
                 $idArchive = $this->archiveProcessing->getIdArchive();
                 $logMessage = "PROCESSED: idArchive = " . $idArchive . ", for {$logMessage}";
             }
         } else {
             $logMessage = "* ALREADY PROCESSED, Fetching idArchive = {$idArchive} (idSite=" . $this->site->getId() . "), for {$logMessage}";
         }
         Piwik::log("{$logMessage}, Visits = " . $this->archiveProcessing->getNumberOfVisits());
         $this->isThereSomeVisits = !$archivingDisabledArchiveNotProcessed && $this->archiveProcessing->isThereSomeVisits();
         $this->idArchive = $idArchive;
     }
     return $archiveJustProcessed;
 }
Esempio n. 3
0
 /**
  * Prepares the archive. Gets the idarchive from the ArchiveProcessing.
  *
  * This will possibly launch the archiving process if the archive was not available.
  * @return bool
  */
 public function prepareArchive()
 {
     $archiveJustProcessed = false;
     $periodString = $this->period->getLabel();
     $plugin = Piwik_ArchiveProcessing::getPluginBeingProcessed($this->getRequestedReport());
     $cacheKey = 'all';
     if ($periodString == 'range') {
         $cacheKey = $plugin;
     }
     if (!isset($this->alreadyChecked[$cacheKey])) {
         $this->isThereSomeVisits = false;
         $this->alreadyChecked[$cacheKey] = true;
         $dayString = $this->period->getPrettyString();
         $logMessage = sprintf("%s (%s), plugin %s", $periodString, $dayString, $plugin);
         // if the END of the period is BEFORE the website creation date
         // we already know there are no stats for this period
         // we add one day to make sure we don't miss the day of the website creation
         if ($this->period->getDateEnd()->addDay(2)->isEarlier($this->site->getCreationDate())) {
             Piwik::log(sprintf("Archive %s skipped, archive is before the website was created.", $logMessage));
             return;
         }
         // if the starting date is in the future we know there is no visit
         if ($this->period->getDateStart()->subDay(2)->isLater(Piwik_Date::today())) {
             Piwik::log(sprintf("Archive %s skipped, archive is after today.", $logMessage));
             return;
         }
         // we make sure the archive is available for the given date
         $periodLabel = $this->period->getLabel();
         $this->archiveProcessing = Piwik_ArchiveProcessing::factory($periodLabel);
         $this->archiveProcessing->setSite($this->site);
         $this->archiveProcessing->setPeriod($this->period);
         $this->archiveProcessing->setSegment($this->segment);
         $this->archiveProcessing->init();
         $this->archiveProcessing->setRequestedReport($this->getRequestedReport());
         $archivingDisabledArchiveNotProcessed = false;
         $idArchive = $this->archiveProcessing->loadArchive();
         if (empty($idArchive)) {
             if ($this->archiveProcessing->isArchivingDisabled()) {
                 $archivingDisabledArchiveNotProcessed = true;
                 $logMessage = sprintf("Archiving disabled, for %s", $logMessage);
             } else {
                 Piwik::log(sprintf("Processing %s, not archived yet...", $logMessage));
                 $archiveJustProcessed = true;
                 // Process the reports
                 $this->archiveProcessing->launchArchiving();
                 $idArchive = $this->archiveProcessing->getIdArchive();
                 $logMessage = sprintf("Processed %d, for %s", $idArchive, $logMessage);
             }
         } else {
             $logMessage = sprintf("Already processed, fetching idArchive = %d (idSite=%d), for %s", $idArchive, $this->site->getId(), $logMessage);
         }
         Piwik::log(sprintf("%s, Visits = %d", $logMessage, $this->archiveProcessing->getNumberOfVisits()));
         $this->isThereSomeVisits = !$archivingDisabledArchiveNotProcessed && $this->archiveProcessing->isThereSomeVisits();
         $this->idArchive = $idArchive;
     }
     return $archiveJustProcessed;
 }
Esempio n. 4
0
 protected function generate()
 {
     if ($this->subperiodsProcessed) {
         return;
     }
     parent::generate();
     $year = $this->date->get("Y");
     for ($i = 1; $i <= 12; $i++) {
         $this->addSubperiod(new Piwik_Period_Month(Piwik_Date::factory("{$year}-{$i}-01")));
     }
 }
 /**
  * Creates a new ArchiveProcessing object
  * 
  * @param string $periodLabel
  * @param string $dateLabel
  * @param string $siteTimezone
  * @return Piwik_ArchiveProcessing
  */
 private function _createArchiveProcessing($periodLabel, $dateLabel, $siteTimezone)
 {
     $site = $this->_createWebsite($siteTimezone);
     $date = Piwik_Date::factory($dateLabel);
     $period = Piwik_Period::factory($periodLabel, $date);
     $archiveProcessing = Piwik_ArchiveProcessing::factory($periodLabel);
     $archiveProcessing->setSite($site);
     $archiveProcessing->setPeriod($period);
     $archiveProcessing->setSegment(new Piwik_Segment('', $site->getId()));
     $archiveProcessing->init();
     return $archiveProcessing;
 }
Esempio n. 6
0
 protected function generate()
 {
     if ($this->subperiodsProcessed) {
         return;
     }
     parent::generate();
     $date = $this->date;
     $startMonth = $date->setDay(1);
     $currentDay = clone $startMonth;
     while ($currentDay->compareMonth($startMonth) == 0) {
         $this->addSubperiod(new Piwik_Period_Day($currentDay));
         $currentDay = $currentDay->addDay(1);
     }
 }
Esempio n. 7
0
 /**
  * General method to get transitions for an action
  * 
  * @param $actionName
  * @param $actionType "url"|"title"
  * @param $idSite
  * @param $period
  * @param $date
  * @param bool $segment
  * @param bool $limitBeforeGrouping
  * @param string $parts
  * @param bool $returnNormalizedUrls
  * @return array
  * @throws Exception
  */
 public function getTransitionsForAction($actionName, $actionType, $idSite, $period, $date, $segment = false, $limitBeforeGrouping = false, $parts = 'all', $returnNormalizedUrls = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // get idaction of the requested action
     $idaction = $this->deriveIdAction($actionName, $actionType);
     if ($idaction < 0) {
         throw new Exception('NoDataForAction');
     }
     // prepare archive processing that can be used by the archiving code
     $archiveProcessing = new Piwik_ArchiveProcessing_Day();
     $archiveProcessing->setSite(new Piwik_Site($idSite));
     $archiveProcessing->setPeriod(Piwik_Period::advancedFactory($period, $date));
     $archiveProcessing->setSegment(new Piwik_Segment($segment, $idSite));
     $archiveProcessing->initForLiveUsage();
     // prepare the report
     $report = array('date' => Piwik_Period_Day::advancedFactory($period, $date)->getLocalizedShortString());
     // add data to the report
     $transitionsArchiving = new Piwik_Transitions();
     if ($returnNormalizedUrls) {
         $transitionsArchiving->returnNormalizedUrls();
     }
     $partsArray = explode(',', $parts);
     if ($parts == 'all' || in_array('internalReferrers', $partsArray)) {
         $this->addInternalReferrers($transitionsArchiving, $archiveProcessing, $report, $idaction, $actionType, $limitBeforeGrouping);
     }
     if ($parts == 'all' || in_array('followingActions', $partsArray)) {
         $includeLoops = $parts != 'all' && !in_array('internalReferrers', $partsArray);
         $this->addFollowingActions($transitionsArchiving, $archiveProcessing, $report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops);
     }
     if ($parts == 'all' || in_array('externalReferrers', $partsArray)) {
         $this->addExternalReferrers($transitionsArchiving, $archiveProcessing, $report, $idaction, $actionType, $limitBeforeGrouping);
     }
     // derive the number of exits from the other metrics
     if ($parts == 'all') {
         $report['pageMetrics']['exits'] = $report['pageMetrics']['pageviews'] - $transitionsArchiving->getTotalTransitionsToFollowingActions() - $report['pageMetrics']['loops'];
     }
     // replace column names in the data tables
     $reportNames = array('previousPages' => true, 'previousSiteSearches' => false, 'followingPages' => true, 'followingSiteSearches' => false, 'outlinks' => true, 'downloads' => true);
     foreach ($reportNames as $reportName => $replaceLabel) {
         if (isset($report[$reportName])) {
             $columnNames = array(Piwik_Archive::INDEX_NB_ACTIONS => 'referrals');
             if ($replaceLabel) {
                 $columnNames[Piwik_Archive::INDEX_NB_ACTIONS] = 'referrals';
             }
             $report[$reportName]->filter('ReplaceColumnNames', array($columnNames));
         }
     }
     return $report;
 }
Esempio n. 8
0
 protected function generate()
 {
     if ($this->subperiodsProcessed) {
         return;
     }
     parent::generate();
     $date = $this->date;
     if ($date->toString('N') > 1) {
         $date = $date->subDay($date->toString('N') - 1);
     }
     $startWeek = $date;
     $currentDay = clone $startWeek;
     while ($currentDay->compareWeek($startWeek) == 0) {
         $this->addSubperiod(new Piwik_Period_Day($currentDay));
         $currentDay = $currentDay->addDay(1);
     }
 }
 /**
  * Inits the object
  * 
  * @return void
  */
 protected function loadArchiveProperties()
 {
     $this->idsite = $this->site->getId();
     $this->periodId = $this->period->getId();
     $this->dateStart = $this->period->getDateStart();
     $this->dateEnd = $this->period->getDateEnd();
     $this->tableArchiveNumeric = new Piwik_TablePartitioning_Monthly('archive_numeric');
     $this->tableArchiveNumeric->setIdSite($this->idsite);
     $this->tableArchiveNumeric->setTimestamp($this->dateStart->get());
     $this->tableArchiveBlob = new Piwik_TablePartitioning_Monthly('archive_blob');
     $this->tableArchiveBlob->setIdSite($this->idsite);
     $this->tableArchiveBlob->setTimestamp($this->dateStart->get());
     $this->strDateStart = $this->dateStart->toString();
     $this->strDateEnd = $this->dateEnd->toString();
     // if the current archive is a DAY and if it's today,
     // we set this maxTimestampArchive that defines the lifetime value of today's archive
     $this->maxTimestampArchive = 0;
     if ($this->period->getNumberOfSubperiods() == 0 && $this->period->toString() == date("Y-m-d")) {
         $this->maxTimestampArchive = time() - Zend_Registry::get('config')->General->time_before_today_archive_considered_outdated;
     } else {
         if ($this->period->isFinished()) {
             $this->maxTimestampArchive = $this->period->getDateEnd()->setTime('00:00:00')->addDay(1)->getTimestamp();
         } else {
             $this->maxTimestampArchive = Piwik_Date::today()->getTimestamp();
         }
     }
 }
Esempio n. 10
0
 protected function generate()
 {
     if ($this->subperiodsProcessed) {
         return;
     }
     parent::generate();
     if (preg_match('/(last|previous)([0-9]*)/', $this->strDate, $regs)) {
         $lastN = $regs[2];
         $lastOrPrevious = $regs[1];
         if (!is_null($this->defaultEndDate)) {
             $defaultEndDate = $this->defaultEndDate;
         } else {
             $defaultEndDate = Piwik_Date::today();
         }
         if ($lastOrPrevious == 'last') {
             $endDate = $defaultEndDate;
         } elseif ($lastOrPrevious == 'previous') {
             $endDate = $this->removePeriod($defaultEndDate, 1);
         }
         // last1 means only one result ; last2 means 2 results so we remove only 1 to the days/weeks/etc
         $lastN--;
         $lastN = abs($lastN);
         $lastN = $this->getMaxN($lastN);
         $startDate = $this->removePeriod($endDate, $lastN);
     } elseif (preg_match('/([0-9]{4}-[0-9]{1,2}-[0-9]{1,2}),([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})/', $this->strDate, $regs)) {
         $strDateStart = $regs[1];
         $strDateEnd = $regs[2];
         $startDate = Piwik_Date::factory($strDateStart);
         $endDate = Piwik_Date::factory($strDateEnd);
     } else {
         throw new Exception("The date '{$this->strDate}' is not a date range. Should have the following format: 'lastN' or 'previousN' or 'YYYY-MM-DD,YYYY-MM-DD'.");
     }
     $endSubperiod = Piwik_Period::factory($this->strPeriod, $endDate);
     $arrayPeriods = array();
     $arrayPeriods[] = $endSubperiod;
     while ($endDate->isLater($startDate)) {
         $endDate = $this->removePeriod($endDate, 1);
         $subPeriod = Piwik_Period::factory($this->strPeriod, $endDate);
         $arrayPeriods[] = $subPeriod;
     }
     $arrayPeriods = array_reverse($arrayPeriods);
     foreach ($arrayPeriods as $period) {
         $this->addSubperiod($period);
     }
 }
Esempio n. 11
0
 /**
  * Generate advisory lock name
  *
  * @param int $idsite
  * @param Piwik_Period $period
  * @return string
  */
 public static function getArchiveProcessingLockName($idsite, $period, Piwik_Segment $segment)
 {
     $config = Zend_Registry::get('config');
     $lockName = 'piwik.' . $config->database->dbname . '.' . $config->database->tables_prefix . '/' . $idsite . '/' . (!$segment->isEmpty() ? $segment->getHash() . '/' : '') . $period->getId() . '/' . $period->getDateStart()->toString('Y-m-d') . ',' . $period->getDateEnd()->toString('Y-m-d');
     return $lockName . '/' . md5($lockName . $config->superuser->salt);
 }
Esempio n. 12
0
 /**
  * @param Piwik_Segment $segment
  * @param Piwik_Period $period
  * @return bool
  */
 protected static function shouldProcessReportsAllPluginsFor($segment, $period)
 {
     if ($segment->isEmpty() && $period->getLabel() != 'range') {
         return true;
     }
     $segmentsToProcess = Piwik::getKnownSegmentsToArchive();
     if (!empty($segmentsToProcess)) {
         // If the requested segment is one of the segments to pre-process
         // we ensure that any call to the API will trigger archiving of all reports for this segment
         $segment = $segment->getString();
         if (in_array($segment, $segmentsToProcess)) {
             return true;
         }
     }
     return false;
 }
Esempio n. 13
0
	/**
	 * Sets general variables to the view that are used by various templates and Javascript.
	 * If any error happens, displays the login screen
	 * @param Piwik_View $view
	 * @return void
	 */
	protected function setGeneralVariablesView($view)
	{
		$view->date = $this->strDate;
		
		try {
			$view->idSite = $this->idSite;
			if(empty($this->site) || empty($this->idSite))
			{
				throw new Exception("The requested website idSite is not found in the request, or is invalid.
				Please check that you are logged in Piwik and have permission to access the specified website.");
			}
			$this->setPeriodVariablesView($view);
			
			$rawDate = Piwik_Common::getRequestVar('date');
			$periodStr = Piwik_Common::getRequestVar('period');
			if($periodStr != 'range')
			{
				$date = Piwik_Date::factory($this->strDate);
				$period = Piwik_Period::factory($periodStr, $date);
			}
			else
			{
				$period = new Piwik_Period_Range($periodStr, $rawDate, $this->site->getTimezone());
			}
			$view->rawDate = $rawDate;
			$view->prettyDate = $period->getPrettyString();
			$view->siteName = $this->site->getName();
			$view->siteMainUrl = $this->site->getMainUrl();
			
			$datetimeMinDate = $this->site->getCreationDate()->getDatetime();
			$minDate = Piwik_Date::factory($datetimeMinDate, $this->site->getTimezone());
			$this->setMinDateView($minDate, $view);

			$maxDate = Piwik_Date::factory('now', $this->site->getTimezone());
			$this->setMaxDateView($maxDate, $view);
			
			// Setting current period start & end dates, for pre-setting the calendar when "Date Range" is selected 
			$dateStart = $period->getDateStart();
			if($dateStart->isEarlier($minDate)) { $dateStart = $minDate; } 
			$dateEnd = $period->getDateEnd();
			if($dateEnd->isLater($maxDate)) { $dateEnd = $maxDate; }
			
			$view->startDate = $dateStart;
			$view->endDate = $dateEnd;
			
			$this->setBasicVariablesView($view);
		} catch(Exception $e) {
			Piwik_ExitWithMessage($e->getMessage());
		}
	}
 /**
  * Returns the idArchive if the archive is available in the database.
  * Returns false if the archive needs to be computed.
  * 
  * An archive is available if
  * - for today, the archive was computed less than minDatetimeArchiveProcessedUTC seconds ago
  * - for any other day, if the archive was computed once this day was finished
  * - for other periods, if the archive was computed once the period was finished
  *
  * @return int|false
  */
 protected function isArchived()
 {
     $bindSQL = array($this->idsite, $this->period->getDateStart()->toString('Y-m-d'), $this->period->getDateEnd()->toString('Y-m-d'), $this->periodId);
     $timeStampWhere = '';
     if ($this->minDatetimeArchiveProcessedUTC) {
         $timeStampWhere = " AND ts_archived >= ? ";
         $bindSQL[] = Piwik_Date::factory($this->minDatetimeArchiveProcessedUTC)->getDatetime();
     }
     // When a Segment is specified, we try and only process the requested report in the archive
     // As a limitation, we don't know all the time which plugin should process which report
     // There is a catch all flag 'all' appended to archives containing all reports already
     // We look for this 'done.ABCDEFG.all', or for an archive that contains only our plugin data 'done.ABDCDEFG.Referers'
     $done = $this->getDoneStringFlag();
     $doneAllPluginsProcessed = $this->getDoneStringFlag($flagArchiveAsAllPlugins = true);
     $sqlSegmentsFindArchiveAllPlugins = '';
     if ($done != $doneAllPluginsProcessed) {
         $sqlSegmentsFindArchiveAllPlugins = "OR (name = '" . $doneAllPluginsProcessed . "' AND value = " . Piwik_ArchiveProcessing::DONE_OK . ")\n\t\t\t\t\tOR (name = '" . $doneAllPluginsProcessed . "' AND value = " . Piwik_ArchiveProcessing::DONE_OK_TEMPORARY . ")";
     }
     $sqlQuery = "\tSELECT idarchive, value, name, date1 as startDate\n\t\t\t\t\t\tFROM " . $this->tableArchiveNumeric->getTableName() . "\n\t\t\t\t\t\tWHERE idsite = ?\n\t\t\t\t\t\t\tAND date1 = ?\n\t\t\t\t\t\t\tAND date2 = ?\n\t\t\t\t\t\t\tAND period = ?\n\t\t\t\t\t\t\tAND ( (name = '" . $done . "' AND value = " . Piwik_ArchiveProcessing::DONE_OK . ")\n\t\t\t\t\t\t\t\t\tOR (name = '" . $done . "' AND value = " . Piwik_ArchiveProcessing::DONE_OK_TEMPORARY . ")\n\t\t\t\t\t\t\t\t\t{$sqlSegmentsFindArchiveAllPlugins}\n\t\t\t\t\t\t\t\t\tOR name = 'nb_visits')\n\t\t\t\t\t\t\t{$timeStampWhere}\n\t\t\t\t\t\tORDER BY ts_archived DESC";
     $results = Piwik_FetchAll($sqlQuery, $bindSQL);
     if (empty($results)) {
         return false;
     }
     $idarchive = false;
     // we look for the more recent idarchive
     foreach ($results as $result) {
         if ($result['name'] == $done || $result['name'] == $doneAllPluginsProcessed) {
             $idarchive = $result['idarchive'];
             $this->timestampDateStart = Piwik_Date::factory($result['startDate'])->getTimestamp();
             break;
         }
     }
     // case when we have a nb_visits entry in the archive, but the process is not finished yet or failed to finish
     // therefore we don't have the done=OK
     if ($idarchive === false) {
         return false;
     }
     if ($this->getPluginBeingProcessed($this->getRequestedReport()) == 'VisitsSummary') {
         $this->isThereSomeVisits = false;
     }
     // we look for the nb_visits result for this most recent archive
     foreach ($results as $result) {
         if ($result['name'] == 'nb_visits' && $result['idarchive'] == $idarchive) {
             $this->isThereSomeVisits = $result['value'] > 0;
             $this->setNumberOfVisits($result['value']);
             break;
         }
     }
     return $idarchive;
 }
Esempio n. 15
0
 public function getSitesInfo($isWidgetized)
 {
     Piwik::checkUserHasSomeViewAccess();
     $displayRevenueColumn = Piwik_Common::isGoalPluginEnabled();
     $date = Piwik_Common::getRequestVar('date', 'today');
     $period = Piwik_Common::getRequestVar('period', 'day');
     $siteIds = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess();
     list($minDate, $maxDate) = $this->getMinMaxDateAcrossWebsites($siteIds);
     // overwrites the default Date set in the parent controller
     // Instead of the default current website's local date,
     // we set "today" or "yesterday" based on the default Piwik timezone
     $piwikDefaultTimezone = Piwik_SitesManager_API::getInstance()->getDefaultTimezone();
     if ($period != 'range') {
         $date = $this->getDateParameterInTimezone($date, $piwikDefaultTimezone);
         $this->setDate($date);
         $date = $date->toString();
     }
     $dataTable = Piwik_MultiSites_API::getInstance()->getAll($period, $date, $segment = false);
     // put data into a form the template will understand better
     $digestableData = array();
     foreach ($siteIds as $idSite) {
         $isEcommerceEnabled = Piwik_Site::isEcommerceEnabledFor($idSite);
         $digestableData[$idSite] = array('idsite' => $idSite, 'main_url' => Piwik_Site::getMainUrlFor($idSite), 'name' => Piwik_Site::getNameFor($idSite), 'visits' => 0, 'pageviews' => 0);
         if ($period != 'range') {
             $digestableData[$idSite]['visits_evolution'] = 0;
             $digestableData[$idSite]['pageviews_evolution'] = 0;
         }
         if ($displayRevenueColumn) {
             $revenueDefault = $isEcommerceEnabled ? 0 : "'-'";
             if ($period != 'range') {
                 $digestableData[$idSite]['revenue_evolution'] = $revenueDefault;
             }
         }
     }
     foreach ($dataTable->getRows() as $row) {
         $idsite = (int) $row->getMetadata('idsite');
         $site =& $digestableData[$idsite];
         $site['visits'] = (int) $row->getColumn('nb_visits');
         $site['pageviews'] = (int) $row->getColumn('nb_pageviews');
         if ($displayRevenueColumn) {
             if ($row->getColumn('revenue') !== false) {
                 $site['revenue'] = $row->getColumn('revenue');
             }
         }
         if ($period != 'range') {
             $site['visits_evolution'] = $row->getColumn('visits_evolution');
             $site['pageviews_evolution'] = $row->getColumn('pageviews_evolution');
             if ($displayRevenueColumn) {
                 $site['revenue_evolution'] = $row->getColumn('revenue_evolution');
             }
         }
     }
     $this->applyPrettyMoney($digestableData);
     $view = new Piwik_View("MultiSites/templates/index.tpl");
     $view->isWidgetized = $isWidgetized;
     $view->sitesData = array_values($digestableData);
     $view->evolutionBy = $this->evolutionBy;
     $view->period = $period;
     $view->page = $this->page;
     $view->limit = $this->limit;
     $view->orderBy = $this->orderBy;
     $view->order = $this->order;
     $view->totalVisits = $dataTable->getMetadata('total_nb_visits');
     $view->totalRevenue = $dataTable->getMetadata('total_revenue');
     $view->displayRevenueColumn = $displayRevenueColumn;
     $view->totalPageviews = $dataTable->getMetadata('total_nb_pageviews');
     $view->pastTotalVisits = $dataTable->getMetadata('last_period_total_nb_visits');
     $view->totalVisitsEvolution = $dataTable->getMetadata('total_visits_evolution');
     if ($view->totalVisitsEvolution > 0) {
         $view->totalVisitsEvolution = '+' . $view->totalVisitsEvolution;
     }
     if ($period != 'range') {
         $lastPeriod = Piwik_Period::factory($period, $dataTable->getMetadata('last_period_date'));
         $view->pastPeriodPretty = self::getCalendarPrettyDate($lastPeriod);
     }
     $params = $this->getGraphParamsModified();
     $view->dateSparkline = $period == 'range' ? $date : $params['date'];
     $view->autoRefreshTodayReport = false;
     // if the current date is today, or yesterday,
     // in case the website is set to UTC-12), or today in UTC+14, we refresh the page every 5min
     if (in_array($date, array('today', date('Y-m-d'), 'yesterday', Piwik_Date::factory('yesterday')->toString('Y-m-d'), Piwik_Date::factory('now', 'UTC+14')->toString('Y-m-d')))) {
         $view->autoRefreshTodayReport = Piwik_Config::getInstance()->General['multisites_refresh_after_seconds'];
     }
     $this->setGeneralVariablesView($view);
     $this->setMinDateView($minDate, $view);
     $this->setMaxDateView($maxDate, $view);
     $view->show_sparklines = Piwik_Config::getInstance()->General['show_multisites_sparklines'];
     echo $view->render();
 }
Esempio n. 16
0
 /**
  * Builds an Archive object or returns the same archive if previously built.
  *
  * @param string|int idSite integer, or comma separated list of integer
  * @param string|Piwik_Date $date 'YYYY-MM-DD' or magic keywords 'today' @see Piwik_Date::factory()
  * @param string $period 'week' 'day' etc.
  * 
  * @return Piwik_Archive
  */
 public static function build($idSite, $period, $strDate)
 {
     if ($idSite === 'all') {
         $sites = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess();
     } else {
         $sites = Piwik_Site::getIdSitesFromIdSitesString($idSite);
     }
     // idSite=1,3 or idSite=all
     if (count($sites) > 1 || $idSite === 'all') {
         require_once 'Archive/Array/IndexedBySite.php';
         $archive = new Piwik_Archive_Array_IndexedBySite($sites, $period, $strDate);
     } elseif (is_string($strDate) && (ereg('^(last|previous){1}([0-9]*)$', $strDate, $regs) || ereg('^([0-9]{4}-[0-9]{1,2}-[0-9]{1,2}),([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})$', $strDate, $regs))) {
         $oSite = new Piwik_Site($idSite);
         require_once 'Archive/Array/IndexedByDate.php';
         $archive = new Piwik_Archive_Array_IndexedByDate($oSite, $period, $strDate);
     } else {
         if (is_string($strDate)) {
             $oDate = Piwik_Date::factory($strDate);
         } else {
             $oDate = $strDate;
         }
         $date = $oDate->toString();
         if (isset(self::$alreadyBuilt[$idSite][$date][$period])) {
             return self::$alreadyBuilt[$idSite][$date][$period];
         }
         $oPeriod = Piwik_Period::factory($period, $oDate);
         $archive = new Piwik_Archive_Single();
         $archive->setPeriod($oPeriod);
         $archive->setSite(new Piwik_Site($idSite));
         $archiveJustProcessed = $archive->prepareArchive();
         //we don't cache the archives just processed, the datatable were freed from memory
         if (!$archiveJustProcessed) {
             self::$alreadyBuilt[$idSite][$date][$period] = $archive;
         }
     }
     return $archive;
 }
Esempio n. 17
0
 function fillArraySubPeriods($startDate, $endDate, $period)
 {
     $arrayPeriods = array();
     $endSubperiod = Piwik_Period::factory($period, $endDate);
     $arrayPeriods[] = $endSubperiod;
     while ($endDate->isLater($startDate)) {
         $endDate = self::removePeriod($period, $endDate, 1);
         $subPeriod = Piwik_Period::factory($period, $endDate);
         $arrayPeriods[] = $subPeriod;
     }
     $arrayPeriods = array_reverse($arrayPeriods);
     foreach ($arrayPeriods as $period) {
         $this->addSubperiod($period);
     }
 }
	/**
	 * Inits the object
	 */
	protected function loadArchiveProperties()
	{		
		$this->idsite = $this->site->getId();
		
		$this->periodId = $this->period->getId();
		
		$this->dateStart = $this->period->getDateStart();
		$this->dateEnd = $this->period->getDateEnd();
		
		$this->tableArchiveNumeric = new Piwik_TablePartitioning_Monthly('archive_numeric');
		$this->tableArchiveNumeric->setIdSite($this->idsite);
		$this->tableArchiveNumeric->setTimestamp($this->dateStart->get());
		$this->tableArchiveBlob = new Piwik_TablePartitioning_Monthly('archive_blob');
		$this->tableArchiveBlob->setIdSite($this->idsite);	
		$this->tableArchiveBlob->setTimestamp($this->dateStart->get());

		$this->strDateStart = $this->dateStart->toString();
		$this->strDateEnd = $this->dateEnd->toString();
		
		// if the current archive is a DAY and if it's today,
		// we set this maxTimestampArchive that defines the lifetime value of today's archive
		$this->maxTimestampArchive = 0;
		if( $this->period->getNumberOfSubperiods() == 0
			&& $this->period->toString() == date("Y-m-d")
			)
		{
			$this->maxTimestampArchive = time() - Zend_Registry::get('config')->General->time_before_today_archive_considered_outdated;
		}
		// either
		// - if the period we're looking for is finished, we look for a ts_archived that 
		//   is greater than the last day of the archive 
		// - if the period we're looking for is not finished, we look for a recent enough archive
		//   recent enough means maxTimestampArchive = 00:00:01 this morning
		else
		{
			if($this->period->isFinished())
			{
				$this->maxTimestampArchive = $this->period->getDateEnd()->setTime('00:00:00')->addDay(1)->getTimestamp();
			}
			else
			{
				$this->maxTimestampArchive = Piwik_Date::today()->getTimestamp();
			}
		}

		$db = Zend_Registry::get('db');
		$this->compressBlob = $db->hasBlobDataType();
	}
Esempio n. 19
0
 /**
  * Add transitions data to the report.
  * Fake ArchiveProcessing to do the queries live.
  */
 private function addLiveTransitionsDataToReport(&$report, $pageUrl, $idSite, $period, $date, $segment, $limitBeforeGrouping)
 {
     // get idaction of page url
     $actionsPlugin = new Piwik_Actions();
     $idaction = $actionsPlugin->getIdActionFromSegment($pageUrl, 'idaction');
     // prepare archive processing that can be reused by the archiving code
     $archiveProcessing = new Piwik_ArchiveProcessing_Day();
     $archiveProcessing->setSite(new Piwik_Site($idSite));
     $archiveProcessing->setPeriod(Piwik_Period::advancedFactory($period, $date));
     $archiveProcessing->setSegment(new Piwik_Segment($segment, $idSite));
     $archiveProcessing->initForLiveUsage();
     // launch the archiving code - but live
     $transitionsArchiving = new Piwik_Transitions();
     $data = $transitionsArchiving->queryInternalReferrers($idaction, $archiveProcessing, $limitBeforeGrouping);
     $report['previousPages'] =& $data['previousPages'];
     $report['pageMetrics']['loops'] = intval($data['loops']);
     $data = $transitionsArchiving->queryFollowingActions($idaction, $archiveProcessing, $limitBeforeGrouping);
     foreach ($data as $tableName => $table) {
         $report[$tableName] = $table;
     }
     $data = $transitionsArchiving->queryExternalReferrers($idaction, $archiveProcessing, $limitBeforeGrouping);
     $report['pageMetrics']['entries'] = 0;
     $report['referrers'] = array();
     foreach ($data->getRows() as $row) {
         $referrerId = $row->getColumn('label');
         $visits = $row->getColumn(Piwik_Archive::INDEX_NB_VISITS);
         if ($visits) {
             // load details (i.e. subtables)
             $details = array();
             if ($idSubTable = $row->getIdSubDataTable()) {
                 $subTable = Piwik_DataTable_Manager::getInstance()->getTable($idSubTable);
                 foreach ($subTable->getRows() as $subRow) {
                     $details[] = array('label' => $subRow->getColumn('label'), 'referrals' => $subRow->getColumn(Piwik_Archive::INDEX_NB_VISITS));
                 }
             }
             $report['referrers'][] = array('label' => $this->getReferrerLabel($referrerId), 'shortName' => Piwik_getRefererTypeFromShortName($referrerId), 'visits' => $visits, 'details' => $details);
             $report['pageMetrics']['entries'] += $visits;
         }
     }
     // if there's no data for referrers, Piwik_API_ResponseBuilder::handleMultiDimensionalArray
     // does not detect the multi dimensional array and the data is rendered differently, which
     // causes an exception.
     if (count($report['referrers']) == 0) {
         $report['referrers'][] = array('label' => $this->getReferrerLabel(Piwik_Common::REFERER_TYPE_DIRECT_ENTRY), 'shortName' => Piwik_getRefererTypeLabel(Piwik_Common::REFERER_TYPE_DIRECT_ENTRY), 'visits' => 0);
     }
 }
Esempio n. 20
0
 /**
  * Builds an Archive object or returns the same archive if previously built.
  *
  * @param string|int idSite integer, or comma separated list of integer
  * @param string|Piwik_Date $date 'YYYY-MM-DD' or magic keywords 'today' @see Piwik_Date::factory()
  * @param string $period 'week' 'day' etc.
  * @param string Segment definition - defaults to false for Backward Compatibility
  * 
  * @return Piwik_Archive
  */
 public static function build($idSite, $period, $strDate, $segment = false)
 {
     if ($idSite === 'all') {
         $sites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess();
     } else {
         $sites = Piwik_Site::getIdSitesFromIdSitesString($idSite);
     }
     if (!$segment instanceof Piwik_Segment) {
         $segment = new Piwik_Segment($segment, $idSite);
     }
     // idSite=1,3 or idSite=all
     if (count($sites) > 1 || $idSite === 'all') {
         $archive = new Piwik_Archive_Array_IndexedBySite($sites, $period, $strDate, $segment);
     } elseif (is_string($strDate) && self::isMultiplePeriod($strDate, $period)) {
         $oSite = new Piwik_Site($idSite);
         $archive = new Piwik_Archive_Array_IndexedByDate($oSite, $period, $strDate, $segment);
     } else {
         $oSite = new Piwik_Site($idSite);
         if ($period == 'range') {
             $oPeriod = new Piwik_Period_Range('range', $strDate, $oSite->getTimezone(), Piwik_Date::factory('today', $oSite->getTimezone()));
         } else {
             if (is_string($strDate)) {
                 if ($strDate == 'now' || $strDate == 'today') {
                     $strDate = date('Y-m-d', Piwik_Date::factory('now', $oSite->getTimezone())->getTimestamp());
                 } elseif ($strDate == 'yesterday' || $strDate == 'yesterdaySameTime') {
                     $strDate = date('Y-m-d', Piwik_Date::factory('now', $oSite->getTimezone())->subDay(1)->getTimestamp());
                 }
                 $oDate = Piwik_Date::factory($strDate);
             } else {
                 $oDate = $strDate;
             }
             $date = $oDate->toString();
             $oPeriod = Piwik_Period::factory($period, $oDate);
         }
         $archive = new Piwik_Archive_Single();
         $archive->setPeriod($oPeriod);
         $archive->setSite($oSite);
         $archive->setSegment($segment);
     }
     return $archive;
 }
Esempio n. 21
0
 protected function setGeneralVariablesView($view)
 {
     $view->date = $this->strDate;
     try {
         $this->setPeriodVariablesView($view);
         $period = Piwik_Period::factory(Piwik_Common::getRequestVar('period'), Piwik_Date::factory($this->strDate));
         $view->prettyDate = $period->getLocalizedLongString();
         $idSite = Piwik_Common::getRequestVar('idSite');
         $view->idSite = $idSite;
         $site = new Piwik_Site($idSite);
         $view->siteName = $site->getName();
         $view->siteMainUrl = $site->getMainUrl();
         $minDate = $site->getCreationDate();
         $view->minDateYear = $minDate->toString('Y');
         $view->minDateMonth = $minDate->toString('m');
         $view->minDateDay = $minDate->toString('d');
     } catch (Exception $e) {
         self::redirectToIndex(Piwik::getModule(), Piwik::getAction());
     }
 }
Esempio n. 22
0
 /**
  * Returns pretty date for use in period selector widget.
  * 
  * @param Piwik_Period $period
  * @return string
  */
 public static function getCalendarPrettyDate($period)
 {
     if ($period instanceof Piwik_Period_Month) {
         return $period->getLocalizedLongString();
     } else {
         return $period->getPrettyString();
     }
 }
Esempio n. 23
0
	public function getSitesInfo()
	{
		$view = new Piwik_View("MultiSites/templates/index.tpl");
		$mySites = Piwik_SitesManager_API::getSitesWithAtLeastViewAccess();


		$params = $this->getGraphParamsModified();
		$this->dateToStr = $params['date'];

		$ids = 'all';
		$this->period = PiwiK_Common::getRequestVar('period', 'day');		

		$this->date = PiwiK_Common::getRequestVar('date', 'today');
		$lastDate =  date('Y-m-d',strtotime("-1 ".$this->period, strtotime($this->date)));

		$visits = Piwik_VisitsSummary_API::getVisits($ids, $this->period, $this->date);
		$lastVisits = Piwik_VisitsSummary_API::getVisits($ids, $this->period, $lastDate);

		$actions = Piwik_VisitsSummary_API::getActions($ids, $this->period, $this->date);
		$lastActions = Piwik_VisitsSummary_API::getActions($ids, $this->period, $lastDate);

		$uniqueUsers = Piwik_VisitsSummary_API::getUniqueVisitors($ids, $this->period, $this->date);
		$lastUniqueUsers = Piwik_VisitsSummary_API::getUniqueVisitors($ids, $this->period, $lastDate);

		$visitsSummary = $this->getSummary($lastVisits, $visits, $mySites, "visits");
		$actionsSummary = $this->getSummary($lastActions, $actions, $mySites, "actions");
		$uniqueSummary = $this->getSummary($lastUniqueUsers, $uniqueUsers, $mySites, "unique");

		$visitsArray = $visits->getArray();
		$actionsArray = $actions->getArray();
		$uniqueUsersArray = $uniqueUsers->getArray();
		$lastVisitsArray = $lastVisits->getArray();
		$lastActionsArray = $lastActions->getArray();
		$lastUniqueUsersArray = $lastUniqueUsers->getArray();
		foreach($mySites as &$site)
		{
			$idSite = $site['idsite'];
			$site['visits'] = array_shift($visitsArray[$idSite]->getColumn(0));
			$site['actions'] = array_shift($actionsArray[$idSite]->getColumn(0));
			$site['unique'] = array_shift($uniqueUsersArray[$idSite]->getColumn(0));
			$site['lastVisits'] = array_shift($lastVisitsArray[$idSite]->getColumn(0));
			$site['lastActions'] = array_shift($lastActionsArray[$idSite]->getColumn(0));
			$site['lastUnique'] = array_shift($lastUniqueUsersArray[$idSite]->getColumn(0));
			$site['visitsSummaryValue'] = $visitsSummary[$idSite];
			$site['actionsSummaryValue'] = $actionsSummary[$idSite];
			$site['uniqueSummaryValue'] = $uniqueSummary[$idSite];
		}

		$view->mySites = $mySites;
		$view->arrowAsc = '<img src="plugins/MultiSites/images/arrow_asc.gif" width="16px" height="16px" />';
		$view->arrowDesc = '<img src="plugins/MultiSites/images/arrow_desc.gif" width="16px" height="16px" />';
		$view->evolutionBy = $this->evolutionBy;
		$view->period = $this->period;
		$view->date = $this->date;
		$view->page = $this->page;
		$view->limit = $this->limit;
		$view->orderBy = $this->orderBy;
		$view->order = $this->order;
		$view->dateToStr = $this->dateToStr;
		
		$this->setGeneralVariablesView($view);
		$period = Piwik_Period::factory(Piwik_Common::getRequestVar('period'), Piwik_Date::factory($this->strDate));
		$view->prettyDate = $period->getLocalizedLongString();
		
		echo $view->render();
	}
Esempio n. 24
0
 /**
  * Sends the http headers for csv file
  */
 protected function renderHeader()
 {
     $fileName = 'Piwik ' . Piwik_Translate('General_Export');
     $period = Piwik_Common::getRequestVar('period', false);
     $date = Piwik_Common::getRequestVar('date', false);
     if ($period || $date) {
         if ($period == 'range') {
             $period = new Piwik_Period_Range($period, $date);
         } else {
             if (strpos($date, ',') !== false) {
                 $period = new Piwik_Period_Range('range', $date);
             } else {
                 $period = Piwik_Period::factory($period, Piwik_Date::factory($date));
             }
         }
         $prettyDate = $period->getLocalizedLongString();
         $meta = $this->getApiMetaData();
         $fileName .= ' _ ' . $meta['name'] . ' _ ' . $prettyDate . '.csv';
     }
     // silent fail otherwise unit tests fail
     @header('Content-Type: application/vnd.ms-excel');
     @header('Content-Disposition: attachment; filename="' . $fileName . '"');
     Piwik::overrideCacheControlHeaders();
 }
Esempio n. 25
0
 public function getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal = false, $language = false, $showTimer = true)
 {
     $timer = new Piwik_Timer();
     if ($apiParameters === false) {
         $apiParameters = array();
     }
     if (!empty($idGoal) && empty($apiParameters['idGoal'])) {
         $apiParameters['idGoal'] = $idGoal;
     }
     // Is this report found in the Metadata available reports?
     $reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date);
     if (empty($reportMetadata)) {
         throw new Exception("Requested report {$apiModule}.{$apiAction} for Website id={$idSite} not found in the list of available reports. \n");
     }
     $reportMetadata = reset($reportMetadata);
     // Generate Api call URL passing custom parameters
     $parameters = array_merge($apiParameters, array('method' => $apiModule . '.' . $apiAction, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'format' => 'original', 'serialize' => '0', 'language' => $language));
     if (!empty($segment)) {
         $parameters['segment'] = $segment;
     }
     $url = Piwik_Url::getQueryStringFromParameters($parameters);
     $request = new Piwik_API_Request($url);
     try {
         /** @var Piwik_DataTable */
         $dataTable = $request->process();
     } catch (Exception $e) {
         throw new Exception("API returned an error: " . $e->getMessage() . "\n");
     }
     list($newReport, $columns, $rowsMetadata) = $this->handleTableReport($idSite, $dataTable, $reportMetadata, isset($reportMetadata['dimension']));
     foreach ($columns as $columnId => &$name) {
         $name = ucfirst($name);
     }
     $website = new Piwik_Site($idSite);
     //    	$segment = new Piwik_Segment($segment, $idSite);
     if (Piwik_Archive::isMultiplePeriod($date, $period)) {
         $period = new Piwik_Period_Range($period, $date);
     } else {
         if ($period == 'range') {
             $period = new Piwik_Period_Range($period, $date);
         } else {
             $period = Piwik_Period::factory($period, Piwik_Date::factory($date));
         }
     }
     $period = $period->getLocalizedLongString();
     $return = array('website' => $website->getName(), 'prettyDate' => $period, 'metadata' => $reportMetadata, 'columns' => $columns, 'reportData' => $newReport, 'reportMetadata' => $rowsMetadata);
     if ($showTimer) {
         $return['timerMillis'] = $timer->getTimeMs(0);
     }
     return $return;
 }
Esempio n. 26
0
	/**
	 * Builds an Archive object or returns the same archive if previously built.
	 *
	 * @param string|int idSite integer, or comma separated list of integer
	 * @param string|Piwik_Date $date 'YYYY-MM-DD' or magic keywords 'today' @see Piwik_Date::factory()
	 * @param string $period 'week' 'day' etc.
	 * 
	 * @return Piwik_Archive
	 */
	static public function build($idSite, $period, $strDate )
	{
		if($idSite === 'all')
		{
			$sites = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess();
		}
		else
		{
			$sites = Piwik_Site::getIdSitesFromIdSitesString($idSite);
		}
		
		// idSite=1,3 or idSite=all
		if( count($sites) > 1 
			|| $idSite === 'all' )
		{
			$archive = new Piwik_Archive_Array_IndexedBySite($sites, $period, $strDate);
		}
		// if a period date string is detected: either 'last30', 'previous10' or 'YYYY-MM-DD,YYYY-MM-DD'
		elseif(is_string($strDate) 
			&& (
				preg_match('/^(last|previous){1}([0-9]*)$/', $strDate, $regs)
				|| preg_match('/^([0-9]{4}-[0-9]{1,2}-[0-9]{1,2}),([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})$/', $strDate, $regs)
				)
			)
		{
			$oSite = new Piwik_Site($idSite);
			$archive = new Piwik_Archive_Array_IndexedByDate($oSite, $period, $strDate);
		}
		// case we request a single archive
		else
		{
			if(is_string($strDate))
			{
				$oDate = Piwik_Date::factory($strDate);
			}
			else
			{
				$oDate = $strDate;
			}
			$date = $oDate->toString();
			
			if(isset(self::$alreadyBuilt[$idSite][$date][$period]))
			{
				return self::$alreadyBuilt[$idSite][$date][$period];
			}
			
			$oPeriod = Piwik_Period::factory($period, $oDate);
			
			$archive = new Piwik_Archive_Single();
			$archive->setPeriod($oPeriod);
			$archive->setSite(new Piwik_Site($idSite));
			$archiveJustProcessed = $archive->prepareArchive();
			
			//we don't cache the archives just processed, the datatable were freed from memory 
			if(!$archiveJustProcessed)
			{
				self::$alreadyBuilt[$idSite][$date][$period] = $archive;
			}
		}
		
		return $archive;
	}
Esempio n. 27
0
 /**
  * Inits the object
  */
 protected function loadArchiveProperties()
 {
     $this->idsite = $this->site->getId();
     $this->periodId = $this->period->getId();
     $this->dateStart = $this->period->getDateStart();
     $this->dateEnd = $this->period->getDateEnd();
     $this->tableArchiveNumeric = new Piwik_TablePartitioning_Monthly('archive_numeric');
     $this->tableArchiveNumeric->setIdSite($this->idsite);
     $this->tableArchiveNumeric->setTimestamp($this->dateStart->get());
     $this->tableArchiveBlob = new Piwik_TablePartitioning_Monthly('archive_blob');
     $this->tableArchiveBlob->setIdSite($this->idsite);
     $this->tableArchiveBlob->setTimestamp($this->dateStart->get());
     $this->strDateStart = $this->dateStart->toString();
     $this->strDateEnd = $this->dateEnd->toString();
     // if the current archive is a DAY and if it's today,
     // we set this maxTimestampArchive that defines the lifetime value of today's archive
     $this->maxTimestampArchive = 0;
     if ($this->period->getNumberOfSubperiods() == 0 && $this->period->toString() == date("Y-m-d")) {
         $this->maxTimestampArchive = time() - Zend_Registry::get('config')->General->time_before_today_archive_considered_outdated;
         $browserArchivingEnabled = Zend_Registry::get('config')->General->enable_browser_archiving_triggering;
         // see #1150; if new archives are not triggered from the browser,
         // we still want to try and return the latest archive available for today (rather than return nothing)
         if (!$browserArchivingEnabled) {
             $this->maxTimestampArchive = 0;
         }
     } else {
         if ($this->period->isFinished()) {
             $this->maxTimestampArchive = $this->period->getDateEnd()->setTime('00:00:00')->addDay(1)->getTimestamp();
         } else {
             $this->maxTimestampArchive = Piwik_Date::today()->getTimestamp();
         }
     }
     $db = Zend_Registry::get('db');
     $this->compressBlob = $db->hasBlobDataType();
 }
Esempio n. 28
0
	private function loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment = false, $filter_limit = false, $maxIdVisit = false, $visitorId = false, $minTimestamp = false)
	{
//		var_dump($period); var_dump($date); var_dump($filter_limit); var_dump($maxIdVisit); var_dump($visitorId);
//var_dump($minTimestamp);
		if(empty($filter_limit))
		{
			$filter_limit = 100;
		}
		$where = $whereBind = array();
		$where[] = "log_visit.idsite = ? ";
		$whereBind[] = $idSite;
		$orderBy = "idsite, visit_last_action_time DESC";
		$orderByParent = "sub.visit_last_action_time DESC";
		if(!empty($visitorId))
		{
			$where[] = "log_visit.idvisitor = ? ";
			$whereBind[] = Piwik_Common::hex2bin($visitorId);
		}

		if(!empty($maxIdVisit))
		{
			$where[] = "log_visit.idvisit < ? ";
			$whereBind[] = $maxIdVisit;
			$orderBy = "idvisit DESC";
			$orderByParent = "sub.idvisit DESC";
		}
		
		if(!empty($minTimestamp))
		{
			$where[] = "log_visit.visit_last_action_time > ? ";
			$whereBind[] = date("Y-m-d H:i:s", $minTimestamp);
		}
		
		// If no other filter, only look at the last 24 hours of stats
		if(empty($visitorId)
			&& empty($maxIdVisit)
			&& empty($period) 
			&& empty($date))
		{
			$period = 'day';
			$date = 'yesterdaySameTime';
		}

		// SQL Filter with provided period
		if (!empty($period) && !empty($date))
		{
			$currentSite = new Piwik_Site($idSite);
			$currentTimezone = $currentSite->getTimezone();
		
			$dateString = $date;
			if($period == 'range') 
			{ 
				$processedPeriod = new Piwik_Period_Range('range', $date);
				if($parsedDate = Piwik_Period_Range::parseDateRange($date))
				{
					$dateString = $parsedDate[2];
				}
			}
			else
			{
				$processedDate = Piwik_Date::factory($date);
				if($date == 'today'
					|| $date == 'now'
					|| $processedDate->toString() == Piwik_Date::factory('now', $currentTimezone)->toString())
				{
					$processedDate = $processedDate->subDay(1);
				}
				$processedPeriod = Piwik_Period::factory($period, $processedDate); 
			}
			$dateStart = $processedPeriod->getDateStart()->setTimezone($currentTimezone);
			$where[] = "log_visit.visit_last_action_time >= ?";
			$whereBind[] = $dateStart->toString('Y-m-d H:i:s');
			
			if(!in_array($date, array('now', 'today', 'yesterdaySameTime'))
				&& strpos($date, 'last') === false
				&& strpos($date, 'previous') === false
				&& Piwik_Date::factory($dateString)->toString('Y-m-d') != Piwik_Date::factory('now', $currentTimezone)->toString())
			{
				$dateEnd = $processedPeriod->getDateEnd()->setTimezone($currentTimezone);
				$where[] = " log_visit.visit_last_action_time <= ?";
				$dateEndString = $dateEnd->addDay(1)->toString('Y-m-d H:i:s');
				$whereBind[] = $dateEndString;
			}
		}

		$sqlWhere = "";
		if(count($where) > 0)
		{
			$sqlWhere = "
			WHERE " . join(" 
				AND ", $where);
		}

		$segment = new Piwik_Segment($segment, $idSite);
		$segmentSql = $segment->getSql();
		$sqlSegment = $segmentSql['sql'];
		if(!empty($sqlSegment)) $sqlSegment = ' AND '.$sqlSegment;
		$whereBind = array_merge ( $whereBind, $segmentSql['bind'] );
		
		// Subquery to use the indexes for ORDER BY
		// Group by idvisit so that a visitor converting 2 goals only appears twice
		$sql = "
				SELECT sub.* 
				FROM ( 
					SELECT 	*
					FROM " . Piwik_Common::prefixTable('log_visit') . " AS log_visit
					$sqlWhere
					$sqlSegment
					ORDER BY $orderBy
					LIMIT ".(int)$filter_limit."
				) AS sub
				GROUP BY sub.idvisit
				ORDER BY $orderByParent
			"; 
		try {
			$data = Piwik_FetchAll($sql, $whereBind);
		} catch(Exception $e) {
			echo $e->getMessage();exit;
		}
		
//var_dump($whereBind);	echo($sql);
//var_dump($data);
		return $data;
	}
Esempio n. 29
0
 /**
  * Builds an Archive object or returns the same archive if previously built.
  *
  * @param int $idSite
  * @param string|Piwik_Date $date 'YYYY-MM-DD' or magic keywords 'today' @see Piwik_Date::factory()
  * @param string $period 'week' 'day' etc.
  * 
  * @return Piwik_Archive
  */
 public static function build($idSite, $period, $strDate)
 {
     $oSite = new Piwik_Site($idSite);
     // if a period date string is detected: either 'last30', 'previous10' or 'YYYY-MM-DD,YYYY-MM-DD'
     if (is_string($strDate) && (ereg('^(last|previous){1}([0-9]*)$', $strDate, $regs) || ereg('^([0-9]{4}-[0-9]{1,2}-[0-9]{1,2}),([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})$', $strDate, $regs))) {
         require_once 'Archive/Array.php';
         $archive = new Piwik_Archive_Array($oSite, $period, $strDate);
     } else {
         if (is_string($strDate)) {
             $oDate = Piwik_Date::factory($strDate);
         } else {
             $oDate = $strDate;
         }
         $date = $oDate->toString();
         if (isset(self::$alreadyBuilt[$idSite][$date][$period])) {
             return self::$alreadyBuilt[$idSite][$date][$period];
         }
         $oPeriod = Piwik_Period::factory($period, $oDate);
         $archive = new Piwik_Archive_Single();
         $archive->setPeriod($oPeriod);
         $archive->setSite($oSite);
         self::$alreadyBuilt[$idSite][$date][$period] = $archive;
     }
     return $archive;
 }
Esempio n. 30
0
 /** Returns period object
  * @return Piwik_Period */
 private function getPeriod($date, $period)
 {
     return Piwik_Period::factory($period, Piwik_Date::factory($date));
 }