Пример #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;
	}
Пример #2
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;
 }
Пример #3
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;
 }
Пример #4
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;
 }
Пример #5
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;
 }
Пример #6
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;
 }
Пример #7
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());
		}
	}