Beispiel #1
0
 /**
  * Returns the list of metrics (pages, downloads, outlinks)
  * 
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param string $segment
  */
 public function get($idSite, $period, $date, $segment = false, $columns = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     $metrics = array('Actions_nb_pageviews' => 'nb_pageviews', 'Actions_nb_uniq_pageviews' => 'nb_uniq_pageviews', 'Actions_nb_downloads' => 'nb_downloads', 'Actions_nb_uniq_downloads' => 'nb_uniq_downloads', 'Actions_nb_outlinks' => 'nb_outlinks', 'Actions_nb_uniq_outlinks' => 'nb_uniq_outlinks');
     // get requested columns
     $columns = Piwik::getArrayFromApiParameter($columns);
     if (!empty($columns)) {
         // get the columns that are available and requested
         $columns = array_intersect($columns, array_values($metrics));
         $columns = array_values($columns);
         // make sure indexes are right
         $nameReplace = array();
         foreach ($columns as $i => $column) {
             $fullColumn = array_search($column, $metrics);
             $columns[$i] = $fullColumn;
             $nameReplace[$fullColumn] = $column;
         }
     } else {
         // get all columns
         $columns = array_keys($metrics);
         $nameReplace =& $metrics;
     }
     $table = $archive->getDataTableFromNumeric($columns);
     // replace labels (remove Actions_)
     $table->filter('ReplaceColumnNames', array($nameReplace));
     return $table;
 }
Beispiel #2
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;
 }
Beispiel #3
0
 function worldMap()
 {
     if (!Piwik_PluginsManager::getInstance()->isPluginActivated('UserCountry')) {
         return '';
     }
     $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int');
     Piwik::checkUserHasViewAccess($idSite);
     $period = Piwik_Common::getRequestVar('period');
     $date = Piwik_Common::getRequestVar('date');
     $token_auth = Piwik::getCurrentUserTokenAuth();
     $view = Piwik_View::factory('worldmap');
     $view->dataUrl = "?module=API" . "&method=API.getProcessedReport&format=XML" . "&apiModule=UserCountry&apiAction=getCountry" . "&idSite=" . $idSite . "&period=" . $period . "&date=" . $date . "&token_auth=" . $token_auth . "&segment=" . Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('segment', '')) . "&filter_limit=-1";
     // definition of the color scale
     $view->hueMin = 218;
     $view->hueMax = 216;
     $view->satMin = "0.285";
     $view->satMax = "0.9";
     $view->lgtMin = ".97";
     $view->lgtMax = ".44";
     $request = new Piwik_API_Request('method=API.getMetadata&format=PHP' . '&apiModule=UserCountry&apiAction=getCountry' . '&idSite=' . $idSite . '&period=' . $period . '&date=' . $date . '&token_auth=' . $token_auth . '&filter_limit=-1');
     $metaData = $request->process();
     $metrics = array();
     foreach ($metaData[0]['metrics'] as $id => $val) {
         if (Piwik_Common::getRequestVar('period') == 'day' || $id != 'nb_uniq_visitors') {
             $metrics[] = array($id, $val);
         }
     }
     foreach ($metaData[0]['processedMetrics'] as $id => $val) {
         $metrics[] = array($id, $val);
     }
     $view->metrics = $metrics;
     $view->defaultMetric = 'nb_visits';
     echo $view->render();
 }
Beispiel #4
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;
 }
Beispiel #5
0
 /**
  * Returns the list of all URLs registered for the given idSite (main_url + alias URLs).
  * 
  * @exception if the website ID doesn't exist or the user doesn't have access to it
  * @return array list of URLs
  */
 public static function getSiteUrlsFromId($idSite)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $site = self::getSiteFromId($idSite);
     $urls = self::getAliasSiteUrlsFromId($idSite);
     return array_merge(array($site['main_url']), $urls);
 }
Beispiel #6
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;
 }
Beispiel #7
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;
 }
Beispiel #8
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;
	}
Beispiel #9
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;
 }
Beispiel #10
0
 function displayJavascriptCode()
 {
     $idSite = Piwik_Common::getRequestVar('idsite', 1);
     Piwik::checkUserHasViewAccess($idSite);
     $jsTag = Piwik::getJavascriptCode($idSite, Piwik_Url::getCurrentUrlWithoutFileName());
     $view = new Piwik_View('SitesManager/templates/DisplayJavascriptCode.tpl');
     $view->menu = Piwik_GetAdminMenu();
     $view->jsTag = $jsTag;
     echo $view->render();
 }
