Example #1
0
	function getTemperaturesEvolution($date, $period)
	{
		$period = new Piwik_Period_Range($period, 'last30');
		$dateStart = $period->getDateStart()->get('Y-m-d'); // eg. "2009-04-01"
		$dateEnd = $period->getDateEnd()->get('Y-m-d'); // eg. "2009-04-30"
		
		// here you could select from your custom table in the database, eg.
		$query = "SELECT AVG(temperature)
					FROM server_temperatures
					WHERE date > ?
						AND date < ?
					GROUP BY date
					ORDER BY date ASC";
		//$result = Piwik_FetchAll($query, array($dateStart, $dateEnd));
		// to keep things simple, we generate the data
		foreach($period->getSubperiods() as $subPeriod)
		{
			$server1 = rand(50,90);
			$server2 = rand(40, 110);
			$value = array('server1' => $server1, 'server2' => $server2);
			$temperatures[$subPeriod->getLocalizedShortString()] = $value;
		}
		
		// convert this array to a DataTable object
		$dataTable = new Piwik_DataTable();
		$dataTable->addRowsFromArrayWithIndexLabel($temperatures);
		return $dataTable;
	}
Example #2
0
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate, Piwik_Segment $segment)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate, $oSite->getTimezone());
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate, $segment->getString());
         $archive->setSegment($segment);
         $this->archives[] = $archive;
     }
 }
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate);
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate);
         $archive->prepareArchive();
         $timestamp = $archive->getTimestampStartDate();
         $this->archives[$timestamp] = $archive;
     }
     ksort($this->archives);
 }
Example #4
0
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate);
     // TODO fix this when aggregating data from multiple websites
     // CAREFUL this class wouldnt work as is if handling archives from multiple websites
     // works only when managing archives from multiples dates/periods
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate);
         $archive->prepareArchive();
         $timestamp = $archive->getTimestampStartDate();
         $this->archives[$timestamp] = $archive;
     }
     ksort($this->archives);
 }
Example #5
0
 public function __construct()
 {
     parent::__construct();
     $this->period = Piwik_Common::getRequestVar("period");
     if (isset($this->date)) {
         $this->range = Piwik_Period_Range::factory($this->period, $this->date);
     }
 }
Example #6
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;
	}
Example #7
0
 /**
  * @group Core
  * @group Period
  * @group Period_Range
  */
 public function testGetPrettyString()
 {
     Piwik_Translate::getInstance()->loadEnglishTranslation();
     $month = new Piwik_Period_Range('range', '2007-02-09,2007-03-15');
     $shouldBe = 'From 2007-02-09 to 2007-03-15';
     $this->assertEquals($shouldBe, $month->getPrettyString());
 }
Example #8
0
 /**
  * Returns true if it is likely that the data for this report has been purged and if the
  * user should be told about that.
  * 
  * In order for this function to return true, the following must also be true:
  * - The data table for this report must either be empty or not have been fetched.
  * - The period of this report is not a multiple period.
  * - The date of this report must be older than the delete_reports_older_than config option.
  * @return bool
  */
 public function hasReportBeenPurged()
 {
     $strPeriod = Piwik_Common::getRequestVar('period', false);
     $strDate = Piwik_Common::getRequestVar('date', false);
     if ($strPeriod !== false && $strDate !== false && (is_null($this->dataTable) || $this->dataTable->getRowsCount() == 0)) {
         // if range, only look at the first date
         if ($strPeriod == 'range') {
             $idSite = Piwik_Common::getRequestVar('idSite', '');
             if (intval($idSite) != 0) {
                 $site = new Piwik_Site($idSite);
                 $timezone = $site->getTimezone();
             } else {
                 $timezone = 'UTC';
             }
             $period = new Piwik_Period_Range('range', $strDate, $timezone);
             $reportDate = $period->getDateStart();
         } else {
             if (Piwik_Archive::isMultiplePeriod($strDate, $strPeriod)) {
                 return false;
             } else {
                 $reportDate = Piwik_Date::factory($strDate);
             }
         }
         $reportYear = $reportDate->toString('Y');
         $reportMonth = $reportDate->toString('m');
         if (class_exists('Piwik_PrivacyManager') && Piwik_PrivacyManager::shouldReportBePurged($reportYear, $reportMonth)) {
             return true;
         }
     }
     return false;
 }
