Exemplo n.º 1
0
 /**
  * Computes the output for the given data table
  *
  * @param DataTable $table
  * @return string
  * @throws Exception
  */
 protected function renderTable($table)
 {
     if (!$table instanceof DataTable\Map || $table->getKeyName() != 'date') {
         throw new Exception("RSS feeds can be generated for one specific website &idSite=X." . "\nPlease specify only one idSite or consider using &format=XML instead.");
     }
     $idSite = Common::getRequestVar('idSite', 1, 'int');
     $period = Common::getRequestVar('period');
     $piwikUrl = Url::getCurrentUrlWithoutFileName() . "?module=CoreHome&action=index&idSite=" . $idSite . "&period=" . $period;
     $out = "";
     $moreRecentFirst = array_reverse($table->getDataTables(), true);
     foreach ($moreRecentFirst as $date => $subtable) {
         /** @var DataTable $subtable */
         $timestamp = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_PERIOD_INDEX)->getDateStart()->getTimestamp();
         $site = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_SITE_INDEX);
         $pudDate = date('r', $timestamp);
         $dateInSiteTimezone = Date::factory($timestamp)->setTimezone($site->getTimezone())->toString('Y-m-d');
         $thisPiwikUrl = Common::sanitizeInputValue($piwikUrl . "&date={$dateInSiteTimezone}");
         $siteName = $site->getName();
         $title = $siteName . " on " . $date;
         $out .= "\t<item>\n\t\t<pubDate>{$pudDate}</pubDate>\n\t\t<guid>{$thisPiwikUrl}</guid>\n\t\t<link>{$thisPiwikUrl}</link>\n\t\t<title>{$title}</title>\n\t\t<author>http://piwik.org</author>\n\t\t<description>";
         $out .= Common::sanitizeInputValue($this->renderDataTable($subtable));
         $out .= "</description>\n\t</item>\n";
     }
     $header = $this->getRssHeader();
     $footer = $this->getRssFooter();
     return $header . $out . $footer;
 }
Exemplo n.º 2
0
 /**
  * Returns the javascript tag for the given idSite.
  * This tag must be included on every page to be tracked by Piwik
  *
  * @param int $idSite
  * @param string $piwikUrl
  * @param bool $mergeSubdomains
  * @param bool $groupPageTitlesByDomain
  * @param bool $mergeAliasUrls
  * @param bool $visitorCustomVariables
  * @param bool $pageCustomVariables
  * @param bool $customCampaignNameQueryParam
  * @param bool $customCampaignKeywordParam
  * @param bool $doNotTrack
  * @internal param $
  * @return string The Javascript tag ready to be included on the HTML pages
  */
 public function getJavascriptTag($idSite, $piwikUrl = '', $mergeSubdomains = false, $groupPageTitlesByDomain = false, $mergeAliasUrls = false, $visitorCustomVariables = false, $pageCustomVariables = false, $customCampaignNameQueryParam = false, $customCampaignKeywordParam = false, $doNotTrack = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     if (empty($piwikUrl)) {
         $piwikUrl = Url::getCurrentUrlWithoutFileName();
     }
     $piwikUrl = Common::sanitizeInputValues($piwikUrl);
     $htmlEncoded = Piwik::getJavascriptCode($idSite, $piwikUrl, $mergeSubdomains, $groupPageTitlesByDomain, $mergeAliasUrls, $visitorCustomVariables, $pageCustomVariables, $customCampaignNameQueryParam, $customCampaignKeywordParam, $doNotTrack);
     $htmlEncoded = str_replace(array('<br>', '<br />', '<br/>'), '', $htmlEncoded);
     return $htmlEncoded;
 }
Exemplo n.º 3
0
 /**
  * Returns the URL to this Piwik instance, eg. **http://demo.piwik.org/** or **http://example.org/piwik/**.
  *
  * @return string
  * @api
  */
 public static function getPiwikUrl()
 {
     $url = Option::get(self::OPTION_PIWIK_URL);
     $isPiwikCoreDispatching = defined('PIWIK_ENABLE_DISPATCH') && PIWIK_ENABLE_DISPATCH;
     if (Common::isPhpCliMode() || SettingsServer::isArchivePhpTriggered() || !$isPiwikCoreDispatching) {
         return $url;
     }
     $currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
     // when script is called from /misc/cron/archive.php, Piwik URL is /index.php
     $currentUrl = str_replace("/misc/cron", "", $currentUrl);
     if (empty($url) || $currentUrl != $url) {
         if (strlen($currentUrl) >= strlen('http://a/')) {
             self::overwritePiwikUrl($currentUrl);
         }
         $url = $currentUrl;
     }
     if (ProxyHttp::isHttps()) {
         $url = str_replace("http://", "https://", $url);
     }
     return $url;
 }
