<?php

if (!defined('ROOT'))
    exit('Can\'t Access !');

function array_col_values($arr, $col) {
    $ret = array();
    foreach ($arr as $row) {
        if (isset($row[$col])) {
            $ret[] = $row[$col];
        }
    }
    return $ret;
}

function _highlight($string, $words, $links, $pre, $times) {
    $string = str_replace('\"', '"', $string);
    if ($words) {
        foreach ($words as $key => $word) {
            if ($GLOBALS['replaced'][$word] < $times[$key]) {
                $string = preg_replace("/" . preg_quote($word) . "/", $links[$key], $string);
                if (strpos($string, $word) !== false) {
                    $GLOBALS['replaced'][$word] += 1;
                }
            }
        }
    }
    return $pre . $string;
}

function getHtmlRule($cate) {
    $filename = ROOT . '/data/htmlrule.php';
    $arr = include $filename;
    $htmlrulearr[''] = '请选择';
    foreach ($arr as $v) {
        if ($cate == $v['cate'])
            $htmlrulearr[$v['htmlrule']] = $v['hrname'];
    }
    return $htmlrulearr;
}

function savepic($out) {
    $domain = front::domain();
    preg_match('@http://([^/|\s]*)@is', $out[2], $out1);
    $opts = array(
        'http' => array(
            'method' => "GET",
            'timeout' => 30,
        )
    );
    $ext = end(explode('.', basename($out[2])));
    $arr = array('jpg', 'gif', 'png'); //自动保存的图片类型
    if (in_array($ext, $arr)) {  //是否图片
        if ($domain != $out1[1]) {  //是否外站图片
            $context = stream_context_create($opts);
            $content = @file_get_contents($out[2], false, $context);
            if ($content) {  //读取是否成功
                $dir = 'upload/images/' . date('Ym') . '/';
                tool::mkdir($dir);
                $name = $dir . substr(md5(time() . mt_rand(0, 9)), 16) . '.' . $ext;
                $newname = config::get('site_url') . $name;
                if (file_put_contents($name, $content)) { //写入是否成功
                    return $out[1] . $newname;
                }
            }
        }
    }
    return $out[0];
}

function getcategoryparentsid($catid) {
    $p = category::getparentsid($catid);
    $n = count($p);
    $c = $p[$n - 1];
    return $c;
}

function index_archive($catid) {
    $index_archive = new archive();
    $index_category = category::getInstance();
    $index_view_category = $index_category->category;
    if (front::get('page'))
        $page = front::get('page');
    else
        $page = 1;
    $index_view_page = $page;
    front::check_type($page);
    $_catpage = category::categorypages($catid);
    if ($_catpage) {
        $index_pagesize = $_catpage;
    } else {
        $index_pagesize = config::get('list_pagesize');
    }
    front::check_type($index_pagesize);
    $index_view_categorys = category::getpositionlink2($catid);
    $topid = category::gettopparent($catid);
    if (!isset($index_category->category[$catid]) ||
            !isset($index_category->category[$topid])) {
        $this->out('message/error.html');
    }
    $limit = (($index_view_page - 1) * $index_pagesize) . ',' . $index_pagesize;
    $categories = array();
    if (@$index_category->category[$catid]['ispages'])
        $categories = $index_category->sons($catid);
    $categories[] = $catid;
    $index_view_pages = @$index_category->category[$catid]['ispages'];
    if (!rank::catget($catid, $index_view_usergroupid))
        $this->out('message/error.html');
    $order = "`listorder` asc,`adddate` DESC";
    if (@$index_category->category[$catid]['includecatarchives'])
        $articles = $index_archive->getrows('catid in (' . implode(',', $categories) . ') and checked=1', $limit, $order);
    else
        $articles = $index_archive->getrows('catid=' . $catid . ' and checked=1', $limit, $order);
    if (!is_array($articles)) {
        $this->out('message/error.html');
    }
    foreach ($articles as $order => $arc) {
        $articles[$order]['url'] = archive::url($arc);
        $articles[$order]['catname'] = category::name($arc['catid']);
        $articles[$order]['caturl'] = category::url($arc['catid']);
        $articles[$order]['adddate'] = sdate($arc['adddate']);
        $articles[$order]['stitle'] = strip_tags($arc['title']);
        $articles[$order]['strgrade'] = archive::getgrade($arc['grade']);
    }
    $index_view_archives = $articles;
    if (@$index_category->category[$catid]['includecatarchives'])
        $index_view_record_count = $index_archive->rec_count('catid in(' . implode(',', $categories) . ')');
    else
        $index_view_record_count = $index_archive->rec_count('catid=' . $catid);
    front::$record_count = $index_view_record_count;
    return $index_view_archives;
}

function index_pagination($catid, $tpl='system/index_pagination.html') {
    front::$view->_var->catid = $catid;
    return template($tpl);
}