Example #9
0
 /**
  * @group Core
  * @group Period
  * @group Period_Range
  * @dataProvider getDataForLastNLimitsTest
  */
 public function testLastNLimits($period, $lastN, $expectedLastN)
 {
     $range = new Piwik_Period_Range($period, 'last' . $lastN);
     $this->assertEquals($expectedLastN, $range->getNumberOfSubperiods());
 }
Example #10
0
 /**
  * Given for example, $period = month, $lastN = 'last6', $endDate = '2011-07-01', 
  * It will return the $date = '2011-01-01,2011-07-01' which is useful to draw graphs for the last N periods
  * 
  * @param string      $period
  * @param string      $lastN
  * @param string      $endDate
  * @param Piwik_Site  $site
  * @return string
  */
 public static function getDateRangeRelativeToEndDate($period, $lastN, $endDate, $site)
 {
     $last30Relative = new Piwik_Period_Range($period, $lastN, $site->getTimezone());
     $last30Relative->setDefaultEndDate(Piwik_Date::factory($endDate));
     $date = $last30Relative->getDateStart()->toString() . "," . $last30Relative->getDateEnd()->toString();
     return $date;
 }
Example #11
0
 /**
  * Returns the array of new processed parameters once the parameters are applied.
  * For example: if you set range=last30 and date=2008-03-10, 
  *  the date element of the returned array will be "2008-02-10,2008-03-10"
  * 
  * Parameters you can set:
  * - range: last30, previous10, etc.
  * - date: YYYY-MM-DD, today, yesterday
  * - period: day, week, month, year
  * 
  * @param array  paramsToSet = array( 'date' => 'last50', 'viewDataTable' =>'sparkline' )
  */
 protected function getGraphParamsModified($paramsToSet = array())
 {
     if (!isset($paramsToSet['range'])) {
         $range = 'last30';
     } else {
         $range = $paramsToSet['range'];
     }
     if (!isset($paramsToSet['date'])) {
         $endDate = $this->strDate;
     } else {
         $endDate = $paramsToSet['date'];
     }
     if (!isset($paramsToSet['period'])) {
         $period = Piwik_Common::getRequestVar('period');
     } else {
         $period = $paramsToSet['period'];
     }
     $last30Relative = new Piwik_Period_Range($period, $range);
     $last30Relative->setDefaultEndDate(Piwik_Date::factory($endDate));
     $paramDate = $last30Relative->getDateStart()->toString() . "," . $last30Relative->getDateEnd()->toString();
     $params = array_merge($paramsToSet, array('date' => $paramDate));
     return $params;
 }
Example #12
0
 /** 
  * Given an API report to query (eg. "Referers.getKeywords", and a Label (eg. "free%20software"), 
  * this function will query the API for the previous days/weeks/etc. and will return 
  * a ready to use data structure containing the metrics for the requested Label, along with enriched information (min/max values, etc.) 
  * 
  * @return array
  */
 public function getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $label = false, $segment = false, $column = false, $language = false, $idGoal = false, $legendAppendMetric = true, $labelUseAbsoluteUrl = true)
 {
     // validation of requested $period & $date
     if ($period == 'range') {
         // load days in the range
         $period = 'day';
     }
     if (!Piwik_Archive::isMultiplePeriod($date, $period)) {
         throw new Exception("Row evolutions can not be processed with this combination of \\'date\\' and \\'period\\' parameters.");
     }
     // this is needed because Piwik_API_Proxy uses Piwik_Common::getRequestVar which in turn
     // uses Piwik_Common::sanitizeInputValue. This causes the > that separates recursive labels
     // to become &gt; and we need to undo that here.
     $label = Piwik_Common::unsanitizeInputValue($label);
     if ($label) {
         $labels = explode(',', $label);
         $labels = array_unique($labels);
     } else {
         $range = new Piwik_Period_Range($period, $date);
         $lastDate = $range->getDateEnd();
         // retrieve top labels for the most recent period
         $mostRecentDataTable = $this->loadRowEvolutionDataFromAPI($idSite, $period, $lastDate, $apiModule, $apiAction, null, $segment, $idGoal);
         $labels = $mostRecentDataTable->getColumn('label');
         //@review $labelCount can be equal to 0, this means there are no data what should this API return in that case?
         if (!count($labels)) {
             return null;
         }
     }
     if (count($labels) > 1) {
         $data = $this->getMultiRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $labels, $segment, $column, $language, $idGoal, $legendAppendMetric, $labelUseAbsoluteUrl);
     } else {
         $data = $this->getSingleRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $labels[0], $segment, $language, $idGoal, $labelUseAbsoluteUrl);
     }
     return $data;
 }
