setLocale() public static method

Set locale
public static setLocale ( string $language = null, boolean $force = false )
$language string The language to load, if not provided we will load the language based on the URL.
$force boolean Force the language, so don't check if the language is active.
Beispiel #1
0
 /**
  * Process the query string
  */
 private function processQueryString()
 {
     // store the query string local, so we don't alter it.
     $queryString = trim($this->request->getPathInfo(), '/');
     // split into chunks
     $chunks = (array) explode('/', $queryString);
     $hasMultiLanguages = $this->getContainer()->getParameter('site.multilanguage');
     // single language
     if (!$hasMultiLanguages) {
         // set language id
         $language = $this->get('fork.settings')->get('Core', 'default_language', SITE_DEFAULT_LANGUAGE);
     } else {
         // multiple languages
         // default value
         $mustRedirect = false;
         // get possible languages
         $possibleLanguages = (array) Language::getActiveLanguages();
         $redirectLanguages = (array) Language::getRedirectLanguages();
         // the language is present in the URL
         if (isset($chunks[0]) && in_array($chunks[0], $possibleLanguages)) {
             // define language
             $language = (string) $chunks[0];
             // try to set a cookie with the language
             try {
                 // set cookie
                 CommonCookie::set('frontend_language', $language);
             } catch (\SpoonCookieException $e) {
                 // settings cookies isn't allowed, because this isn't a real problem we ignore the exception
             }
             // set sessions
             \SpoonSession::set('frontend_language', $language);
             // remove the language part
             array_shift($chunks);
         } elseif (CommonCookie::exists('frontend_language') && in_array(CommonCookie::get('frontend_language'), $redirectLanguages)) {
             // set languageId
             $language = (string) CommonCookie::get('frontend_language');
             // redirect is needed
             $mustRedirect = true;
         } else {
             // default browser language
             // set languageId & abbreviation
             $language = Language::getBrowserLanguage();
             // try to set a cookie with the language
             try {
                 // set cookie
                 CommonCookie::set('frontend_language', $language);
             } catch (\SpoonCookieException $e) {
                 // settings cookies isn't allowed, because this isn't a real problem we ignore the exception
             }
             // redirect is needed
             $mustRedirect = true;
         }
         // redirect is required
         if ($mustRedirect) {
             // build URL
             $URL = rtrim('/' . $language . '/' . $this->getQueryString(), '/');
             // when we are just adding the language to the domain, it's a temporary redirect because
             // Safari keeps the 301 in cache, so the cookie to switch language doesn't work any more
             $redirectCode = $URL == '/' . $language ? 302 : 301;
             // set header & redirect
             \SpoonHTTP::redirect($URL, $redirectCode);
         }
     }
     // define the language
     defined('FRONTEND_LANGUAGE') || define('FRONTEND_LANGUAGE', $language);
     // sets the locale file
     Language::setLocale($language);
     // list of pageIds & their full URL
     $keys = Navigation::getKeys();
     // rebuild our URL, but without the language parameter. (it's tripped earlier)
     $URL = implode('/', $chunks);
     $startURL = $URL;
     // loop until we find the URL in the list of pages
     while (!in_array($URL, $keys)) {
         // remove the last chunk
         array_pop($chunks);
         // redefine the URL
         $URL = implode('/', $chunks);
     }
     // remove language from query string
     if ($hasMultiLanguages) {
         $queryString = trim(substr($queryString, strlen($language)), '/');
     }
     // if it's the homepage AND parameters were given (not allowed!)
     if ($URL == '' && $queryString != '') {
         // get 404 URL
         $URL = Navigation::getURL(404);
         // remove language
         if ($hasMultiLanguages) {
             $URL = str_replace('/' . $language, '', $URL);
         }
     }
     // set pages
     $URL = trim($URL, '/');
     // currently not in the homepage
     if ($URL != '') {
         // explode in pages
         $pages = explode('/', $URL);
         // reset pages
         $this->setPages($pages);
         // reset parameters
         $this->setParameters(array());
     }
     // set parameters
     $parameters = trim(substr($startURL, strlen($URL)), '/');
     // has at least one parameter
     if ($parameters != '') {
         // parameters will be separated by /
         $parameters = explode('/', $parameters);
         // set parameters
         $this->setParameters($parameters);
     }
     // pageId, parentId & depth
     $pageId = Navigation::getPageId(implode('/', $this->getPages()));
     $pageInfo = Navigation::getPageInfo($pageId);
     // invalid page, or parameters but no extra
     if ($pageInfo === false || !empty($parameters) && !$pageInfo['has_extra']) {
         // get 404 URL
         $URL = Navigation::getURL(404);
         // remove language
         if ($hasMultiLanguages) {
             $URL = trim(str_replace('/' . $language, '', $URL), '/');
         }
         // currently not in the homepage
         if ($URL != '') {
             // explode in pages
             $pages = explode('/', $URL);
             // reset pages
             $this->setPages($pages);
             // reset parameters
             $this->setParameters(array());
         }
     }
     // is this an internal redirect?
     if (isset($pageInfo['redirect_page_id']) && $pageInfo['redirect_page_id'] != '') {
         // get url for item
         $newPageURL = Navigation::getURL((int) $pageInfo['redirect_page_id']);
         $errorURL = Navigation::getURL(404);
         // not an error?
         if ($newPageURL != $errorURL) {
             // redirect
             \SpoonHTTP::redirect($newPageURL, $pageInfo['redirect_code']);
         }
     }
     // is this an external redirect?
     if (isset($pageInfo['redirect_url']) && $pageInfo['redirect_url'] != '') {
         // redirect
         \SpoonHTTP::redirect($pageInfo['redirect_url'], $pageInfo['redirect_code']);
     }
 }
