public function tearDown()
 {
     MultilingualRootURLController::set_use_locale_url($this->origLocaleRoutingEnabled);
     Translatable::set_current_locale($this->origCurrentLocale);
     Translatable::set_default_locale($this->origLocale);
     Translatable::set_allowed_locales($this->origAllowedLocales);
     i18n::set_locale($this->origi18nLocale);
     Cookie::force_expiry('language');
     if ($this->origCookieLocale) {
         Cookie::set('language', $this->origCookieLocale);
     }
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $this->origAcceptLanguage;
     MultilingualRootURLController::reset();
     parent::tearDown();
 }
예제 #2
0
 /**
  * Logs this member out.
  */
 public function logOut()
 {
     $this->extend('beforeMemberLoggedOut');
     Session::clear("loggedInAs");
     if (Member::config()->login_marker_cookie) {
         Cookie::set(Member::config()->login_marker_cookie, null, 0);
     }
     Session::destroy();
     $this->extend('memberLoggedOut');
     $this->RememberLoginToken = null;
     Cookie::set('alc_enc', null);
     // // Clear the Remember Me cookie
     Cookie::force_expiry('alc_enc');
     // Switch back to live in order to avoid infinite loops when
     // redirecting to the login screen (if this login screen is versioned)
     Session::clear('readingMode');
     $this->write();
     // Audit logging hook
     $this->extend('memberLoggedOut');
 }
예제 #3
0
 public function inst_destroy($removeCookie = true)
 {
     if (session_id()) {
         if ($removeCookie) {
             $path = Config::inst()->get('Session', 'cookie_path') ?: Director::baseURL();
             $domain = Config::inst()->get('Session', 'cookie_domain');
             $secure = Config::inst()->get('Session', 'cookie_secure');
             Cookie::force_expiry(session_name(), $path, $domain, $secure, true);
         }
         session_destroy();
         // Clean up the superglobal - session_destroy does not do it.
         // http://nz1.php.net/manual/en/function.session-destroy.php
         unset($_SESSION);
         $this->data = array();
     }
 }
예제 #4
0
파일: DB.php 프로젝트: ntd/sapphire
 /**
  * Set an alternative database in a browser cookie,
  * with the cookie lifetime set to the browser session.
  * This is useful for integration testing on temporary databases.
  *
  * There is a strict naming convention for temporary databases to avoid abuse:
  * <prefix> (default: 'ss_') + tmpdb + <7 digits>
  * As an additional security measure, temporary databases will
  * be ignored in "live" mode.
  *
  * Note that the database will be set on the next request.
  * Set it to null to revert to the main database.
  */
 public static function set_alternative_database_name($name = null)
 {
     if ($name) {
         if (!self::valid_alternative_database_name($name)) {
             throw new InvalidArgumentException(sprintf('Invalid alternative database name: "%s"', $name));
         }
         $key = Config::inst()->get('Security', 'token');
         if (!$key) {
             throw new LogicException('"Security.token" not found, run "sake dev/generatesecuretoken"');
         }
         if (!function_exists('mcrypt_encrypt')) {
             throw new LogicException('DB::set_alternative_database_name() requires the mcrypt PHP extension');
         }
         $key = md5($key);
         // Ensure key is correct length for chosen cypher
         $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB);
         $iv = mcrypt_create_iv($ivSize);
         $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $name, MCRYPT_MODE_CFB, $iv);
         // Set to browser session lifetime, and restricted to HTTP access only
         Cookie::set("alternativeDatabaseName", base64_encode($encrypted), 0, null, null, false, true);
         Cookie::set("alternativeDatabaseNameIv", base64_encode($iv), 0, null, null, false, true);
     } else {
         Cookie::force_expiry("alternativeDatabaseName", null, null, false, true);
         Cookie::force_expiry("alternativeDatabaseNameIv", null, null, false, true);
     }
 }
 public function destroy($session_id)
 {
     $this->currentCookieData = null;
     Cookie::force_expiry($this->cookie);
 }
 /**
  * Determines the locale best matching the given list of browser locales
  * @return {string} The matching locale, or null if none could be determined
  */
 public static function detect_browser_locale()
 {
     if ($language = Cookie::get('language')) {
         if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) {
             $locale = $language;
         } else {
             $locale = i18n::get_locale_from_lang($language);
         }
         if (in_array($locale, Translatable::get_allowed_locales())) {
             return $locale;
         } else {
             Cookie::force_expiry('language');
         }
     }
     // Given multiple canditates, narrow down the final result using the client's preferred languages
     $inputLocales = array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
     if (empty($inputLocales)) {
         return null;
     }
     // Generate mapping of priority => list of languages at this priority
     // break up string into pieces (languages and q factors)
     preg_match_all('/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\\s*(;\\s*q\\s*=\\s*(?<priority>1|0\\.[0-9]+))?/i', $inputLocales, $parsedLocales);
     $prioritisedLocales = array();
     if (count($parsedLocales['code'])) {
         // create a list like "en" => 0.8
         $parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']);
         // Generate nested list of priorities => [languages]
         foreach ($parsedLocales as $language => $priority) {
             $priority = empty($priority) ? 1.0 : floatval($priority);
             if (empty($prioritisedLocales[$priority])) {
                 $prioritisedLocales[$priority] = array();
             }
             $prioritisedLocales[$priority][] = $language;
         }
         // sort list based on value
         krsort($prioritisedLocales, SORT_NUMERIC);
     }
     // Check each requested language against loaded languages
     foreach ($prioritisedLocales as $priority => $parsedLocales) {
         foreach ($parsedLocales as $browserLocale) {
             foreach (Translatable::get_allowed_locales() as $language) {
                 if (stripos(preg_replace('/_/', '-', $language), $browserLocale) === 0) {
                     return $language;
                 }
             }
         }
     }
     return null;
 }