Example #13
0
 function test_range_year_last1()
 {
     $range = new Piwik_Period_Range('year', 'last1');
     $currentYear = new Piwik_Period_Year(Piwik_Date::today());
     $this->assertEqual($range->getNumberOfSubperiods(), 1);
     $this->assertEqual($range->toString(), array($currentYear->toString()));
 }
Example #14
0
 function test_InvalidRange_throws()
 {
     try {
         $range = new Piwik_Period_Range('range', '0001-01-01,today');
         echo $range->getLocalizedLongString();
         $this->fail();
     } catch (Exception $e) {
         $this->pass();
     }
 }
Example #15
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);
     }
     $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) && (preg_match('/^(last|previous){1}([0-9]*)$/', $strDate, $regs) || Piwik_Period_Range::parseDateRange($strDate)) && $period != 'range') {
         $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;
 }
Example #16
0
 public function getSitesInfo()
 {
     Piwik::checkUserHasSomeViewAccess();
     // 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();
     $dateRequest = Piwik_Common::getRequestVar('date', 'today');
     $period = Piwik_Common::getRequestVar('period', 'day');
     $date = $dateRequest;
     if ($period != 'range') {
         $date = $this->getDateParameterInTimezone($dateRequest, $piwikDefaultTimezone);
         $date = $date->toString();
     }
     $mySites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess();
     $ids = 'all';
     $visits = Piwik_VisitsSummary_API::getInstance()->getVisits($ids, $period, $date);
     $actions = Piwik_VisitsSummary_API::getInstance()->getActions($ids, $period, $date);
     $uniqueUsers = Piwik_VisitsSummary_API::getInstance()->getUniqueVisitors($ids, $period, $date);
     if ($period != 'range') {
         $lastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1);
         $lastVisits = Piwik_VisitsSummary_API::getInstance()->getVisits($ids, $period, $lastDate);
         $lastActions = Piwik_VisitsSummary_API::getInstance()->getActions($ids, $period, $lastDate);
         $lastUniqueUsers = Piwik_VisitsSummary_API::getInstance()->getUniqueVisitors($ids, $period, $lastDate);
         $visitsSummary = $this->getSummary($lastVisits, $visits, $mySites, "visits");
         $actionsSummary = $this->getSummary($lastActions, $actions, $mySites, "actions");
         $uniqueSummary = $this->getSummary($lastUniqueUsers, $uniqueUsers, $mySites, "unique");
         $lastVisitsArray = $lastVisits->getArray();
         $lastActionsArray = $lastActions->getArray();
         $lastUniqueUsersArray = $lastUniqueUsers->getArray();
     }
     $visitsArray = $visits->getArray();
     $actionsArray = $actions->getArray();
     $uniqueUsersArray = $uniqueUsers->getArray();
     $totalVisits = $totalActions = 0;
     foreach ($mySites as &$site) {
         $idSite = $site['idsite'];
         $tmp = $visitsArray[$idSite]->getColumn(0);
         $site['visits'] = $tmp[0];
         $totalVisits += $tmp[0];
         $tmp = $actionsArray[$idSite]->getColumn(0);
         $site['actions'] = $tmp[0];
         $totalActions += $tmp[0];
         $tmp = $uniqueUsersArray[$idSite]->getColumn(0);
         $site['unique'] = $tmp[0];
         if ($period != 'range') {
             $tmp = $lastVisitsArray[$idSite]->getColumn(0);
             $site['lastVisits'] = $tmp[0];
             $tmp = $lastActionsArray[$idSite]->getColumn(0);
             $site['lastActions'] = $tmp[0];
             $tmp = $lastUniqueUsersArray[$idSite]->getColumn(0);
             $site['lastUnique'] = $tmp[0];
         }
         $site['visitsSummaryValue'] = isset($visitsSummary[$idSite]) ? $visitsSummary[$idSite] : 0;
         $site['actionsSummaryValue'] = isset($actionsSummary[$idSite]) ? $actionsSummary[$idSite] : 0;
         $site['uniqueSummaryValue'] = isset($uniqueSummary[$idSite]) ? $uniqueSummary[$idSite] : 0;
     }
     $view = new Piwik_View("MultiSites/templates/index.tpl");
     $view->mySites = $mySites;
     $view->evolutionBy = $this->evolutionBy;
     $view->period = $period;
     $view->dateRequest = $dateRequest;
     $view->page = $this->page;
     $view->limit = $this->limit;
     $view->orderBy = $this->orderBy;
     $view->order = $this->order;
     $view->totalVisits = $totalVisits;
     $view->totalActions = $totalActions;
     $params = $this->getGraphParamsModified();
     $view->dateSparkline = $period == 'range' ? $dateRequest : $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 = true;
     }
     $this->setGeneralVariablesView($view);
     $this->setMinMaxDateAcrossWebsites($mySites, $view);
     $view->show_sparklines = Zend_Registry::get('config')->General->show_multisites_sparklines;
     echo $view->render();
 }