Beispiel #2
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         $this->frm->cleanupFields();
         // shorten the fields
         $txtName = $this->frm->getField('name');
         $txtEmail = $this->frm->getField('email');
         $ddmMethod = $this->frm->getField('method');
         $txtSuccessMessage = $this->frm->getField('success_message');
         $txtIdentifier = $this->frm->getField('identifier');
         $emailAddresses = (array) explode(',', $txtEmail->getValue());
         // validate fields
         $txtName->isFilled(BL::getError('NameIsRequired'));
         $txtSuccessMessage->isFilled(BL::getError('SuccessMessageIsRequired'));
         if ($ddmMethod->isFilled(BL::getError('NameIsRequired')) && $ddmMethod->getValue() == 'database_email') {
             $error = false;
             // check the addresses
             foreach ($emailAddresses as $address) {
                 $address = trim($address);
                 if (!\SpoonFilter::isEmail($address)) {
                     $error = true;
                     break;
                 }
             }
             // add error
             if ($error) {
                 $txtEmail->addError(BL::getError('EmailIsInvalid'));
             }
         }
         // identifier
         if ($txtIdentifier->isFilled()) {
             // invalid characters
             if (!\SpoonFilter::isValidAgainstRegexp('/^[a-zA-Z0-9\\.\\_\\-]+$/', $txtIdentifier->getValue())) {
                 $txtIdentifier->setError(BL::getError('InvalidIdentifier'));
             } elseif (BackendFormBuilderModel::existsIdentifier($txtIdentifier->getValue())) {
                 // unique identifier
                 $txtIdentifier->setError(BL::getError('UniqueIdentifier'));
             }
         }
         if ($this->frm->isCorrect()) {
             // build array
             $values['language'] = BL::getWorkingLanguage();
             $values['user_id'] = BackendAuthentication::getUser()->getUserId();
             $values['name'] = $txtName->getValue();
             $values['method'] = $ddmMethod->getValue();
             $values['email'] = $ddmMethod->getValue() == 'database_email' ? serialize($emailAddresses) : null;
             $values['success_message'] = $txtSuccessMessage->getValue(true);
             $values['identifier'] = $txtIdentifier->isFilled() ? $txtIdentifier->getValue() : BackendFormBuilderModel::createIdentifier();
             $values['created_on'] = BackendModel::getUTCDate();
             $values['edited_on'] = BackendModel::getUTCDate();
             // insert the item
             $id = BackendFormBuilderModel::insert($values);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $values));
             // set frontend locale
             FL::setLocale(BL::getWorkingLanguage(), true);
             // create submit button
             $field['form_id'] = $id;
             $field['type'] = 'submit';
             $field['settings'] = serialize(array('values' => \SpoonFilter::ucfirst(FL::getLabel('Send'))));
             BackendFormBuilderModel::insertField($field);
             // everything is saved, so redirect to the editform
             $this->redirect(BackendModel::createURLForAction('Edit') . '&id=' . $id . '&report=added&var=' . urlencode($values['name']) . '#tabFields');
         }
     }
 }
