/**
	 * Adds metadata information to the Piwik_DataTable_Array 
	 * using the information given by the Archive
	 *
	 * @param Piwik_DataTable_Array $table
	 * @param Piwik_Archive $archive
	 */
	protected function loadMetadata(Piwik_DataTable_Array $table, $archive)
	{
		$table->metadata[$archive->getPrettyDate()] = array( 
				'timestamp' => $archive->getTimestampStartDate(),
				'site' => $archive->getSite(),
				'period' => $archive->getPeriod(),
			);
	}
Example #2
0
 /**
  * The advanced factory method is easier to use from the API than the factory
  * method above. It doesn't require an instance of Piwik_Date and works for
  * period=range. Generally speaking, anything that can be passed as period
  * and range to the API methods can directly be forwarded to this factory
  * method in order to get a suitable instance of Piwik_Period.
  * 
  * @param string $strPeriod "day", "week", "month", "year", "range"
  * @param string $strDate
  * @return Piwik_Period
  */
 public static function advancedFactory($strPeriod, $strDate)
 {
     if (Piwik_Archive::isMultiplePeriod($strDate, $strPeriod) || $strPeriod == 'range') {
         return new Piwik_Period_Range($strPeriod, $strDate);
     }
     return self::factory($strPeriod, Piwik_Date::factory($strDate));
 }
Example #3
0
 public function getByDayOfWeek($fetch = false)
 {
     $view = $this->getGraph(__FUNCTION__, 'VisitTime.getByDayOfWeek', 'VisitTime_DayOfWeek', $limit = 7, $sort = false);
     $view->disableSort();
     if ($view instanceof Piwik_ViewDataTable_GenerateGraphHTML) {
         $view->showAllTicks();
     }
     // get query params
     $idsite = Piwik_Common::getRequestVar('idSite');
     $date = Piwik_Common::getRequestVar('date');
     $period = Piwik_Common::getRequestVar('period');
     // create a period instance
     $oSite = new Piwik_Site($idsite);
     $oPeriod = Piwik_Archive::makePeriodFromQueryParams($oSite, $period, $date);
     // set the footer message using the period start & end date
     $start = $oPeriod->getDateStart()->toString();
     $end = $oPeriod->getDateEnd()->toString();
     if ($start == $end) {
         $dateRange = $start;
     } else {
         $dateRange = $start . " – " . $end;
     }
     $view->setFooterMessage(Piwik_Translate('General_ReportGeneratedFrom', $dateRange));
     return $this->renderView($view, $fetch);
 }
Example #4
0
 /** Get data table from archive
  * @return Piwik_DataTable */
 public static function getDataTable($name, $idsite, $period, $date, $numeric = false)
 {
     Piwik::checkUserHasViewAccess($idsite);
     if (is_array($name)) {
         foreach ($name as &$col) {
             $col = 'SiteSearch_' . $col;
         }
     } else {
         $name = 'SiteSearch_' . $name;
     }
     if (!is_string($period) && get_class($period) != 'Piwik_Period_Range') {
         $periodMap = array('Piwik_Period_Day' => 'day', 'Piwik_Period_Week' => 'week', 'Piwik_Period_Month' => 'month', 'Piwik_Period_Year' => 'year');
         $period = $periodMap[get_class($period)];
     }
     $archive = Piwik_Archive::build($idsite, $period, $date);
     if ($numeric) {
         // numeric archives are only used for search evolution
         $dataTable = $archive->getDataTableFromNumeric($name);
         $dataTable->queueFilter('ReplaceColumnNames', array(array('SiteSearch_totalSearches' => self::HITS, 'SiteSearch_visitsWithSearches' => self::UNIQUE_HITS)));
         $dataTable->applyQueuedFilters();
     } else {
         $dataTable = $archive->getDataTable($name);
     }
     return $dataTable;
 }
