<?php

class Chain
{
    const APP = 'chain';
    const APPID = iCMS_APP_CHAIN;
    const CACHE_KEY = 'chain';

    public static function cache()
    {
        $result = ChainModel::orderBy('CHAR_LENGTH(`keyword`)', 'DESC')->select();
        $array = array();
        foreach ((array) $result as $i => $val) {
            $a = array($val['keyword']);
            if (Request::isUrl($val['replace'], true)) {
                $val['replace'] = self::getLink($val['keyword'], $val['replace'], false);
            } else {
                $val['replace'] = htmlspecialchars_decode($val['replace']);
                $val['replace'] = str_replace(array('&#34;', '&#39;'), array('"', "'"), $val['replace']);
            }
            $array[] = array($val['keyword'], $val['replace']);
        }
        Cache::set(self::CACHE_KEY, $array, 0);
    }
    public static function getLink($name, $url, $flag = true)
    {
        $link = sprintf('<a href="%s" target="_blank" class="chain">%s</a>', $url, $name);
        if ($flag) {
            $link = htmlspecialchars($link);
            $link = str_replace(array('"', "'"), array('&#34;', '&#39;'), $link);
        }
        return $link;
    }
}
