<?php

//获取项目类型名称
function get_project_typename($type)
{
    $CI = &get_instance();
    $type_list = $CI->config->item('project_types');
    return $type_list[$type];
}

function GetAreaName($HT_areaType, $HT_areaID)
{
    $CI = &get_instance();
    $CI->load->model('Area_model');
    return $CI->Area_model->get_area_name($HT_areaType, $HT_areaID);
}

//查找作者名称，根据参数类型判断查作者表还是翰特表
function get_author_name($author_code_id)
{
    $CI = &get_instance();
    if (is_numeric($author_code_id)) {
        $CI->load->model('Infoauthors_model');
        $user = $CI->Infoauthors_model->detail_by_id($author_code_id);
        if ($user) {
            return $user->a_name;
        }
    } else {
        $CI->load->model('Operator_model');
        $user = $CI->Operator_model->get_user($author_code_id);
        if ($user) {
            return $user['OPI_Name'];
        }
    }
    return false;
}

//根据站点id获取站点名称
function get_sitecode($site_id, $site_array)
{
    foreach ($site_array as $item) {
        if ($item['site_id'] == $site_id) {
            return $item['site_code'];
        }
    }
    return 'FALSE';
}

/*
 * 递归创建文件夹
 */

function create_folder_by_path($dir, $mode = 0777)
{
    if (!is_dir($dir)) {
        return @mkdir($dir, $mode, true);
    }
    return;
}

/**
 * 获取iis rewrite之前的原始url
 */
function get_origin_url()
{
    $CI = &get_instance();
    if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
        $origin_url = str_replace($CI->config->item('index_page'), '/', $_SERVER['HTTP_X_REWRITE_URL']);
    } else {
        $origin_url = str_replace($CI->config->item('index_page'), '/', $_SERVER['REQUEST_URI']);
    }
    return str_replace('//', '/', urldecode($origin_url));
}

//是否是系列站
function is_series_site()
{
    $CI = &get_instance();
    $sitecode = $CI->config->item('site_code');
    if (in_array($sitecode, array('jp', 'vc', 'vac', 'ru', 'it', 'gh_jp', 'gh_vc', 'gh_vac', 'gh_ru', 'gh_it', 'gh_gm', 'gm'))) {
        return true;
    } else {
        return false;
    }
}


//是否是子站点
function is_sub_site()
{
    $CI = &get_instance();
    $sitecode = $CI->config->item('site_code');
    if ($sitecode == 'yz' || $sitecode == 'tbt' || $sitecode == 'mbj' || $sitecode == 'sht' || $sitecode == 'gl') {
        return true;
    } else {
        return false;
    }
}


//是否是移动优先站点
function is_mobile_first()
{
    $CI = &get_instance();
    $sitecode = $CI->config->item('site_code');
    if ($sitecode == 'ch' || $sitecode == 'ah' || $sitecode == 'chinatravel' || $sitecode == 'gh' || $sitecode == 'shanghai') {
        return true;
    } else {
        return false;
    }
}

function add_meta($im_ic_id, $im_key, $im_value)
{
    $CI = &get_instance();
    $CI->load->model('InfoMetas_model');
    return $CI->InfoMetas_model->add($im_ic_id, $im_key, $im_value);
}

function get_meta($im_ic_id, $im_key)
{
    $CI = &get_instance();
    $CI->load->model('InfoMetas_model');
    return $CI->InfoMetas_model->get($im_ic_id, $im_key);
}

function update_meta($im_ic_id, $im_key, $im_value)
{
    $CI = &get_instance();
    $CI->load->model('InfoMetas_model');
    return $CI->InfoMetas_model->update($im_ic_id, $im_key, $im_value);
}

function delete_meta($im_ic_id, $im_key)
{
    $CI = &get_instance();
    $CI->load->model('InfoMetas_model');
    return $CI->InfoMetas_model->delete($im_ic_id, $im_key);
}

//检查是否有短消息
function have_unread_sms($m_object_type, $m_object_id)
{
    $CI = &get_instance();
    $CI->load->model('InfoSMS_model');
    $sms_list = $CI->InfoSMS_model->unread_sms($m_object_type, $m_object_id);
    $admin_info = $CI->session->userdata('session_admin');
    if (empty($sms_list)) {
        return false;
    } else {
        $sender = get_author_name($sms_list[0]->m_sender);
        if ($admin_info['OPI_Name'] == $sender) {
            return false;
        } else {
            return true;
        }
    }
}

//截取字符串
function get_text_short($str, $length = 40, $ext = '', $only_content = false)
{
    $str = strip_tags($str);
    $str = htmlspecialchars_decode($str);
    $strlenth = 0;
    $out = '';
    $output = '';
    $is_length = false;
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match);
    foreach ($match[0] as $v) {
        preg_match("/[\xe0-\xef][\x80-\xbf]{2}/", $v, $matchs);
        if (!empty($matchs[0])) {
            $strlenth += 1;
        } elseif (is_numeric($v)) {
            $strlenth += 0.5;    // 字符字节长度比例 汉字为1
        } else {
            $strlenth += 0.5;    // 字符字节长度比例 汉字为1
        }
        if ($strlenth > $length) {
            $output .= $ext;
            $is_length = true;
            break;
        }
        $output .= $v;
    }
    $data['content'] = $output;
    $data['length'] = $is_length;
    if ($only_content) {
        return $data['content'];
    }
    return $data;
}