Example #17
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::factory('now', $this->timezone);
         }
         $period = $this->strPeriod;
         if ($period == 'range') {
             $period = 'day';
         }
         if ($lastOrPrevious == 'last') {
             $endDate = $defaultEndDate;
         } elseif ($lastOrPrevious == 'previous') {
             $endDate = self::removePeriod($period, $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 = self::removePeriod($period, $endDate, $lastN);
     } elseif ($dateRange = Piwik_Period_Range::parseDateRange($this->strDate)) {
         $strDateStart = $dateRange[1];
         $strDateEnd = $dateRange[2];
         $startDate = Piwik_Date::factory($strDateStart);
         if ($strDateEnd == 'today') {
             $strDateEnd = 'now';
         } elseif ($strDateEnd == 'yesterday') {
             $strDateEnd = 'yesterdaySameTime';
         }
         // we set the timezone in the Date object only if the date is relative eg. 'today', 'yesterday', 'now'
         $timezone = null;
         if (strpos($strDateEnd, '-') === false) {
             $timezone = $this->timezone;
         }
         $endDate = Piwik_Date::factory($strDateEnd, $timezone);
     } else {
         throw new Exception(Piwik_TranslateException('General_ExceptionInvalidDateRange', array($this->strDate, ' \'lastN\', \'previousN\', \'YYYY-MM-DD,YYYY-MM-DD\'')));
     }
     if ($this->strPeriod != 'range') {
         $this->fillArraySubPeriods($startDate, $endDate, $this->strPeriod);
         return;
     }
     $this->processOptimalSubperiods($startDate, $endDate);
     // When period=range, we want End Date to be the actual specified end date,
     // rather than the end of the month / week / whatever is used for processing this range
     $this->endDate = $endDate;
 }
Example #18
0
 /**
  * Indicate if $dateString and $period correspond to multiple periods
  *
  * @static
  * @param  $dateString
  * @param  $period
  * @return boolean
  */
 public static function isMultiplePeriod($dateString, $period)
 {
     return (preg_match('/^(last|previous){1}([0-9]*)$/D', $dateString, $regs) || Piwik_Period_Range::parseDateRange($dateString)) && $period != 'range';
 }
Example #19
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());
		}
	}