function user_cb_item($table, $field, $value) {
    return user_select_option($field, setting::$var[$table][$field], $value);
}

function user_cb_data(&$data, $table='archive') {
    foreach ($data as $key => $value) {
        if (preg_match('/^my_/', $key) && isset(setting::$var[$table][$key]) && @setting::$var[$table][$key]['selecttype']) {
            $data[$key] = user_cb_item($table, $key, $value);
        }
    }
}

function user_select_option($name, $form, $value) {
    $num = $value - 1;
    preg_match_all('/\(([\d\w]+)\)(\S+)/im', $form['select'], $result, PREG_SET_ORDER);
    $tmp = array();
    foreach ($result as $rs) {
        $tmp[$rs[1]] = $rs[2];
    }
    $values = explode(',', trim($value, ','));
    $res = array();
    foreach ($values as $key => $value) {
        $res[$key] = $tmp[$value];
    }
    return implode(',', $res);
}

function formatPath($path) {
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1) != '/') {
        $path = $path . '/';
    }
    return $path;
}

function createtDir($path, $mode = 0777) {
    if (is_dir($path)) {
        return true;
    }
    $path = formatPath($path);
    $temp = explode('/', $path);
    $curDir = '';
    $max = count($temp) - 1;
    for ($i = 0; $i < $max; $i++) {
        $curDir .= $temp[$i] . '/';
        if (is_dir($curDir))
            continue;
        if (!@mkdir($curDir, 0777)) {
            @mkdir($curDir, 0777);
        }
        @chmod($curDir, 0777);
    }
    return is_dir($path);
}

function deleteDir($dir) {
    $dir = formatPath($dir);
    if (!is_dir($dir)) {
        return false;
    }
    if (substr($dir, 0, 1) == '.') {
        exit("Cannot remove dir $dir !");
    }
    $list = glob($dir . '*');
    foreach ($list as $v) {
        is_dir($v) ? deleteDir($v) : @unlink($v);
    }
    return @rmdir($dir);
}

function listDirOne($path, $exts = '') {
    $list = array();
    $path = formatPath($path);
    $files = glob($path . '*');
    foreach ($files as $v) {
        $fileext = fileext($v);
        if (!$exts || preg_match("/\.($exts)/i", $v)) {
            $list[] = $v;
        }
    }
    return $list;
}

function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function read_modules($directory = '.') {
    global $_LANG;
    $dir = opendir($directory);
    $set_modules = true;
    $modules = array();
    while (false !== ($file = @readdir($dir))) {
        if (preg_match("/^.*?\.php$/", $file)) {
            include_once($directory . '/' . $file);
        }
    }
    @closedir($dir);
    unset($set_modules);
    foreach ($modules AS $key => $value) {
        ksort($modules[$key]);
    }
    ksort($modules);
    return $modules;
}

function unserialize_config($cfg) {
    if (is_string($cfg) && ($arr = unserialize($cfg)) !== false) {
        $config = array();
        foreach ($arr AS $key => $val) {
            $config[$val['name']] = $val['value'];
        }
        return $config;
    } else {
        return false;
    }
}

function getwebsite($site=null) {
    $path = ROOT . '/config/website';
    if (!$site) {
        $dir = opendir($path);
        $website_num = 0;
        $website = array();
        while ($file = readdir($dir)) {
            if (!($file == '..')) {
                if (!($file == '.')) {
                    if (!is_dir($path . '/' . $file)) {
                        $tmparr = include $path . '/' . $file;
                        $website_num++;
                        $tmparr['website']['id'] = $website_num;
                        $tmparr['website']['url'] = $tmparr['site_url'];
                        $tmparr['website']['path'] = substr($file, 0, -4);
                        $args = array('username' => $tmparr['site_username'], 'password' => md5($tmparr['site_password']));
                        $tmparr['website']['admindir'] = $tmparr['site_admindir'];
                        $tmparr['website']['args'] = urlencode(base64_encode(xxtea_encrypt(serialize($args), $tmparr['cookie_password'])));
                        $tmparr['website']['addr'] = $tmparr['site_url'] . 'index.php?case=admin&act=remotelogin&admin_dir=' . $tmparr['website']['admindir'] . '&args=' . $tmparr['website']['args'] . '&submit=1';
                        $website[] = $tmparr['website'];
                    }
                }
            }
        }
    } else {
        $tmparr = include $path . '/' . $site . '.php';
        $website[] = $tmparr['website'];
    }
    return $website;
}