Beispiel #11
0
 public function getLastVisits($idSite = false, $limit = 10, $minIdVisit = false)
 {
     if (is_null($idSite)) {
         Piwik::checkUserIsSuperUser();
     } else {
         Piwik::checkUserHasViewAccess($idSite);
     }
     $visitorDetails = self::loadLastVisitorDetailsFromDatabase(null, $idSite, $limit, $minIdVisit);
     $table = self::getCleanedVisitorsFromDetails($visitorDetails);
     return $table;
 }
Beispiel #12
0
	function displayJavascriptCode()
	{
		$idSite = Piwik_Common::getRequestVar('idsite', 1);
		Piwik::checkUserHasViewAccess($idSite);
		$jsTag = Piwik::getJavascriptCode($idSite, Piwik_Url::getCurrentUrlWithoutFileName());
		$view = Piwik_View::factory('DisplayJavascriptCode');
		$this->setGeneralVariablesView($view);
		$view->menu = Piwik_GetAdminMenu();
		$view->jsTag = $jsTag;
		echo $view->render();
	}
Beispiel #13
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;
 }
Beispiel #14
0
 /**
  * Displays the admin UI page showing all tracking tags
  * @return unknown_type
  */
 function displayJavascriptCode()
 {
     $idSite = Piwik_Common::getRequestVar('idSite');
     Piwik::checkUserHasViewAccess($idSite);
     $jsTag = Piwik::getJavascriptCode($idSite, Piwik_Url::getCurrentUrlWithoutFileName());
     $view = Piwik_View::factory('Tracking');
     $this->setBasicVariablesView($view);
     $view->menu = Piwik_GetAdminMenu();
     $view->idSite = $idSite;
     $site = new Piwik_Site($idSite);
     $view->displaySiteName = $site->getName();
     $view->jsTag = $jsTag;
     echo $view->render();
 }
Beispiel #15
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;
 }
Beispiel #16
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;
 }
Beispiel #17
0
    /** Get latest link referrers
     * @return Piwik_DataTable */
    public function getLatestLinks($idSite, $period, $date, $onlyNew = false, $type = false)
    {
        Piwik::checkUserHasViewAccess($idSite);
        $group = array();
        $onlyNewSql = '';
        if ($onlyNew) {
            $onlyNewSql = 'HAVING `' . Piwik_LatestReferrers::OCCURRENCES . '` = 1';
        } else {
            $group[] = 'visit.referer_name';
            $group[] = 'visit.visit_entry_idaction_url';
        }
        if (!$type) {
            $type = Piwik_Common::REFERER_TYPE_WEBSITE;
        }
        if ($type == Piwik_Common::REFERER_TYPE_WEBSITE) {
            $group[] = 'visit.referer_url';
            $select = 'visit.referer_url AS `' . Piwik_LatestReferrers::REFERRER_URL . '`';
        } else {
            $group[] = 'visit.referer_keyword';
            $select = 'visit.referer_keyword AS `' . Piwik_LatestReferrers::REFERRER_KEYWORD . '`';
        }
        $sql = '
			SELECT
				visit.referer_name AS `' . Piwik_LatestReferrers::REFERRER . '`,
				visit.visit_entry_idaction_url AS `' . Piwik_LatestReferrers::ENTRY_URL . '`,
				action.name AS `' . Piwik_LatestReferrers::ENTRY_URL . '`,
				COUNT(idvisit) AS `' . Piwik_LatestReferrers::OCCURRENCES . '`,
				MAX(visit.visit_first_action_time) AS `' . Piwik_LatestReferrers::TIME . '`,
				' . $select . '
			FROM
				' . Piwik_Common::prefixTable('log_visit') . ' AS visit
			LEFT JOIN
				' . Piwik_Common::prefixTable('log_action') . ' AS action
				ON visit.visit_entry_idaction_url = action.idaction
			WHERE
				visit.idsite = ' . intval($idSite) . ' AND
				visit.referer_type = ' . intval($type) . '
			GROUP BY
				' . implode(', ', $group) . '
			' . $onlyNewSql . '
			ORDER BY
				`' . Piwik_LatestReferrers::TIME . '` DESC
			LIMIT
				0, 20
		';
        return $this->buildDataTableFromSql($sql);
    }
