<?php
/**
 * Feed抽象类
 * User: yzxh24
 * Date: 11-8-13
 * Time: 下午4:22
 * To change this template use File | Settings | File Templates.
 */
abstract class FAbstract
{
    /**
     * 缓存Key
     * @var string
     */
    private $_cacheKey = 'iOrangeFeed';
    
    /**
     * 创建一条feed
     * @param string $feed
     * @param int $uid
     * @param string $type
     * @return void|int
     */
    public function create($feed, $uid, $type = 'bbs') {}

    /**
     * 缓存最新的一条feed
     * @param string $feed
     * @return void
     */
    public function setOneCache($feed)
    {
        $GLOBALS['cache']->set($this->cacheKey(), $feed, 60);
    }

    /**
     * 获取一条最新的feed
     * @param bool $br
     * @return void
     */
    public function getOneCache($br = true) {}

    /**
     * 获取最新的feed
     * @param int $num
     * @return array
     */
    public function getNews($num = 1) {}

    /**
     * 获取一组UID的动态
     * @param array $uids
     * @return mixed
     */
    public function getFeedsByUids($uids) {}

    /**
     * 设置一个搜索条件
     * @param  $array
     * @return $this
     */
    public function condition($array) {}

    /**
     * 聚合数据
     * @return int
     */
    public function count() {}

    /**
     * 数据查询
     * @return array
     */
    public function findAll() {}

    /**
     * 将feed翻译成可用代码
     * @param string $feed
     * @param boolean $time 是否过滤掉前面的时间
     * @return string
     */
    public function analyzeFeed($feed, $time = false)
    {
        preg_match('/{{time=(\d+)}}/i', $feed, $match);
        $feed = preg_replace('/{{time=\d+}}/i', ($time ? '' : time2Units($match[1], CTIME).'前'), $feed);
        preg_match('/{{(\d+)}}/i', $feed, $match);
        if (!is_numeric($match[1]))
        {
            return preg_replace('/{{\d+}}/i', '', $feed);
        }

        $uid = $match[1];
	    $userName = userName($uid);
        $feed = preg_replace('/{{\d+}}/i', ilink(filter_content($userName),url('system',array('s'=>'member','uid'=>$uid))), $feed);
        $feed = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)([^\[\"']+?))?\](.+?)\[\/url\]/ies", "parseurl('\\1', '\\5')", $feed);
        $feed = preg_replace_callback("/(<|\s)href\s*=\s*(\"|\')([^\\2>\s]*)\\2/i", 'autoFeedLabel', $feed);

        return $feed;
    }

    /**
     * 获取xxx时间前
     * @param int $end
     * @param int $start
     * @return string
     */
    public function time2Units($end, $start = null)
    {
        return time2Units($end, $start);
    }
    
    public function cacheKey()
    {
        return $this->_cacheKey;
    }
}

/**
 * 给feed的url后面添加一个ifd参数，方便统计feed带来的流量
 * @param array $matches
 * @return string
 */
function autoFeedLabel($matches)
{
    $href = $matches[3];
    if (false === strpos($href, 'ifd=1'))
    {
        $href .= (false === strpos($href, '?')) ? '?' : '&amp;';
        $href .= 'ifd=1';
    }

    return str_replace($matches[3], $href, $matches[0]);
}
