<?php
/* =================================================================================
 * License: GPL-2.0 license
 * Author: 众产®  https://ciy.cn/code
 * Version: 0.7.8
====================================================================================*/
/*
 * web.php 常用公共函数库
 * 
 * 页面相关
 * diehtml                              报错输出页面/跳转
 * markdown_code
 * inzone
 */
namespace ciy;
function diehtml($msg, $title = '提示信息') {
    echo '<!DOCTYPE html><html><head><meta http-equiv="Content-type" content="text/html; charset=utf-8">';
    echo '<title>' . $title . '</title><meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0"/><meta name="format-detection" content="telephone=no,email=no"/>';
    echo '<meta name="apple-mobile-web-app-capable" content="yes" /></head><body>';
    $selfname = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '/') + 1, -4);
    echo '<fieldset style="margin:2em;border-radius: 0.5em;border: 1px solid #eeeeee;line-height:2em;"><legend style="font-size: 1.3em;padding: 0.2em 0.5em;">' . $title . '</legend><div style="padding:0 15px 15px 15px;"><b>来源： ' . str_replace('.php', '', $selfname) . '</b><br/>' . $msg . '</div></fieldset>';
    echo '</body></html>';
    die();
}

function markdown_convert($markdown) {
    // #,!,`,@cr,[]
    //行首:  标题#    对齐@    _HTML   无 独立div    图片!http://.jpg|ALT
    //行中:  `强调`    \uhttp://xxx|链接字\u
    if(substr($markdown,0, 4) != '[MD]')
        return $markdown;
    $mds = explode("\n", trim(substr($markdown,4)));
    $html = '';
    foreach ($mds as $mi) {
        if (empty($mi)) {
            $html .= '<br/>';
            continue;
        }
        if ($mi[0] == '#') {   //#一级标题   ##二级标题   ###三级标题
            if (substr($mi,0, 3) == '###')
                $html .= '<h3 class="md-h3">' . markdown_convertcode(substr($mi,3)) . '</h3>';
            else if (substr($mi,0, 2) == '##')
                $html .= '<h2 class="md-h2">' . markdown_convertcode(substr($mi,2)) . '</h2>';
            else if ($mi[1] == 'c')
                $html .= '<h1 class="md-h1" style="text-align:center;">' . markdown_convertcode(substr($mi,2)) . '</h1>';
            else if ($mi[1] == 'r')
                $html .= '<h1 class="md-h1" style="text-align:right;">' . markdown_convertcode(substr($mi,2)) . '</h1>';
            else
                $html .= '<h1 class="md-h1">' . markdown_convertcode(substr($mi,1)) . '</h1>';

        } else if ($mi[0] == '@') {//c居中，r靠右
            if ($mi[1] == 'c')
                $html .= '<div style="text-align:center;">' . markdown_convertcode(substr($mi,2)) . '</div>';
            else if ($mi[1] == 'r')
                $html .= '<div style="text-align:right;margin-right:1em;">' . markdown_convertcode(substr($mi,2)) . '</div>';
            else
                $html .= substr($mi,1);

        } else if ($mi[0] == '!') { //!图片地址  !图片地址|ALT文字
            $mis = explode('|',$mi);
            $url = $mis[0];
            $url = substr($url, 1);
            $alt = '';
            if(isset($mis[1]))
                $alt = ' alt="' . str_replace('"',"",$mis[1]). '"';
            $html .= '<div style="font-size:0"><img src="' . $url . '" style="max-width:100%;"'.$alt.'/></div>';
        } else if ($mi[0] == '_') { //HTML
            $html .= substr($mi, 1);
        } else {
            $html .= '<div class="md-content">' . markdown_convertcode($mi) . '</div>';
        }
    }
    return $html;
}
function markdown_convertcode($md) {
    $bcode = false;
    $md = str_replace('  ','　',$md);
    $md = str_replace(' ','&nbsp;',$md);
    while (true) {
        $ind = strpos($md,'`');
        if ($ind === false)
            break;
        $el = '<code class="md-code">';
        if ($bcode) {
            $bcode = false;
            $el = '</code>';
        }
        else
            $bcode = true;
        $md = substr($md,0, $ind) . $el . substr($md,$ind + 1);
    }
    if ($bcode)
        $md .= '</code>';
    while (true) {
        $ind = strpos($md,'\\u');
        if ($ind === false)
            break;
        $ind2 = strpos($md,'\\u', $ind+1);
        if ($ind2 === false)
            break;
        $mis = explode('|',substr($md,$ind + 2, $ind2-$ind-2));
        $url = $mis[0];
        $text = $url;
        if(isset($mis[1]))
            $text = $mis[1];
        if($text[0] == '!'){
            $html = '<a href="'.$url.'" target="_blank" nofollow><img src="' . substr($text,1) . '" style="max-width:100%;"/></a>';
        }else{
            $html = '<a href="'.$url.'" target="_blank" nofollow>' . $text . '</a>';
        }
        $md = substr($md,0,$ind) . $html . substr($md,$ind2+2);
    }
    return $md;
}
function convertseowords($db, $content, $keystr = '') {
    $csql = new sql('a_web_word');
    $seowords = $db->get($csql);
    $seo = array();
    $max = rand(2, 5);
    shuffle($seowords);
    foreach ($seowords as $row) {
        if ($row['rank'] > rand(0, 100))
            $seo[$row['name']] = $row['url'];
    }
    $repcnt = 0;
    foreach ($seo as $key => $val) {
        $keyind = 0;
        for($i=0;$i<5;$i++){
            $ind = strpos($content, $key,$keyind);
            if ($ind === false)
                break;
            $tmp = substr($content, 0, $ind);
            $inda = strrpos($tmp, '<a ciy href=');
            if ($inda !== false) {
                $indb = strpos($tmp, '</a>', $inda);
                if ($indb === false){ //包含
                    $keyind = $ind + 1;
                    continue;
                }
            }
            $inda = strrpos($tmp, ' alt="');
            if ($inda !== false) {
                $indb = strpos($tmp, '"', $inda+6);
                if ($indb === false){ //包含
                    $keyind = $ind + 1;
                    continue;
                }
            }
            break;
        }
        if ($ind === false)
            continue;
        $content = substr_replace($content, '<a ciy href="' . $val . '">' . $key . '</a>', $ind, strlen($key));
        $repcnt++;
        if ($repcnt >= $max)
            break;
    }
    if (!empty($keystr)) {
        $keystr = str_replace('，', ',', $keystr);
        $keystr = str_replace(';', ',', $keystr);
        $keystr = str_replace('；', ',', $keystr);
        $keys = explode(',', $keystr);
        foreach ($keys as $key) {
            if (empty($key))
                continue;
            $keyind = 0;
            for($i=0;$i<5;$i++){
                $ind = strpos($content, $key,$keyind);
                if ($ind === false)
                    break;
                $tmp = substr($content, 0, $ind);
                $inda = strrpos($tmp, '<strong>');
                if ($inda !== false) {
                    $indb = strpos($tmp, '</strong>', $inda);
                    if ($indb === false){ //包含
                        $keyind = $ind + 1;
                        continue;
                    }
                }
                $inda = strrpos($tmp, ' alt="');
                if ($inda !== false) {
                    $indb = strpos($tmp, '"', $inda+6);
                    if ($indb === false){ //包含
                        $keyind = $ind + 1;
                        continue;
                    }
                }
                break;
            }
            if ($ind === false)
                continue;
            $content = substr_replace($content, '<strong>' . $key . '</strong>', $ind, strlen($key));
        }
    }
    return $content;
}