Exemplo n.º 4
0
 private function checkPiwikIsNotInstalled()
 {
     if (!SettingsPiwik::isPiwikInstalled()) {
         return;
     }
     \Piwik\Plugins\Login\Controller::clearSession();
     $message = Piwik::translate('Installation_InvalidStateError', array('<br /><strong>', '</strong>', '<a href=\'' . Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName()) . '\'>', '</a>'));
     Piwik::exitWithErrorMessage($message);
 }
 /**
  * returns piwikBaseURL
  *
  * @return	string
  */
 public function getPiwikBaseURL()
 {
     if (TYPO3_MODE == 'BE') {
         tx_piwikintegration_install::getInstaller()->getConfigObject()->initPiwikFrameWork();
         $path = \Piwik\Url::getCurrentUrlWithoutFileName();
         $path = dirname($path);
         $path .= '/typo3conf/piwik/piwik/';
     } else {
         $path = 'http://' . $_SERVER['SERVER_NAME'] . dirname($_SERVER['SCRIPT_NAME']) . '/typo3conf/piwik/piwik/';
     }
     return $path;
 }
Exemplo n.º 6
0
 /**
  * Returns URL to Piwik root.
  *
  * @return string
  */
 public static function getRootUrl()
 {
     $piwikUrl = Url::getCurrentUrlWithoutFileName();
     $pathBeforeRoot = 'tests';
     // Running from a plugin
     if (strpos($piwikUrl, 'plugins/') !== false) {
         $pathBeforeRoot = 'plugins';
     }
     $testsInPath = strpos($piwikUrl, $pathBeforeRoot . '/');
     if ($testsInPath !== false) {
         $piwikUrl = substr($piwikUrl, 0, $testsInPath);
     }
     // in case force_ssl=1, or assume_secure_protocol=1, is set in tests
     // we don't want to require Travis CI or devs to setup HTTPS on their local machine
     $piwikUrl = str_replace("https://", "http://", $piwikUrl);
     return $piwikUrl;
 }
Exemplo n.º 7
0
 public function siteWithoutData()
 {
     $javascriptGenerator = new TrackerCodeGenerator();
     $piwikUrl = Url::getCurrentUrlWithoutFileName();
     return $this->renderTemplate('siteWithoutData', array('siteName' => $this->site->getName(), 'trackingHelp' => $this->renderTemplate('_displayJavascriptCode', array('displaySiteName' => Common::unsanitizeInputValue($this->site->getName()), 'jsTag' => $javascriptGenerator->generate($this->idSite, $piwikUrl), 'idSite' => $this->idSite, 'piwikUrl' => $piwikUrl))));
 }
Exemplo n.º 8
0
 /**
  * Returns the URL to this Piwik instance, eg. **http://demo.piwik.org/** or **http://example.org/piwik/**.
  *
  * @return string
  * @api
  */
 public static function getPiwikUrl()
 {
     // Only set in tests
     if (self::$piwikUrlCache !== null) {
         return self::$piwikUrlCache;
     }
     $key = 'piwikUrl';
     $url = Option::get($key);
     if (Common::isPhpCliMode() || SettingsServer::isArchivePhpTriggered() || defined('PIWIK_MODE_ARCHIVE')) {
         return $url;
     }
     $currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
     if (empty($url) || $currentUrl != $url) {
         if (strlen($currentUrl) >= strlen('http://a/')) {
             Option::set($key, $currentUrl, $autoLoad = true);
         }
         $url = $currentUrl;
     }
     return $url;
 }
Exemplo n.º 9
0
 /**
  * Constructor.
  * 
  * @param string $templateFile The template file to load. Must be in the following format:
  *                             `"@MyPlugin/templateFileName"`. Note the absence of .twig
  *                             from the end of the name.
  */
 public function __construct($templateFile)
 {
     $templateExt = '.twig';
     if (substr($templateFile, -strlen($templateExt)) !== $templateExt) {
         $templateFile .= $templateExt;
     }
     $this->template = $templateFile;
     $this->initializeTwig();
     $this->piwik_version = Version::VERSION;
     $this->piwikUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
 }
