<?php
/**
 * 标签操作库
 * @copyright reginx.com
 * $Id$
 */
class tag_lib {


    /**
     * tag 新增
     *
     * @param unknown_type $ctype
     * @param unknown_type $id
     * @param unknown_type $str
     */
    public static function add($ctype , $id , $str){
        $list = self::format(filter::text($str) , $ctype);
        if(!empty($list)){
            $obj = core::getobj('tag_tab');
            $lsobj = core::getobj('tag_list_tab');
            foreach ($list as $v){
                $tagid = $v['id'];
                if(!empty($v['name']) && $v['id'] === 0 && (int)$obj->where("name = '{$v['name']}' and ctype = {$ctype}")->count() === 0){
                    $obj->set("name"  , $v['name']);
                    $obj->set("ctype" , $ctype);
                    $obj->set("sort"  , 0);
                    $obj->set("sname" , $v['sname']);
                    $obj->set("pyh"   , strtolower(substr($v['sname'] , 0 , 1 )));
                    $ret = $obj->save();
                    if((int)$ret['code'] === 0){
                        $tagid = $ret['msg'];
                    }
                }
                $lsobj->set('refid' , $id)->set('ctype' , $ctype)->set('tagid' , $tagid);
                $lsobj->replace();
            }
        }
    }

    /**
     * 标签格式化
     *
     * @param unknown_type $str
     * @return unknown
     */
    public static function format($str , $ctype = 0){
        $ret  =  array_map(array('filter' , 'text') , explode(',' , $str));
        if(!empty($ret)){
            $ret = array_map(array('filter' , 'ult') , $ret);
        }
        $list = core::getobj('tag_tab')->where("name in ('" .(join("','" , $ret)). "')")->getall();
        if($list){
            // 过滤已经存在的tag
            foreach ($list as $v){
                if(in_array($v['name'] , $ret)){
                    unset($ret[array_search($v['name'] , $ret)]);
                }
            }
        }
        foreach ($ret as $v){
            if(($v = trim($v)) != ''){
                $temp = array();
                $temp['id'] = 0;
                $temp['name']  = preg_replace('/(\.|\s)+/i' , '_' , $v);
                $temp['sname'] = py_lib::get($v , '');
                $list[] = $temp;
            }
        }
        return $list;
    }


    /**
     * 删除tag关系
     *
     * @param unknown_type $id
     */
    public static function dellist($id , $ctype){
        core::getobj('tag_list_tab')->where("refid = $id and ctype = $ctype ")->del();
    }

}
?>