예제 #7
0
 /**
  * Choose the stage the site is currently on.
  *
  * If $_GET['stage'] is set, then it will use that stage, and store it in
  * the session.
  *
  * if $_GET['archiveDate'] is set, it will use that date, and store it in
  * the session.
  *
  * If neither of these are set, it checks the session, otherwise the stage
  * is set to 'Live'.
  *
  * @param Session $session Optional session within which to store the resulting stage
  */
 public static function choose_site_stage($session = null)
 {
     // Check any pre-existing session mode
     $preexistingMode = $session ? $session->inst_get('readingMode') : Session::get('readingMode');
     // Determine the reading mode
     if (isset($_GET['stage'])) {
         $stage = ucfirst(strtolower($_GET['stage']));
         if (!in_array($stage, array('Stage', 'Live'))) {
             $stage = 'Live';
         }
         $mode = 'Stage.' . $stage;
     } elseif (isset($_GET['archiveDate']) && strtotime($_GET['archiveDate'])) {
         $mode = 'Archive.' . $_GET['archiveDate'];
     } elseif ($preexistingMode) {
         $mode = $preexistingMode;
     } else {
         $mode = self::DEFAULT_MODE;
     }
     // Save reading mode
     Versioned::set_reading_mode($mode);
     // Try not to store the mode in the session if not needed
     if ($preexistingMode && $preexistingMode !== $mode || !$preexistingMode && $mode !== self::DEFAULT_MODE) {
         if ($session) {
             $session->inst_set('readingMode', $mode);
         } else {
             Session::set('readingMode', $mode);
         }
     }
     if (!headers_sent() && !Director::is_cli()) {
         if (Versioned::current_stage() == 'Live') {
             // clear the cookie if it's set
             if (Cookie::get('bypassStaticCache')) {
                 Cookie::force_expiry('bypassStaticCache', null, null, false, true);
             }
         } else {
             // set the cookie if it's cleared
             if (!Cookie::get('bypassStaticCache')) {
                 Cookie::set('bypassStaticCache', '1', 0, null, null, false, true);
             }
         }
     }
 }
 /**
  * Log the currently logged in user out of the local SilverStripe website.
  * This function should only be called after logging out of the identity provider.
  *
  * @see logout()
  */
 public function loggedout()
 {
     self::force_ssl();
     //Log out SilverStripe members
     if ($member = Member::currentUser()) {
         $member->logout();
     }
     Cookie::force_expiry('SimpleSAMLAuthToken');
     //Use the BackURL for redirection if avaiable, or use the default logged out URL
     $backUrl = Session::get('BackURL');
     $dest = !empty($backUrl) ? $backUrl : $this->config()->default_logged_out_url;
     Session::clear('BackURL');
     return $this->redirect($dest);
 }
    public function onBeforeInit()
    {
        // Theme is not yet defined properly at this time
        /* @var $request SS_HttpRequest */
        $request = $this->owner->getRequest();
        $url = $request->getURL();
        if (strpos($url, 'dev/build') === 0) {
            return;
        }
        if ($this->isAdminBackend()) {
            $member = Member::currentUser();
            // Silverstripe does not redirect if invalid login to the /admin section so layout will be broken
            if ($member && $member->ID) {
                if (class_exists('Subsite')) {
                    Subsite::$disable_subsite_filter = true;
                }
                $access = Permission::checkMember($member, 'CMS_ACCESS');
                if (class_exists('Subsite')) {
                    Subsite::$disable_subsite_filter = false;
                }
                if (!$access) {
                    $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : Director::baseURL();
                    Session::set("Security.Message.message", _t('Security.ALREADYLOGGEDIN'));
                    Session::set("Security.Message.type", 'warning');
                    Session::set("BackURL", $uri);
                    Session::save();
                    header('Location:' . Director::absoluteBaseURL() . '/Security/login' . "?BackURL=" . urlencode($uri));
                    exit;
                }
            }
            return;
        }
        $conf = $this->config();
        if ($iframe = $request->getVar('iframe')) {
            if (!$iframe || $iframe == 'disabled') {
                Cookie::force_expiry('iframe');
            } else {
                Cookie::set('iframe', true);
            }
        }
        $outdated = $conf->outdated_browser;
        if ($outdated && $outdated['enabled']) {
            if (Director::isDev()) {
                ThemeHeadRequirements::javascript(THEME_FRAMEWORK_PATH . '/javascript/outdatedbrowser/outdatedbrowser.js');
                Requirements::css(THEME_FRAMEWORK_PATH . '/javascript/outdatedbrowser/outdatedbrowser.css');
            } else {
                ThemeHeadRequirements::javascript(THEME_FRAMEWORK_PATH . '/javascript/outdatedbrowser/outdatedbrowser.min.js');
                Requirements::css(THEME_FRAMEWORK_PATH . '/javascript/outdatedbrowser/outdatedbrowser.min.css');
            }
            ThemeHeadRequirements::javascriptTemplate(THEME_FRAMEWORK_PATH . '/javascript/outdated.js', array('BgColor' => $outdated['bg_color'], 'Color' => $outdated['color'], 'LowerThan' => $outdated['lower_than'], 'Lang' => i18n::get_lang_from_locale(i18n::get_locale())));
        }
        if ($conf->include_jquery) {
            FormExtraJquery::include_jquery();
        }
        if ($conf->include_jquery_ui) {
            FormExtraJquery::include_jquery_ui();
        }
        $uikit = $conf->uikit;
        if ($uikit && $uikit['enabled']) {
            $uikitTheme = 'uikit';
            if ($uikit['theme']) {
                $uikitTheme .= '.' . $uikit['theme'];
            }
            $uikitComponents = $uikit['components'];
            if (Director::isDev()) {
                Requirements::javascript(THEME_FRAMEWORK_PATH . '/uikit/js/uikit.js');
                if ($uikit['theme_enabled']) {
                    Requirements::css(THEME_FRAMEWORK_PATH . '/uikit/css/' . $uikitTheme . '.css');
                }
                foreach ($uikitComponents as $component) {
                    Requirements::javascript(THEME_FRAMEWORK_PATH . '/uikit/js/components/' . $component . '.js');
                    if ($uikit['theme_enabled']) {
                        $componentTheme = '';
                        if ($uikit['theme']) {
                            $componentTheme = '.' . $uikit['theme'];
                        }
                        Requirements::css(THEME_FRAMEWORK_PATH . '/uikit/css/components/' . $component . $componentTheme . '.css');
                    }
                }
            } else {
                Requirements::javascript(THEME_FRAMEWORK_PATH . '/uikit/js/uikit.min.js');
                if ($uikit['theme_enabled']) {
                    Requirements::css(THEME_FRAMEWORK_PATH . '/uikit/css/' . $uikitTheme . '.min.css');
                }
                foreach ($uikitComponents as $component) {
                    Requirements::javascript(THEME_FRAMEWORK_PATH . '/uikit/js/components/' . $component . '.min.js');
                    if ($uikit['theme_enabled']) {
                        $componentTheme = '';
                        if ($uikit['theme']) {
                            $componentTheme = '.' . $uikit['theme'];
                        }
                        Requirements::css(THEME_FRAMEWORK_PATH . '/uikit/css/components/' . $component . $componentTheme . '.min.css');
                    }
                }
            }
            // If we loaded notify
            if (in_array('notify', $uikitComponents)) {
                if ($this->owner->hasMethod('SessionMessage') && $this->owner->SessionMessage(false)) {
                    $this->sessionMessage = $message = $this->owner->SessionMessage();
                    $content = Convert::raw2js($message->Content);
                    $type = Convert::raw2js($message->Type);
                    // Convert default Silverstripe types
                    switch ($type) {
                        case self::MESSAGE_BAD:
                            $type = self::NOTIFY_DANGER;
                            break;
                        case self::MESSAGE_GOOD:
                            $type = self::NOTIFY_SUCCESS;
                            break;
                        case self::MESSAGE_WARNING:
                            $type = self::NOTIFY_WARNING;
                            break;
                        case self::MESSAGE_INFO:
                            $type = self::NOTIFY_INFO;
                            break;
                    }
                    Requirements::customScript(<<<JS
UIkit.notify('{$content}',{
  status: '{$type}',
  timeout: 0
});
JS
);
                }
            }
        }
        $noty = $conf->noty;
        if ($noty && $noty['enabled']) {
            if (Director::isDev()) {
                Requirements::javascript(THEME_FRAMEWORK_PATH . '/javascript/noty/packaged/jquery.noty.packaged.js');
            } else {
                Requirements::javascript(THEME_FRAMEWORK_PATH . '/javascript/noty/packaged/jquery.noty.packaged.min.js');
            }
            $theme = $noty['theme'];
            $layout = $noty['layout'];
            Requirements::css(THEME_FRAMEWORK_PATH . '/javascript/noty/themes/' . $theme . '.css');
            Requirements::customScript(<<<JS
jQuery.extend(jQuery.noty.defaults,{
  theme: '{$theme}',
  layout: '{$layout}',
  closeWith: ['click','button']
});
JS
);
            // Flash messages
            if ($this->owner->hasMethod('SessionMessage') && $this->owner->SessionMessage(false)) {
                $this->sessionMessage = $message = $this->owner->SessionMessage();
                $content = Convert::raw2js($message->Content);
                $type = Convert::raw2js($message->Type);
                // Convert default Silverstripe types
                switch ($type) {
                    case self::MESSAGE_BAD:
                        $type = self::NOTY_ERROR;
                        break;
                    case self::MESSAGE_GOOD:
                        $type = self::NOTY_SUCCESS;
                        break;
                    case self::MESSAGE_WARNING:
                        $type = self::NOTY_ALERT;
                        break;
                    case self::MESSAGE_INFO:
                        $type = self::NOTY_INFO;
                        break;
                }
                Requirements::customScript(<<<JS
noty({
  text: '{$content}',
  type: '{$type}',
  timeout: false
});
JS
);
            }
        }
        // Forcing js to bottom allow to put some scripts tags in the head if we want to
        Requirements::set_force_js_to_bottom(true);
    }
 function Logout()
 {
     Cookie::set('_pmspu', false);
     Cookie::force_expiry('_pmspu');
 }