Beispiel #18
0
 /**
  * This method combines various reports (both from this and from other plugins) and
  * returns a complete report. The report is used in the Transitions API to load all
  * data at once.
  */
 public function getFullReport($pageUrl, $idSite, $period, $date, $segment = false, $limitBeforeGrouping = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $pageUrl = Piwik_Common::unsanitizeInputValue($pageUrl);
     $report = array();
     $this->addMainPageMetricsToReport($report, $pageUrl, $idSite, $period, $date, $segment);
     $this->addLiveTransitionsDataToReport($report, $pageUrl, $idSite, $period, $date, $segment, $limitBeforeGrouping);
     // replace column names in the data tables
     $columnNames = array('label' => 'url', Piwik_Archive::INDEX_NB_ACTIONS => 'referrals');
     $reportNames = array('previousPages', 'followingPages', 'outlinks', 'downloads');
     foreach ($reportNames as $reportName) {
         if (isset($report[$reportName])) {
             $report[$reportName]->filter('ReplaceColumnNames', array($columnNames));
         }
     }
     return $report;
 }
Beispiel #19
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;
 }
Beispiel #20
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;
 }
Beispiel #21
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;
 }
Beispiel #22
0
 public function getExperiments($idSite)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $experiment_table = Piwik_Common::prefixTable('experiment');
     $experiment_page_table = Piwik_Common::prefixTable('experiment_page');
     $goal_table = Piwik_Common::prefixTable('goal');
     $experiments = Piwik_FetchAll("SELECT " . $experiment_table . ".*, " . $goal_table . ".name as goal_name, " . $goal_table . ".idgoal\n\t\t\t\t\t\t\t\t   FROM   " . $experiment_table . ", " . $goal_table . " \n\t\t\t\t\t\t\t\t   WHERE  " . $experiment_table . ".idsite = ?\n\t\t\t\t\t\t\t\t   AND    " . $experiment_table . ".idgoal = " . $goal_table . ".idgoal\n\t\t\t\t\t\t\t\t   AND    " . $experiment_table . ".deleted = 0", array($idSite));
     $experimentsById = array();
     foreach ($experiments as &$experiment) {
         $experiment_pages = Piwik_FetchAll("SELECT *\n  \t\t\t\t\t\t\t\t                    \t FROM   " . $experiment_page_table . "\n  \t\t\t\t\t\t\t\t\t\t\t                 WHERE  idsite = ?\n  \t\t\t\t\t\t\t\t\t\t\t                 AND idexperiment = ?\n  \t\t\t\t\t\t\t\t\t\t\t                 AND deleted = 0", array($idSite, $experiment['idexperiment']));
         $experiment['variation_pages'] = array();
         foreach ($experiment_pages as $experiment_page) {
             if ($experiment_page['original'] == 1) {
                 $experiment['original_page'] = $experiment_page;
             } else {
                 $experiment['variation_pages'][] = $experiment_page;
             }
         }
         $experimentsById[$experiment['idexperiment']] = $experiment;
     }
     return $experimentsById;
 }
    function getKeywordsForPage()
    {
        Piwik::checkUserHasViewAccess($this->idSite);
        $requestUrl = '&date=previous1' . '&period=week' . '&idSite=' . $this->idSite;
        $topPageUrlRequest = $requestUrl . '&method=Actions.getPageUrls' . '&filter_limit=50' . '&format=original';
        $request = new Piwik_API_Request($topPageUrlRequest);
        $request = $request->process();
        $tables = $request->getArray();
        $topPageUrls = $tables[key($tables)];
        $topPageUrls = $topPageUrls->getRowsMetadata('url');
        $topPageUrl = current(array_values($topPageUrls));
        if (empty($topPageUrl)) {
            $topPageUrl = $this->site->getMainUrl();
        }
        $url = $topPageUrl;
        // HTML
        $api = Piwik_Url::getCurrentUrlWithoutFileName() . '?module=API&method=Referers.getKeywordsForPageUrl' . '&format=php' . '&filter_limit=10' . '&token_auth=' . Piwik::getCurrentUserTokenAuth();
        $api .= $requestUrl;
        $code = '
// This function will call the API to get best keyword for current URL.
// Then it writes the list of best keywords in a HTML list
function DisplayTopKeywords($url = "")
{
	// Do not spend more than 1 second fetching the data
	@ini_set("default_socket_timeout", $timeout = 1);
	// Get the Keywords data
	$url = empty($url) ? "http://". $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] : $url;
	$api = "' . $api . '&url=" . urlencode($url);
	$keywords = @unserialize(file_get_contents($api));
	if($keywords === false || isset($keywords["result"])) {
		// DEBUG ONLY: uncomment for troubleshooting an empty output (the URL output reveals the token_auth)
		// echo "Error while fetching the <a href=\'$api\'>Top Keywords from Piwik</a>";
		return;
	}

	// Display the list in HTML
	$output = "<h2>Top Keywords for <a href=\'$url\'>$url</a></h2><ul>";
	foreach($keywords as $keyword) {
		$output .= "<li>". $keyword[0]. "</li>";
	}
	if(empty($keywords)) { $output .= "Nothing yet..."; }
	$output .= "</ul>";
	echo $output;
}
';
        $jsonRequest = str_replace('format=php', 'format=json', $api);
        echo "<p>This widget is designed to work in your website directly.\n\t\tThis widget makes it easy to use Piwik to <i>automatically display the list of Top Keywords</i>, for each of your website Page URLs.</p>\n\t\t<p>\n\t\t<b>Example API URL</b> - For example if you would like to get the top 10 keywords, used last week, to land on the page <a target='_blank' href='{$topPageUrl}'>{$topPageUrl}</a>,\n\t\tin format JSON: you would dynamically fetch the data using <a target='_blank' href='{$jsonRequest}&url=" . urlencode($topPageUrl) . "'>this API request URL</a>. Make sure you encode the 'url' parameter in the URL.</p>\n\t\t\n\t\t<p><b>PHP Function ready to use!</b> - If you use PHP on your website, we have prepared a small code snippet that you can copy paste in your Website PHP files. You can then simply call the function <code>DisplayTopKeywords();</code> anywhere in your template, at the bottom of the content or in your blog sidebar.\n\t\tIf you run this code in your page {$topPageUrl}, it would output the following:";
        echo "<div style='width:400px;margin-left:20px;padding:10px;border:1px solid black;'>";
        function DisplayTopKeywords($url = "", $api)
        {
            // Do not spend more than 1 second fetching the data
            @ini_set("default_socket_timeout", $timeout = 1);
            // Get the Keywords data
            $url = empty($url) ? "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] : $url;
            $api = $api . "&url=" . urlencode($url);
            $keywords = @unserialize(file_get_contents($api));
            if ($keywords === false || isset($keywords["result"])) {
                // DEBUG ONLY: uncomment for troubleshooting an empty output (the URL output reveals the token_auth)
                //echo "Error while fetching the <a href=\'".$api."\'>Top Keywords from Piwik</a>";
                return;
            }
            // Display the list in HTML
            $output = "<h2>Top Keywords for <a href=\\'{$url}\\'>{$url}</a></h2><ul>";
            foreach ($keywords as $keyword) {
                $output .= "<li>" . $keyword[0] . "</li>";
            }
            if (empty($keywords)) {
                $output .= "Nothing yet...";
            }
            $output .= "</ul>";
            echo $output;
        }
        DisplayTopKeywords($topPageUrl, $api);
        echo "</div><br/>\n\t\t<p>Here is the PHP function that you can paste in your pages:</P>\n\t\t<textarea cols=60 rows=8>&lt;?php\n" . htmlspecialchars($code) . "\n DisplayTopKeywords();</textarea>\n\t\t";
        echo "\n\t\t<p><b>Notes</b>: You can for example edit the code to to make the Top search keywords link to your Website search result pages.\n\t\t<br/>On medium to large traffic websites, we recommend to cache this data, as to minimize the performance impact of calling the Piwik API on each page view.\n\t\t</p>\n\t\t";
    }
