Пример #1
0
 protected function getNumeric($idSite, $period, $date, $segment, $toFetch)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTableFromNumeric($toFetch);
     return $dataTable;
 }
Пример #2
0
 /**
  * @param bool $standalone When set to true, the Top controls will be hidden to provide better full screen view
  * @param bool $fetch
  * @param bool|string $segmentOverride
  *
  * @return string
  */
 public function realtimeMap($standalone = false, $fetch = false, $segmentOverride = false)
 {
     $this->checkUserCountryPluginEnabled();
     $idSite = Common::getRequestVar('idSite', 1, 'int');
     Piwik::checkUserHasViewAccess($idSite);
     $token_auth = Piwik::getCurrentUserTokenAuth();
     $view = new View('@UserCountryMap/realtimeMap');
     $view->mapIsStandaloneNotWidget = $standalone;
     $view->metrics = $this->getMetrics($idSite, 'range', self::REAL_TIME_WINDOW, $token_auth);
     $view->defaultMetric = 'nb_visits';
     $liveRefreshAfterMs = (int) Config::getInstance()->General['live_widget_refresh_after_seconds'] * 1000;
     $goals = APIGoals::getInstance()->getGoals($idSite);
     $site = new Site($idSite);
     $hasGoals = !empty($goals) || $site->isEcommerceEnabled();
     // maximum number of visits to be displayed in the map
     $maxVisits = Common::getRequestVar('filter_limit', 100, 'int');
     // some translations
     $locale = array('nb_actions' => Piwik::translate('VisitsSummary_NbActionsDescription'), 'local_time' => Piwik::translate('VisitTime_ColumnLocalTime'), 'from' => Piwik::translate('General_FromReferrer'), 'seconds' => Piwik::translate('UserCountryMap_Seconds'), 'seconds_ago' => Piwik::translate('UserCountryMap_SecondsAgo'), 'minutes' => Piwik::translate('UserCountryMap_Minutes'), 'minutes_ago' => Piwik::translate('UserCountryMap_MinutesAgo'), 'hours' => Piwik::translate('UserCountryMap_Hours'), 'hours_ago' => Piwik::translate('UserCountryMap_HoursAgo'), 'days_ago' => Piwik::translate('UserCountryMap_DaysAgo'), 'actions' => Piwik::translate('VisitsSummary_NbPageviewsDescription'), 'searches' => Piwik::translate('UserCountryMap_Searches'), 'goal_conversions' => Piwik::translate('UserCountryMap_GoalConversions'));
     $segment = $segmentOverride ?: Request::getRawSegmentFromRequest() ?: '';
     $params = array('period' => 'range', 'idSite' => $idSite, 'segment' => $segment, 'token_auth' => $token_auth);
     $realtimeWindow = Common::getRequestVar('realtimeWindow', self::REAL_TIME_WINDOW, 'string');
     if ($realtimeWindow != 'false') {
         // handle special value
         $params['date'] = $realtimeWindow;
     }
     $reqParams = $this->getEnrichedRequest($params, $encode = false);
     $view->config = array('metrics' => array(), 'svgBasePath' => $view->piwikUrl . 'plugins/UserCountryMap/svg/', 'liveRefreshAfterMs' => $liveRefreshAfterMs, '_' => $locale, 'reqParams' => $reqParams, 'siteHasGoals' => $hasGoals, 'maxVisits' => $maxVisits, 'changeVisitAlpha' => Common::getRequestVar('changeVisitAlpha', true, 'int'), 'removeOldVisits' => Common::getRequestVar('removeOldVisits', true, 'int'), 'showFooterMessage' => Common::getRequestVar('showFooterMessage', true, 'int'), 'showDateTime' => Common::getRequestVar('showDateTime', true, 'int'), 'doNotRefreshVisits' => Common::getRequestVar('doNotRefreshVisits', false, 'int'), 'enableAnimation' => Common::getRequestVar('enableAnimation', true, 'int'), 'forceNowValue' => Common::getRequestVar('forceNowValue', false, 'int'));
     return $view->render();
 }