function getwebtitle($db, $id) {
    $csql = new sql('a_web_seo');
    $csql->where('url', $_SERVER['REQUEST_URI']);
    $webtitrow = $db->getone($csql);
    if (is_array($webtitrow)) {
        if ($webtitrow['pagecount'] < 1)
            $webtitrow['pagecount'] = 20;
        return $webtitrow;
    }
    $csql = new sql('a_web_seo');
    $csql->where('id', $id);
    $webtitrow = $db->getone($csql);
    if (is_array($webtitrow)) {
        if ($webtitrow['pagecount'] < 1)
            $webtitrow['pagecount'] = 20;
        return $webtitrow;
    }
    $webtitrow = array();
    $webtitrow['name'] = '众产平台';
    $webtitrow['keys'] = '众产平台,众产事业';
    $webtitrow['desc'] = '众产事业网站';
    $webtitrow['pagecount'] = 30;
    return $webtitrow;
}
function titrep($str, $dat, $content = '') {
    foreach ($dat as $key => $val) {
        $str = str_replace('{' . $key . '}', $val, $str);
    }
    $str = str_replace('农业农业', '农业', $str);
    if (empty($content))
        return $str;
    $ind = strpos($str, '{content');
    if ($ind === false)
        return $str;
    $ind2 = strpos($str, '}', $ind);
    if ($ind2 === false)
        return $str;
    if ($ind2 - $ind == 8) {
        return str_replace('{content}', leftchinese($content), $str);
    } else {
        $len = substr($str, $ind + 8, $ind2 - $ind - 8);
        return str_replace(substr($str, $ind, $ind2 - $ind + 1), leftchinese($content, $len), $str);
    }
}
function leftchinese($content, $len = 0) {
    $content = htmlspecialchars_decode($content);
    $content = str_replace(" ", "", $content);
    $content = str_replace("\n", "", $content);
    $content = str_replace("\r", "", $content);
    $content = str_replace("\t", "", $content);
    $content = strip_tags($content);
    $content = trim($content);
    if ($len <= 0)
        return $content;
    if (mb_strlen($content, 'utf-8') > $len)
        return mb_substr($content, 0, $len, "utf-8");
    return $content;
}
function showpage($count, $pageno, $pagecount, $pageurl) {
    if ($count <= 0) {
        // 1...3,4,5,6,7,8
        $isend = (-$count < $pagecount);
        //if($pageno < 20) $isend = false;
        $epage = $pageno + 2;
        $spage = $pageno - 6;
        if ($isend)
            $epage = $pageno;
        if ($spage < 1)
            $spage = 1;
        echo '<a ' . ($pageno <= 1 ? ' class="disabled"' : " href=\"" . $pageurl . ($pageno - 1) . "/\"") . '>上页</a>';
        echo '<a ' . ($isend ? ' class="disabled"' : " href=\"" . $pageurl . ($pageno + 1) . "/\"") . '>下页</a>';

        if ($spage > 1)
            echo '<a href="' . $pageurl . '1/">1</a>';
        if ($spage > 2)
            echo '<span>...</span>';

        for ($i = $spage; $i <= $epage; $i++)
            echo '<a ' . ($i == $pageno ? ' class="active"' : " href=\"" . $pageurl . $i . "/\"") . '>' . $i . '</a>';
    } else {
        //1...3,4,5,6,7...n
        $epage = $pageno + 4;
        $spage = $pageno - 4;
        $pagemax = ceil($count / $pagecount);
        if ($spage < 1)
            $spage = 1;
        if ($epage > $pagemax)
            $epage = $pagemax;
        echo '<a ' . ($pageno <= 1 ? ' class="disabled"' : " href=\"" . $pageurl . ($pageno - 1) . "/\"") . '>上页</a>';
        echo '<a ' . ($pageno >= $pagemax ? ' class="disabled"' : " href=\"" . $pageurl . ($pageno + 1) . "/\"") . '>下页</a>';
        if ($spage > 1)
            echo '<a href="' . $pageurl . '1/">1</a>';
        if ($spage > 2)
            echo '<span>...</span>';

        for ($i = $spage; $i <= $epage; $i++)
            echo '<a ' . ($i == $pageno ? ' class="active"' : " href=\"" . $pageurl . $i . "/\"") . '>' . $i . '</a>';
        if ($epage < $pagemax - 1)
            echo '<span>...</span>';
        if ($epage < $pagemax)
            echo '<a href="' . $pageurl . $pagemax . '/">' . $pagemax . '</a>';
    }
}

