isHttps() публичный статический Метод

Returns true if the current request appears to be a secure HTTPS connection
public static isHttps ( ) : boolean
Результат boolean
Пример #1
0
 public function addJsGlobalVariables(&$out)
 {
     if (ProxyHttp::isHttps()) {
         $isHttps = 'true';
     } else {
         $isHttps = 'false';
     }
     $out .= "piwik.hasServerDetectedHttps = {$isHttps};\n";
 }
 /**
  * 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();
 }
Пример #3
0
 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);
 }
Пример #4
0
 /**
  * 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);
 }
Пример #5
0
 /**
  * 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();
 }
Пример #6
0
 /**
  * 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();
 }
Пример #7
0
 /**
  * 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;
     }
 }
Пример #8
0
 /**
  * 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';
     }
     # Improved Security with IBM Bluemix
     # With SSL ALWAYS available for all Bluemix apps, let's require all requests
     # to be made over SSL (https) so that data is NOT sent in the clear.
     # Non-ssl requests will trigger a
     #    Error: Form security failed.
     #    Please reload the form and check that your cookies are enabled
     # Reference: http://piwik.org/faq/how-to/faq_91/
     # Reference: https://developer.ibm.com/answers/questions/8312/how-do-i-enable-tlsssl-for-my-bluemix-application/
     $config->General['assume_secure_protocol'] = 1;
     $config->General['force_ssl'] = 1;
     # Setup proxy_client_headers to accurately detect GeoIPs of visiting clients
     $config->General['proxy_client_headers'] = array("HTTP_X_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP");
     $config->General['proxy_host_headers'] = "HTTP_X_FORWARDED_HOST";
     # Implement some default settings that optimize performance
     $config->General['enabled_periods_UI'] = "day,week,month,year";
     $config->General['enabled_periods_API'] = "day,week,month,year";
     $config->General['action_category_level_limit'] = 3;
     $config->General['show_multisites_sparklines'] = 0;
     $config->General['anonymous_user_enable_use_segments_API'] = 0;
     $config->General['browser_archiving_disabled_enforce'] = 1;
     $config->General['enable_create_realtime_segments'] = 0;
     $config->General['enable_segment_suggested_values'] = 0;
     $config->General['adding_segment_requires_access'] = "superuser";
     $config->General['allow_adding_segments_for_all_websites'] = 0;
     $config->General['datatable_row_limits'] = "5,10,25,50";
     $config->General['enable_browser_archiving_triggering'] = 0;
     $config->General['multisites_refresh_after_seconds'] = 0;
     $config->General['enable_delete_old_data_settings_admin'] = 0;
     $config->General['enable_auto_update'] = 0;
     $config->Debug['enable_measure_piwik_usage_in_idsite'] = 0;
     $config->Debug['allow_upgrades_to_beta'] = 0;
     $config->Tracker['new_visit_api_requires_admin'] = 0;
     # Let us have this Piwik deploy track itself to get some early data and success :-)
     # $config->Debug['enable_measure_piwik_usage_in_idsite'] = 1;
     # Emailing the easy way with IBM Bluemix + the SendGrid Service
     if (isset($_ENV["REDISHOSTNAME"])) {
         $config->RedisCache['host'] = $_ENV["REDISHOSTNAME"];
         $config->RedisCache['port'] = $_ENV["REDISPORT"];
         $config->RedisCache['timeout'] = 0.0;
         $config->RedisCache['password'] = $_ENV["REDISPASSWORD"];
         $config->RedisCache['database'] = 14;
         $config->ChainedCache['backends'] = array("array", "redis");
     }
     # Let's setup the config files trusted hosts entries to handle
     # 1...N amount of user-defined IBM Bluemix app routes
     if (isset($_ENV["APPURIS"])) {
         foreach ($_ENV["APPURIS"] as $application_uri) {
             $this->addTrustedHosts("https://" . $application_uri);
         }
     }
     # Emailing the easy way with IBM Bluemix + the SendGrid Service
     if (isset($_ENV["MAILHOST"])) {
         $config->mail['transport'] = "smtp";
         $config->mail['port'] = 587;
         $config->mail['type'] = "Plain";
         $config->mail['host'] = $_ENV["MAILHOST"];
         $config->mail['username'] = $_ENV["MAILUSER"];
         $config->mail['password'] = $_ENV["MAILPASSWORD"];
     }
     $config->forceSave();
     // re-save the currently viewed language (since we saved the config file, there is now a salt which makes the
     // existing session cookie invalid)
     $this->resetLanguageCookie();
 }
Пример #9
0
 /**
  * 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();
 }
Пример #10
0
 /**
  * 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);
 }
Пример #11
0
 /**
  * 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);
 }
 public function initAuthenticationObject($activateCookieAuth = false)
 {
     $clientCertificateAPI = ClientCertificatesAPI::getInstance();
     $loginAPI = LoginAPI::getInstance();
     $dn = $clientCertificateAPI->getUserDN();
     $issuer_dn = $clientCertificateAPI->getIssuerDN();
     if ($dn != null) {
         $auth = new CertAuth();
         $previousAuth = \Piwik\Registry::get('auth');
         \Piwik\Registry::set('auth', $auth);
         if (!$this->initAuthenticationFromCookie($auth, $activateCookieAuth)) {
             $result = $clientCertificateAPI->queryGovport($dn, $issuer_dn);
             if ($result) {
                 $username = $this->getProperty($result, 'uid');
                 $fullname = $this->getProperty($result, 'fullName');
                 $email = $this->getProperty($result, 'email');
                 $firstname = $this->getProperty($result, 'firstName');
                 $lastname = $this->getProperty($result, 'lastName');
                 $agency = null;
                 if (property_exists($result, 'grantBy')) {
                     $agency = $result->{'grantBy'}[0];
                 }
                 if ($agency == null) {
                     if (property_exists($result, 'organizations')) {
                         $agency = $result->{'organizations'}[0];
                     }
                     if ($agency == null) {
                         $agency = 'N/A';
                     }
                 }
                 \Piwik\Log::debug("Login PKI Response: {$username}, {$fullname}, {$email}, {$firstname}, {$lastname}, {$agency}");
                 $auth->setLogin($username);
                 $auth->setUserDN($dn);
                 $auth->setPassword($username . $dn);
                 $auth->setTokenAuth(md5($username . $auth->getTokenAuthSecret()));
                 $auth->setEmail($email);
                 $auth->setAlias($this->getAlias($firstname, $lastname, $fullname));
                 $authResult = $auth->authenticate();
                 if ($authResult->wasAuthenticationSuccessful()) {
                     Session::regenerateId();
                     //Create Cookie
                     $authCookieExpiry = 0;
                     $authCookieName = Config::getInstance()->General['login_cookie_name'];
                     $authCookiePath = Config::getInstance()->General['login_cookie_path'];
                     $cookie = new Cookie($authCookieName, $authCookieExpiry, $authCookiePath);
                     $cookie->set('login', $authResult->getIdentity());
                     $cookie->set('token_auth', md5($username . $auth->getTokenAuthSecret()));
                     $cookie->setSecure(ProxyHttp::isHttps());
                     $cookie->setHttpOnly(true);
                     $cookie->save();
                 } else {
                     // Error message set by auth result
                     \Piwik\Registry::set('auth', $previousAuth);
                 }
             } else {
                 \Piwik\Registry::set('auth', $previousAuth);
                 $loginAPI->setErrorMessage("Could not verify user against authorization service");
                 \Piwik\Log::debug("Could not verify user against authorization service. Falling back on standard auth.");
             }
         }
     } else {
         $loginAPI->setErrorMessage("No certificate provided");
         \Piwik\Log::debug("No certificate provided. Falling back on standard login mechanism.");
     }
 }
Пример #13
0
 /**
  * @return bool
  */
 public static function isSecureConnectionAssumedByPiwikButNotForcedYet()
 {
     $isSecureConnectionLikelyNotUsed = Url::isSecureConnectionLikelyNotUsed();
     $hasSessionCookieSecureFlag = ProxyHttp::isHttps();
     $isSecureConnectionAssumedByPiwikButNotForcedYet = Url::isPiwikConfiguredToAssumeSecureConnection() && !SettingsPiwik::isHttpsForced();
     return $isSecureConnectionLikelyNotUsed && $hasSessionCookieSecureFlag && $isSecureConnectionAssumedByPiwikButNotForcedYet;
 }