Beispiel #24
0
 /**
  * Returns the list of reports matching the passed parameters
  * 
  * @param int $idSite If specified, will filter reports that belong to a specific idsite
  * @param string $period If specified, will filter reports that are scheduled for this period (day,week,month)
  * @param int $idReport If specified, will filter the report that has the given idReport 
  * @return array
  * @throws Exception if $idReport was specified but the report wasn't found
  */
 public function getReports($idSite = false, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = false)
 {
     Piwik::checkUserIsNotAnonymous();
     $cacheKey = (int) $idSite . '.' . (string) $period . '.' . (int) $idReport . '.' . (int) $ifSuperUserReturnOnlySuperUserReports;
     if (isset(self::$cache[$cacheKey])) {
         return self::$cache[$cacheKey];
     }
     $sqlWhere = '';
     $bind = array();
     // Super user gets all reports back, other users only their own
     if (!Piwik::isUserIsSuperUser() || $ifSuperUserReturnOnlySuperUserReports) {
         $sqlWhere .= "AND login = ?";
         $bind[] = Piwik::getCurrentUserLogin();
     }
     if (!empty($period)) {
         $this->validateReportPeriod($period);
         $sqlWhere .= " AND period = ? ";
         $bind[] = $period;
     }
     if (!empty($idSite)) {
         Piwik::checkUserHasViewAccess($idSite);
         $sqlWhere .= " AND " . Piwik_Common::prefixTable('site') . ".idsite = ?";
         $bind[] = $idSite;
     }
     if (!empty($idReport)) {
         $sqlWhere .= " AND idreport = ?";
         $bind[] = $idReport;
     }
     // Joining with the site table to work around pre-1.3 where reports could still be linked to a deleted site
     $reports = Piwik_FetchAll("SELECT * \n\t\t\t\t\t\t\t\tFROM " . Piwik_Common::prefixTable('report') . "\n\t\t\t\t\t\t\t\t\tJOIN " . Piwik_Common::prefixTable('site') . "\n\t\t\t\t\t\t\t\t\tUSING (idsite)\n\t\t\t\t\t\t\t\tWHERE deleted = 0\n\t\t\t\t\t\t\t\t\t{$sqlWhere}", $bind);
     // When a specific report was requested and not found, throw an error
     if ($idReport !== false && empty($reports)) {
         throw new Exception("Requested report couldn't be found.");
     }
     foreach ($reports as &$report) {
         // decode report parameters
         $report['parameters'] = Piwik_Common::json_decode($report['parameters'], true);
         // decode report list
         $report['reports'] = Piwik_Common::json_decode($report['reports'], true);
     }
     // static cache
     self::$cache[$cacheKey] = $reports;
     return $reports;
 }