Example #5
0
 protected function getDataTable($idSite, $period, $date, $segment, $expanded, $idSubtable)
 {
     $dataTable = Piwik_Archive::getDataTableFromArchive('CustomVariables_valueByName', $idSite, $period, $date, $segment, $expanded, $idSubtable);
     $dataTable->filter('Sort', array(Piwik_Archive::INDEX_NB_VISITS, 'desc', $naturalSort = false, $expanded));
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
Example #6
0
    public function __construct($string, $idSites)
    {
    	$string = Piwik_Common::unsanitizeInputValue($string);
        $string = trim($string);
		if( !Piwik_Archive::isSegmentationEnabled() 
			&& !empty($string))
		{
			throw new Exception("The Super User has disabled the use of 'segments' for the anonymous user. 
									Please log in to use Segmentation in the API.");
		}
        // As a preventive measure, we restrict the filter size to a safe limit
        $string = substr($string, 0, self::SEGMENT_TRUNCATE_LIMIT);
        
        $this->string = $string;
        $this->idSites = $idSites;
        $segment = new Piwik_SegmentExpression($string);
        $this->segment = $segment;

        // parse segments
        $expressions = $segment->parseSubExpressions();
        
        // convert segments name to sql segment
        // check that user is allowed to view this segment
        // and apply a filter to the value to match if necessary (to map DB fields format)
        $cleanedExpressions = array();
        foreach($expressions as $expression)
        {
            $operand = $expression[Piwik_SegmentExpression::INDEX_OPERAND];
            $cleanedExpression = $this->getCleanedExpression($operand);
            $expression[Piwik_SegmentExpression::INDEX_OPERAND] = $cleanedExpression;
            $cleanedExpressions[] = $expression;
        }
        $segment->setSubExpressionsAfterCleanup($cleanedExpressions);
    }
Example #7
0
 protected function getNumeric($idSite, $period, $date, $segment, $toFetch)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getNumeric($toFetch);
     return $dataTable;
 }
Example #8
0
 protected function getDataTable($name, $idSite, $period, $date, $segment, $column = Piwik_Archive::INDEX_NB_VISITS)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable($name);
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
 /**
  * @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($sites, $strPeriod, $strDate, Piwik_Segment $segment)
 {
     foreach ($sites as $idSite) {
         $archive = Piwik_Archive::build($idSite, $strPeriod, $strDate, $segment);
         $this->archives[$idSite] = $archive;
     }
     ksort($this->archives);
 }
Example #10
0
 /** Get data table from archive
  * @return Piwik_DataTable */
 public static function getDataTable($name, $idsite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idsite);
     $name = 'SiteUsers_' . $name;
     $archive = Piwik_Archive::build($idsite, $period, $date);
     $dataTable = $archive->getDataTable($name);
     return $dataTable;
 }
Example #11
0
 /** Get evolution of search percentage
  * @return Piwik_DataTable */
 public function getSearchPercentageEvolution($idSite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     $dataTable = $archive->getDataTableFromNumeric(array('SiteSearch_visitsWithSearches', 'nb_visits'));
     $dataTable->filter('ColumnCallbackAddColumnQuotient', array('search_percentage', 'SiteSearch_visitsWithSearches', 'nb_visits', 4));
     $dataTable->filter('ColumnCallbackReplace', array('search_percentage', array($this, 'quotientToPercentageSafe')));
     return $dataTable;
 }
Example #12
0
	protected function getDataTable($name, $idSite, $period, $date, $segment )
	{
		Piwik::checkUserHasViewAccess( $idSite );
		$archive = Piwik_Archive::build($idSite, $period, $date, $segment );
		$dataTable = $archive->getDataTable($name);
		$dataTable->filter('Sort', array('label', 'asc', true));
		$dataTable->queueFilter('ColumnCallbackReplace', array('label', 'Piwik_getTimeLabel'));
		$dataTable->queueFilter('ReplaceColumnNames');
		return $dataTable;
	}
Example #13
0
 protected function getDataTable($name, $idSite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     $dataTable = $archive->getDataTable($name);
     $dataTable->filter('Sort', array(Piwik_Archive::INDEX_NB_VISITS));
     $dataTable->queueFilter('ReplaceColumnNames');
     $dataTable->queueFilter('Sort', array('label', 'asc', true));
     return $dataTable;
 }
Example #14
0
 /**
  * @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($sites, $strPeriod, $strDate)
 {
     foreach ($sites as $idSite) {
         $archive = Piwik_Archive::build($idSite, $strPeriod, $strDate);
         $archive->setSite(new Piwik_Site($idSite));
         $archive->prepareArchive();
         $this->archives[$idSite] = $archive;
     }
     ksort($this->archives);
 }
Example #15
0
 /**
  * Adds Referer widgets
  */
 function addWidgets()
 {
     Piwik_AddWidget('Referers_Referers', 'Referers_WidgetKeywords', 'Referers', 'getKeywords');
     Piwik_AddWidget('Referers_Referers', 'Referers_WidgetExternalWebsites', 'Referers', 'getWebsites');
     Piwik_AddWidget('Referers_Referers', 'Referers_WidgetSearchEngines', 'Referers', 'getSearchEngines');
     Piwik_AddWidget('Referers_Referers', 'Referers_WidgetCampaigns', 'Referers', 'getCampaigns');
     Piwik_AddWidget('Referers_Referers', 'Referers_WidgetOverview', 'Referers', 'getRefererType');
     if (Piwik_Archive::isSegmentationEnabled()) {
         Piwik_AddWidget('SEO', 'Top Keywords for Page URL', 'Referers', 'getKeywordsForPage');
     }
 }