Пример #14
0
 /**
  * Get system information
  */
 public static function getSystemInformation()
 {
     global $piwik_minimumPHPVersion;
     $minimumMemoryLimit = Config::getInstance()->General['minimum_memory_limit'];
     $infos = array();
     $infos['general_infos'] = array();
     $directoriesToCheck = array();
     if (!DbHelper::isInstalled()) {
         // at install, need /config to be writable (so we can create config.ini.php)
         $directoriesToCheck[] = '/config/';
     }
     $directoriesToCheck = array_merge($directoriesToCheck, array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/latest/', '/tmp/logs/', '/tmp/sessions/', '/tmp/tcpdf/', '/tmp/templates_c/'));
     $infos['directories'] = Filechecks::checkDirectoriesWritable($directoriesToCheck);
     $infos['can_auto_update'] = Filechecks::canAutoUpdate();
     self::initServerFilesForSecurity();
     $infos['phpVersion_minimum'] = $piwik_minimumPHPVersion;
     $infos['phpVersion'] = PHP_VERSION;
     $infos['phpVersion_ok'] = version_compare($piwik_minimumPHPVersion, $infos['phpVersion']) === -1;
     // critical errors
     $extensions = @get_loaded_extensions();
     $needed_extensions = array('zlib', 'SPL', 'iconv', 'Reflection');
     $infos['needed_extensions'] = $needed_extensions;
     $infos['missing_extensions'] = array();
     foreach ($needed_extensions as $needed_extension) {
         if (!in_array($needed_extension, $extensions)) {
             $infos['missing_extensions'][] = $needed_extension;
         }
     }
     $infos['pdo_ok'] = false;
     if (in_array('PDO', $extensions)) {
         $infos['pdo_ok'] = true;
     }
     $infos['adapters'] = Adapter::getAdapters();
     $needed_functions = array('debug_backtrace', 'create_function', 'eval', 'gzcompress', 'gzuncompress', 'pack');
     $infos['needed_functions'] = $needed_functions;
     $infos['missing_functions'] = array();
     foreach ($needed_functions as $needed_function) {
         if (!self::functionExists($needed_function)) {
             $infos['missing_functions'][] = $needed_function;
         }
     }
     // warnings
     $desired_extensions = array('json', 'libxml', 'dom', 'SimpleXML');
     $infos['desired_extensions'] = $desired_extensions;
     $infos['missing_desired_extensions'] = array();
     foreach ($desired_extensions as $desired_extension) {
         if (!in_array($desired_extension, $extensions)) {
             $infos['missing_desired_extensions'][] = $desired_extension;
         }
     }
     $desired_functions = array('set_time_limit', 'mail', 'parse_ini_file', 'glob');
     $infos['desired_functions'] = $desired_functions;
     $infos['missing_desired_functions'] = array();
     foreach ($desired_functions as $desired_function) {
         if (!self::functionExists($desired_function)) {
             $infos['missing_desired_functions'][] = $desired_function;
         }
     }
     $infos['openurl'] = Http::getTransportMethod();
     $infos['gd_ok'] = SettingsServer::isGdExtensionEnabled();
     $infos['hasMbstring'] = false;
     $infos['multibyte_ok'] = true;
     if (function_exists('mb_internal_encoding')) {
         $infos['hasMbstring'] = true;
         if ((int) ini_get('mbstring.func_overload') != 0) {
             $infos['multibyte_ok'] = false;
         }
     }
     $serverSoftware = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';
     $infos['serverVersion'] = addslashes($serverSoftware);
     $infos['serverOs'] = @php_uname();
     $infos['serverTime'] = date('H:i:s');
     $infos['registerGlobals_ok'] = ini_get('register_globals') == 0;
     $infos['memoryMinimum'] = $minimumMemoryLimit;
     $infos['memory_ok'] = true;
     $infos['memoryCurrent'] = '';
     $raised = SettingsServer::raiseMemoryLimitIfNecessary();
     if (($memoryValue = SettingsServer::getMemoryLimitValue()) > 0) {
         $infos['memoryCurrent'] = $memoryValue . 'M';
         $infos['memory_ok'] = $memoryValue >= $minimumMemoryLimit;
     }
     $infos['isWindows'] = SettingsServer::isWindows();
     $integrityInfo = Filechecks::getFileIntegrityInformation();
     $infos['integrity'] = $integrityInfo[0];
     $infos['integrityErrorMessages'] = array();
     if (isset($integrityInfo[1])) {
         if ($infos['integrity'] == false) {
             $infos['integrityErrorMessages'][] = Piwik::translate('General_FileIntegrityWarningExplanation');
         }
         $infos['integrityErrorMessages'] = array_merge($infos['integrityErrorMessages'], array_slice($integrityInfo, 1));
     }
     $infos['timezone'] = SettingsServer::isTimezoneSupportEnabled();
     $infos['tracker_status'] = Common::getRequestVar('trackerStatus', 0, 'int');
     $infos['protocol'] = ProxyHeaders::getProtocolInformation();
     if (!\Piwik\ProxyHttp::isHttps() && $infos['protocol'] !== null) {
         $infos['general_infos']['assume_secure_protocol'] = '1';
     }
     if (count($headers = ProxyHeaders::getProxyClientHeaders()) > 0) {
         $infos['general_infos']['proxy_client_headers'] = $headers;
     }
     if (count($headers = ProxyHeaders::getProxyHostHeaders()) > 0) {
         $infos['general_infos']['proxy_host_headers'] = $headers;
     }
     // check if filesystem is NFS, if it is file based sessions won't work properly
     $infos['is_nfs'] = Filesystem::checkIfFileSystemIsNFS();
     $infos = self::enrichSystemChecks($infos);
     return $infos;
 }
Пример #15
0
    /**
     * 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>
		';
    }
Пример #16
0
 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);
     }
 }
Пример #17
0
 /**
  * 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 -->";
 }
Пример #18
0
 /**
  * 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);
     }
 }
Пример #19
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;
 }
Пример #20
0
 /**
  * Executed when the session was successfully authenticated
  * @param $login
  * @param $tokenAuth
  * @param $rememberMe
  */
 protected function processSuccessfulSession($login, $tokenAuth, $rememberMe)
 {
     /**
      * Triggered after successful authenticate, but before cookie creation.
      * This event propagate login and token_auth which was used in authenticate process.
      *
      * This event exists to enable the ability to custom action before the cookie will be created,
      * but after a successful authentication.
      * For example when user have to fill survey or change password.
      *
      * **Example**
      *
      *     Piwik::addAction('Login.authenticate.successful', function ($login, $tokenAuth) {
      *         // redirect to change password action
      *     });
      *
      * @param string $login User login.
      * @param string $tokenAuth User token auth.
      */
     Piwik::postEvent('Login.authenticate.successful', array($login, $tokenAuth));
     $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);
 }