Example #20
0
 /**
  * Returns a report displaying the total visits, actions and revenue, as
  * well as the evolution of these values, of all existing sites over a
  * specified period of time.
  * 
  * If the specified period is not a 'range', this function will calculcate
  * evolution metrics. Evolution metrics are metrics that display the
  * percent increase/decrease of another metric since the last period.
  * 
  * This function will merge the result of the archive query so each
  * row in the result DataTable will correspond to the metrics of a single
  * site. If a date range is specified, the result will be a
  * DataTable_Array, but it will still be merged.
  * 
  * @param string $period The period type to get data for.
  * @param string $date The date(s) to get data for.
  * @param string $segment The segments to get data for.
  */
 public function getAll($period, $date, $segment = false)
 {
     Piwik::checkUserHasSomeViewAccess();
     $isGoalPluginEnabled = Piwik_Common::isGoalPluginEnabled();
     // get site data for every viewable site and cache them
     if (Piwik::isUserIsSuperUser()) {
         $sites = Piwik_SitesManager_API::getInstance()->getAllSites();
         Piwik_Site::setSites($sites);
     } else {
         $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess();
         Piwik_Site::setSitesFromArray($sites);
     }
     // build the archive type used to query archive data
     $archive = Piwik_Archive::build('all', $period, $date, $segment);
     // determine what data will be displayed
     $fieldsToGet = array('nb_visits', 'nb_actions');
     if ($isGoalPluginEnabled) {
         $revenueMetric = Piwik_Goals::getRecordName('revenue');
         $fieldsToGet[] = $revenueMetric;
     }
     // get the data
     $dataTable = $archive->getDataTableFromNumeric($fieldsToGet);
     // get rid of the DataTable_Array that is created by the IndexedBySite archive type
     $dataTable = $dataTable->mergeChildren();
     // if the period isn't a range & a lastN/previousN date isn't used, we get the same
     // data for the last period to show the evolution of visits/actions/revenue
     if ($period != 'range' && !preg_match('/(last|previous)([0-9]*)/', $date, $regs)) {
         if (strpos($date, ',')) {
             $rangePeriod = new Piwik_Period_Range($period, $date);
             $lastStartDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateStart(), $n = 1);
             $lastEndDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateEnd(), $n = 1);
             $strLastDate = "{$lastStartDate},{$lastEndDate}";
         } else {
             $strLastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1)->toString();
         }
         $pastArchive = Piwik_Archive::build('all', $period, $strLastDate, $segment);
         $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet);
         $pastData = $pastData->mergeChildren();
         // use past data to calculate evolution percentages
         $this->calculateEvolutionPercentages($dataTable, $pastData, $fieldsToGet);
     }
     // move the site id to a metadata column
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite'));
     // set the label of each row to the site name
     $getNameFor = array('Piwik_Site', 'getNameFor');
     $dataTable->filter('ColumnCallbackReplace', array('label', $getNameFor));
     // rename the revenue column from the metric name to 'revenue'
     if ($isGoalPluginEnabled) {
         $mapping = array($revenueMetric => 'revenue');
         $dataTable->filter('ReplaceColumnNames', array($mapping));
     }
     // Ensures data set sorted, for Metadata output
     $dataTable->filter('Sort', array('nb_visits', 'desc', $naturalSort = false));
     return $dataTable;
 }