Пример #3
0
 /**
  * Displays the admin UI page showing all tracking tags
  * @return string
  */
 function displayJavascriptCode()
 {
     $idSite = Common::getRequestVar('idSite');
     Piwik::checkUserHasViewAccess($idSite);
     $jsTag = Piwik::getJavascriptCode($idSite, SettingsPiwik::getPiwikUrl());
     $site = new Site($idSite);
     return $this->renderTemplate('displayJavascriptCode', array('idSite' => $idSite, 'displaySiteName' => $site->getName(), 'jsTag' => $jsTag));
 }
Пример #4
0
 private function getDataTable($name, $idSite, $period, $date, $segment, $expanded, $idSubtable)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $recordName = Dimensions::getRecordNameForAction($name);
     $dataTable = Archive::getDataTableFromArchive($recordName, $idSite, $period, $date, $segment, $expanded, $idSubtable);
     $this->filterDataTable($dataTable);
     return $dataTable;
 }
Пример #5
0
 protected function getDataTable($name, $idSite, $period, $date, $segment, $column = Metrics::INDEX_NB_VISITS)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable($name);
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
Пример #6
0
 /**
  * @param string $name
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param string $segment
  * @return DataTable
  */
 protected function getDataTable($name, $idSite, $period, $date, $segment)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable($name);
     $dataTable->queueFilter('ReplaceColumnNames');
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Пример #7
0
 /**
  * Get a report of all User Ids.
  *
  * @param int $idSite
  *
  * @param string  $period
  * @param int  $date
  * @param string|bool  $segment
  *
  * @return DataTable
  */
 public function getUsers($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable(Archiver::USERID_ARCHIVE_RECORD);
     $dataTable->queueFilter('ReplaceColumnNames');
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Пример #8
0
 /**
  * Return the number of visitors that visited every site in the given list for the
  * given date range. Includes the number of visitors that visited at least one site
  * and the number that visited every site.
  *
  * This data is calculated on demand, and for very large tables can take a long time
  * to run.
  *
  * See {@link Model\DistinctMetricsAggregator} for more information.
  *
  * @param string $idSite comma separated list of site IDs, ie, `"1,2,3"`
  * @param string $period
  * @param string $date
  * @return array Metrics **nb_total_visitors** and **nb_shared_visitors**.
  * @throws Exception if $idSite references zero sites or just one site.
  */
 public function getCommonVisitors($idSite, $period, $date, $segment = false)
 {
     if (empty($idSite)) {
         throw new Exception("No sites to get common visitors for.");
     }
     $idSites = Site::getIdSitesFromIdSitesString($idSite);
     Piwik::checkUserHasViewAccess($idSites);
     $segment = new Segment($segment, $idSites);
     $period = PeriodFactory::build($period, $date);
     return $this->distinctMetricsAggregator->getCommonVisitorCount($idSites, $period->getDateStart(), $period->getDateEnd(), $segment);
 }
Пример #9
0
 public function getProvider($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $dataTable = $archive->getDataTable(Archiver::PROVIDER_RECORD_NAME);
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'url', __NAMESPACE__ . '\\getHostnameUrl'));
     $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\\getPrettyProviderName'));
     $dataTable->queueFilter('ReplaceColumnNames');
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Пример #10
0
 /**
  * This method renders a widget as defined in "init()". It's on you how to generate the content of the
  * widget. As long as you return a string everything is fine. You can use for instance a "Piwik\View" to render a
  * twig template. In such a case don't forget to create a twig template (eg. myViewTemplate.twig) in the
  * "templates" directory of your plugin.
  *
  * @return string
  */
 public function spaceSummary()
 {
     // Make sure there is an idSite URL parameter
     $idSite = Common::getRequestVar('idSite', null, 'int');
     // Make sure the user has at least view access for the specified site. This is useful if you want to display data that is related to the specified site.
     Piwik::checkUserHasViewAccess($idSite);
     $space_id = Common::getRequestVar('space_id', null, 'int');
     $space_type = Common::getRequestVar('space_type', 'operation', 'string');
     // $view = new View('@HumanitarianResponse/myViewTemplate');
     // return $view->render();
     return $space_id;
 }
