<?php
/**
 * feed存储MySQL实现
 * User: yzxh24
 * Date: 11-8-13
 * Time: 下午4:21
 * To change this template use File | Settings | File Templates.
 */
require_once 'FAbstract.php';
class FMySQL extends FAbstract
{
    public $condition = '';
    
    private $_table = 'ig_feed';

    private $_db = null;

    private $_cache = null;

    public function __construct()
    {
        global $db, $cache;
        $this->setCache($cache);
        $this->setDb($db);
    }

    /**
     * 创建一条feed
     * @param string $feed
     * @param int $uid
     * @param string $type
     * @return void|int
     */
    public function create($feed, $uid, $type = 'bbs')
    {
        // admin或者隐身登录的用户动态不记录
        if (isGM($uid) || Members::isHiddenLogin($uid))
        {
            return;
        }

        $feed = preg_replace('/st=\d/i', '', $feed);
        $feed = preg_replace('/ruid=\d+/i', '', $feed);
        $feed = filter_content('{{time='.CTIME.'}}'.sFilter($feed));
        $this->db()->insert($this->tableName())->value(array('feed'=>$feed,'uid'=>$uid,'createdate'=>CTIME,'type'=>$type))->q();
        $this->setOneCache($feed);

        return $this->db()->getInsertId();
    }

    /**
     * 获取一条最新的feed
     * @param bool $br
     * @return bool|string
     */
    public function getOneCache($br = true)
    {
        $feed = $this->cache()->get($this->cacheKey());
        //var_dump($feed);die;
        if (false === $feed)
        {
            $feed = $this->db()->getValue('SELECT feed FROM '.$this->tableName().' ORDER BY id DESC LIMIT 1');
            if (empty($feed))
            {
                return false;
            }
            $this->setOneCache($feed);
        }

        return $this->analyzeFeed($feed) . ($br ? '<br/>' : '');
    }

    public function condition($conditions)
    {
        if (empty($conditions))
        {
            return $this;
        }
        
        if (is_array($conditions))
        {
            /**
            * 写法1
            * $conditions = array('field1' => 'value1','field2' => 'value2');
            *
            * 写法2
            * $conditions = array(array('fields', 'value', 'operator'));
            */
            foreach ($conditions as $key => $value)
            {
                if (is_array($value))
                {
                    $operator = !empty($value[2]) ? $value[2] : '=';
                    if ('in' == strtolower($operator))
                    {
                        $where[] = '`' . $value[0] . '` IN (' . implode(',', $value[1]) . ')';
                    }
                    else
                    {
                        $where[] = '`' . $value[0] . "` $operator '" . $value[1] . "'";
                    }
                }
                else
                {
                    $where[] = '`' . $key . "` = '" . $value . "'";
                }
            }
            $condition = implode(' AND ', $where);
        }
        else if (is_string($conditions))
        {
            $condition = $conditions;
        }

        $this->condition = ' WHERE ' . $condition;

        return $this;
    }

    public function count()
    {
        return $this->db()->getValue('SELECT COUNT(*) FROM '.$this->tableName().$this->condition);
    }

    public function findAll($fields = '*', $sort = array(), $offset = 0, $limit = 10)
    {
        $query = 'SELECT ';
        if (is_string($fields) && '*' == $fields)
        {
            $query .= $fields;
        }
        else if (is_array($fields))
        {
            foreach ($fields as $value)
            {
                $keys[] = '`' . $value . '`';
            }
            $query .= implode(',', $keys);
        }

        $orderBy = '';
        if (array() !== $sort)
        {
            $tmp = array();
            foreach ($sort as $k => $v)
            {
                $tmp[] = ($k == 'createdate' ? 'id' : $k) . ' ' . ($v == 1 ? 'ASC' : 'DESC');
            }
            $orderBy = ' ORDER BY ' . implode(',', $tmp);
        }
        $query .= ' FROM ' . $this->tableName() . $this->condition . $orderBy . ' LIMIT '. $offset . ',' . $limit;
        $result = $this->db()->setQueryString($query)->find();

        return $result;
    }

    /**
     * 获取最新的feed
     * @param int $num
     * @return array
     */
    public function getNews($num = 1)
    {
        $feeds = $this->db()->select(array('feed'))->from($this->tableName())->desc('id')->limit(5)->find();
        if (empty($feeds))
        {
            return false;
        }

        foreach ($feeds as &$feed)
        {
            $feed['feed'] = $this->analyzeFeed($feed['feed'], true);
        }

        return $feeds;
    }

    /**
     * 获取一组UID的动态
     * @param array $uids
     * @return mixed
     */
    public function getFeedsByUids($uids)
    {
        $feeds = $this->db()->select(array('feed'))->from($this->tableName())->where('uid IN ('.implode(',', $uids).')')->desc('createdate')->limit(5)->find();
        if (empty($feeds))
        {
            return false;
        }

        foreach ($feeds as &$feed)
        {
            $feed['feed'] = $this->analyzeFeed($feed['feed']);
        }

        return $feeds;
    }

    public function setDb($db)
    {
        $this->_db = $db;
    }

    /**
     * @return Db
     */
    public function db()
    {
        return $this->_db;
    }

    public function setCache($cache)
    {
        $this->_cache = $cache;
    }

    /**
     * @return Cache
     */
    public function cache()
    {
        return $this->_cache;
    }

    public function tableName()
    {
        return $this->_table;
    }
}