Beispiel #25
0
 /**
  * Triggers a hook to ask plugins for available Reports.
  * Returns metadata information about each report (category, name, dimension, metrics, etc.)
  *
  * @param string $idSites Comma separated list of website Ids
  * @return array
  */
 public function getReportMetadata($idSites = '', $period = false, $date = false)
 {
     $idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites);
     if (!empty($idSites)) {
         Piwik::checkUserHasViewAccess($idSites);
     }
     $parameters = array('idSites' => $idSites, 'period' => $period, 'date' => $date);
     $availableReports = array();
     Piwik_PostEvent('API.getReportMetadata', $availableReports, $parameters);
     foreach ($availableReports as &$availableReport) {
         if (!isset($availableReport['metrics'])) {
             $availableReport['metrics'] = $this->getDefaultMetrics();
         }
         if (!isset($availableReport['processedMetrics'])) {
             $availableReport['processedMetrics'] = $this->getDefaultProcessedMetrics();
         }
         if (!isset($availableReport['metricsDocumentation'])) {
             $availableReport['metricsDocumentation'] = $this->getDefaultMetricsDocumentation();
         }
     }
     // Some plugins need to add custom metrics after all plugins hooked in
     Piwik_PostEvent('API.getReportMetadata.end', $availableReports, $parameters);
     // Oh this is not pretty! Until we have event listeners order parameter...
     Piwik_PostEvent('API.getReportMetadata.end.end', $availableReports, $parameters);
     // Sort results to ensure consistent order
     usort($availableReports, array($this, 'sort'));
     // Add the magic API.get report metadata aggregating all plugins API.get API calls automatically
     $this->addApiGetMetdata($availableReports);
     $knownMetrics = array_merge($this->getDefaultMetrics(), $this->getDefaultProcessedMetrics());
     foreach ($availableReports as &$availableReport) {
         // Ensure all metrics have a translation
         $metrics = $availableReport['metrics'];
         $cleanedMetrics = array();
         foreach ($metrics as $metricId => $metricTranslation) {
             // When simply the column name was given, ie 'metric' => array( 'nb_visits' )
             // $metricTranslation is in this case nb_visits. We look for a known translation.
             if (is_numeric($metricId) && isset($knownMetrics[$metricTranslation])) {
                 $metricId = $metricTranslation;
                 $metricTranslation = $knownMetrics[$metricTranslation];
             }
             $cleanedMetrics[$metricId] = $metricTranslation;
         }
         $availableReport['metrics'] = $cleanedMetrics;
         // Remove array elements that are false (to clean up API output)
         foreach ($availableReport as $attributeName => $attributeValue) {
             if (empty($attributeValue)) {
                 unset($availableReport[$attributeName]);
             }
         }
         // when there are per goal metrics, don't display conversion_rate since it can differ from per goal sum
         if (isset($availableReport['metricsGoal'])) {
             unset($availableReport['processedMetrics']['conversion_rate']);
             unset($availableReport['metricsGoal']['conversion_rate']);
         }
         // Processing a uniqueId for each report,
         // can be used by UIs as a key to match a given report
         $uniqueId = $availableReport['module'] . '_' . $availableReport['action'];
         if (!empty($availableReport['parameters'])) {
             foreach ($availableReport['parameters'] as $key => $value) {
                 $uniqueId .= '_' . $key . '--' . $value;
             }
         }
         $availableReport['uniqueId'] = $uniqueId;
         // Order is used to order reports internally, but not meant to be used outside
         unset($availableReport['order']);
     }
     return $availableReports;
 }
