<?php

use Qii\Autoloader\Import;
use Qii\Autoloader\Psr4;
use Qii\Language\Loader;
if (!function_exists('getallheaders')) {
    /**
     * Get all HTTP header key/values as an associative array for the current request.
     *
     * @return string[string] The HTTP header key/value pairs.
     */
    function getallheaders()
    {
        $headers = array();
        $copy_server = array(
            'CONTENT_TYPE'   => 'Content-Type',
            'CONTENT_LENGTH' => 'Content-Length',
            'CONTENT_MD5'    => 'Content-Md5',
        );
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                $key = substr($key, 5);
                if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) {
                    $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key))));
                    $headers[$key] = $value;
                }
            } elseif (isset($copy_server[$key])) {
                $headers[$copy_server[$key]] = $value;
            }
        }
        if (!isset($headers['Authorization'])) {
            if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
                $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
            } elseif (isset($_SERVER['PHP_AUTH_USER'])) {
                $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
                $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass);
            } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
                $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
            }
        }
        return $headers;
    }
}
/**
 * Qii ...
 * @return null|Qii|Qii\Autoloader\Psr4
 */
function _Qii()
{
	return \Qii::getInstance();
}

/**
 * \Qii::i(.., ...)
 * @return mixed
 */
function _i()
{
    return call_user_func_array('\Qii::i', func_get_args());
}
/**
 * throw new Exception
 */
function _e()
{
    return call_user_func_array('\Qii::e', func_get_args());
}

/**
 * Chrome logs
 * @return mixed
 */
function _log() {
    return call_user_func_array('\Qii\Library\Chrome::log', func_get_args());
}
/**
 * 加载语言包
 * @param string $language 语言包
 * @param string $dir 路径
 */
function _language($language, $dir = '')
{
	Loader::getInstance()->load($language, $dir);
}

/**
 * \Qii_Config_Register:: get or set
 * @param $key
 * @param null $val
 * @return mixed|void|null
 */
function _config($key, $val = null)
{
	if($val === null)
	{
		return \Qii\Config\Register::get($key);
	}
	return \Qii\Config\Register::set($key, $val);
}
/**
 * Adds a base directory for a namespace prefix.
 *
 * @param string $prefix The namespace prefix.
 * @param string $baseDir A base directory for class files in the
 * namespace.
 * @param bool $prepend If true, prepend the base directory to the stack
 * instead of appending it; this causes it to be searched first rather
 * than last.
 * @return void
 */
function _addNamespace($prefix, $baseDir, $prepend = false)
{
	_qii()->addNamespace($prefix, $baseDir, $prepend);
}
/**
 * 加载loader 可以直接加载指定类
 */
function _loader($class = null)
{
	$args = func_get_args();
	if($class != null){
		return call_user_func_array(array(Psr4::getInstance(), 'loadClassOnce'), $args);
	}
	return Psr4::getInstance();
}


/**
 * load library
 * @param $name
 * @return mixed
 */
function _library($name) {
    return \_loadClassOnce("\Qii\Library\\". $name);
}
/**
 * 简便的loadClass方法
 * \Qii\Autoloader\Psr4::getInstance()->loadClass(.., ..);
 */
function _loadClass()
{
	$args = func_get_args();
	return call_user_func_array(array(\_loader(), 'loadClass'), $args);
}

/**
 * 简便的loadClassOnce方法
 * \Qii\Autoloader\Psr4::getInstance()->loadClassOnce(.., ..);
 */
function _loadClassOnce()
{
    $args = func_get_args();
    return call_user_func_array(array(\_loader(), 'loadClassOnce'), $args);
}
/**
 * 根据文件前缀获取文件路径
 *
 * @param string $file 文件名
 */
function _getFileByPrefix($file)
{
	return \_loader()->getFileByPrefix($file);
}

/**
 * 数据库操作类
 *
 * @param Qii_Driver_Rules $rule 规则
 * @param array|null $privateKey 主键
 * @param array|null $fieldsVal 值
 * @return mixed
 */
function _DBDriver(\Qii\Driver\Rules $rule, $privateKey = null, $fieldsVal = null)
{
    $rules = _loadClassOnce('Qii\Driver\Easy')->_initialize();
    if ($privateKey) $rules->setPrivateKey($privateKey);
    $rules->setRules($rule);
    if ($fieldsVal) $rules->setFieldsVal($fieldsVal);
    return $rules;
}
/**
 * _include include文件
 */
function _include($files){
	return Import::includes($files);
}

function _require($files)
{
	return Import::requires($files);
}

/**
 * 检测字符的编码
 *
 * @param string $str
 * @return false|string
 */
function detectEncode($str) {
    return mb_detect_encoding($str, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
}
/**
 * 将字符串转换成指定编码
 *
 * @param string $str 需要转换的字符串
 * @param string $to  转换到的编码
 * @return string
 */
function convertCode($str, $to)
{
    $fromCode = detectEncode($str);
    if($fromCode == $to) return $str;
    return mb_convert_encoding($str, $to, $fromCode);
}

/**
 * 将字符串转换成格式
 *
 * @param string $str 需要转换的字符串
 * @return string
 */
function toUTF8($str)
{
	return convertCode($str, 'UTF-8');
}

/**
 * 将字符串转换成GBK
 *
 * @param string $str 文本
 * @return string
 */
function toGBK($str)
{
	return convertCode($str, 'GBK');
}

/**
 * 字符串是否包含
 *
 * @param string $haystack
 * @param string $needle
 * @return bool
 */
function strContains(string $haystack, string $needle)
{
    return '' === $needle || false !== strpos($haystack, $needle);
}

/**
 * 以xxx开头
 * @param string $haystack
 * @param string $needle
 * @return bool
 */
function strStartsWith($haystack, $needle)
{
    return 0 === strncmp($haystack, $needle, \strlen($needle));
}

/**
 * 以xx结尾
 * @param string $haystack
 * @param string $needle
 * @return bool
 */
function strEndsWith($haystack, $needle)
{
    if ('' === $needle || $needle === $haystack) {
        return true;
    }

    if ('' === $haystack) {
        return false;
    }

    $needleLength = \strlen($needle);

    return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
}