<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModArticle extends Module {
    protected $_filters = array(
        'check_login' => '{recentarticles}{article_content}{fullist}{recentshort}'
    );
    
    private $stack = array();
    private $findout = array();

    public function fullist() {
        $this->_layout = 'frontpage';

        // The default article category
        $curr_article_category = new ArticleCategory();
        $curr_article_category->name = __('All Articles');

        $caa_id = trim(ParamHolder::get('caa_id', '0'));
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $curr_locale = trim(SessionHolder::get('_LOCALE'));

        $search_where = '';
        $search_params = array();
        $article_keyword = trim(ParamHolder::get('article_keyword', ''));
        if (strlen($article_keyword) > 0) {
            $search_where = ' AND (title LIKE ? OR content LIKE ?)';
            $search_params = array('%'.$article_keyword.'%', '%'.$article_keyword.'%');
            $this->assign('article_keyword', $article_keyword);
        }// 02/06/2010 Edit >>
        else if (intval($caa_id) > 1) {
        //if (intval($cap_id) > 1) {
        // 02/06/2010 Edit <<
        	$article_category = new ArticleCategory();
        	$article_categories = $article_category->findAll();
        	if(empty($article_categories)) $article_categories = array();
        	foreach($article_categories as $k => $v)
        	{
        		$this->stack[$v->id] = $v->article_category_id;
        	}
        	$this->findout[] = $caa_id;
        	$this->getCategoryList();
        	$search_where = " AND article_category_id IN ('' ";
    		foreach($this->findout as $k => $v)
    		{
    			$search_where .= ",$v";
    		}
//    		$len = strlen($search_where);
//    		$search_where[$len-1] = ''; 
    		$search_where .= ') AND article_category_id <> 0';//die($search_where);
            $curr_article_category = new ArticleCategory($caa_id);
        }
        try {
            $now = time();
            $o_article = new Article();
            /**
             * Add 02/08/2010
             */
            include_once(P_LIB.'/pager.php');

            if ($user_role == '{admin}') {
            	$str_sql = "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND article_category_id<>2";
//                if(empty($caa_id))
//                {
//                	$str_sql .= " AND article_category_id=2";//article_category is news.
//                }         
                
                $article_data =&
                    Pager::pageByObject('article',
                        $str_sql. " AND s_locale=?".$search_where,
                        array_merge(array($now, $now, $now, $now, $curr_locale), $search_params),
                        "ORDER BY `i_order` DESC,`create_time` DESC");
            } else {
            	$str_sql = "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND article_category_id<>2";
//            	if(empty($caa_id))
//                {
//                	$str_sql .= " AND article_category_id=2";//article_category is news.
//                }         
                         
                $article_data =&
                    Pager::pageByObject('article',
                        $str_sql .= " AND for_roles LIKE ? AND s_locale=?".$search_where,
                        array_merge(array($now, $now, $now, $now, '%'.$user_role.'%', $curr_locale), $search_params),
                        "ORDER BY `i_order` DESC,`create_time` DESC");
            }

            $this->assign('page_title', $curr_article_category->name);

            $this->assign('category', $curr_article_category);
            $this->assign('articles', $article_data['data']);
            $this->assign('pager', $article_data['pager']);
            $this->assign('caa_id', $caa_id);
            $this->assign('article_keyword', $article_keyword);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

    }

    public function article_content() {
        $this->_layout = 'frontpage';
        $article_id = ParamHolder::get('article_id', '0');
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        if (intval($article_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        try {
            $now = time();
            $o_article = new Article();
            if ($user_role == '{admin}') {
                $curr_article =& $o_article->find("`id`=? AND "
                            ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND article_category_id<>2 AND s_locale=?",
                        array($article_id, $now, $now, $now, $now, $curr_locale));
                $curr_article->v_num++;
                $curr_article->save();
            } else {
                $curr_article =& $o_article->find("`id`=? AND "
                            ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND article_category_id<>2 AND for_roles LIKE ? AND s_locale=?",
                        array($article_id, $now, $now, $now, $now, '%'.$user_role.'%', $curr_locale));
                if(sizeof($curr_article) > 0) {
                    $curr_article->v_num++;
                    $curr_article->save();
                } else {
                    $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
                    return '_error';
                }
            }
            $this->assign('page_title', $curr_article->title);
            $this->assign('curr_article', $curr_article);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }
    }

    public function recentarticles() {
        $list_size = trim(ParamHolder::get('article_reclst_size'));
        if (!is_numeric($list_size) || strlen($list_size) == 0) {
            $list_size = '5';
        }
        $article_category = trim(ParamHolder::get('article_category'));
        $this->assign('article_category', $article_category);
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        // 02/06/2010 Add >>
        $childids = $this->getCategoryChildIds($article_category, $curr_locale);
        $article_category = !empty($childids) ? $childids.$article_category : $article_category;
        // 02/06/2010 Add <<
        $o_article = new Article();
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        if ($user_role == '{admin}') {
            if($article_category == 0) {
                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? ", array($curr_locale),
                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);
            } else {
//                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? and article_category_id=? ", array($curr_locale,$article_category),
//                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);
                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? and article_category_id IN(".$article_category.") ", array($curr_locale),
                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);            }
        } else {
			if($article_category == 0) {
                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? AND for_roles LIKE ? ", array($curr_locale, '%'.$user_role.'%'),
                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);
            } else {
//                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? and article_category_id=? AND for_roles LIKE ? ", array($curr_locale,$article_category, '%'.$user_role.'%'),
//                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);
                $articles = $o_article->findAll("article_category_id<>2 AND published='1' AND s_locale=? and article_category_id IN(".$article_category.") AND for_roles LIKE ? ", array($curr_locale, '%'.$user_role.'%'),
                            "ORDER BY `i_order` DESC, `create_time` DESC LIMIT ".$list_size);
            }
        }

        $this->assign('articles', $articles);
    }

    public function recentshort() {
        return $this->recentarticles();
    }
    
	public function getCategoryList()
    {
    	$i = $j = count($this->stack);
    	$flag = true;
    	while(($j < $i) || $flag)
    	{
	    	$i = $j;
    		foreach($this->stack as $k => $v)
	    	{
	    		if(in_array($v,$this->findout))
	    		{
	    			$this->findout[] = $k;
	    			unset($this->stack[$k]);
	    		}
	    	}
	    	$j = count($this->stack);
	    	$flag = false;
    	}
    }
    
    // 02/06/2010 Add >>
    private function getCategoryChildIds( $parentid, $curr_locale )
    {
    	$article_childcategories = array();
    	$article_category = new ArticleCategory();
    	$article_childcategories = $article_category->findAll("article_category_id = '{$parentid}' AND s_locale = '{$curr_locale}'");
    	
    	$childids = '';
    	if ( count($article_childcategories) ) {
    		foreach( $article_childcategories as $val )
    		{
    			$childids .= $val->id.',';
				$childids .= $this->getCategoryChildIds($val->id, $curr_locale);
    		}
    	}
    	
    	return $childids;
    }
    // 02/06/2010 Add <<
}
?>