Beispiel #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);
 }
Beispiel #27
0
 public function getNumberOfDistinctCountries($idSite, $period, $date)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     return $archive->getDataTableFromNumeric('UserCountry_distinctCountries');
 }
Beispiel #28
0
 /**
  * Utility method that retrieve an archived DataTable for a specific site, date range,
  * segment and goal. If not goal is specified, this method will retrieve and sum the
  * data for every goal.
  *
  * @param string $recordName The archive entry name.
  * @param int|string $idSite The site(s) to select data for.
  * @param string $period The period type.
  * @param string $date The date type.
  * @param string $segment The segment.
  * @param int|bool $idGoal The id of the goal to get data for. If this is set to false,
  *                         data for every goal that belongs to $idSite is returned.
  */
 protected function getGoalSpecificDataTable($recordName, $idSite, $period, $date, $segment, $idGoal)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date, $segment);
     // check for the special goal ids
     $realGoalId = $idGoal != true ? false : self::convertSpecialGoalIds($idGoal);
     // get the data table
     $dataTable = $archive->getDataTable(Piwik_Goals::getRecordName($recordName, $realGoalId), $idSubtable = null);
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
Beispiel #29
0
 public function get($idSite, $period, $date, $idFunnel = false, $columns = array())
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Piwik_Archive::build($idSite, $period, $date);
     if (!empty($columns)) {
         $toFetch = $columns;
     } else {
         $toFetch = array();
         $funnels = $this->getFunnels($idSite);
         $stepNumericColumnNames = array('nb_entry', 'nb_exit', 'nb_actions', 'nb_next_step_actions', 'percent_next_step_actions');
         foreach ($stepNumericColumnNames as $columnName) {
             if (!empty($idFunnel)) {
                 $funnel = $funnels[$idFunnel];
                 foreach ($funnel['steps'] as $step) {
                     $toFetch[] = Piwik_Funnels::getRecordName($columnName, $idFunnel, $step['idstep']);
                 }
             }
         }
         $funnelColumnNames = array('nb_actions', 'conversion_rate');
         foreach ($funnelColumnNames as $columnName) {
             if (!empty($idFunnel)) {
                 $funnel = $funnels[$idFunnel];
                 $toFetch[] = Piwik_Funnels::getRecordName($columnName, $idFunnel, false);
             }
         }
     }
     $dataTable = $archive->getDataTableFromNumeric($toFetch);
     return $dataTable;
 }
Beispiel #30
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;
 }