Example #21
0
 private function buildDataTable($sites, $period, $date, $segment, $_restrictSitesToLogin, $enhanced)
 {
     $allWebsitesRequested = $sites == 'all';
     if ($allWebsitesRequested) {
         if (Piwik::isUserIsSuperUser() && !Piwik_TaskScheduler::isTaskBeingExecuted()) {
             Piwik_Site::setSites(Piwik_SitesManager_API::getInstance()->getAllSites());
         } else {
             Piwik_Site::setSitesFromArray(Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin));
         }
     }
     // build the archive type used to query archive data
     $archive = Piwik_Archive::build($sites, $period, $date, $segment, $_restrictSitesToLogin);
     // determine what data will be displayed
     $fieldsToGet = array();
     $columnNameRewrites = array();
     $apiECommerceMetrics = array();
     $apiMetrics = Piwik_MultiSites_API::getApiMetrics($enhanced);
     foreach ($apiMetrics as $metricName => $metricSettings) {
         $fieldsToGet[] = $metricSettings[self::METRIC_RECORD_NAME_KEY];
         $columnNameRewrites[$metricSettings[self::METRIC_RECORD_NAME_KEY]] = $metricName;
         if ($metricSettings[self::METRIC_IS_ECOMMERCE_KEY]) {
             $apiECommerceMetrics[$metricName] = $metricSettings;
         }
     }
     // get the data
     // $dataTable instanceOf Piwik_DataTable_Array
     $dataTable = $archive->getDataTableFromNumeric($fieldsToGet);
     // get rid of the DataTable_Array that is created by the IndexedBySite archive type
     if ($dataTable instanceof Piwik_DataTable_Array && $allWebsitesRequested) {
         $dataTable = $dataTable->mergeChildren();
     } else {
         if (!$dataTable instanceof Piwik_DataTable_Array) {
             $firstDataTableRow = $dataTable->getFirstRow();
             $firstDataTableRow->setColumn('label', $sites);
         }
     }
     // if the period isn't a range & a lastN/previousN date isn't used, we get the same
     // data for the last period to show the evolution of visits/actions/revenue
     if ($period != 'range' && !preg_match('/(last|previous)([0-9]*)/', $date, $regs)) {
         if (strpos($date, ',')) {
             $rangePeriod = new Piwik_Period_Range($period, $date);
             $lastStartDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateStart(), $n = 1);
             $lastEndDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateEnd(), $n = 1);
             $strLastDate = "{$lastStartDate},{$lastEndDate}";
         } else {
             $strLastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1)->toString();
         }
         $pastArchive = Piwik_Archive::build('all', $period, $strLastDate, $segment, $_restrictSitesToLogin);
         $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet);
         $pastData = $pastData->mergeChildren();
         // use past data to calculate evolution percentages
         $this->calculateEvolutionPercentages($dataTable, $pastData, $apiMetrics);
     }
     // remove eCommerce related metrics on non eCommerce Piwik sites
     // note: this is not optimal in terms of performance: those metrics should not be retrieved in the first place
     if ($enhanced) {
         // $dataTableRows instanceOf Piwik_DataTable_Row[]
         $dataTableRows = $dataTable->getRows();
         foreach ($dataTableRows as $dataTableRow) {
             $siteId = $dataTableRow->getColumn('label');
             if (!Piwik_Site::isEcommerceEnabledFor($siteId)) {
                 foreach ($apiECommerceMetrics as $metricSettings) {
                     $dataTableRow->deleteColumn($metricSettings[self::METRIC_RECORD_NAME_KEY]);
                     $dataTableRow->deleteColumn($metricSettings[self::METRIC_EVOLUTION_COL_NAME_KEY]);
                 }
             }
         }
     }
     // move the site id to a metadata column
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite'));
     // set the label of each row to the site name
     if ($allWebsitesRequested) {
         $getNameFor = array('Piwik_Site', 'getNameFor');
         $dataTable->filter('ColumnCallbackReplace', array('label', $getNameFor));
     } else {
         $dataTable->filter('ColumnDelete', array('label'));
     }
     // replace record names with user friendly metric names
     $dataTable->filter('ReplaceColumnNames', array($columnNameRewrites));
     // Ensures data set sorted, for Metadata output
     $dataTable->filter('Sort', array(self::NB_VISITS_METRIC, 'desc', $naturalSort = false));
     // filter rows without visits
     // note: if only one website is queried and there are no visits, we can not remove the row otherwise Piwik_API_ResponseBuilder throws 'Call to a member function getColumns() on a non-object'
     if ($allWebsitesRequested) {
         $dataTable->filter('ColumnCallbackDeleteRow', array(self::NB_VISITS_METRIC, create_function('$value', 'return $value != 0;')));
     }
     return $dataTable;
 }
Example #22
0
 /**
  * Based on the period, date and evolution_{$period}_last_n query parameters,
  * calculates the date range this evolution chart will display data for.
  */
 private function calculateEvolutionDateRange()
 {
     $period = Piwik_Common::getRequestVar('period');
     $defaultLastN = self::getDefaultLastN($period);
     $this->originalDate = Piwik_Common::getRequestVar('date', 'last' . $defaultLastN, 'string');
     if ($period != 'range') {
         $this->alwaysShowLimitDropdown();
         // set the evolution_{$period}_last_n query param
         if (Piwik_Period_Range::parseDateRange($this->originalDate)) {
             // overwrite last_n param using the date range
             $oPeriod = new Piwik_Period_Range($period, $this->originalDate);
             $lastN = count($oPeriod->getSubperiods());
         } else {
             list($newDate, $lastN) = self::getDateRangeAndLastN($period, $this->originalDate, $defaultLastN);
             $this->setParametersToModify(array('date' => $newDate));
         }
         $lastNParamName = self::getLastNParamName($period);
         $this->setParametersToModify(array($lastNParamName => $lastN));
     }
 }