Пример #11
0
 public function getAverageVisitTimeData($idSite, $lastMinutes = 30, $lastDays = 30)
 {
     \Piwik\Piwik::checkUserHasViewAccess($idSite);
     $lastMinutes = (int) $lastMinutes;
     $lastDays = (int) $lastDays;
     /* Time is UTC in database. */
     $refNow = Date::factory('now');
     $timeLimit = $refNow->subDay($lastDays)->toString('Y-m-d H:i:s');
     $sql = "SELECT MAX(g.average_time) AS maxtime\n                FROM (\n                  SELECT    AVG(visit_total_time) as average_time\n                  FROM      " . \Piwik\Common::prefixTable("log_visit") . "\n                  WHERE     visit_last_action_time >= ?\n                  AND       idsite = ?\n                  GROUP BY  round(UNIX_TIMESTAMP(visit_last_action_time) / ?)\n        ) g";
     $maxtime = \Piwik\Db::fetchOne($sql, array($timeLimit, $idSite, $lastMinutes * 60));
     $timeLimit = $refNow->subHour($lastMinutes / 60)->toString('Y-m-d H:i:s');
     $sql = "SELECT AVG(visit_total_time)\n                FROM " . \Piwik\Common::prefixTable("log_visit") . "\n                WHERE idsite = ?\n                AND visit_last_action_time >= ?";
     $average_time = \Piwik\Db::fetchOne($sql, array($idSite, $timeLimit));
     return array('maxtime' => (int) $maxtime, 'average_time' => (int) $average_time);
 }
Пример #12
0
 /**
  * Returns the list of metrics (pages, downloads, outlinks)
  *
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param bool|string $segment
  * @param bool|array $columns
  * @return DataTable
  */
 public function get($idSite, $period, $date, $segment = false, $columns = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     $metrics = Archiver::$actionsAggregateMetrics;
     $metrics['Actions_avg_time_generation'] = 'avg_time_generation';
     // 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;
         }
         if (false !== ($avgGenerationTimeRequested = array_search('Actions_avg_time_generation', $columns))) {
             unset($columns[$avgGenerationTimeRequested]);
             $avgGenerationTimeRequested = true;
         }
     } else {
         // get all columns
         unset($metrics['Actions_avg_time_generation']);
         $columns = array_keys($metrics);
         $nameReplace =& $metrics;
         $avgGenerationTimeRequested = true;
     }
     if ($avgGenerationTimeRequested) {
         $tempColumns[] = Archiver::METRIC_SUM_TIME_RECORD_NAME;
         $tempColumns[] = Archiver::METRIC_HITS_TIMED_RECORD_NAME;
         $columns = array_merge($columns, $tempColumns);
         $columns = array_unique($columns);
         $nameReplace[Archiver::METRIC_SUM_TIME_RECORD_NAME] = 'sum_time_generation';
         $nameReplace[Archiver::METRIC_HITS_TIMED_RECORD_NAME] = 'nb_hits_with_time_generation';
     }
     $table = $archive->getDataTableFromNumeric($columns);
     // replace labels (remove Actions_)
     $table->filter('ReplaceColumnNames', array($nameReplace));
     // compute avg generation time
     if ($avgGenerationTimeRequested) {
         $table->filter('ColumnCallbackAddColumnQuotient', array('avg_time_generation', 'sum_time_generation', 'nb_hits_with_time_generation', 3));
         $table->deleteColumns(array('sum_time_generation', 'nb_hits_with_time_generation'));
     }
     return $table;
 }
Пример #13
0
 private function getDataTable($name, $idSite, $period, $date, $segment, $expanded, $idSubtable)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $recordName = Dimensions::getRecordNameForAction($name);
     $dataTable = Archive::getDataTableFromArchive($recordName, $idSite, $period, $date, $segment, $expanded, $idSubtable);
     if (empty($idSubtable)) {
         $dataTable->filter('AddSegmentValue', array(function ($label) {
             if ($label === Archiver::CONTENT_PIECE_NOT_SET) {
                 return false;
             }
             return $label;
         }));
     }
     $this->filterDataTable($dataTable);
     return $dataTable;
 }