Example #16
0
 public function getProvider($idSite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     $dataTable = $archive->getDataTable('Provider_hostnameExt');
     $dataTable->filter('Sort', array(Piwik_Archive::INDEX_NB_VISITS));
     $dataTable->queueFilter('ColumnCallbackAddMetadata', array('label', 'url', 'Piwik_getHostnameUrl'));
     $dataTable->queueFilter('ColumnCallbackReplace', array('label', 'Piwik_getHostnameName'));
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
 /**
  * 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);
 }
 /**
  * Test that Archive_Single::preFetchBlob won't fetch extra unnecessary blobs.
  * 
  * @group        Integration
  * @group        OneVisitorTwoVisits
  */
 public function testArchiveSinglePreFetchBlob()
 {
     $archive = Piwik_Archive::build(self::$idSite, 'day', self::$dateTime);
     $archive->preFetchBlob('Actions_actions');
     $cache = $archive->getBlobCache();
     $foundSubtable = false;
     $this->assertTrue(count($cache) > 0, "empty blob cache");
     foreach ($cache as $name => $value) {
         $this->assertTrue(strpos($name, "Actions_actions_url") === false, "found blob w/ name '{$name}'");
         if (strpos($name, "Actions_actions_") !== false) {
             $foundSubtable = true;
         }
     }
     $this->assertTrue($foundSubtable, "Actions_actions subtable was not loaded");
 }
Example #19
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 #20
0
 protected function getDataTable($name, $idSite, $period, $date, $expanded, $idSubtable)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     if ($idSubtable === false) {
         $idSubtable = null;
     }
     if ($expanded) {
         $dataTable = $archive->getDataTableExpanded($name, $idSubtable);
     } else {
         $dataTable = $archive->getDataTable($name, $idSubtable);
     }
     $dataTable->filter('Sort', array('nb_visits', 'desc', $naturalSort = false, $expanded));
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Example #21
0
 /**
  * Returns datatable describing the number of visits for each day of the week.
  * 
  * @param string $idSite The site ID. Cannot refer to multiple sites.
  * @param string $period The period type: day, week, year, range...
  * @param string $date The start date of the period. Cannot refer to multiple dates.
  * @param string $segment The segment.
  * @return Piwik_DataTable
  */
 public function getByDayOfWeek($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // disabled for multiple sites/dates
     if (Piwik_Archive::isMultipleSites($idSite)) {
         throw new Exception("VisitTime.getByDayOfWeek does not support multiple sites.");
     }
     if (Piwik_Archive::isMultiplePeriod($date, $period)) {
         throw new Exception("VisitTime.getByDayOfWeek does not support multiple dates.");
     }
     // metrics to query
     $metrics = Piwik_ArchiveProcessing::getCoreMetrics();
     // get metric data for every day within the supplied period
     $oSite = new Piwik_Site($idSite);
     $oPeriod = Piwik_Archive::makePeriodFromQueryParams($oSite, $period, $date);
     $dateRange = $oPeriod->getDateStart()->toString() . ',' . $oPeriod->getDateEnd()->toString();
     $archive = Piwik_Archive::build($idSite, 'day', $dateRange, $segment);
     $dataTable = $archive->getDataTableFromNumeric($metrics)->mergeChildren();
     // if there's no data for this report, don't bother w/ anything else
     if ($dataTable->getRowsCount() == 0) {
         return $dataTable;
     }
     // group by the day of the week (see below for dayOfWeekFromDate function)
     $dataTable->filter('GroupBy', array('label', 'Piwik_VisitTime_dayOfWeekFromDate'));
     // create new datatable w/ empty rows, then add calculated datatable
     $rows = array();
     foreach (array(1, 2, 3, 4, 5, 6, 7) as $day) {
         $rows[] = array('label' => $day, 'nb_visits' => 0);
     }
     $result = new Piwik_DataTable();
     $result->addRowsFromSimpleArray($rows);
     $result->addDataTable($dataTable);
     // set day of week integer as metadata
     $result->filter('ColumnCallbackAddMetadata', array('label', 'day_of_week'));
     // translate labels
     $result->filter('ColumnCallbackReplace', array('label', 'Piwik_VisitTime_translateDayOfWeek'));
     // set datatable metadata for period start & finish
     $result->setMetadata('date_start', $oPeriod->getDateStart());
     $result->setMetadata('date_end', $oPeriod->getDateEnd());
     return $result;
 }
Example #22
0
 public function getIntranetSubNetwork($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable('IntranetSubNetwork_networkNameExt');
     $dataTable->filter('Sort', array(Piwik_Archive::INDEX_NB_VISITS));
     $dataTable->queueFilter('ColumnCallbackReplace', array('label', 'Piwik_getSubnetName'));
     $dataTable->queueFilter('ReplaceColumnNames');
     //$dataTable->queueFilter('ReplaceSummaryRowLabel');
     $column = 'nb_visits';
     $percCol = 'nb_visits_percentage';
     $percColName = 'General_ColumnPercentageVisits';
     $visitsSums = $archive->getNumeric($column);
     //$visitsSum = Piwik_VisitsSummary_API::getInstance()->getVisits($idSite, $period, $date);
     //print_r($visitsSums);
     // check whether given tables are arrays
     if ($dataTable instanceof Piwik_DataTable_Array) {
         $tableArray = $dataTable->getArray();
         $visitSumsArray = $visitsSums->getArray();
     } else {
         $tableArray = array($dataTable);
         $visitSumsArray = array($visitsSums);
     }
     // walk through the results and calculate the percentage
     foreach ($tableArray as $key => $table) {
         foreach ($visitSumsArray as $k => $visits) {
             if ($k == $key) {
                 if (is_object($visits)) {
                     $visitsSumTotal = (double) $visits->getFirstRow()->getColumn(0);
                 } else {
                     $visitsSumTotal = (double) $visits;
                 }
             }
         }
         $table->filter('ColumnCallbackAddColumnPercentage', array($percCol, Piwik_Archive::INDEX_NB_VISITS, $visitsSumTotal, 1));
         // we don't want <0% or >100%:
         $table->filter('RangeCheck', array($percCol));
     }
     return $dataTable;
 }
Example #23
0
 /**
  * Gibt eine sortierte DataTable mit Kollektionen aus den Archiven zur�ck.
  * @param int $idSite
  * @param unknown_type $period
  * @param unknown_type $date
  * @param boolean $segment
  * @return Piwik_DataTable
  */
 protected function getCollectionTableFromArchive($idSite, $period, $date, $segment)
 {
     //	defined('PIWIK_INCLUDE_PATH') or die('Restricted access');
     Piwik_cdebug::clog('getCollectionTableFromArchive: ' . $idSite . ' period: ' . $period);
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable("DigitalCollections_value");
     Piwik_cdebug::clog('getCollectionTableFromArchive: dataTable: ' . count($dataTable));
     Piwik_cdebug::clog('getCollectionTableFromArchive: dataTable: ' . print_r($dataTable, 1));
     $dataTable->filter('Sort', array(Piwik_DigitalCollections::$valuefield, 'desc'));
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'url', 'getCollectionUrlFromID', array($date, $period)));
     $dataTable->filter('ColumnCallbackReplace', array('label', 'getCollectionNames'));
     $dataTable->filter('ReplaceColumnNames');
     //INDEX_NB_VISITS-Spalte zur richtigen Graphen-Anzeige hinzuf�gen --> ACHTUNG! Muss im Controller ausgeblendet werden!
     $rows = $dataTable->getRows();
     Piwik_cdebug::clog('getCollectionTableFromArchive: rows: ' . count($rows));
     foreach ($rows as $i => $row) {
         Piwik_cdebug::clog('getCollectionTableFromArchive: ' . $i);
         $row->addColumn(Piwik_Archive::INDEX_NB_VISITS, $row->getColumn("visits"));
     }
     return $dataTable;
 }