function fillsource($str) {
    $source = explode('|', $str);
    if (!isset($source[1]))
        return $source[0];
    else
        return '<a href="' . $source[1] . '" target="_blank" nofollow>' . '转自' . $source[0] . '</a>';
}
function showh1($webtit, $artrow) {
    $h1 = titrep($webtit['h1'], $artrow);
    $htip = titrep($webtit['htip'], $artrow);
    if (empty($h1))
        echo '';
    else if ($h1[0] == '<')
        echo $h1;
    else
        echo '<h1>' . $h1 . '</h1>';
    if (empty($htip))
        echo '';
    else if ($htip[0] == '<')
        echo $htip;
    else
        echo '<div class="vhtip">' . $htip . '</div>';
}

function markdown_fromhtml($content, $baseurl) {
    $html = html::str_get_html($content);
    if ($html === false || $html === null)
        return '';
    $md = '';
    _html2md_child($baseurl, $html->childNodes(), $md);
    return $md;
}
function _html2md_child($baseurl, $childs, &$md) {
    if ($childs === null)
        return;
    foreach ($childs as $child) {
        if ($child->tag == 'table') {
            $md .= '_' . str_replace("\n", "", $child->outertext) . "\n";
        } else if ($child->tag == 'img') {
            if (empty(@$child->attr['src']))
                continue;
            $md .= '!' . urljoin($child->attr['src'], $baseurl) . '|' . @$child->attr['alt'] . "\n";
        } else if ($child->tag == 'ul') {
            //clog('find ul');
        } else {
            $divps = $child->find('div,p');
            if (count($divps) > 0) {
                $txt = trim($child->plaintext);
                _html2md_child($baseurl, $child->childNodes(), $md);
            } else {
                $divimgs = $child->find('img');
                foreach ($divimgs as $divimg) {
                    if (empty(@$divimg->attr['src']))
                        continue;
                    $md .= '!' . urljoin($divimg->attr['src'], $baseurl) . '|' . @$divimg->attr['alt'] . "\n";
                }
                $txtpre = '';
                $txt = $child->plaintext;
                $txt = str_replace('&nbsp;', '', $txt);
                $txt = trim($txt);
                $style = @$child->attr['style'] . ',' . @$child->attr['align'];
                if (strpos($style, 'right') !== false)
                    $txtpre = '@r';
                else if (strpos($style, 'center') !== false)
                    $txtpre = '@c';
                if (!empty($txt)) {
                    $txts = explode("\n", $txt);
                    foreach ($txts as $tx) {
                        $tx = trim($tx);
                        while (true) {
                            if (substr($tx, 0, 3) != '　')
                                break;
                            $tx = substr($tx, 3);
                        }
                        if (empty($tx))
                            continue;
                        $md .= $txtpre . $tx . "\n";
                    }
                }
            }
        }
    }
}
//相对网址转绝对网址
function urljoin($srcurl, $baseurl) {
    $srcinfo = parse_url($srcurl);
    if (isset($srcinfo['scheme'])) {
        return $srcurl;
    }
    $baseinfo = parse_url($baseurl);
    $url = $baseinfo['scheme'] . '://' . $baseinfo['host'];
    if (substr($srcinfo['path'], 0, 1) == '/') {
        $path = $srcinfo['path'];
    } else {
        $path = dirname($baseinfo['path']) . '/' . $srcinfo['path'];
    }
    $rst = array();
    $path_array = explode('/', $path);
    if (!$path_array[0]) {
        $rst[] = '';
    }
    foreach ($path_array as $key => $dir) {
        if ($dir == '..') {
            if (end($rst) == '..') {
                $rst[] = '..';
            } elseif (!array_pop($rst)) {
                $rst[] = '..';
            }
        } elseif ($dir && $dir != '.') {
            $rst[] = $dir;
        }
    }
    if (!end($path_array)) {
        $rst[] = '';
    }
    $url .= implode('/', $rst);
    return str_replace('\\', '/', $url);
}