Пример #14
0
 /**
  * Returns the list of metrics (pages, downloads, outlinks)
  *
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param bool|string $segment
  * @param bool|array $columns
  * @return DataTable
  */
 public function get($idSite, $period, $date, $segment = false, $columns = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $report = Report::factory("Actions", "get");
     $archive = Archive::build($idSite, $period, $date, $segment);
     $requestedColumns = Piwik::getArrayFromApiParameter($columns);
     $columns = $report->getMetricsRequiredForReport($allColumns = null, $requestedColumns);
     $inDbColumnNames = array_map(function ($value) {
         return 'Actions_' . $value;
     }, $columns);
     $dataTable = $archive->getDataTableFromNumeric($inDbColumnNames);
     $dataTable->deleteColumns(array_diff($requestedColumns, $columns));
     $newNameMapping = array_combine($inDbColumnNames, $columns);
     $dataTable->filter('ReplaceColumnNames', array($newNameMapping));
     $columnsToShow = $requestedColumns ?: $report->getAllMetrics();
     $dataTable->queueFilter('ColumnDelete', array($columnsToRemove = array(), $columnsToShow));
     return $dataTable;
 }
Пример #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
  * @return array
  * @throws Exception
  */
 public function getTransitionsForAction($actionName, $actionType, $idSite, $period, $date, $segment = false, $limitBeforeGrouping = false, $parts = 'all')
 {
     Piwik::checkUserHasViewAccess($idSite);
     // get idaction of the requested action
     $idaction = $this->deriveIdAction($actionName, $actionType);
     if ($idaction < 0) {
         throw new Exception('NoDataForAction');
     }
     // prepare log aggregator
     $segment = new Segment($segment, $idSite);
     $site = new Site($idSite);
     $period = Period\Factory::build($period, $date);
     $params = new ArchiveProcessor\Parameters($site, $period, $segment);
     $logAggregator = new LogAggregator($params);
     // prepare the report
     $report = array('date' => Period\Factory::build($period->getLabel(), $date)->getLocalizedShortString());
     $partsArray = explode(',', $parts);
     if ($parts == 'all' || in_array('internalReferrers', $partsArray)) {
         $this->addInternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
     }
     if ($parts == 'all' || in_array('followingActions', $partsArray)) {
         $includeLoops = $parts != 'all' && !in_array('internalReferrers', $partsArray);
         $this->addFollowingActions($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops);
     }
     if ($parts == 'all' || in_array('externalReferrers', $partsArray)) {
         $this->addExternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
     }
     // derive the number of exits from the other metrics
     if ($parts == 'all') {
         $report['pageMetrics']['exits'] = $report['pageMetrics']['pageviews'] - $this->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(Metrics::INDEX_NB_ACTIONS => 'referrals');
             if ($replaceLabel) {
                 $columnNames[Metrics::INDEX_NB_ACTIONS] = 'referrals';
             }
             $report[$reportName]->filter('ReplaceColumnNames', array($columnNames));
         }
     }
     return $report;
 }
Пример #16
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 bool|string $segment The segment.
  * @throws Exception
  * @return DataTable
  */
 public function getByDayOfWeek($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // metrics to query
     $metrics = Metrics::getVisitsMetricNames();
     unset($metrics[Metrics::INDEX_MAX_ACTIONS]);
     // disabled for multiple dates
     if (Period::isMultiplePeriod($date, $period)) {
         throw new Exception("VisitTime.getByDayOfWeek does not support multiple dates.");
     }
     // get metric data for every day within the supplied period
     $oPeriod = Period\Factory::makePeriodFromQueryParams(Site::getTimezoneFor($idSite), $period, $date);
     $dateRange = $oPeriod->getDateStart()->toString() . ',' . $oPeriod->getDateEnd()->toString();
     $archive = Archive::build($idSite, 'day', $dateRange, $segment);
     // disabled for multiple sites
     if (count($archive->getParams()->getIdSites()) > 1) {
         throw new Exception("VisitTime.getByDayOfWeek does not support multiple sites.");
     }
     $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', __NAMESPACE__ . '\\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 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', __NAMESPACE__ . '\\translateDayOfWeek'));
     // set datatable metadata for period start & finish
     $result->setMetadata('date_start', $oPeriod->getDateStart());
     $result->setMetadata('date_end', $oPeriod->getDateEnd());
     return $result;
 }