function sendMsg($mobile, $content) {
    $tc = file_get_contents('config/sms.tmp.php');
    $tmp = explode('@', $tc);
    if ($tmp[0] >= config::get('sms_maxnum') && $tmp[1] == date('Y-m-d')) {
        return;
    }
    include_once("phprpc/phprpc_client.php");
    $client = new PHPRPC_Client();
    $client->setProxy(NULL);
    $client->useService('http://pay.cmseasy.cn/sms.php');
    $client->setKeyLength(128);
    $client->setEncryptMode(3);
    $keys = config::get('sms_keyword');
    if ($keys != '') {
        $keys = explode(',', $keys);
        $content = str_ireplace($keys, '*', $content);
    }
    $rs = $client->sendMsg($mobile, $content, config::get('sms_username'), md5(config::get('sms_password')));
    if ($rs->SendSMSResult == '0') {
        $num = $tmp[0] + 1;
        file_put_contents('config/sms.tmp.php', $num . '@' . date('Y-m-d'));
    }
    return $rs;
}

//特殊功能的explode函数，专为导入phpweb数据服务的
function super_explode($str) {
    //最终截取完后得到的数组
    $result = array();
    //临时存储每一个数组元素
    $tmp = '';
    //用来判断是否到字符串末尾
    $i = 0;
    //用来记录是否已经匹配到一对单引号
    $j = 0;

    while (1) {
        //当到了字符串尾部的时候跳出循环
        if (!isset($str[$i])) {
            $result[] = $tmp;
            break;
        }
        //echo $str[$i];
        if ($str[$i] == "'") {
            $j++;
            if ($j == 2)
                $j = 0;
        }elseif ($str[$i] == ",") {
            if ($j == 0) {
                $result[] = $tmp;
                $tmp = '';
            } elseif ($j == 1) {
                $tmp .= $str[$i];
            }
        } else {
            $tmp .= $str[$i];
        }
        $i++;
    }
    return $result;
}

//将获取的数据插入到数据库中
function put_into_db($tbname, $data) {
    $fields = "";
    $values = "";
    foreach ($data as $k => $v) {
        $fields .= empty($fields) ? "`{$k}`" : ",`{$k}`";
        $values .= empty($values) ? "'{$v}'" : ",'{$v}'";
    }
    $sql = "INSERT INTO `{$tbname}`({$fields}) VALUES({$values})";
    @mysql_query($sql);
    return mysql_insert_id();
}

function listPageJs($total_page, $num, $current) {//依次传入，总数，每页显示条目，显示链接总数,当前所在页
    $link = array();
    $link_str = '';
    if ($total_page == 0) {
        return '';
    }
    if ($total_page == 1) {
        return '<a>1</a>';
    }
    if ($current < 1)
        $current = 1;
    if ($current > $total_page)
        $current = $total_page;

    if ($total_page <= 10) {
        $link = range(1, $total_page);
    } else {
        if ($current < 8) {
            $link = range(1, 10);
        } elseif ($current > $total_page - 6) {
            $link = range($total_page - 9, $total_page);
        } else {
            $link = range($current - 5, $current + 4);
        }
    }

    foreach ($link as $v) {
        if ($v == $current) {
            $link_str .= '<a href="javascript:picload(' . front::get('amid') . ',' . $v . ');" style="color:red">' . $v . '</a>';
        } else {
            $link_str .= '<a href="javascript:picload(' . front::get('amid') . ',' . $v . ');">' . $v . '</a>';
        }
    }
    if ($total_page > 10) {
        if (!in_array(1, $link))
            $link_str = '<a href="javascript:picload(' . front::get('amid') . ',1);">1...</a>' . $link_str;
        if (!in_array($total_page, $link))
            $link_str .= '<a href="javascript:picload(' . front::get('amid') . ',' . $total_page . ');">...' . $total_page . '</a>';
    }
    return $link_str;
}

function listPage($total_page, $num, $current) {//依次传入，总数，每页显示条目，显示链接总数,当前所在页
    $link = array();
    $link_str = '';
    //$total_page = ceil($total/$num);
    if ($total_page == 0) {
        return '';
    }
    if ($total_page == 1) {
        return '<a>1</a>';
    }
    if ($current < 1)
        $current = 1;
    if ($current > $total_page)
        $current = $total_page;

    if ($total_page <= 10) {
        $link = range(1, $total_page);
    } else {
        if ($current < 8) {
            $link = range(1, 10);
        } elseif ($current > $total_page - 6) {
            $link = range($total_page - 9, $total_page);
        } else {
            $link = range($current - 5, $current + 4);
        }
    }
    $url = preg_replace('/&page=[0-9]*/', '', $_SERVER['REQUEST_URI']);
    foreach ($link as $v) {
        if ($v == $current) {
            $link_str .= '<a href="' . $url . '&page=' . $v . '" style="color:red">' . $v . '</a>';
        } else {
            $link_str .= '<a href="' . $url . '&page=' . $v . '">' . $v . '</a>';
        }
    }
    if ($total_page > 10) {
        if (!in_array(1, $link))
            $link_str = '<a href="' . $url . '&page=1">1...</a>' . $link_str;
        if (!in_array($total_page, $link))
            $link_str .= '<a href="' . $url . '&page=' . $total_page . '">...' . $total_page . '</a>';
    }
    return $link_str;
}