//平台头部展示所有未读消息数量
function get_all_unread_sms($type = 'author', $author = false)
{
    $CI = &get_instance();
    $CI->load->model('InfoSMS_model');
    if (!$author) {
        $admin_info = $CI->session->userdata('session_admin');
        $author = $admin_info['OPI_Code'];
    }

    if ($type == 'info') {
        $unread_sms = $CI->InfoSMS_model->info_unread_sms($author, 'info');
    } else {
        $unread_sms = $CI->InfoSMS_model->all_unread_sms($author, 'task');
    }
    return $unread_sms;
}

//获取不同任务状态的任务数量
function get_task_count_by_status()
{
    $CI = &get_instance();
    $CI->load->model('Infotasks_model');
    $task_count_by_status = $CI->Infotasks_model->get_task_count_by_status();
    return $task_count_by_status;
}

//获取作者头像
function get_author_photo($author_code_id = false)
{
    $CI = &get_instance();
    $root_url = ''; //'http://data.chtcdn.com';
    $avatar = $root_url . '/css/images/avatar.jpg';
    if ($author_code_id && is_numeric($author_code_id)) {
        $CI->load->model('Infoauthors_model');
        $user = $CI->Infoauthors_model->detail_by_id($author_code_id);
        if (isset($user->a_photo) && $user->a_photo != '') {
            $avatar = $root_url . '/author/document/profile_photo/' . $user->a_photo;
        }
    }
    return $avatar;
}

//补全图片路径
function get_photo_url($photo)
{
    $root_url = ''; //'http://data.chtcdn.com';
    if ($photo == '') {
        $avatar = $root_url . '/css/images/uploadPic.jpg';
    } else {
        $avatar = $root_url . '/author/document/profile_photo/' . $photo;
    }
    return $avatar;
}

//获取待审核作者数量
function un_active_count()
{
    $CI = &get_instance();
    $CI->load->model('Infoauthors_model');
    $num = $CI->Infoauthors_model->un_active_count();
    return $num;
}

//分页函数
function show_page($page)
{
    $pageSize = $page['pageSize'];
    $total = $page['total'];
    $url = $page['url'];
    $pageNumber = ceil($total / $pageSize);
    $currentPage = $page['current'] ? $page['current'] : 1;
    $startPage = ($currentPage - 1) * $pageSize;

    $befor = $after = 0;
    $nowview = ceil(($currentPage + 1) / 10);
    $befor = $nowview == 1 ? ($nowview - 1) * 10 + 1 : ($nowview - 1) * 10;
    if ($pageNumber >= $nowview * 10) {
        $after = $nowview * 10;
    } else {
        $after = $pageNumber;
    }

    $html = '';
    if ($nowview > 1)
        $befor--;
    if ($pageSize <= $total) {
        for ($i = $befor; $i <= $after; $i++) {
            if ($i == $currentPage) {
                $html .= "<li class=\"active\"><a href=\"javascript:void(0)\">{$i}</a></li>";
            } else {
                $html .= "<li><a href=\"{$url}/{$i}\">$i</a></li>";
            }
        }
    }
    $res['htmls'] = $html;
    $res['prepage'] = $currentPage - 1;
    $res['nextpage'] = $currentPage + 1;
    $res['totalpage'] = $pageNumber;
    return $res;
}

//请求URL并返回数组数据
function get_content_by_url($url)
{
    //echo $url;
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    if ($response === FALSE) {
        #echo "cURL Error: " . curl_error($ch);
        return false;
    }
    return $response;
}


function GET_HTTP($url, $data = '', $method = 'GET')
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    // if (isset($_SERVER['HTTP_USER_AGENT'])) {
    //     $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
    // } else {
    $HTTP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; curl) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36';
    // }
    curl_setopt($curl, CURLOPT_USERAGENT, $HTTP_USER_AGENT); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    if ($method == 'POST' && !empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($httpCode >= 400) { //页面状态，如果大于400说明页面打不开
        log_message('error', " curl {$httpCode} {$url} ");
        return false;
    }
    $errno = curl_errno($curl);
    if ($errno !== 0) {
        return false;
        $error_message = $errno . ' ' . curl_error($curl); //记录错误日志
        log_message('error', "train/get_http curl {$error_message}");
    }
    curl_close($curl); //关闭CURL会话
    return $tmpInfo; //返回数据
}

//获取内容中图片地址
function get_image_url_by_source($source)
{
    $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpeg|\.png|\.jpg]))[\'|\"].*?[\/]?>/";
    preg_match_all($pattern, $source, $match);
    return $match;
}

//压缩css代码
function compress_css($buffer)
{
    /* remove comments */
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
}

//把临时多媒体中心预览图片地址替换为网前地址
function replace_image_url($ic_content)
{
    $CI = &get_instance();
    return str_replace($CI->config->item('media_image_url'), $CI->config->item('site_image_url'), $ic_content);
}