<?php

/**
 *--------------------------------------
 * article
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-07-07
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class ArticleModl extends Modl {
	public function get_articleCount($where = array()) {
		$where['ac.lang'] = array('EQ', LANG_NAME);
		$_count = M('Article')->join('__ARTICLE_CATEGORY__ AS ac ON ac.article_category_id = __ARTICLE__.article_category_id')->where($where)->count();
		return $_count;
	}

	public function get_articleList($where = array(), $order = '`a_rank` DESC, `a_edit_time` DESC', $limit = 10) {
		$where['ac.lang'] = array('EQ', LANG_NAME);

		if('`random`' == substr($order, 0, 8)) {
			$where['_string'] = '__ARTICLE__.article_id >= ((SELECT MAX(article_id) FROM __ARTICLE__) - (SELECT MIN(article_id) FROM __ARTICLE__)) * RAND() + (SELECT MIN(article_id) FROM __ARTICLE__)';
			$order = '`a_rank` DESC, `a_edit_time` DESC';
		}

		$_AL = M('Article')->field('__ARTICLE__.`article_id`,`a_title`,`a_thumb`,`a_keywords`,`a_description`,`a_property`,`a_image`,`a_annex`,`a_addon_field`,`a_add_time`,`a_edit_time`,`a_add_ip`,`a_edit_ip`,`a_view_count`,`a_review_count`,`a_support_count`,`a_oppose_count`,`a_rank`,`a_status`,`a_review_switch`,`a_url_jump`,`af_alias`,__ARTICLE__.`article_category_id`,`ac_name`,`ac_keywords`,`ac_description`,`ac_display_switch`')
			->join('__ARTICLE_CATEGORY__ AS ac ON ac.article_category_id = __ARTICLE__.article_category_id')
			->where($where)->order($order)->limit($limit)->select();

		foreach($_AL as $k => $v) {
			$_AL[$k]['a_url'] = Url::U('home@article/show_article?article_id='.$v['article_id']);
			$_AL[$k]['ac_url'] = $_AL[$k]['ac_display_switch'] ? Url::U('home@article/show_category?article_category_id='.$v['article_category_id']) : '';
			$_AL[$k]['a_property'] = unserialize($v['a_property']);
			$_AL[$k]['a_image'] = unserialize($v['a_image']);
			$_AL[$k]['a_annex'] = unserialize($v['a_annex']);
			$_AL[$k]['a_addon_field'] = unserialize($v['a_addon_field']);
			if(MAGIC_QUOTES_GPC) {
				$_AL[$k]['a_property'] = stripslashes_array($_AL[$k]['a_property']);
				$_AL[$k]['a_image'] = stripslashes_array($_AL[$k]['a_image']);
				$_AL[$k]['a_annex'] = stripslashes_array($_AL[$k]['a_annex']);
				$_AL[$k]['a_addon_field'] = stripslashes_array($_AL[$k]['a_addon_field']);
			}
			if(!empty($_AL[$k]['a_addon_field'])) {
				$_AL[$k] = array_merge($_AL[$k], $_AL[$k]['a_addon_field']);
			}
			unset($_AL[$k]['a_addon_field']);
		}

		return $_AL;
	}

	public function get_articleInfo($articleId, $output = false) {
		$where = array();
		$where['__ARTICLE__.article_id'] = array('EQ', $articleId);
		$where['ac.lang'] = array('EQ', LANG_NAME);

		$_AI = $this->where($where)->join('__ARTICLE_CATEGORY__ AS ac ON ac.article_category_id = __ARTICLE__.article_category_id')->find();
		if(empty($_AI)) {
			return null;
		}

		/* article flag */
		$_AI['af_alias'] = explode(',', $_AI['af_alias']);
		$_AI['a_url'] = Url::U('home@article/show_article?article_id='.$_AI['article_id']);
		$_AI['ac_url'] = $_AI['ac_display_switch'] ? Url::U('home@article/show_category?article_category_id='.$_AI['article_category_id']) : '';
		$_AI['a_property'] = unserialize($_AI['a_property']);
		$_AI['a_image'] = unserialize($_AI['a_image']);
		$_AI['a_annex'] = unserialize($_AI['a_annex']);
		$_AI['a_addon_field'] = unserialize($_AI['a_addon_field']);
		$_AI['ac_addon_field'] = unserialize($_AI['ac_addon_field']);
		if(MAGIC_QUOTES_GPC) {
			$_AI['a_property'] = stripslashes_array($_AI['a_property']);
			$_AI['a_image'] = stripslashes_array($_AI['a_image']);
			$_AI['a_annex'] = stripslashes_array($_AI['a_annex']);
			$_AI['a_addon_field'] = stripslashes_array($_AI['a_addon_field']);
			$_AI['ac_addon_field'] = stripslashes_array($_AI['ac_addon_field']);
		}
		if(!empty($_AI['a_addon_field'])) {
			$_AI = array_merge($_AI, $_AI['a_addon_field']);
		}
		unset($_AI['a_addon_field']);

		/* get previous and next article */
		$_t_where = array();
		$_t_where['a_status'] = array('EQ', 1);
		$_t_where['article_category_id'] = array('EQ', $_AI['article_category_id']);
		$_t_where['article_id'] = array('LT', $_AI['article_id']);
 		/* prev */
		$_AI['a_prev'] = $this->field('`a_title`,`a_thumb`,`article_id`')->order('`article_id` DESC')->where($_t_where)->find();
		if(!empty($_AI['a_prev'])) {
			$_AI['a_prev']['a_url'] = Url::U('home@article/show_article?article_id='.$_AI['a_prev']['article_id']);
		}
		$_t_where['article_id'] = array('GT', $_AI['article_id']);
 		/* next */
		$_AI['a_next'] = $this->field('`a_title`,`a_thumb`,`article_id`')->order('`article_id` ASC')->where($_t_where)->find();
		if(!empty($_AI['a_next'])) {
			$_AI['a_next']['a_url'] = Url::U('home@article/show_article?article_id='.$_AI['a_next']['article_id']);
		}

		return $_AI;
	}

	public function add_article($data) {
		$result = array('data' => '', 'error' => '');

		if(isset($data['a_thumb'])) {
			$data['a_thumb'] = AFilter::url($data['a_thumb'], 255);
		}
		foreach($data['a_property'] as $apk => $apv) {
			$data['a_property'][$apk] = array('name' => AFilter::plain_text(strval($apv['name'])), 'value' => AFilter::text(strval($apv['value'])));
		}
		$data['a_property'] = serialize(array_values($data['a_property']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_property'] = addslashes($data['a_property']);
		}
		foreach($data['a_image'] as $aik => $aiv) {
			$data['a_image'][$aik] = array(
				'url' => AFilter::url(strval($aiv['url'])),
				'title' => AFilter::plain_text(strval($aiv['title'])),
				'description' => AFilter::text(strval($aiv['description'])),
			);
		}
		$data['a_image'] = serialize(array_values($data['a_image']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_image'] = addslashes($data['a_image']);
		}
		foreach($data['a_annex'] as $aak => $aav) {
			$data['a_annex'][$aak] = array(
				'url' => AFilter::url(strval($aav['url'])),
				'title' => AFilter::plain_text(strval($aav['title'])),
				'description' => AFilter::text(strval($aav['description'])),
			);
		}
		$data['a_annex'] = serialize(array_values($data['a_annex']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_annex'] = addslashes($data['a_annex']);
		}

		/* addon field */
		$_aci = M('ArticleCategory')->get_categoryInfo($data['article_category_id']);
		$addonField = array();
		foreach($_aci['ac_addon_field'] as $acaf) {
			if(array_key_exists($acaf['key'], $data['a_addon_field'])) {
				$addonField[$acaf['key']] = get_fieldValue($data['a_addon_field'][$acaf['key']], $acaf['type']);
			}
		}
		$data['a_addon_field'] = serialize($addonField);
		if(MAGIC_QUOTES_GPC) {
			$data['a_addon_field'] = addslashes($data['a_addon_field']);
		}

		unset($data['article_id']);
		$result['data'] = $this->insert($data);
		if(false === $result['data']) {
			$result['error'] = L('ADD_FAILED');
			return $result;
		}

		if(1 == $data['a_status']) {
			M('ArticleCategory')->step_articleCount($data['article_category_id']);
		}

		return $result;
	}

	public function edit_article($data) {
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_articleInfo($data['article_id']);
		if(empty($_AI)) {
			$result['error'] = L('ITEM_INEXISTENCE');
			return $result;
		}

		if(isset($data['a_thumb'])) {
			$data['a_thumb'] = AFilter::url($data['a_thumb'], 255);
		}
		foreach($data['a_property'] as $apk => $apv) {
			$data['a_property'][$apk] = array('name' => AFilter::plain_text(strval($apv['name'])), 'value' => AFilter::text(strval($apv['value'])));
		}
		$data['a_property'] = serialize(array_values($data['a_property']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_property'] = addslashes($data['a_property']);
		}
		foreach($data['a_image'] as $aik => $aiv) {
			$data['a_image'][$aik] = array(
				'url' => AFilter::url(strval($aiv['url'])),
				'title' => AFilter::plain_text(strval($aiv['title'])),
				'description' => AFilter::text(strval($aiv['description'])),
			);
		}
		$data['a_image'] = serialize(array_values($data['a_image']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_image'] = addslashes($data['a_image']);
		}
		foreach($data['a_annex'] as $aak => $aav) {
			$data['a_annex'][$aak] = array(
				'url' => AFilter::url(strval($aav['url'])),
				'title' => AFilter::plain_text(strval($aav['title'])),
				'description' => AFilter::text(strval($aav['description'])),
			);
		}
		$data['a_annex'] = serialize(array_values($data['a_annex']));
		if(MAGIC_QUOTES_GPC) {
			$data['a_annex'] = addslashes($data['a_annex']);
		}

		/* addon field */
		$_aci = M('ArticleCategory')->get_categoryInfo($data['article_category_id']);
		$addonField = array();
		foreach($_aci['ac_addon_field'] as $acaf) {
			if(array_key_exists($acaf['key'], $data['a_addon_field'])) {
				$addonField[$acaf['key']] = get_fieldValue($data['a_addon_field'][$acaf['key']], $acaf['type']);
			}
		}
		$data['a_addon_field'] = serialize($addonField);
		if(MAGIC_QUOTES_GPC) {
			$data['a_addon_field'] = addslashes($data['a_addon_field']);
		}

		if(false === $this->update($data)) {
			$result['error'] = L('UPDATE_FAILED');
			return $result;
		}

		/* update member credit and article count of category */
		if(1 != $_AI['a_status']) {
			if(1 == $data['a_status']) {
				M('ArticleCategory')->step_articleCount($data['article_category_id']);
				if($data['article_category_id'] != $_AI['article_category_id']) {
					M('ArticleCategory')->step_articleCount($_AI['article_category_id'], false);
				}
			}
		}
		else {
			if(1 != $data['a_status']) {
				M('ArticleCategory')->step_articleCount($_AI['article_category_id'], false);
			}
			else {
				if($data['article_category_id'] != $_AI['article_category_id']) {
					M('ArticleCategory')->step_articleCount($data['article_category_id']);
					M('ArticleCategory')->step_articleCount($_AI['article_category_id'], false);
				}
			}
		}

		$this->_clear_articleCache($data['article_id']);

		return $result;
	}

	public function delete_article($articleId) {
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_articleInfo($articleId);
		if(empty($_AI)) {
			$result['error'] = L('ITEM_INEXISTENCE');
			return $result;
		}

		if(false === $this->delete($articleId)) {
			$result['error'] = L('DELETE_FAILED');
			return $result;
		}

		if(1 == $_AI['a_status']) {
			M('ArticleCategory')->step_articleCount($data['article_category_id'], false);
		}

		$this->_clear_articleCache($articleId);

		return $result;
	}

	public function update_count($articleId) {
		$result = array('data' => '', 'error' => '');

		$aRC = M('ArticleReview')->where(array('article_id' => array('EQ', $articleId), 'ar_status' => array('EQ', 1)))->count();

		$this->where(array('article_id' => array('EQ', $articleId)))->set_field(array('a_review_count'), array($aRC));

		$result['data'] = array('a_review_count' => $aRC);

		$this->_clear_articleCache($articleId);

		return $result;
	}

	public function change_category($articleId, $aStatus, $articleCategoryIdTo, $articleCategoryIdFrom) {
		$result = array('data' => '', 'error' => '');

		if($articleCategoryIdTo == $articleCategoryIdFrom) {
			return $result;
		}

		$data = array(
			'article_id' => $articleId,
			'article_category_id' => $articleCategoryIdTo,
		);

		if(false === $this->update($data)) {
			$result['error'] = L('CHANGE_FAILED');
			return $result;
		}

		if(1 == $aStatus) {
			M('ArticleCategory')->step_articleCount($articleCategoryIdTo);
			M('ArticleCategory')->step_articleCount($articleCategoryIdFrom, false);
		}

		$this->_clear_articleCache($articleId);

		return $result;
	}

	public function add_flag($articleId, $afALias) {
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_articleInfo($articleId);
		if(empty($_AI)) {
			$result['error'] = L('ITEM_INEXISTENCE');
			return $result;
		}

		/* get flag */
		$afAliasValue = $this->_get_flagValue($afALias);

		if(!$afAliasValue) {
			$result['error'] = L('PARAMS_ERROR');
			return $result;
		}

		/* add flag */
		$_t_sql = "UPDATE `".C('DB.PREFIX').'article'.C('DB.SUFFIX')."` SET `af_alias` = `af_alias` | {$afAliasValue} WHERE `article_id` = '{$articleId}';";
		if(!$this->execute($_t_sql)) {
			$result['error'] = L('ADD_FLAG_FAILED');
			return $result;
		}

		$this->_clear_articleCache($articleId);

		return $result;
	}

	public function delete_flag($articleId, $afALias) {
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_articleInfo($articleId);
		if(empty($_AI)) {
			$result['error'] = L('ITEM_INEXISTENCE');
			return $result;
		}

		/* get flag */
		$afAliasValue = $this->_get_flagValue($afALias);

		if(!$afAliasValue) {
			$result['error'] = L('PARAMS_ERROR');
			return $result;
		}

		/* delete flag */
		$_t_sql = "UPDATE `".C('DB.PREFIX').'article'.C('DB.SUFFIX')."` SET `af_alias` = `af_alias` &~ {$afAliasValue} WHERE `article_id` = '{$articleId}';";
		if(!$this->execute($_t_sql)) {
			$result['error'] = L('DELETE_FLAG_FAILED');
			return $result;
		}

		$this->_clear_articleCache($articleId);

		return $result;
	}

	private function _get_flagValue($afAlias) {
		$_AFK = array_keys(EO('article_flag'));
		foreach($_AFK as $k => $flag) {
			if($afAlias == $flag) {
				return pow(2, $k);
			}
		}
		return false;
	}

	private function _clear_articleCache($articleId) {
		$pageSign = md5('A|'.$articleId);
		S('_AI'.$pageSign, null, null, array('temp' => TEMP_PATH.D_S.'home'));
	}
}

?>