Exemplo n.º 10
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 = Url::getCurrentUrlWithoutFileName() . '?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[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\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[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><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";
    }
Exemplo n.º 11
0
 /**
  * The previous step is valid if it is either
  * - any step before (OK to go back)
  * - the current step (case when validating a form)
  * If step is invalid, then exit.
  *
  * @param string $currentStep Current step
  */
 protected function checkPreviousStepIsValid($currentStep)
 {
     $error = false;
     if (empty($this->session->currentStepDone)) {
         $error = true;
     } else {
         if ($currentStep == 'finished' && $this->session->currentStepDone == 'finished') {
             // ok to refresh this page or use language selector
         } else {
             if (file_exists(Config::getLocalConfigPath())) {
                 $error = true;
             }
             $steps = array_keys($this->steps);
             // the currentStep
             $currentStepId = array_search($currentStep, $steps);
             // the step before
             $previousStepId = array_search($this->session->currentStepDone, $steps);
             // not OK if currentStepId > previous+1
             if ($currentStepId > $previousStepId + 1) {
                 $error = true;
             }
         }
     }
     if ($error) {
         \Piwik\Plugins\Login\Controller::clearSession();
         $message = Piwik::translate('Installation_ErrorInvalidState', array('<br /><strong>', '</strong>', '<a href=\'' . Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName()) . '\'>', '</a>'));
         Piwik::exitWithErrorMessage($message);
     }
 }
Exemplo n.º 12
0
 private function initPiwikHost()
 {
     // If archive.php run as a web cron, we use the current hostname+path
     if (!Common::isPhpCliMode()) {
         // example.org/piwik/misc/cron/
         $piwikUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
         // example.org/piwik/
         $piwikUrl = $piwikUrl . "../../";
     } else {
         // If archive.php run as CLI/shell we require the piwik url to be set
         $piwikUrl = $this->isParameterSet("url", true);
         if (!$piwikUrl) {
             $this->logFatalErrorUrlExpected();
         }
         if (!\Piwik\UrlHelper::isLookLikeUrl($piwikUrl)) {
             // try adding http:// in case it's missing
             $piwikUrl = "http://" . $piwikUrl;
         }
         if (!\Piwik\UrlHelper::isLookLikeUrl($piwikUrl)) {
             $this->logFatalErrorUrlExpected();
         }
         // ensure there is a trailing slash
         if ($piwikUrl[strlen($piwikUrl) - 1] != '/') {
             $piwikUrl .= '/';
         }
     }
     $this->initConfigObject($piwikUrl);
     if (Config::getInstance()->General['force_ssl'] == 1) {
         $piwikUrl = str_replace('http://', 'https://', $piwikUrl);
     }
     $this->piwikUrl = $piwikUrl . "index.php";
 }
Exemplo n.º 13
0
 /**
  * Displays the admin UI page showing all tracking tags
  * @return void
  */
 function displayJavascriptCode()
 {
     $idSite = Common::getRequestVar('idSite');
     Piwik::checkUserHasViewAccess($idSite);
     $jsTag = Piwik::getJavascriptCode($idSite, Url::getCurrentUrlWithoutFileName());
     $view = new View('@SitesManager/displayJavascriptCode');
     $this->setBasicVariablesView($view);
     $view->idSite = $idSite;
     $site = new Site($idSite);
     $view->displaySiteName = $site->getName();
     $view->jsTag = $jsTag;
     return $view->render();
 }
Exemplo n.º 14
0
 public function siteWithoutData()
 {
     $javascriptGenerator = new TrackerCodeGenerator();
     $piwikUrl = Url::getCurrentUrlWithoutFileName();
     if (!$this->site) {
         throw new UnexpectedWebsiteFoundException('Invalid site ' . $this->idSite);
     }
     return $this->renderTemplate('siteWithoutData', array('siteName' => $this->site->getName(), 'idSite' => $this->site->getId(), 'trackingHelp' => $this->renderTemplate('_displayJavascriptCode', array('displaySiteName' => Common::unsanitizeInputValue($this->site->getName()), 'jsTag' => $javascriptGenerator->generate($this->idSite, $piwikUrl), 'idSite' => $this->idSite, 'piwikUrl' => $piwikUrl))));
 }