/** * Returns a list of languages the user has selected in their browser’s settings, canonicalized using * {@link LocaleData::getCanonicalID}. * * Internally, this method checks the Accept-Language header that should have accompanied the request. * If that header was not present, the method will return `false`. * * @return array|false The preferred languages, or `false` if Craft is unable to determine them. */ public function getBrowserLanguages() { if (!isset($this->_browserLanguages)) { $this->_browserLanguages = array(); if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && preg_match_all('/([\\w\\-_]+)\\s*(?:;\\s*q\\s*=\\s*(\\d*\\.\\d*))?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches, PREG_SET_ORDER)) { $weights = array(); foreach ($matches as $match) { $this->_browserLanguages[] = LocaleData::getCanonicalID($match[1]); $weights[] = !empty($match[2]) ? floatval($match[2]) : 1; } // Sort the languages by their weight array_multisort($weights, SORT_NUMERIC, SORT_DESC, $this->_browserLanguages); } } if ($this->_browserLanguages) { return $this->_browserLanguages; } else { return false; } }
/** * Returns the user preferred languages sorted by preference. * The returned language IDs will be canonicalized using {@link LocaleData::getCanonicalID}. * This method returns false if the user does not have language preferences. * * @return array the user preferred languages. */ public function getBrowserLanguages() { if ($this->_browserLanguages === null) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n = preg_match_all('/([\\w\\-_]+)\\s*(;\\s*q\\s*=\\s*(\\d*\\.\\d*))?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches)) > 0) { $languages = array(); for ($i = 0; $i < $n; ++$i) { $languages[$matches[1][$i]] = empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]); } // Sort by it's weight. arsort($languages); foreach ($languages as $language => $pref) { $this->_browserLanguages[] = LocaleData::getCanonicalID($language); } } if ($this->_browserLanguages === null) { return false; } } return $this->_browserLanguages; }