Пример #17
0
 /**
  * Fetch a report for the given idDimension. Only reports for active dimensions can be fetched. Requires at least
  * view access.
  *
  * @param int $idDimension
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param bool|false $segment
  * @param bool|false $expanded
  * @param bool|false $flat
  * @param int|null   $idSubtable
  * @return DataTable|DataTable\Map
  * @throws \Exception
  */
 public function getCustomDimension($idDimension, $idSite, $period, $date, $segment = false, $expanded = false, $flat = false, $idSubtable = null)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $dimension = new Dimension($idDimension, $idSite);
     $dimension->checkActive();
     $record = Archiver::buildRecordNameForCustomDimensionId($idDimension);
     $dataTable = Archive::createDataTableFromArchive($record, $idSite, $period, $date, $segment, $expanded, $flat, $idSubtable);
     if (isset($idSubtable) && $dataTable->getRowsCount()) {
         $parentTable = Archive::createDataTableFromArchive($record, $idSite, $period, $date, $segment);
         foreach ($parentTable->getRows() as $row) {
             if ($row->getIdSubDataTable() == $idSubtable) {
                 $parentValue = $row->getColumn('label');
                 $dataTable->queueFilter('Piwik\\Plugins\\CustomDimensions\\DataTable\\Filter\\AddSubtableSegmentMetadata', array($idDimension, $parentValue));
                 break;
             }
         }
     } else {
         $dataTable->queueFilter('Piwik\\Plugins\\CustomDimensions\\DataTable\\Filter\\AddSegmentMetadata', array($idDimension));
     }
     $dataTable->filter('Piwik\\Plugins\\CustomDimensions\\DataTable\\Filter\\RemoveUserIfNeeded', array($idSite, $period, $date));
     return $dataTable;
 }