Beispiel #3
0
 /**
  * Set the language
  *
  * @param string $value The (interface-)language, will be used to parse labels.
  */
 public function setLanguage($value)
 {
     // get the possible languages
     $possibleLanguages = Language::getActiveLanguages();
     // validate
     if (!in_array($value, $possibleLanguages)) {
         // only 1 active language?
         if (!Model::getContainer()->getParameter('site.multilanguage') && count($possibleLanguages) == 1) {
             $this->language = array_shift($possibleLanguages);
         } else {
             // multiple languages available but none selected
             throw new Exception('Language invalid.');
         }
     } else {
         // language is valid: set property
         $this->language = (string) $value;
     }
     // define constant
     defined('FRONTEND_LANGUAGE') || define('FRONTEND_LANGUAGE', $this->language);
     // set the locale (we need this for the labels)
     Language::setLocale($this->language);
 }
Beispiel #4
0
 /**
  * Parse the default error messages
  */
 private function parseErrorMessages()
 {
     // set frontend locale
     FL::setLocale(BL::getWorkingLanguage(), true);
     // assign error messages
     $this->tpl->assign('errors', BackendFormBuilderModel::getErrors());
 }
Beispiel #5
0
 /**
  * Get the URL for a give module & action combination
  *
  * @param string $module   The module to get the URL for.
  * @param string $action   The action to get the URL for.
  * @param string $language The language to use, if not provided we will use the working language.
  * @return string
  */
 public static function getURLForBlock($module, $action = null, $language = null)
 {
     $module = (string) $module;
     $action = $action !== null ? (string) $action : null;
     $language = $language !== null ? (string) $language : Language::getWorkingLanguage();
     $pageIdForURL = null;
     $navigation = self::getNavigation($language);
     // loop types
     foreach ($navigation as $level) {
         foreach ($level as $pages) {
             foreach ($pages as $pageId => $properties) {
                 // only process pages with extra_blocks
                 if (!isset($properties['extra_blocks']) || $properties['hidden']) {
                     continue;
                 }
                 // loop extras
                 foreach ($properties['extra_blocks'] as $extra) {
                     if ($extra['module'] == $module && $extra['action'] == $action) {
                         // exact page was found, so return
                         return self::getURL($properties['page_id'], $language);
                     } elseif ($extra['module'] == $module && $extra['action'] == null) {
                         $pageIdForURL = (int) $pageId;
                     }
                 }
             }
         }
     }
     // still no page id?
     if ($pageIdForURL === null) {
         return self::getURL(404);
     }
     $URL = self::getURL($pageIdForURL, $language);
     // set locale with force
     FrontendLanguage::setLocale($language, true);
     // append action
     $URL .= '/' . urldecode(FrontendLanguage::act(\SpoonFilter::toCamelCase($action)));
     // return the unique URL!
     return $URL;
 }
