<?php
class LinksApp
{
    public function do_iCMS()
    {
        $this->target();
    }
    public function API_iCMS()
    {
        $this->target();
    }
    public static function target()
    {
        $target = urldecode($_GET['target']);
        $parse  = parse_url($target);
        $whitelist = Cache::get('links/whitelist');
        $blacklist = Cache::get('links/blacklist');
        $isWhite = false;
        $isBlack = false;
        if ($whitelist) foreach ($whitelist as $key => $value) {
            if (strpos($parse['host'], $value) !== false) {
                $isWhite = true;
                break;
            }
        }
        if ($blacklist) foreach ($blacklist as $key => $value) {
            if (strpos($target, $value) !== false) {
                $isBlack = true;
                break;
            }
        }
        View::assign('links', [
            'url' => $target,
            'isWhite' => $isWhite,
            'isBlack' => $isBlack
        ]);
        $template = Config::get('links.template');
        View::display($template?:'/tools/links.target.htm');
    }
    /**
     * [钩子:外链跳转]
     * @param String $content [参数]
     * @return string        [返回替换过的内容]
     */
    public static function HOOK_run($content)
    {
        preg_match_all("/<a.*?href=[\"|'](.+?)[\"|'][^>]*?>(.*?)<\/a>/", $content, $matches);
        if($matches[1]){
            $base = Config::get('links.base');
            $urls = array_unique($matches[1]);
            usort($urls, function ($a, $b) {
                $al = strlen($a);
                $bl = strlen($b);
                if ($al  ==  $bl) {
                    return  0;
                }
                return ($al  >  $bl) ? -1  :  1;
            });
            $target = [];
            if($urls)foreach ($urls as $key => $url) {
                $target[$key] = Route::make(['target'=>$url], $base);
            }
            $content = str_replace($urls,$target,$content);
        }
        return $content;
    }
}