Example #24
0
 private function addReportData()
 {
     $archive = Piwik_Archive::build($this->idSite, 'year', $this->dateTime);
     $archive->getNumeric('nb_visits', 'nb_hits');
     Piwik_VisitorInterest_API::getInstance()->getNumberOfVisitsPerVisitDuration($this->idSite, 'year', $this->dateTime);
     // months are added via the 'year' period, but weeks must be done manually
     for ($daysAgo = $this->daysAgoStart; $daysAgo > 0; $daysAgo -= 7) {
         $dateTime = $this->dateTime->subDay($daysAgo);
         $archive = Piwik_Archive::build($this->idSite, 'week', $dateTime);
         $archive->getNumeric('nb_visits');
         Piwik_VisitorInterest_API::getInstance()->getNumberOfVisitsPerVisitDuration($this->idSite, 'week', $dateTime);
     }
     // add segment for one day
     $archive = Piwik_Archive::build($this->idSite, 'day', '2012-01-14', 'browserName==FF');
     $archive->getNumeric('nb_visits', 'nb_hits');
     Piwik_VisitorInterest_API::getInstance()->getNumberOfVisitsPerVisitDuration($this->idSite, 'day', '2012-01-14', 'browserName==FF');
     // add range within January
     $rangeEnd = Piwik_Date::factory('2012-01-29');
     $rangeStart = $rangeEnd->subDay(1);
     $range = $rangeStart->toString('Y-m-d') . "," . $rangeEnd->toString('Y-m-d');
     $rangeArchive = Piwik_Archive::build($this->idSite, 'range', $range);
     $rangeArchive->getNumeric('nb_visits', 'nb_hits');
     Piwik_VisitorInterest_API::getInstance()->getNumberOfVisitsPerVisitDuration($this->idSite, 'range', $range);
     // add range between January & February
     $rangeStart = $rangeEnd;
     $rangeEnd = $rangeStart->addDay(3);
     $range = $rangeStart->toString('Y-m-d') . "," . $rangeEnd->toString('Y-m-d');
     $rangeArchive = Piwik_Archive::build($this->idSite, 'range', $range);
     $rangeArchive->getNumeric('nb_visits', 'nb_hits');
     Piwik_VisitorInterest_API::getInstance()->getNumberOfVisitsPerVisitDuration($this->idSite, 'range', $range);
     // when archiving is initiated, the archive metrics & reports for EVERY loaded plugin
     // are archived. don't want this test to depend on every possible metric, so get rid of
     // the unwanted archive data now.
     $metricsToSave = array('nb_visits', 'nb_actions', Piwik_Goals::getRecordName('revenue'), Piwik_Goals::getRecordName('nb_conversions', 1), Piwik_Goals::getRecordName('revenue', Piwik_Tracker_GoalManager::IDGOAL_ORDER));
     $archiveTables = $this->getArchiveTableNames();
     foreach ($archiveTables['numeric'] as $table) {
         $realTable = Piwik_Common::prefixTable($table);
         Piwik_Query("DELETE FROM {$realTable} WHERE name NOT IN ('" . implode("','", $metricsToSave) . "') AND name NOT LIKE 'done%'");
     }
     foreach ($archiveTables['blob'] as $table) {
         $realTable = Piwik_Common::prefixTable($table);
         Piwik_Query("DELETE FROM {$realTable} WHERE name NOT IN ('VisitorInterest_timeGap')");
     }
     // add garbage metrics
     $janDate1 = '2012-01-05';
     $febDate1 = '2012-02-04';
     $sql = "INSERT INTO %s (idarchive,name,idsite,date1,date2,period,ts_archived,value)\n\t\t                VALUES (10000,?,1,?,?,?,?,?)";
     // one metric for jan & one for feb
     Piwik_Query(sprintf($sql, Piwik_Common::prefixTable($archiveTables['numeric'][0])), array(self::GARBAGE_FIELD, $janDate1, $janDate1, $janDate1, 1, 100));
     Piwik_Query(sprintf($sql, Piwik_Common::prefixTable($archiveTables['numeric'][1])), array(self::GARBAGE_FIELD, $febDate1, $febDate1, $febDate1, 1, 200));
     // add garbage reports
     Piwik_Query(sprintf($sql, Piwik_Common::prefixTable($archiveTables['blob'][0])), array(self::GARBAGE_FIELD, $janDate1, $janDate1, $janDate1, 10, 'blobval'));
     Piwik_Query(sprintf($sql, Piwik_Common::prefixTable($archiveTables['blob'][1])), array(self::GARBAGE_FIELD, $febDate1, $febDate1, $febDate1, 20, 'blobval'));
 }
Example #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;
 }
Example #26
0
 private function getNumeric($name, $idSite, $period, $date, $segment)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     return $archive->getDataTableFromNumeric($name);
 }
Example #27
0
 public function getNumberOfDistinctCountries($idSite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     return $archive->getDataTableFromNumeric('UserCountry_distinctCountries');
 }
Example #28
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 #29
0
 /**
  * Helper - Loads a DataTable from the Archive.
  * Optionally loads the table recursively,
  * or optionally fetches a given subtable with $idSubtable
  */
 public static function getDataTableFromArchive($name, $idSite, $period, $date, $segment, $expanded, $idSubtable = null)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     if ($idSubtable === false) {
         $idSubtable = null;
     }
     if ($expanded) {
         $dataTable = $archive->getDataTableExpanded($name, $idSubtable);
     } else {
         $dataTable = $archive->getDataTable($name, $idSubtable);
     }
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Example #30
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;
 }