Пример #18
0
    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 Request($topPageUrlRequest);
        $request = $request->process();
        /** @var $request Map */
        $tables = $request->getDataTables();
        $topPageUrl = false;
        $first = key($tables);
        if (!empty($first)) {
            $topPageUrls = $tables[$first];
            $topPageUrls = $topPageUrls->getRowsMetadata('url');
            $tmpTopPageUrls = array_values($topPageUrls);
            $topPageUrl = current($tmpTopPageUrls);
        }
        if (empty($topPageUrl)) {
            $topPageUrl = $this->site->getMainUrl();
        }
        $url = $topPageUrl;
        // HTML
        $api = SettingsPiwik::getPiwikUrl() . '?module=API&method=Referrers.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
	$url = htmlspecialchars($url, ENT_QUOTES);
	$output = "<h2>Top Keywords for <a href=\'$url\'>$url</a></h2><ul>";
	foreach($keywords as $keyword) {
		$output .= "<li>". $keyword . "</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\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
            $url = htmlspecialchars($url, ENT_QUOTES);
            $output = "<h2>Top Keywords for <a href=\\'{$url}\\'>{$url}</a></h2><ul>";
            foreach ($keywords as $keyword) {
                $output .= "<li>" . $keyword . "</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><strong>Notes</strong>: 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";
    }
Пример #19
0
 public function getNumberOfDistinctCountries($idSite, $period, $date, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     return $archive->getDataTableFromNumeric(Archiver::DISTINCT_COUNTRIES_METRIC);
 }
Пример #20
0
 protected function getDataTable($name, $idSite, $period, $date, $segment, $expanded = false, $idSubtable = null, $secondaryDimension = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $this->checkSecondaryDimension($name, $secondaryDimension);
     $recordName = $this->getRecordNameForAction($name, $secondaryDimension);
     $dataTable = Archive::getDataTableFromArchive($recordName, $idSite, $period, $date, $segment, $expanded, $idSubtable);
     $this->filterDataTable($dataTable);
     return $dataTable;
 }
Пример #21
0
 /**
  * Same as getAll but for a unique Piwik site
  * @see Piwik\Plugins\MultiSites\API::getAll()
  *
  * @param int $idSite Id of the Piwik site
  * @param string $period The period type to get data for.
  * @param string $date The date(s) to get data for.
  * @param bool|string $segment The segments to get data for.
  * @param bool|string $_restrictSitesToLogin Hack used to enforce we restrict the returned data to the specified username
  *                                        Only used when a scheduled task is running
  * @param bool|string $enhanced When true, return additional goal & ecommerce metrics
  * @return DataTable
  */
 public function getOne($idSite, $period, $date, $segment = false, $_restrictSitesToLogin = false, $enhanced = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $sites = $this->getSiteFromId($idSite);
     return $this->buildDataTable($sites, $period, $date, $segment, $_restrictSitesToLogin, $enhanced, $multipleWebsitesRequested = false, $showColumns = array());
 }
Пример #22
0
 /**
  * Helper function that creates an Archive instance and queries for report data using
  * query parameter data. API methods can use this method to reduce code redundancy.
  * 
  * @param string $name The name of the report to return.
  * @param int|string|array $idSite @see {@link build()}
  * @param string $period @see {@link build()}
  * @param string $date @see {@link build()}
  * @param string $segment @see {@link build()}
  * @param bool $expanded If true, loads all subtables. See {@link getDataTableExpanded()}
  * @param int|null $idSubtable See {@link getDataTableExpanded()}
  * @param bool $skipAggregationOfSubTables Whether or not we should skip the aggregation of all sub-tables and only aggregate parent DataTable.
  * @param int|null $depth See {@link getDataTableExpanded()}
  * @return DataTable|DataTable\Map See {@link getDataTable()} and
  *                                 {@link getDataTableExpanded()} for more
  *                                 information
  */
 public static function getDataTableFromArchive($name, $idSite, $period, $date, $segment, $expanded, $idSubtable = null, $skipAggregationOfSubTables = false, $depth = null)
 {
     Piwik::checkUserHasViewAccess($idSite);
     if ($skipAggregationOfSubTables && ($expanded || $idSubtable)) {
         throw new \Exception("Not expected to skipAggregationOfSubTables when expanded=1 or idSubtable is set.");
     }
     $archive = Archive::build($idSite, $period, $date, $segment, $_restrictSitesToLogin = false, $skipAggregationOfSubTables);
     if ($idSubtable === false) {
         $idSubtable = null;
     }
     if ($expanded) {
         $dataTable = $archive->getDataTableExpanded($name, $idSubtable, $depth);
     } else {
         $dataTable = $archive->getDataTable($name, $idSubtable);
     }
     $dataTable->queueFilter('ReplaceSummaryRowLabel');
     return $dataTable;
 }
Пример #23
0
 private function getNumeric($name, $idSite, $period, $date, $segment)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = Archive::build($idSite, $period, $date, $segment);
     return $archive->getDataTableFromNumeric($name);
 }
Пример #24
0
 /**
  * This method is called when the JS from startOverlaySession() detects that the target domain
  * is not configured for the current site.
  */
 public function showErrorWrongDomain()
 {
     $idSite = Common::getRequestVar('idSite', 0, 'int');
     Piwik::checkUserHasViewAccess($idSite);
     $url = Common::getRequestVar('url', '');
     $url = Common::unsanitizeInputValue($url);
     $message = Piwik::translate('Overlay_RedirectUrlError', array($url, "\n"));
     $message = nl2br(htmlentities($message));
     $view = new View('@Overlay/showErrorWrongDomain');
     $this->addCustomLogoInfo($view);
     $view->message = $message;
     if (Piwik::isUserHasAdminAccess($idSite)) {
         // TODO use $idSite to link to the correct row. This is tricky because the #rowX ids don't match
         // the site ids when sites have been deleted.
         $url = 'index.php?module=SitesManager&action=index';
         $troubleshoot = htmlentities(Piwik::translate('Overlay_RedirectUrlErrorAdmin'));
         $troubleshoot = sprintf($troubleshoot, '<a href="' . $url . '" target="_top">', '</a>');
         $view->troubleshoot = $troubleshoot;
     } else {
         $view->troubleshoot = htmlentities(Piwik::translate('Overlay_RedirectUrlErrorUser'));
     }
     return $view->render();
 }