Example #23
0
	public function getSitesInfo()
	{
		Piwik::checkUserHasSomeViewAccess();
		$displayRevenueColumn = Piwik_Common::isGoalPluginEnabled();
		
		// 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();
		$dateRequest = Piwik_Common::getRequestVar('date', 'today');
		$period = Piwik_Common::getRequestVar('period', 'day');	
		$date = $dateRequest;
		if($period != 'range')
		{
			$date = $this->getDateParameterInTimezone($dateRequest, $piwikDefaultTimezone);
			$date = $date->toString();
		}
		
		$mySites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess();
		
		$ids = 'all';
		
		// Current date - select metrics
		$dataTableArray = Piwik_VisitsSummary_API::getInstance()->get($ids, $period, $date, $segment = false, $columns = array('nb_visits', 'nb_actions'));
		$currentVisits = $this->getArrayFromAPI($dataTableArray, 'nb_visits');
		$currentActions = $this->getArrayFromAPI($dataTableArray, 'nb_actions');
		if($displayRevenueColumn)
		{
		    $dataTableArray = Piwik_Goals_API::getInstance()->get($ids, $period, $date, $segment = false, $idGoal = false, $columns = array('revenue'));
		    $currentRevenue = $this->getArrayFromAPI($dataTableArray, 'revenue');
		}
		// Previous date
		$lastVisits = $lastActions = $lastRevenue = array();
		if($period != 'range')
		{
			$lastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1 );
			$dataTableArray = Piwik_VisitsSummary_API::getInstance()->get($ids, $period, $lastDate, $segment = false, $columns = array('nb_visits', 'nb_actions'));
			$lastVisits =  $this->getArrayFromAPI($dataTableArray, 'nb_visits');
			$lastActions =  $this->getArrayFromAPI($dataTableArray, 'nb_actions');
			if($displayRevenueColumn)
			{
			    $dataTableArray = Piwik_Goals_API::getInstance()->get($ids, $period, $lastDate, $segment = false, $idGoal = false, $columns = array('revenue'));
			    $lastRevenue = $this->getArrayFromAPI($dataTableArray, 'revenue');
			}
		}
		
		$visitsSummary = $this->getChangeCurrentVsLast($currentVisits, $lastVisits);
		$actionsSummary = $this->getChangeCurrentVsLast($currentActions, $lastActions);
		if($displayRevenueColumn)
		{
		    $revenueSummary = $this->getChangeCurrentVsLast($currentRevenue, $lastRevenue);
		}
		$totalVisits = $totalActions = $totalRevenue = 0;
		
		foreach($mySites as &$site)
		{
			$idSite = $site['idsite'];
			if($period != 'range')
			{
				$site['lastVisits'] = $lastVisits[$idSite];
				$site['lastActions'] = $lastActions[$idSite];
				if($displayRevenueColumn)
				{
				    $site['lastRevenue'] = $lastRevenue[$idSite];
				}
			}
			
			$site['visits'] = $currentVisits[$idSite];
			$site['actions'] = $currentActions[$idSite];
			$totalVisits += $site['visits'];
			$totalActions += $site['actions'];
			$site['visitsSummaryValue'] = $visitsSummary[$idSite];
			$site['actionsSummaryValue'] = $actionsSummary[$idSite];
			$site['revenue'] = $site['revenueSummaryValue'] = 0;
			if($displayRevenueColumn)
			{
    			$site['revenue'] = $currentRevenue[$idSite];
    			$totalRevenue += $site['revenue'];
    			$site['revenueSummaryValue'] = $revenueSummary[$idSite];
			}
		}
		$mySites = $this->applyPrettyMoney($mySites);
		
		$view = new Piwik_View("MultiSites/templates/index.tpl");
		$view->mySites = $mySites;
		$view->evolutionBy = $this->evolutionBy;
		$view->period = $period;
		$view->dateRequest = $dateRequest;
		$view->page = $this->page;
		$view->limit = $this->limit;
		$view->orderBy = $this->orderBy;
		$view->order = $this->order;
		$view->totalVisits = $totalVisits;
		$view->totalRevenue = $totalRevenue;
		$view->displayRevenueColumn = $displayRevenueColumn;
		$view->totalActions = $totalActions;
	
		$params = $this->getGraphParamsModified();
		$view->dateSparkline = $period == 'range' ? $dateRequest : $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 = Zend_Registry::get('config')->General->multisites_refresh_after_seconds;
		}
		$this->setGeneralVariablesView($view);
		$this->setMinMaxDateAcrossWebsites($mySites, $view);
		$view->show_sparklines = Zend_Registry::get('config')->General->show_multisites_sparklines;

		echo $view->render();
	}