예제 #11
0
 /**
  * Check we can remove cookies and we can access their original values
  */
 public function testForceExpiry()
 {
     //load an existing cookie
     $cookieJar = new CookieJar(array('cookieExisting' => 'i woz here'));
     Injector::inst()->registerService($cookieJar, 'Cookie_Backend');
     //make sure it's available
     $this->assertEquals('i woz here', Cookie::get('cookieExisting'));
     //remove the cookie
     Cookie::force_expiry('cookieExisting');
     //check it's gone
     $this->assertEmpty(Cookie::get('cookieExisting'));
     //check we can get it's original value
     $this->assertEquals('i woz here', Cookie::get('cookieExisting', false));
     //check we can add a new cookie and remove it and it doesn't leave any phantom values
     Cookie::set('newCookie', 'i am new');
     //check it's set by not recieved
     $this->assertEquals('i am new', Cookie::get('newCookie'));
     $this->assertEmpty(Cookie::get('newCookie', false));
     //remove it
     Cookie::force_expiry('newCookie');
     //check it's neither set nor reveived
     $this->assertEmpty(Cookie::get('newCookie'));
     $this->assertEmpty(Cookie::get('newCookie', false));
 }
 /** 
  * destroy_temp_basket_id
  * Destroy the TempBasketID for the current user.
  *
  * @return Boolean
  */
 public static function destroy_temp_basket_id()
 {
     return Cookie::force_expiry('TempBasketID') ? true : false;
 }