Пример #25
0
 /**
  * Returns the list of all URLs registered for the given idSite (main_url + alias URLs).
  *
  * @throws Exception if the website ID doesn't exist or the user doesn't have access to it
  * @param int $idSite
  * @return array list of URLs
  */
 public function getSiteUrlsFromId($idSite)
 {
     Piwik::checkUserHasViewAccess($idSite);
     return $this->getModel()->getSiteUrlsFromId($idSite);
 }
Пример #26
0
 /**
  * Returns the visitor ID of the most recent visit.
  *
  * @param int $idSite
  * @param bool|string $segment
  * @return string
  */
 public function getMostRecentVisitorId($idSite, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1);
     if (0 >= $dataTable->getRowsCount()) {
         return false;
     }
     $visitorFactory = new VisitorFactory();
     $visitDetails = $dataTable->getFirstRow()->getColumns();
     $visitor = $visitorFactory->create($visitDetails);
     return $visitor->getVisitorId();
 }
Пример #27
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.
  * @return false|DataTable
  */
 protected function getGoalSpecificDataTable($recordName, $idSite, $period, $date, $segment, $idGoal)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $archive = 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(Archiver::getRecordName($recordName, $realGoalId), $idSubtable = null);
     $dataTable->queueFilter('ReplaceColumnNames');
     return $dataTable;
 }
Пример #28
0
 /**
  * Returns the list of all URLs registered for the given idSite (main_url + alias URLs).
  *
  * @throws Exception if the website ID doesn't exist or the user doesn't have access to it
  * @param int $idSite
  * @return array list of URLs
  */
 public function getSiteUrlsFromId($idSite)
 {
     Piwik::checkUserHasViewAccess($idSite);
     $site = new Site($idSite);
     $urls = $this->getAliasSiteUrlsFromId($idSite);
     return array_merge(array($site->getMainUrl()), $urls);
 }
Пример #29
0
 /**
  * Returns the visitor ID of the most recent visit.
  *
  * @param int $idSite
  * @param bool|string $segment
  * @return string
  */
 public function getMostRecentVisitorId($idSite, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // for faster performance search for a visitor within the last 7 days first
     $minTimestamp = Date::now()->subDay(7)->getTimestamp();
     $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp);
     if (0 >= $dataTable->getRowsCount()) {
         $minTimestamp = Date::now()->subYear(1)->getTimestamp();
         // no visitor found in last 7 days, look further back for up to 1 year. This query will be slower
         $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp);
     }
     if (0 >= $dataTable->getRowsCount()) {
         // no visitor found in last year, look over all logs. This query might be quite slow
         $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1);
     }
     if (0 >= $dataTable->getRowsCount()) {
         return false;
     }
     $visitorFactory = new VisitorFactory();
     $visitDetails = $dataTable->getFirstRow()->getColumns();
     $visitor = $visitorFactory->create($visitDetails);
     return $visitor->getVisitorId();
 }
Пример #30
0
 /** Do cookie authentication. This way, the token can remain secret. */
 private function authenticate($idSite)
 {
     /**
      * Triggered immediately before the user is authenticated.
      *
      * This event can be used by plugins that provide their own authentication mechanism
      * to make that mechanism available. Subscribers should set the `'Piwik\Auth'` object in
      * the container to an object that implements the {@link Piwik\Auth} interface.
      *
      * **Example**
      *
      *     use Piwik\Container\StaticContainer;
      *
      *     public function initAuthenticationObject($activateCookieAuth)
      *     {
      *         StaticContainer::getContainer()->set('Piwik\Auth', new LDAPAuth($activateCookieAuth));
      *     }
      *
      * @param bool $activateCookieAuth Whether authentication based on `$_COOKIE` values should
      *                                        be allowed.
      */
     Piwik::postEvent('Request.initAuthenticationObject', array($activateCookieAuth = true));
     $auth = StaticContainer::get('Piwik\\Auth');
     $success = Access::getInstance()->reloadAccess($auth);
     if (!$success) {
         throw new Exception('Authentication failed');
     }
     Piwik::checkUserHasViewAccess($idSite);
 }