Beispiel #6
0
 /**
  * Get an unique URL for a page
  *
  * @param string $URL      The URL to base on.
  * @param int    $id       The id to ignore.
  * @param int    $parentId The parent for the page to create an url for.
  * @param bool   $isAction Is this page an action.
  * @return string
  */
 public static function getURL($URL, $id = null, $parentId = 0, $isAction = false)
 {
     $URL = (string) $URL;
     $parentIds = array((int) $parentId);
     // 0, 1, 2, 3, 4 are all top levels, so we should place them on the same level
     if ($parentId == 0 || $parentId == 1 || $parentId == 2 || $parentId == 3 || $parentId == 4) {
         $parentIds = array(0, 1, 2, 3, 4);
     }
     // get db
     $db = BackendModel::getContainer()->get('database');
     // no specific id
     if ($id === null) {
         // no items?
         if ((bool) $db->getVar('SELECT 1
              FROM pages AS i
              INNER JOIN meta AS m ON i.meta_id = m.id
              WHERE i.parent_id IN(' . implode(',', $parentIds) . ') AND i.status = ? AND m.url = ?
                 AND i.language = ?
              LIMIT 1', array('active', $URL, BL::getWorkingLanguage()))) {
             // add a number
             $URL = BackendModel::addNumber($URL);
             // recall this method, but with a new URL
             return self::getURL($URL, null, $parentId, $isAction);
         }
     } else {
         // one item should be ignored
         // there are items so, call this method again.
         if ((bool) $db->getVar('SELECT 1
              FROM pages AS i
              INNER JOIN meta AS m ON i.meta_id = m.id
              WHERE i.parent_id IN(' . implode(',', $parentIds) . ') AND i.status = ?
                 AND m.url = ? AND i.id != ? AND i.language = ?
              LIMIT 1', array('active', $URL, $id, BL::getWorkingLanguage()))) {
             // add a number
             $URL = BackendModel::addNumber($URL);
             // recall this method, but with a new URL
             return self::getURL($URL, $id, $parentId, $isAction);
         }
     }
     // get full URL
     $fullURL = self::getFullUrl($parentId) . '/' . $URL;
     // get info about parent page
     $parentPageInfo = self::get($parentId, null, BL::getWorkingLanguage());
     // does the parent have extras?
     if ($parentPageInfo['has_extra'] == 'Y' && !$isAction) {
         // set locale
         FrontendLanguage::setLocale(BL::getWorkingLanguage(), true);
         // get all on-site action
         $actions = FrontendLanguage::getActions();
         // if the new URL conflicts with an action we should rebuild the URL
         if (in_array($URL, $actions)) {
             // add a number
             $URL = BackendModel::addNumber($URL);
             // recall this method, but with a new URL
             return self::getURL($URL, $id, $parentId, $isAction);
         }
     }
     // check if folder exists
     if (is_dir(PATH_WWW . '/' . $fullURL) || is_file(PATH_WWW . '/' . $fullURL)) {
         // add a number
         $URL = BackendModel::addNumber($URL);
         // recall this method, but with a new URL
         return self::getURL($URL, $id, $parentId, $isAction);
     }
     // check if it is an application
     if (in_array(trim($fullURL, '/'), array_keys(\ApplicationRouting::getRoutes()))) {
         // add a number
         $URL = BackendModel::addNumber($URL);
         // recall this method, but with a new URL
         return self::getURL($URL, $id, $parentId, $isAction);
     }
     // return the unique URL!
     return $URL;
 }
Beispiel #7
0
 /**
  * Get the locale that is used in the frontend but doesn't exists.
  *
  * @param string $language The language to check.
  * @return array
  */
 public static function getNonExistingFrontendLocale($language)
 {
     $used = array();
     $finder = new Finder();
     $finder->notPath('cache')->name('*.php')->name('*.tpl')->name('*.js');
     // loop files
     foreach ($finder->files()->in(FRONTEND_PATH) as $file) {
         /** @var $file \SplFileInfo */
         // grab content
         $content = $file->getContents();
         // process the file based on extension
         switch ($file->getExtension()) {
             // javascript file
             case 'js':
                 $matches = array();
                 // get matches
                 preg_match_all('/\\{\\$(act|err|lbl|msg)(.*)(\\|.*)?\\}/iU', $content, $matches);
                 // any matches?
                 if (isset($matches[2])) {
                     // loop matches
                     foreach ($matches[2] as $key => $match) {
                         // set type
                         $type = $matches[1][$key];
                         // init if needed
                         if (!isset($used[$match])) {
                             $used[$type][$match] = array('files' => array());
                         }
                         // add file
                         if (!in_array($file->getRealPath(), $used[$type][$match]['files'])) {
                             $used[$type][$match]['files'][] = $file->getRealPath();
                         }
                     }
                 }
                 break;
                 // PHP file
             // PHP file
             case 'php':
                 $matches = array();
                 // get matches
                 preg_match_all('/(FrontendLanguage|FL)::(get(Action|Label|Error|Message)|act|lbl|err|msg)\\(\'(.*)\'\\)/iU', $content, $matches);
                 // any matches?
                 if (!empty($matches[4])) {
                     // loop matches
                     foreach ($matches[4] as $key => $match) {
                         $type = 'lbl';
                         if ($matches[3][$key] == 'Action') {
                             $type = 'act';
                         }
                         if ($matches[2][$key] == 'act') {
                             $type = 'act';
                         }
                         if ($matches[3][$key] == 'Error') {
                             $type = 'err';
                         }
                         if ($matches[2][$key] == 'err') {
                             $type = 'err';
                         }
                         if ($matches[3][$key] == 'Message') {
                             $type = 'msg';
                         }
                         if ($matches[2][$key] == 'msg') {
                             $type = 'msg';
                         }
                         // init if needed
                         if (!isset($used[$type][$match])) {
                             $used[$type][$match] = array('files' => array());
                         }
                         // add file
                         if (!in_array($file->getRealPath(), $used[$type][$match]['files'])) {
                             $used[$type][$match]['files'][] = $file->getRealPath();
                         }
                     }
                 }
                 break;
                 // template file
             // template file
             case 'tpl':
                 $matches = array();
                 // get matches
                 preg_match_all('/\\{\\$(act|err|lbl|msg)([a-z-_]*)(\\|.*)?\\}/iU', $content, $matches);
                 // any matches?
                 if (isset($matches[2])) {
                     // loop matches
                     foreach ($matches[2] as $key => $match) {
                         // set type
                         $type = $matches[1][$key];
                         // init if needed
                         if (!isset($used[$type][$match])) {
                             $used[$type][$match] = array('files' => array());
                         }
                         // add file
                         if (!in_array($file->getRealPath(), $used[$type][$match]['files'])) {
                             $used[$type][$match]['files'][] = $file->getRealPath();
                         }
                     }
                 }
                 break;
         }
     }
     // init var
     $nonExisting = array();
     // set language
     FL::setLocale($language);
     // check if the locale is present in the current language
     foreach ($used as $type => $items) {
         // loop items
         foreach ($items as $key => $data) {
             // process based on type
             switch ($type) {
                 case 'act':
                     // if the action isn't available add it to the list
                     if (FL::act($key, false) == '{$' . $type . $key . '}') {
                         $nonExisting['Frontend' . $key . $type] = array('language' => $language, 'application' => 'Frontend', 'module' => 'Core', 'type' => $type, 'name' => $key, 'used_in' => serialize($data['files']));
                     }
                     break;
                 case 'err':
                     // if the error isn't available add it to the list
                     if (FL::err($key, false) == '{$' . $type . $key . '}') {
                         $nonExisting['Frontend' . $key . $type] = array('language' => $language, 'application' => 'Frontend', 'module' => 'Core', 'type' => $type, 'name' => $key, 'used_in' => serialize($data['files']));
                     }
                     break;
                 case 'lbl':
                     // if the label isn't available add it to the list
                     if (FL::lbl($key, false) == '{$' . $type . $key . '}') {
                         $nonExisting['Frontend' . $key . $type] = array('language' => $language, 'application' => 'Frontend', 'module' => 'Core', 'type' => $type, 'name' => $key, 'used_in' => serialize($data['files']));
                     }
                     break;
                 case 'msg':
                     // if the message isn't available add it to the list
                     if (FL::msg($key, false) == '{$' . $type . $key . '}') {
                         $nonExisting['Frontend' . $key . $type] = array('language' => $language, 'application' => 'Frontend', 'module' => 'Core', 'type' => $type, 'name' => $key, 'used_in' => serialize($data['files']));
                     }
                     break;
             }
         }
     }
     ksort($nonExisting);
     return $nonExisting;
 }