_preferredLanguages===null)
{
$sortedLanguages=array();
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
{
$languages=array();
for($i=0;$i<$n;++$i)
{
$q=$matches[2][$i];
if($q==='')
$q=1;
if($q)
$languages[]=array((float)$q,$matches[1][$i]);
}
usort($languages, array($this, 'stringCompare'));
foreach($languages as $language)
$sortedLanguages[]=$language[1];
}
$this->_preferredLanguages=$sortedLanguages;
}
return $this->_preferredLanguages;
}
/**
* Returns the user-preferred language that should be used by this application.
* The language resolution is based on the user preferred languages and the languages
* supported by the application. The method will try to find the best match.
* @param array $languages a list of the languages supported by the application.
* If empty, this method will return the first language returned by [[getPreferredLanguages()]].
* @return string the language that the application should use. false is returned if both [[getPreferredLanguages()]]
* and `$languages` are empty.
*/
public function getPreferredLanguage($languages=array())
{
$preferredLanguages=$this->getPreferredLanguages();
if(empty($languages)) {
return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
}
foreach ($preferredLanguages as $preferredLanguage) {
$preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
foreach ($languages as $language) {
$language=CLocale::getCanonicalID($language);
// en_us==en_us, en==en_us, en_us==en
if($language===$preferredLanguage || strpos($preferredLanguage,$language.'_')===0 || strpos($language,$preferredLanguage.'_')===0) {
return $language;
}
}
}
return reset($languages);
}
/**
* Sends a file to user.
* @param string $fileName file name
* @param string $content content to be set.
* @param string $mimeType mime type of the content. If null, it will be guessed automatically based on the given file name.
* @param boolean $terminate whether to terminate the current application after calling this method
* @throws CHttpException
*/
public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
{
if($mimeType===null)
{
if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
$mimeType='text/plain';
}
$fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
$contentStart=0;
$contentEnd=$fileSize-1;
$httpVersion=$this->getHttpVersion();
if(isset($_SERVER['HTTP_RANGE']))
{
header('Accept-Ranges: bytes');
//client sent us a multibyte range, can not hold this one for now
if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
{
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
throw new CHttpException(416,'Requested Range Not Satisfiable');
}
$range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
//range requests starts from "-", so it means that data must be dumped the end point.
if($range[0]==='-')
$contentStart=$fileSize-substr($range,1);
else
{
$range=explode('-',$range);
$contentStart=$range[0];
// check if the last-byte-pos presents in header
if((isset($range[1]) && is_numeric($range[1])))
$contentEnd=$range[1];
}
/* Check the range and make sure it's treated according to the specs.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
// End bytes can not be larger than $end.
$contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
// Validate the requested range and return an error if it's not correct.
$wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
if($wrongContentStart)
{
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
throw new CHttpException(416,'Requested Range Not Satisfiable');
}
header("HTTP/$httpVersion 206 Partial Content");
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
}
else
header("HTTP/$httpVersion 200 OK");
$length=$contentEnd-$contentStart+1; // Calculate new content length
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: $mimeType");
header('Content-Length: '.$length);
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Content-Transfer-Encoding: binary');
$content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length,'8bit') : substr($content,$contentStart,$length);
if($terminate)
{
// clean up the application first because the file downloading could take long time
// which may cause timeout of some resources (such as DB connection)
ob_start();
Yii::app()->end(0,false);
ob_end_clean();
echo $content;
exit(0);
}
else
echo $content;
}
/**
* Sends existing file to a browser as a download using x-sendfile.
*
* X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
* that in turn processes the request, this way eliminating the need to perform tasks like reading the file
* and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
* increase in performance as the web application is allowed to terminate earlier while the webserver is
* handling the request.
*
* The request is sent to the server through a special non-standard HTTP-header.
* When the web server encounters the presence of such header it will discard all output and send the file
* specified by that header using web server internals including all optimizations like caching-headers.
*
* As this header directive is non-standard different directives exists for different web servers applications:
*
* - Apache: {@link http://tn123.org/mod_xsendfile X-Sendfile}
* - Lighttpd v1.4: {@link http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file X-LIGHTTPD-send-file}
* - Lighttpd v1.5: {@link http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file X-Sendfile}
* - Nginx: {@link http://wiki.nginx.org/XSendfile X-Accel-Redirect}
* - Cherokee: {@link http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile X-Sendfile and X-Accel-Redirect}
*
* So for this method to work the X-SENDFILE option/module should be enabled by the web server and
* a proper xHeader should be sent.
*
* Note:
* This option allows to download files that are not under web folders, and even files that are otherwise protected (deny from all) like .htaccess
*
* Side effects:
* If this option is disabled by the web server, when this method is called a download configuration dialog
* will open but the downloaded file will have 0 bytes.
*
* Known issues:
* There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
* an error message like this: "Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found.".
* You can work around this problem by removing the Pragma
-header.
*
* Example:
*
* request->xSendFile('/home/user/Pictures/picture1.jpg',array(
* 'saveName'=>'image1.jpg',
* 'mimeType'=>'image/jpeg',
* 'terminate'=>false,
* ));
* ?>
*
* @param string $filePath file name with full path
* @param array $options additional options:
*
* - saveName: file name shown to the user, if not set real file name will be used
* - mimeType: mime type of the file, if not set it will be guessed automatically based on the file name, if set to null no content-type header will be sent.
* - xHeader: appropriate x-sendfile header, defaults to "X-Sendfile"
* - terminate: whether to terminate the current application after calling this method, defaults to true
* - forceDownload: specifies whether the file will be downloaded or shown inline, defaults to true. (Since version 1.1.9.)
* - addHeaders: an array of additional http headers in header-value pairs (available since version 1.1.10)
*
*/
public function xSendFile($filePath, $options=array())
{
if(!isset($options['forceDownload']) || $options['forceDownload'])
$disposition='attachment';
else
$disposition='inline';
if(!isset($options['saveName']))
$options['saveName']=basename($filePath);
if(!isset($options['mimeType']))
{
if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
$options['mimeType']='text/plain';
}
if(!isset($options['xHeader']))
$options['xHeader']='X-Sendfile';
if($options['mimeType']!==null)
header('Content-Type: '.$options['mimeType']);
header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
if(isset($options['addHeaders']))
{
foreach($options['addHeaders'] as $header=>$value)
header($header.': '.$value);
}
header(trim($options['xHeader']).': '.$filePath);
if(!isset($options['terminate']) || $options['terminate'])
Yii::app()->end();
}
/**
* Returns the random token used to perform CSRF validation.
* The token will be read from cookie first. If not found, a new token
* will be generated.
* @return string the random token for CSRF validation.
* @see enableCsrfValidation
*/
public function getCsrfToken()
{
if($this->_csrfToken===null)
{
$cookie=$this->getCookies()->itemAt($this->csrfTokenName);
if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
{
$cookie=$this->createCsrfCookie();
$this->_csrfToken=$cookie->value;
$this->getCookies()->add($cookie->name,$cookie);
}
}
return $this->_csrfToken;
}
/**
* Creates a cookie with a randomly generated CSRF token.
* Initial values specified in {@link csrfCookie} will be applied
* to the generated cookie.
* @return CHttpCookie the generated cookie
* @see enableCsrfValidation
*/
protected function createCsrfCookie()
{
$securityManager=Yii::app()->getSecurityManager();
$token=$securityManager->generateRandomBytes(32);
$maskedToken=$securityManager->maskToken($token);
$cookie=new CHttpCookie($this->csrfTokenName,$maskedToken);
if(is_array($this->csrfCookie))
{
foreach($this->csrfCookie as $name=>$value)
$cookie->$name=$value;
}
return $cookie;
}
/**
* Performs the CSRF validation.
* This is the event handler responding to {@link CApplication::onBeginRequest}.
* The default implementation will compare the CSRF token obtained
* from a cookie and from a POST field. If they are different, a CSRF attack is detected.
* @param CEvent $event event parameter
* @throws CHttpException if the validation fails
*/
public function validateCsrfToken($event)
{
if ($this->getIsPostRequest() ||
$this->getIsPutRequest() ||
$this->getIsPatchRequest() ||
$this->getIsDeleteRequest())
{
$cookies=$this->getCookies();
$method=$this->getRequestType();
switch($method)
{
case 'POST':
$maskedUserToken=$this->getPost($this->csrfTokenName);
break;
case 'PUT':
$maskedUserToken=$this->getPut($this->csrfTokenName);
break;
case 'PATCH':
$maskedUserToken=$this->getPatch($this->csrfTokenName);
break;
case 'DELETE':
$maskedUserToken=$this->getDelete($this->csrfTokenName);
}
if (!empty($maskedUserToken) && $cookies->contains($this->csrfTokenName))
{
$securityManager=Yii::app()->getSecurityManager();
$maskedCookieToken=$cookies->itemAt($this->csrfTokenName)->value;
$cookieToken=$securityManager->unmaskToken($maskedCookieToken);
$userToken=$securityManager->unmaskToken($maskedUserToken);
$valid=$cookieToken===$userToken;
}
else
$valid = false;
if (!$valid)
throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
}
}
/**
* Returns the version of the HTTP protocol used by client.
*
* @return string the version of the HTTP protocol.
* @since 1.1.16
*/
public function getHttpVersion()
{
if($this->_httpVersion===null)
{
if(isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL']==='HTTP/1.0')
$this->_httpVersion='1.0';
else
$this->_httpVersion='1.1';
}
return $this->_httpVersion;
}
}
/**
* CCookieCollection implements a collection class to store cookies.
*
* You normally access it via {@link CHttpRequest::getCookies()}.
*
* Since CCookieCollection extends from {@link CMap}, it can be used
* like an associative array as follows:
*
* $cookies[$name]=new CHttpCookie($name,$value); // sends a cookie
* $value=$cookies[$name]->value; // reads a cookie value
* unset($cookies[$name]); // removes a cookie
*
*
* @author Qiang Xue
* @package system.web
* @since 1.0
*/
class CCookieCollection extends CMap
{
private $_request;
private $_initialized=false;
/**
* Constructor.
* @param CHttpRequest $request owner of this collection.
*/
public function __construct(CHttpRequest $request)
{
$this->_request=$request;
$this->copyfrom($this->getCookies());
$this->_initialized=true;
}
/**
* @return CHttpRequest the request instance
*/
public function getRequest()
{
return $this->_request;
}
/**
* @return array list of validated cookies
*/
protected function getCookies()
{
$cookies=array();
if($this->_request->enableCookieValidation)
{
$sm=Yii::app()->getSecurityManager();
foreach($_COOKIE as $name=>$value)
{
if(is_string($value) && ($value=$sm->validateData($value))!==false)
$cookies[$name]=new CHttpCookie($name,@unserialize($value));
}
}
else
{
foreach($_COOKIE as $name=>$value)
$cookies[$name]=new CHttpCookie($name,$value);
}
return $cookies;
}
/**
* Adds a cookie with the specified name.
* This overrides the parent implementation by performing additional
* operations for each newly added CHttpCookie object.
* @param mixed $name Cookie name.
* @param CHttpCookie $cookie Cookie object.
* @throws CException if the item to be inserted is not a CHttpCookie object.
*/
public function add($name,$cookie)
{
if($cookie instanceof CHttpCookie)
{
$this->remove($name);
parent::add($name,$cookie);
if($this->_initialized)
$this->addCookie($cookie);
}
else
throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
}
/**
* Removes a cookie with the specified name.
* This overrides the parent implementation by performing additional
* cleanup work when removing a CHttpCookie object.
* Since version 1.1.11, the second parameter is available that can be used to specify
* the options of the CHttpCookie being removed. For example, this may be useful when dealing
* with ".domain.tld" where multiple subdomains are expected to be able to manage cookies:
*
*
* $options=array('domain'=>'.domain.tld');
* Yii::app()->request->cookies['foo']=new CHttpCookie('cookie','value',$options);
* Yii::app()->request->cookies->remove('cookie',$options);
*
*
* @param mixed $name Cookie name.
* @param array $options Cookie configuration array consisting of name-value pairs, available since 1.1.11.
* @return CHttpCookie The removed cookie object.
*/
public function remove($name,$options=array())
{
if(($cookie=parent::remove($name))!==null)
{
if($this->_initialized)
{
$cookie->configure($options);
$this->removeCookie($cookie);
}
}
return $cookie;
}
/**
* Sends a cookie.
* @param CHttpCookie $cookie cookie to be sent
*/
protected function addCookie($cookie)
{
$value=$cookie->value;
if($this->_request->enableCookieValidation)
$value=Yii::app()->getSecurityManager()->hashData(serialize($value));
if(version_compare(PHP_VERSION,'7.3.0','>='))
setcookie($cookie->name,$value,$this->getCookieOptions($cookie));
elseif(version_compare(PHP_VERSION,'5.2.0','>='))
setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
else
setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
}
/**
* Deletes a cookie.
* @param CHttpCookie $cookie cookie to be deleted
*/
protected function removeCookie($cookie)
{
$cookie->expire=0;
if(version_compare(PHP_VERSION,'7.3.0','>='))
setcookie($cookie->name,'',$this->getCookieOptions($cookie));
elseif(version_compare(PHP_VERSION,'5.2.0','>='))
setcookie($cookie->name,'',$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
else
setcookie($cookie->name,'',$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
}
/**
* Builds the setcookie $options parameter.
* @param CHttpCookie $cookie
* @return array
*/
protected function getCookieOptions($cookie)
{
return array(
'expires'=>$cookie->expire,
'path'=>$cookie->path,
'domain'=>$cookie->domain,
'secure'=>$cookie->secure,
'httpOnly'=>$cookie->httpOnly,
'sameSite'=>$cookie->sameSite
);
}
}