/** * @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(); }
public function widget() { $view = new View('@Live/index'); $view->idSite = $this->idSite; $view = $this->setCounters($view); $view->liveRefreshAfterMs = (int) Config::getInstance()->General['live_widget_refresh_after_seconds'] * 1000; $view->visitors = $this->getLastVisitsStart($fetchPlease = true); $view->liveTokenAuth = Piwik::getCurrentUserTokenAuth(); return $this->render($view); }
/** * Returns a HTML page containing help for all the successfully loaded APIs. * For each module it will return a mini help with the method names, parameters to give, * links to get the result in Xml/Csv/etc * * @param bool $outputExampleUrls * @param string $prefixUrls * @return string */ public function getAllInterfaceString($outputExampleUrls = true, $prefixUrls = '') { if (!empty($prefixUrls)) { $prefixUrls = 'http://demo.piwik.org/'; } $str = $toc = ''; $token_auth = "&token_auth=" . Piwik::getCurrentUserTokenAuth(); $parametersToSet = array('idSite' => Common::getRequestVar('idSite', 1, 'int'), 'period' => Common::getRequestVar('period', 'day', 'string'), 'date' => Common::getRequestVar('date', 'today', 'string')); foreach (Proxy::getInstance()->getMetadata() as $class => $info) { $moduleName = Proxy::getInstance()->getModuleNameFromClassName($class); if (in_array($moduleName, $this->modulesToHide)) { continue; } $toc .= "<a href='#{$moduleName}'>{$moduleName}</a><br/>"; $str .= "\n<a name='{$moduleName}' id='{$moduleName}'></a><h2>Module " . $moduleName . "</h2>"; $str .= "<div class='apiDescription'> " . $info['__documentation'] . " </div>"; foreach ($info as $methodName => $infoMethod) { if ($methodName == '__documentation') { continue; } $params = $this->getParametersString($class, $methodName); $str .= "\n <div class='apiMethod'>- <b>{$moduleName}.{$methodName} </b>" . $params . ""; $str .= '<small>'; if ($outputExampleUrls) { // we prefix all URLs with $prefixUrls // used when we include this output in the Piwik official documentation for example $str .= "<span class=\"example\">"; $exampleUrl = $this->getExampleUrl($class, $methodName, $parametersToSet); if ($exampleUrl !== false) { $lastNUrls = ''; if (preg_match('/(&period)|(&date)/', $exampleUrl)) { $exampleUrlRss1 = $prefixUrls . $this->getExampleUrl($class, $methodName, array('date' => 'last10', 'period' => 'day') + $parametersToSet); $exampleUrlRss2 = $prefixUrls . $this->getExampleUrl($class, $methodName, array('date' => 'last5', 'period' => 'week') + $parametersToSet); $lastNUrls = ",\tRSS of the last <a target=_blank href='{$exampleUrlRss1}&format=rss{$token_auth}&translateColumnNames=1'>10 days</a>"; } $exampleUrl = $prefixUrls . $exampleUrl; $str .= " [ Example in\n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=xml{$token_auth}'>XML</a>,\n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=JSON{$token_auth}'>Json</a>,\n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=Tsv{$token_auth}&translateColumnNames=1'>Tsv (Excel)</a>\n\t\t\t\t\t\t\t\t\t{$lastNUrls}\n\t\t\t\t\t\t\t\t\t]"; } else { $str .= " [ No example available ]"; } $str .= "</span>"; } $str .= '</small>'; $str .= "</div>\n"; } $str .= '<div style="margin:15px;"><a href="#topApiRef">↑ Back to top</a></div>'; } $str = "<h2 id='topApiRef' name='topApiRef'>Quick access to APIs</h2>\n\t\t\t\t{$toc}\n\t\t\t\t{$str}"; return $str; }
public function testAllSizes() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@ImageGraph/testAllSizes'); $this->setGeneralVariablesView($view); $period = Common::getRequestVar('period', 'day', 'string'); $date = Common::getRequestVar('date', 'today', 'string'); $_GET['token_auth'] = Piwik::getCurrentUserTokenAuth(); $availableReports = APIPlugins::getInstance()->getReportMetadata($this->idSite, $period, $date); $view->availableReports = $availableReports; $view->graphTypes = array(''); $view->graphSizes = array(array(null, null), array(460, 150), array(300, 150), array(240, 150), array(800, 150), array(600, 300, $fontSize = 18, 300, 150)); return $view->render(); }
public function oneClickUpdate() { Piwik::checkUserHasSuperUserAccess(); $view = new OneClickDone(Piwik::getCurrentUserTokenAuth()); $useHttps = Common::getRequestVar('https', 1, 'int'); try { $messages = $this->updater->updatePiwik($useHttps); } catch (ArchiveDownloadException $e) { $view->httpsFail = $useHttps; $view->error = $e->getMessage(); $messages = $e->getUpdateLogMessages(); } catch (UpdaterException $e) { $view->error = $e->getMessage(); $messages = $e->getUpdateLogMessages(); } $view->feedbackMessages = $messages; $this->addCustomLogoInfo($view); return $view->render(); }
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><?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"; }
public function oneClickUpdate() { Piwik::checkUserHasSuperUserAccess(); $this->newVersion = $this->checkNewVersionIsAvailableOrDie(); SettingsServer::setMaxExecutionTime(0); $url = self::getLatestZipUrl($this->newVersion); $steps = array(array('oneClick_Download', Piwik::translate('CoreUpdater_DownloadingUpdateFromX', $url)), array('oneClick_Unpack', Piwik::translate('CoreUpdater_UnpackingTheUpdate')), array('oneClick_Verify', Piwik::translate('CoreUpdater_VerifyingUnpackedFiles')), array('oneClick_CreateConfigFileBackup', Piwik::translate('CoreUpdater_CreatingBackupOfConfigurationFile', self::CONFIG_FILE_BACKUP))); $incompatiblePlugins = $this->getIncompatiblePlugins($this->newVersion); if (!empty($incompatiblePlugins)) { $namesToDisable = array(); foreach ($incompatiblePlugins as $incompatiblePlugin) { $namesToDisable[] = $incompatiblePlugin->getPluginName(); } $steps[] = array('oneClick_DisableIncompatiblePlugins', Piwik::translate('CoreUpdater_DisablingIncompatiblePlugins', implode(', ', $namesToDisable))); } $steps[] = array('oneClick_Copy', Piwik::translate('CoreUpdater_InstallingTheLatestVersion')); $steps[] = array('oneClick_Finished', Piwik::translate('CoreUpdater_PiwikUpdatedSuccessfully')); $errorMessage = false; $messages = array(); foreach ($steps as $step) { try { $method = $step[0]; $message = $step[1]; $this->{$method}(); $messages[] = $message; } catch (Exception $e) { $errorMessage = $e->getMessage(); break; } } $view = new OneClickDone(Piwik::getCurrentUserTokenAuth()); $view->coreError = $errorMessage; $view->feedbackMessages = $messages; $this->addCustomLogoInfo($view); return $view->render(); }
/** * Checks that the token_auth in the URL matches the currently logged-in user's token_auth. * * This is a protection against CSRF and should be used in all controller * methods that modify Piwik or any user settings. * * **The token_auth should never appear in the browser's address bar.** * * @throws \Piwik\NoAccessException If the token doesn't match. * @api */ protected function checkTokenInUrl() { $tokenRequest = Common::getRequestVar('token_auth', false); $tokenUser = Piwik::getCurrentUserTokenAuth(); if (empty($tokenRequest) && empty($tokenUser)) { return; // UI tests } if ($tokenRequest !== $tokenUser) { throw new NoAccessException(Piwik::translate('General_ExceptionInvalidToken')); } }
/** * Renders the current view. Also sends the stored 'Content-Type' HTML header. * See {@link setContentType()}. * * @return string Generated template. */ public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentAction = Piwik::getAction(); $this->url = Common::sanitizeInputValue(Url::getCurrentUrl()); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsAnonymous = Piwik::isUserIsAnonymous(); $this->userIsSuperUser = Piwik::hasUserSuperUserAccess(); $this->latest_version_available = UpdateCheck::isNewestVersionAvailable(); $this->disableLink = Common::getRequestVar('disableLink', 0, 'int'); $this->isWidget = Common::getRequestVar('widget', 0, 'int'); $piwikAds = StaticContainer::get('Piwik\\ProfessionalServices\\Advertising'); $this->areAdsForProfessionalServicesEnabled = $piwikAds->areAdsForProfessionalServicesEnabled(); if (Development::isEnabled()) { $cacheBuster = rand(0, 10000); } else { $cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster(); } $this->cacheBuster = $cacheBuster; $this->loginModule = Piwik::getLoginPluginName(); $user = APIUsersManager::getInstance()->getUser($this->userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { Log::debug($e); // can fail, for example at installation (no plugin loaded yet) } ProxyHttp::overrideCacheControlHeaders('no-store'); Common::sendHeader('Content-Type: ' . $this->contentType); // always sending this header, sometimes empty, to ensure that Dashboard embed loads // - when calling sendHeader() multiple times, the last one prevails Common::sendHeader('X-Frame-Options: ' . (string) $this->xFrameOptions); return $this->renderTwigTemplate(); }
public function oneClickUpdate() { Piwik::checkUserIsSuperUser(); $this->newVersion = $this->checkNewVersionIsAvailableOrDie(); SettingsServer::setMaxExecutionTime(0); $url = self::getLatestZipUrl($this->newVersion); $steps = array(array('oneClick_Download', Piwik::translate('CoreUpdater_DownloadingUpdateFromX', $url)), array('oneClick_Unpack', Piwik::translate('CoreUpdater_UnpackingTheUpdate')), array('oneClick_Verify', Piwik::translate('CoreUpdater_VerifyingUnpackedFiles')), array('oneClick_CreateConfigFileBackup', Piwik::translate('CoreUpdater_CreatingBackupOfConfigurationFile', self::CONFIG_FILE_BACKUP)), array('oneClick_Copy', Piwik::translate('CoreUpdater_InstallingTheLatestVersion')), array('oneClick_Finished', Piwik::translate('CoreUpdater_PiwikUpdatedSuccessfully'))); $errorMessage = false; $messages = array(); foreach ($steps as $step) { try { $method = $step[0]; $message = $step[1]; $this->{$method}(); $messages[] = $message; } catch (Exception $e) { $errorMessage = $e->getMessage(); break; } } // this is a magic template to trigger the Piwik_View_Update $view = new OneClickDone(Piwik::getCurrentUserTokenAuth()); $view->coreError = $errorMessage; $view->feedbackMessages = $messages; return $view->render(); }
private function getMethodString($moduleName, $class, $parametersToSet, $outputExampleUrls, $prefixUrls, $methodName) { $str = ''; $token_auth = "&token_auth=" . Piwik::getCurrentUserTokenAuth(); $params = $this->getParametersString($class, $methodName); $str .= "\n <div class='apiMethod'>- <b>{$moduleName}.{$methodName} </b>" . $params . ""; $str .= '<small>'; if ($outputExampleUrls) { // we prefix all URLs with $prefixUrls // used when we include this output in the Piwik official documentation for example $str .= "<span class=\"example\">"; $exampleUrl = $this->getExampleUrl($class, $methodName, $parametersToSet); if ($exampleUrl !== false) { $lastNUrls = ''; if (preg_match('/(&period)|(&date)/', $exampleUrl)) { $exampleUrlRss = $prefixUrls . $this->getExampleUrl($class, $methodName, array('date' => 'last10', 'period' => 'day') + $parametersToSet); $lastNUrls = ",\tRSS of the last <a target='_blank' href='{$exampleUrlRss}&format=rss{$token_auth}&translateColumnNames=1'>10 days</a>"; } $exampleUrl = $prefixUrls . $exampleUrl; $str .= " [ Example in\n\t\t\t\t\t\t\t\t\t<a target='_blank' href='{$exampleUrl}&format=xml{$token_auth}'>XML</a>,\n\t\t\t\t\t\t\t\t\t<a target='_blank' href='{$exampleUrl}&format=JSON{$token_auth}'>Json</a>,\n\t\t\t\t\t\t\t\t\t<a target='_blank' href='{$exampleUrl}&format=Tsv{$token_auth}&translateColumnNames=1'>Tsv (Excel)</a>\n\t\t\t\t\t\t\t\t\t{$lastNUrls}\n\t\t\t\t\t\t\t\t\t]"; } else { $str .= " [ No example available ]"; } $str .= "</span>"; } $str .= '</small>'; $str .= "</div>\n"; return $str; }
/** * Renders the current view. Also sends the stored 'Content-Type' HTML header. * See {@link setContentType()}. * * @return string Generated template. */ public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentAction = Piwik::getAction(); $this->url = Common::sanitizeInputValue(Url::getCurrentUrl()); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsSuperUser = Piwik::hasUserSuperUserAccess(); $this->latest_version_available = UpdateCheck::isNewestVersionAvailable(); $this->disableLink = Common::getRequestVar('disableLink', 0, 'int'); $this->isWidget = Common::getRequestVar('widget', 0, 'int'); $this->cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster(); $this->loginModule = Piwik::getLoginPluginName(); $user = APIUsersManager::getInstance()->getUser($this->userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { // can fail, for example at installation (no plugin loaded yet) } try { $this->totalTimeGeneration = Registry::get('timer')->getTime(); $this->totalNumberOfQueries = Profiler::getQueryCount(); } catch (Exception $e) { $this->totalNumberOfQueries = 0; } ProxyHttp::overrideCacheControlHeaders('no-store'); @header('Content-Type: ' . $this->contentType); // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail) @header('X-Frame-Options: ' . (string) $this->xFrameOptions); return $this->renderTwigTemplate(); }
/** * Renders the current view. Also sends the stored 'Content-Type' HTML header. * See {@link setContentType()}. * * @return string Generated template. */ public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentAction = Piwik::getAction(); $userLogin = Piwik::getCurrentUserLogin(); $this->userLogin = $userLogin; $count = SettingsPiwik::getWebsitesCountToDisplay(); $sites = APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($count); usort($sites, function ($site1, $site2) { return strcasecmp($site1["name"], $site2["name"]); }); $this->sites = $sites; $this->url = Common::sanitizeInputValue(Url::getCurrentUrl()); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsSuperUser = Piwik::isUserIsSuperUser(); $this->latest_version_available = UpdateCheck::isNewestVersionAvailable(); $this->disableLink = Common::getRequestVar('disableLink', 0, 'int'); $this->isWidget = Common::getRequestVar('widget', 0, 'int'); if (Config::getInstance()->General['autocomplete_min_sites'] <= count($sites)) { $this->show_autocompleter = true; } else { $this->show_autocompleter = false; } $this->loginModule = Piwik::getLoginPluginName(); $user = APIUsersManager::getInstance()->getUser($userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { // can fail, for example at installation (no plugin loaded yet) } try { $this->totalTimeGeneration = Registry::get('timer')->getTime(); $this->totalNumberOfQueries = Profiler::getQueryCount(); } catch (Exception $e) { $this->totalNumberOfQueries = 0; } ProxyHttp::overrideCacheControlHeaders('no-store'); @header('Content-Type: ' . $this->contentType); // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail) @header('X-Frame-Options: ' . (string) $this->xFrameOptions); return $this->renderTwigTemplate(); }
/** * The "User Settings" admin UI screen view */ public function userSettings() { Piwik::checkUserIsNotAnonymous(); $view = new View('@UsersManager/userSettings'); $userLogin = Piwik::getCurrentUserLogin(); $user = Request::processRequest('UsersManager.getUser', array('userLogin' => $userLogin)); $view->userAlias = $user['alias']; $view->userEmail = $user['email']; $view->userTokenAuth = Piwik::getCurrentUserTokenAuth(); $view->ignoreSalt = $this->getIgnoreCookieSalt(); $userPreferences = new UserPreferences(); $defaultReport = $userPreferences->getDefaultReport(); if ($defaultReport === false) { $defaultReport = $userPreferences->getDefaultWebsiteId(); } $view->defaultReport = $defaultReport; if ($defaultReport == 'MultiSites') { $defaultSiteId = $userPreferences->getDefaultWebsiteId(); $reportOptionsValue = $defaultSiteId; $view->defaultReportIdSite = $defaultSiteId; $view->defaultReportSiteName = Site::getNameFor($defaultSiteId); } else { $reportOptionsValue = $defaultReport; $view->defaultReportIdSite = $defaultReport; $view->defaultReportSiteName = Site::getNameFor($defaultReport); } $view->defaultReportOptions = array(array('key' => 'MultiSites', 'value' => Piwik::translate('General_AllWebsitesDashboard')), array('key' => $reportOptionsValue, 'value' => Piwik::translate('General_DashboardForASpecificWebsite'))); $view->defaultDate = $this->getDefaultDateForUser($userLogin); $view->availableDefaultDates = $this->getDefaultDates(); $languages = APILanguagesManager::getInstance()->getAvailableLanguageNames(); $languageOptions = array(); foreach ($languages as $language) { $languageOptions[] = array('key' => $language['code'], 'value' => $language['name']); } $view->languageOptions = $languageOptions; $view->currentLanguageCode = LanguagesManager::getLanguageCodeForCurrentUser(); $view->currentTimeformat = (int) LanguagesManager::uses12HourClockForCurrentUser(); $view->ignoreCookieSet = IgnoreCookie::isIgnoreCookieFound(); $view->piwikHost = Url::getCurrentHost(); $this->setBasicVariablesView($view); $view->timeFormats = array('1' => Piwik::translate('General_12HourClock'), '0' => Piwik::translate('General_24HourClock')); return $view->render(); }
/** * A report is usually completely automatically rendered for you but you can render the report completely * customized if you wish. Just overwrite the method and make sure to return a string containing the content of the * report. Don't forget to create the defined twig template within the templates folder of your plugin in order to * make it work. Usually you should NOT have to overwrite this render method. * * @return string */ public function render() { /* $view = new View('@ExposureResearchTools/GetExposureResearchTools'); $view->myData = array(); return $view->render(); */ $aLimit = (int) \Piwik\Common::getRequestVar('vlimit', 100, 'int'); if ($aLimit === 0) { $aLimit = 100; } $getVar = (string) \Piwik\Common::getRequestVar('casevar', 'num', 'string'); /* if ($send === 'yes') { $api = \Piwik\Plugins\ExposureResearchTools\API::getInstance(); $data = $api->getExposureResearchTools( \Piwik\Common::getRequestVar('idSite'), \Piwik\Common::getRequestVar('date'), \Piwik\Common::getRequestVar('period'), \Piwik\Common::getRequestVar('segment') ); var_dump($data); exit; } else { */ // Copy all parameters /* $params = ''; foreach ($_REQUEST as $key => $value) { if (in_array($key, array('vlimit', 'casevar', 'format'))) { continue; } $monkey = "\r\n".'<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />'; } */ return '<form action="index.php" method="GET"> <div> <input type="hidden" name="module" value="API" /> <input type="hidden" name="method" value="ExposureResearchTools.getData" /> <input type="hidden" name="idSite" value="' . \Piwik\Common::getRequestVar('idSite') . '" /> <input type="hidden" name="date" value="' . \Piwik\Common::getRequestVar('date') . '" /> <input type="hidden" name="period" value="' . \Piwik\Common::getRequestVar('period') . '" /> <!-- <input type="hidden" name="segment" value="' . \Piwik\Common::getRequestVar('segment', '') . '" /> --> <input type="hidden" name="token_auth" value="' . \Piwik\Piwik::getCurrentUserTokenAuth() . '" /> <input type="hidden" name="format" value="csv" /> <input type="hidden" name="filter_limit" value="-1" /> </div> <table cellspacing="0" cellpadding="0"> <tr> <td style="padding-right: 1em">Limit activities per visit:</td> <td><input type="text" name="vlimit" value="' . $aLimit . '" style="width: 64px" /></td> </tr><tr> <td style="padding-right: 1em">Read subject ID from GET variable:</td> <td><input type="text" name="casevar" value="' . htmlspecialchars($getVar) . '" style="width: 180px" /></td> </tr><tr> <td style="padding-right: 1em">Data structure:</td> <td> <select name="structure" size="1" style="max-width: 100%"> <option value="case">Per participant (many variables, few rows)</option> <option value="page">Per page view (few variables, may rows)</option> </select> </td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"><label> <input type="checkbox" name="aggregate" value="yes" checked="checked" /> Include aggregate reading times per page (sum per page)<br> <span style="font-size: 85%">(applicable in per-participant structure, only)</span> </label></td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"><label> <input type="checkbox" name="server" value="yes" /> Retain domain name in URLs </label></td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"><label> <input type="checkbox" name="noclip" value="yes" /> Retain extension and query string in URLs (anything after the file name) </label></td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"><label> <input type="checkbox" name="disindex" value="yes" /> Distinguish index.html, index.htm, index.php, and homepage (/) </label></td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"><label> <input type="checkbox" name="skipid" value="yes" /> Skip visits without subject ID (only applicable if GET variable for subject ID is set) </label></td> </tr><tr> <td colspan="2" style="padding-top: 0.5em; padding-bottom: 0.5em"> <strong>Note:</strong> All available data will be exported, regardless of the period defined above. </td> </tr> </table> <div style="margin-top: 1em"> <button type="submit">Download CSV</button> </div> </form> <h2>File Structure</h2> <p>Depending on the file structure selected above, the variables in the result will be:</p> <ul style="list-style: circle; padding-left: 24px; margin-bottom: 30px"> <li>Case identification (both structures) <ul style="list-style: circle; padding-left: 24px"> <li><strong style="width: 60px; display: inline-block">id</strong> Piwik\'s ID for the visit</li> <li><strong style="width: 60px; display: inline-block">CASE</strong> Case ID retrieved from the URL (see setting GET variable)</li> </ul> </li> <li>Structured "per participant" <ul style="list-style: circle; padding-left: 24px"> <li><strong style="width: 60px; display: inline-block">T0</strong> Date and time when the first page was retrieved</li> <li><span style="width: 60px; display: inline-block"><strong>A1</strong>–<strong>A<i>n</i></strong></span> Activities performed (pages viewed) during the visit: ID of the first viewed page stored in A1, etc.</li> <li><span style="width: 60px; display: inline-block"><strong>T1</strong>–<strong>T<i>n</i></strong></span> Times spent per activity (time between retrieving one page and the following one): T1 is the time for A1 in seconds, etc.</li> <li><span style="width: 60px; display: inline-block"><strong>AT</strong></span> Times spent during the visit overall.</li> <li><span style="width: 60px; display: inline-block"><strong>AT_<i>xyz</i></strong></span> Aggregate time spent per activity <i>xyz</i> (e.g., page <i>xyz</i>), in seconds. This block of variables will only be available, if "Include aggregate reading times" has been checked above.</li> </ul> </li> <li>Structured "per action" <ul style="list-style: circle; padding-left: 24px"> <li><span style="width: 60px; display: inline-block"><strong>pos</strong></span> Order of actions (page views) during the visit</li> <li><span style="width: 60px; display: inline-block"><strong>aID</strong></span> Unique ID for the action (page)</li> <li><span style="width: 60px; display: inline-block"><strong>url</strong></span> Description of the action (page URL, usually shortend)</li> <li><span style="width: 60px; display: inline-block"><strong>time</strong></span> Time spent on the action (page)</li> <li><span style="width: 60px; display: inline-block"><strong>ontime</strong></span> Beginning of action [sec], relative to the visit\'s first page retrieval</li> <li><span style="width: 60px; display: inline-block"><strong>astime</strong></span> Absolute timestamp of the action (page view)</li> </ul> </li> </ul> <p><strong>Note:</strong> Piwik will not record the time spent on the most recent page (activity). This affects <strong>T<i>n</i></strong>, <strong>AT</strong>, <strong>AT_<i>xyz</i></strong>, and <strong>time</strong>.</p> <p><strong>Note:</strong> If Excel won\'t open the file correctly (all data in one cell), download the CSV file to disk, then start Excel and open via menu → file → open. OpenOffice Calc will cause less trouble.</p> <h2>Additional Information</h2> <p>If you\'re interested in doing selective exposure research with this tool, the following may be helpful:</p> <ul style="list-style: circle; padding-left: 24px; margin-bottom: 30px"> <li> <p>We published a paper about this tool and how to collect SE data with Piwik:</p> <p>Leiner, D. J., Scherr, S., Bartsch, A. (forthcoming). Using Open Source Tools to Measure Online Selective Exposure in Naturalistic Settings. Communication Methods and Measures.</p> </li> <li> <p>There are additional resources on the <a href="https://github.com/BurninLeo/ExposureResearchTools" target="_blank">Plugin Website</a> (on GitHub).</p> <p>Specifically, there\'s a template for SoSci Survey to embed a stimulus presentation (via pop-up) between a pre and post questionnaire. The template takes care of transmitting the respondent ID, so that it appears in the SE data, and to store the times when the pop-up was opened and closed.</p> </li> </ul>'; }
/** * Checks that the token_auth in the URL matches the currently logged-in user's token_auth. * * This is a protection against CSRF and should be used in all controller * methods that modify Piwik or any user settings. * * **The token_auth should never appear in the browser's address bar.** * * @throws \Piwik\NoAccessException If the token doesn't match. * @api */ protected function checkTokenInUrl() { if (Common::getRequestVar('token_auth', false) != Piwik::getCurrentUserTokenAuth()) { throw new NoAccessException(Piwik::translate('General_ExceptionInvalidToken')); } }