public function sendHeader() { if ($this->isJsonp()) { Common::sendHeader('Content-Type: application/javascript; charset=utf-8'); } else { Renderer\Json::sendHeaderJSON(); } ProxyHttp::overrideCacheControlHeaders(); }
public function addJsGlobalVariables(&$out) { if (ProxyHttp::isHttps()) { $isHttps = 'true'; } else { $isHttps = 'false'; } $out .= "piwik.hasServerDetectedHttps = {$isHttps};\n"; }
private static function notifyIfURLIsNotSecure() { $isURLSecure = ProxyHttp::isHttps(); if ($isURLSecure) { return; } if (!Piwik::hasUserSuperUserAccess()) { return; } $message = Piwik::translate('General_CurrentlyUsingUnsecureHttp'); $message .= " "; $message .= Piwik::translate('General_ReadThisToLearnMore', array('<a rel="noreferrer" target="_blank" href="https://piwik.org/faq/how-to/faq_91/">', '</a>')); $notification = new Notification($message); $notification->context = Notification::CONTEXT_WARNING; $notification->raw = true; Notification\Manager::notify('ControllerAdmin_HttpIsUsed', $notification); }
/** * Executed when the session was successfully authenticated. * * @param AuthResult $authResult The successful authentication result. * @param bool $rememberMe Whether the authenticated session should be remembered after * the browser is closed or not. */ protected function processSuccessfulSession(AuthResult $authResult, $rememberMe) { $storage = new Storage($authResult->getIdentity()); /** * @deprecated Create a custom SessionInitializer instead. */ Piwik::postEvent('Login.authenticate.successful', array($authResult->getIdentity(), $authResult->getTokenAuth())); $cookie = $this->getAuthCookie($rememberMe); $cookie->set('login', $authResult->getIdentity()); $cookie->set('token_auth', $this->getHashTokenAuth($authResult->getIdentity(), $authResult->getTokenAuth())); if ($storage->isActive()) { $cookie->set('auth_code', $this->getHashTokenAuth($authResult->getIdentity(), $storage->getSecret())); } $cookie->setSecure(ProxyHttp::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); }
/** * 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(); }
/** * Sends the http headers for csv file */ protected function renderHeader() { $fileName = 'Piwik ' . Piwik::translate('General_Export'); $period = Common::getRequestVar('period', false); $date = Common::getRequestVar('date', false); if ($period || $date) { if ($period == 'range') { $period = new Range($period, $date); } else { if (strpos($date, ',') !== false) { $period = new Range('range', $date); } else { $period = Period\Factory::build($period, Date::factory($date)); } } $prettyDate = $period->getLocalizedLongString(); $meta = $this->getApiMetaData(); $fileName .= ' _ ' . $meta['name'] . ' _ ' . $prettyDate . '.csv'; } // silent fail otherwise unit tests fail Common::sendHeader('Content-Disposition: attachment; filename="' . $fileName . '"', true); ProxyHttp::overrideCacheControlHeaders(); }
public function sendHeader() { Common::sendHeader("Content-Type: application/vnd.ms-excel", true); ProxyHttp::overrideCacheControlHeaders(); }
/** * Authenticates the user and initializes the session. */ public function initSession($login, $md5Password, $rememberMe) { $tokenAuth = API::getInstance()->getTokenAuth($login, $md5Password); $this->setLogin($login); $this->setTokenAuth($tokenAuth); $authResult = $this->authenticate(); $authCookieName = Config::getInstance()->General['login_cookie_name']; $authCookieExpiry = $rememberMe ? time() + Config::getInstance()->General['login_cookie_expire'] : 0; $authCookiePath = Config::getInstance()->General['login_cookie_path']; $cookie = new Cookie($authCookieName, $authCookieExpiry, $authCookiePath); if (!$authResult->wasAuthenticationSuccessful()) { $cookie->delete(); throw new Exception(Piwik::translate('Login_LoginPasswordNotCorrect')); } $cookie->set('login', $login); $cookie->set('token_auth', $this->getHashTokenAuth($login, $authResult->getTokenAuth())); $cookie->setSecure(ProxyHttp::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); @Session::regenerateId(); // remove password reset entry if it exists Login::removePasswordResetInfo($login); }
/** * Executed when the session was successfully authenticated. * * @param AuthResult $authResult The successful authentication result. * @param bool $rememberMe Whether the authenticated session should be remembered after * the browser is closed or not. */ protected function processSuccessfulSession(AuthResult $authResult, $rememberMe) { $cookie = $this->getAuthCookie($rememberMe); $cookie->set('login', $authResult->getIdentity()); $cookie->set('token_auth', $this->getHashTokenAuth($authResult->getIdentity(), $authResult->getTokenAuth())); $cookie->setSecure(ProxyHttp::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); }
/** * Returns image link tracking code for a given site with specified options. * * @param int $idSite The ID to generate tracking code for. * @param string $piwikUrl The domain and URL path to the Piwik installation. * @param int $idGoal An ID for a goal to trigger a conversion for. * @param int $revenue The revenue of the goal conversion. Only used if $idGoal is supplied. * @return string The HTML tracking code. */ public function getImageTrackingCode($idSite, $piwikUrl = '', $actionName = false, $idGoal = false, $revenue = false) { $urlParams = array('idsite' => $idSite, 'rec' => 1); if ($actionName !== false) { $urlParams['action_name'] = urlencode(Common::unsanitizeInputValue($actionName)); } if ($idGoal !== false) { $urlParams['idGoal'] = $idGoal; if ($revenue !== false) { $urlParams['revenue'] = $revenue; } } /** * Triggered when generating image link tracking code server side. Plugins can use * this event to customise the image tracking code that is displayed to the * user. * * @param string &$piwikHost The domain and URL path to the Piwik installation, eg, * `'examplepiwik.com/path/to/piwik'`. * @param array &$urlParams The query parameters used in the <img> element's src * URL. See Piwik's image tracking docs for more info. */ Piwik::postEvent('SitesManager.getImageTrackingCode', array(&$piwikUrl, &$urlParams)); $piwikUrl = (ProxyHttp::isHttps() ? "https://" : "http://") . $piwikUrl . '/piwik.php'; return "<!-- Piwik Image Tracker-->\n<img src=\"{$piwikUrl}?" . Url::getQueryStringFromParameters($urlParams) . "\" style=\"border:0\" alt=\"\" />\n<!-- End Piwik -->"; }
/** * Write configuration file from session-store */ private function createConfigFile($dbInfos) { $config = Config::getInstance(); // make sure DB sessions are used if the filesystem is NFS if (Filesystem::checkIfFileSystemIsNFS()) { $config->General['session_save_handler'] = 'dbtable'; } if (count($headers = ProxyHeaders::getProxyClientHeaders()) > 0) { $config->General['proxy_client_headers'] = $headers; } if (count($headers = ProxyHeaders::getProxyHostHeaders()) > 0) { $config->General['proxy_host_headers'] = $headers; } if (Common::getRequestVar('clientProtocol', 'http', 'string') == 'https') { $protocol = 'https'; } else { $protocol = ProxyHeaders::getProtocolInformation(); } if (!empty($protocol) && !\Piwik\ProxyHttp::isHttps()) { $config->General['assume_secure_protocol'] = '1'; } $config->General['salt'] = Common::generateUniqId(); $config->General['installation_in_progress'] = 1; $config->database = $dbInfos; if (!DbHelper::isDatabaseConnectionUTF8()) { $config->database['charset'] = 'utf8'; } $config->forceSave(); }
/** * If the page is using HTTP, redirect to the same page over HTTPS */ public static function redirectToHttps() { if (ProxyHttp::isHttps()) { return; } $url = self::getCurrentUrl(); $url = str_replace("http://", "https://", $url); self::redirectToUrl($url); }
/** * @param UIAsset $uiAsset */ private function serveJsFile($uiAsset) { ProxyHttp::serverStaticFile($uiAsset->getAbsoluteLocation(), self::JS_MIME_TYPE); }
/** * Executed when the session was successfully authenticated * @param $login * @param $tokenAuth * @param $rememberMe */ protected function processSuccessfullSession($login, $tokenAuth, $rememberMe) { $cookie = $this->getAuthCookie($rememberMe); $cookie->set('login', $login); $cookie->set('token_auth', $this->getHashTokenAuth($login, $tokenAuth)); $cookie->setSecure(ProxyHttp::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); // remove password reset entry if it exists Login::removePasswordResetInfo($login); }
/** * 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 download() { Piwik::checkUserHasSuperUserAccess(); $this->dieIfPluginsAdminIsDisabled(); $pluginName = new PluginName(); $pluginName = $pluginName->getPluginName(); Nonce::checkNonce($pluginName); $filename = $pluginName . '.zip'; try { $pathToPlugin = $this->marketplaceApi->download($pluginName); ProxyHttp::serverStaticFile($pathToPlugin, 'application/zip', $expire = 0, $start = false, $end = false, $filename); } catch (Exception $e) { Common::sendResponseCode(500); Log::warning('Could not download file . ' . $e->getMessage()); } if (!empty($pathToPlugin)) { Filesystem::deleteFileIfExists($pathToPlugin); } }
/** * Start the session * * @param array|bool $options An array of configuration options; the auto-start (bool) setting is ignored * @return void * @throws Exception if starting a session fails */ public static function start($options = false) { if (headers_sent() || self::$sessionStarted || defined('PIWIK_ENABLE_SESSION_START') && !PIWIK_ENABLE_SESSION_START) { return; } self::$sessionStarted = true; // use cookies to store session id on the client side @ini_set('session.use_cookies', '1'); // prevent attacks involving session ids passed in URLs @ini_set('session.use_only_cookies', '1'); // advise browser that session cookie should only be sent over secure connection if (ProxyHttp::isHttps()) { @ini_set('session.cookie_secure', '1'); } // advise browser that session cookie should only be accessible through the HTTP protocol (i.e., not JavaScript) @ini_set('session.cookie_httponly', '1'); // don't use the default: PHPSESSID @ini_set('session.name', self::SESSION_NAME); // proxies may cause the referer check to fail and // incorrectly invalidate the session @ini_set('session.referer_check', ''); $currentSaveHandler = ini_get('session.save_handler'); $config = Config::getInstance(); if (self::isFileBasedSessions()) { // Note: this handler doesn't work well in load-balanced environments and may have a concurrency issue with locked session files // for "files", use our own folder to prevent local session file hijacking $sessionPath = self::getSessionsDirectory(); // We always call mkdir since it also chmods the directory which might help when permissions were reverted for some reasons Filesystem::mkdir($sessionPath); @ini_set('session.save_handler', 'files'); @ini_set('session.save_path', $sessionPath); } elseif ($config->General['session_save_handler'] === 'dbtable' || in_array($currentSaveHandler, array('user', 'mm'))) { // We consider these to be misconfigurations, in that: // - user - we can't verify that user-defined session handler functions have already been set via session_set_save_handler() // - mm - this handler is not recommended, unsupported, not available for Windows, and has a potential concurrency issue $config = array('name' => Common::prefixTable('session'), 'primary' => 'id', 'modifiedColumn' => 'modified', 'dataColumn' => 'data', 'lifetimeColumn' => 'lifetime'); $saveHandler = new DbTable($config); if ($saveHandler) { self::setSaveHandler($saveHandler); } } // garbage collection may disabled by default (e.g., Debian) if (ini_get('session.gc_probability') == 0) { @ini_set('session.gc_probability', 1); } try { parent::start(); register_shutdown_function(array('Zend_Session', 'writeClose'), true); } catch (Exception $e) { Log::error('Unable to start session: ' . $e->getMessage()); $enableDbSessions = ''; if (DbHelper::isInstalled()) { $enableDbSessions = "<br/>If you still experience issues after trying these changes,\n\t\t\t \t\t\twe recommend that you <a href='http://piwik.org/faq/how-to-install/#faq_133' rel='noreferrer' target='_blank'>enable database session storage</a>."; } $pathToSessions = Filechecks::getErrorMessageMissingPermissions(self::getSessionsDirectory()); $message = sprintf("Error: %s %s %s\n<pre>Debug: the original error was \n%s</pre>", Piwik::translate('General_ExceptionUnableToStartSession'), $pathToSessions, $enableDbSessions, $e->getMessage()); $ex = new MissingFilePermissionException($message, $e->getCode(), $e); $ex->setIsHtmlMessage(); throw $ex; } }
/** * Check force_ssl_login and redirect if connection isn't secure and not using a reverse proxy * * @param none * @return void */ protected function checkForceSslLogin() { $forceSslLogin = Config::getInstance()->General['force_ssl_login']; if ($forceSslLogin && !ProxyHttp::isHttps()) { $url = 'https://' . Url::getCurrentHost() . Url::getCurrentScriptName() . Url::getCurrentQueryString(); Url::redirectToUrl($url); } }
// These constants define which action will be performed by the static server. define("NULL_FILE_SRV_MODE", "nullFile"); define("GHOST_FILE_SRV_MODE", "ghostFile"); define("TEST_FILE_SRV_MODE", "testFile"); /** * If the static file server has been requested, the response sent back to the browser will be the content produced by * the execution of Piwik:serverStaticFile(). In this case, unit tests won't be executed */ // Getting the server mode $staticFileServerMode = Common::getRequestVar(SRV_MODE_REQUEST_VAR, ""); // Setting zlib output compression as requested ini_set('zlib.output_compression', Common::getRequestVar(ZLIB_OUTPUT_REQUEST_VAR, '0')); if ($staticFileServerMode === "") { throw new Exception("When this testing file is used as a static file server, the request parameter " . SRV_MODE_REQUEST_VAR . " must be provided."); } switch ($staticFileServerMode) { // The static file server calls Piwik::serverStaticFile with a null file case NULL_FILE_SRV_MODE: ProxyHttp::serverStaticFile(null, TEST_FILE_CONTENT_TYPE); break; // The static file server calls Piwik::serverStaticFile with a non-existing file // The static file server calls Piwik::serverStaticFile with a non-existing file case GHOST_FILE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION . ".ghost", TEST_FILE_CONTENT_TYPE); break; // The static file server calls Piwik::serverStaticFile with the test file // The static file server calls Piwik::serverStaticFile with the test file case TEST_FILE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION, TEST_FILE_CONTENT_TYPE); break; }
protected function handleSSLRedirection() { if (!Common::isPhpCliMode() && Config::getInstance()->General['force_ssl'] == 1 && !ProxyHttp::isHttps() && !(Common::getRequestVar('module', '') == 'CoreAdminHome' && Common::getRequestVar('action', '') == 'optOut')) { $url = Url::getCurrentUrl(); $url = str_replace("http://", "https://", $url); Url::redirectToUrl($url); } }
public function render() { ProxyHttp::overrideCacheControlHeaders(); // See http://www.jqplot.com/docs/files/jqPlotOptions-txt.html $data = array('params' => array('axes' => &$this->axes, 'series' => &$this->series), 'data' => &$this->data); return $data; }
/** * Start an Overlay session: Redirect to the tracked website. The Piwik * tracker will recognize this referrer and start the session. */ public function startOverlaySession() { $idSite = Common::getRequestVar('idSite', 0, 'int'); Piwik::checkUserHasViewAccess($idSite); $view = new View('@Overlay/startOverlaySession'); $sitesManager = APISitesManager::getInstance(); $site = $sitesManager->getSiteFromId($idSite); $urls = $sitesManager->getSiteUrlsFromId($idSite); $view->isHttps = ProxyHttp::isHttps(); $view->knownUrls = json_encode($urls); $view->mainUrl = $site['main_url']; $this->outputCORSHeaders(); Common::sendHeader('Content-Type: text/html; charset=UTF-8'); return $view->render(); }
* the execution of Piwik:serverStaticFile(). In this case, unit tests won't be executed */ // Getting the server mode $staticFileServerMode = Common::getRequestVar(SRV_MODE_REQUEST_VAR, ""); // Setting zlib output compression as requested ini_set('zlib.output_compression', Common::getRequestVar(ZLIB_OUTPUT_REQUEST_VAR, '0')); if ($staticFileServerMode === "") { throw new Exception("When this testing file is used as a static file server, the request parameter " . SRV_MODE_REQUEST_VAR . " must be provided."); } switch ($staticFileServerMode) { // The static file server calls Piwik::serverStaticFile with a null file case NULL_FILE_SRV_MODE: ProxyHttp::serverStaticFile(null, TEST_FILE_CONTENT_TYPE); break; // The static file server calls Piwik::serverStaticFile with a non-existing file // The static file server calls Piwik::serverStaticFile with a non-existing file case GHOST_FILE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION . ".ghost", TEST_FILE_CONTENT_TYPE); break; // The static file server calls Piwik::serverStaticFile with the test file // The static file server calls Piwik::serverStaticFile with the test file case TEST_FILE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION, TEST_FILE_CONTENT_TYPE); break; case PARTIAL_TEST_FILE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION, TEST_FILE_CONTENT_TYPE, $expireFarFutureDays = 100, PARTIAL_BYTE_START, PARTIAL_BYTE_END); break; case WHOLE_TEST_FILE_WITH_RANGE_SRV_MODE: ProxyHttp::serverStaticFile(TEST_FILE_LOCATION, TEST_FILE_CONTENT_TYPE, $expireFarFutureDays = 100, 0, filesize(TEST_FILE_LOCATION)); break; }
/** * Test that php compression isn't enabled ... otherwise, lots of tests will fail * * @group Core */ public function test_phpOutputCompression() { $this->assertFalse(ProxyHttp::isPhpOutputCompressed()); }
/** * Start an Overlay session: Redirect to the tracked website. The Piwik * tracker will recognize this referrer and start the session. */ public function startOverlaySession() { $idSite = Common::getRequestVar('idSite', 0, 'int'); Piwik::checkUserHasViewAccess($idSite); $sitesManager = APISitesManager::getInstance(); $site = $sitesManager->getSiteFromId($idSite); $urls = $sitesManager->getSiteUrlsFromId($idSite); @header('Content-Type: text/html; charset=UTF-8'); return ' <html><head><title></title></head><body> <script type="text/javascript"> function handleProtocol(url) { if (' . (ProxyHttp::isHttps() ? 'true' : 'false') . ') { return url.replace(/http:\\/\\//i, "https://"); } else { return url.replace(/https:\\/\\//i, "http://"); } } function removeUrlPrefix(url) { return url.replace(/http(s)?:\\/\\/(www\\.)?/i, ""); } if (window.location.hash) { var match = false; var urlToRedirect = window.location.hash.substr(1); var urlToRedirectWithoutPrefix = removeUrlPrefix(urlToRedirect); var knownUrls = ' . Common::json_encode($urls) . '; for (var i = 0; i < knownUrls.length; i++) { var testUrl = removeUrlPrefix(knownUrls[i]); if (urlToRedirectWithoutPrefix.substr(0, testUrl.length) == testUrl) { match = true; if (navigator.appName == "Microsoft Internet Explorer") { // internet explorer loses the referrer if we use window.location.href=X var referLink = document.createElement("a"); referLink.href = handleProtocol(urlToRedirect); document.body.appendChild(referLink); referLink.click(); } else { window.location.href = handleProtocol(urlToRedirect); } break; } } if (!match) { var idSite = window.location.href.match(/idSite=([0-9]+)/i)[1]; window.location.href = "index.php?module=Overlay&action=showErrorWrongDomain" + "&idSite=" + idSite + "&url=" + encodeURIComponent(urlToRedirect); } } else { window.location.href = handleProtocol("' . $site['main_url'] . '"); }; </script> </body></html> '; }
protected static function sendToBrowser($filename, $extension, $contentType, $content) { $filename = ReportRenderer::appendExtension($filename, $extension); ProxyHttp::overrideCacheControlHeaders(); header('Content-Description: File Transfer'); header('Content-Type: ' . $contentType); header('Content-Disposition: attachment; filename="' . str_replace('"', '\'', basename($filename)) . '";'); header('Content-Length: ' . strlen($content)); echo $content; }
exit; } /** * piwik.js proxy * * @see core/Piwik.php */ define('PIWIK_INCLUDE_PATH', '..'); define('PIWIK_DOCUMENT_ROOT', '..'); define('PIWIK_USER_PATH', '..'); require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php'; // Composer autoloader if (file_exists(PIWIK_INCLUDE_PATH . '/vendor/autoload.php')) { $path = PIWIK_INCLUDE_PATH . '/vendor/autoload.php'; // Piwik is the main project } else { $path = PIWIK_INCLUDE_PATH . '/../../autoload.php'; // Piwik is installed as a dependency } require $path; $file = '../piwik.js'; $daysExpireFarFuture = 10; $byteStart = $byteEnd = false; if (!defined("PIWIK_KEEP_JS_TRACKER_COMMENT") || !PIWIK_KEEP_JS_TRACKER_COMMENT) { $byteStart = 369; // length of comment header in bytes } $environment = new \Piwik\Application\Environment(null); $environment->init(); ProxyHttp::serverStaticFile($file, "application/javascript; charset=UTF-8", $daysExpireFarFuture, $byteStart, $byteEnd); exit;
public function sendHeader() { Renderer\Json::sendHeaderJSON(); ProxyHttp::overrideCacheControlHeaders(); }
/** * 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; }
<?php /** * Piwik - Open source web analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ use Piwik\ProxyHttp; /** * Tracker proxy */ if ($_SERVER['REQUEST_METHOD'] == 'POST' || !empty($_SERVER['QUERY_STRING'])) { include '../piwik.php'; exit; } /** * piwik.js proxy * * @see core/Piwik.php */ define('PIWIK_INCLUDE_PATH', '..'); define('PIWIK_DOCUMENT_ROOT', '..'); define('PIWIK_USER_PATH', '..'); require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php'; require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; $file = '../piwik.js'; // There is no cache buster parameter so we don't set Expires: header $expireFarFuture = false; ProxyHttp::serverStaticFile($file, "application/javascript; charset=UTF-8", $expireFarFuture); exit;