<?php
/**
* @version	$Id: post_tp.php 12740 2009-10-20 19:39:07Z alex $
* @package	In-Bulletin
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class PostTagProcessor extends kDBTagProcessor {

		function ListPosts($params)
		{
			$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
			$main_object =& $this->Application->recallObject($parent_prefix);
			/* @var $main_object kCatDBItem */

			if ($main_object->isLoaded()) {
				$main_object->RegisterHit();
			}

			return $this->PrintList2($params);
		}

		/**
		 * Returns link to post author public profile
		 *
		 * @param Array $params
		 * @return string
		 */
		function ProfileLink($params)
		{
			$object =& $this->getObject($params);
			$params['user_id'] = $object->GetDBField('CreatedById');

			return $this->Application->ProcessParsedTag('m', 'Link', $params);
		}

		function PosterField($params)
		{
			static $posters = null;

			$object =& $this->getObject($params);

			if (!isset($posters)) {
				$poster_ids = array_unique($object->GetCol('CreatedById'));

				$user_idfield = $this->Application->getUnitOption('u', 'IDField');
				$user_table = $this->Application->getUnitOption('u', 'TableName');

				$sql = 'SELECT u.*, g.Name AS PrimaryGroup
						FROM '.$user_table.' u
						LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON ug.PortalUserId = u.PortalUserId AND ug.PrimaryGroup = 1
						LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON g.GroupId = ug.GroupId
						WHERE u.'.$user_idfield.' IN ('.implode(',', $poster_ids).')';
				$posters = $this->Conn->Query($sql, $user_idfield);
			}

			$poster =& $this->Application->recallObject('u.poster', null, Array('skip_autoload' => true));
			/* @var $poster UsersItem */

			$poster_id = $object->GetDBField('CreatedById');
			if ($poster_id > 0) {
				// not Guest & root
				if ($poster->GetID() != $poster_id) {
					// previous poster differs from requested
					$poster->SetDBFieldsFromHash($posters[$poster_id]);
					$poster->setID($poster_id);
				}
				return $this->Application->ProcessParsedTag('u.poster', 'Field', $params);
			}

			return '';
		}

		/**
		 * Checks if post is made by real user (not Guest or root)
		 *
		 * @param Array $params
		 * @return bool
		 */
		function PosterFound($params)
		{
			$object =& $this->getObject($params);

			return $object->GetDBField('CreatedById') > 0;
		}

		/**
		 * Posts count created by current poster
		 *
		 * @param Array $params
		 * @return int
		 */
		function PosterPostsCount($params)
		{
			static $posts_count = null;

			$object =& $this->getObject($params);

			if (!isset($posts_count)) {
				$poster_ids = array_unique($object->GetCol('CreatedById'));

				$sql = 'SELECT VariableValue, PortalUserId
						FROM '.TABLE_PREFIX.'PersistantSessionData
						WHERE PortalUserId IN ('.implode(',', $poster_ids).') AND VariableName = "bb_posts"';
				$posts_count = $this->Conn->GetCol($sql, 'PortalUserId');
			}

			return $posts_count[$object->GetDBField('CreatedById')];
		}

		function PostSubject($params)
		{
			$object =& $this->getObject($params);

			$post_helper =& $this->Application->recallObject('PostHelper');
			/* @var $post_helper PostHelper */

			return $post_helper->CensorText( $object->GetDBField('Subject') );
		}

		function PostBody($params)
		{
			$object =& $this->getObject($params);

			$post_helper =& $this->Application->recallObject('PostHelper');
			/* @var $post_helper PostHelper */

			$body = $object->GetDBField('PostingText');

			// 2. parse post body
			$sub_blocks = Array (
                	'smileys' => $params['smiley_render_as'],
                	'bbcode' => $params['bbcode_render_as'],
                	'quote' => $params['quote_render_as'],
                );
			$body = $post_helper->parsePostBody($body, $object->GetDBField('Options'), $sub_blocks);

			return $body;
		}

		/**
		 * Checks if poster signature needs to be shown together with post
		 *
		 * @param Array $params
		 * @return bool
		 */
		function ShowPostSignature($params)
		{
			$object =& $this->getObject($params);
			$post_options = $object->GetDBField('Options');

			$post_helper =& $this->Application->recallObject('PostHelper');
			/* @var $post_helper PostHelper */

			// show poster signature in this post
			if ($post_helper->GetPostOption('show_sig', $post_options)) {
				// logged-in user wishes to view signatures in posts
                $show_other_signatures = $this->Application->RecallPersistentVar('bb_signatures');
                if ($show_other_signatures) {
                	// don't show signature when it is empty
                	$signature = $this->getUserSignature($object->GetDBField('CreatedById'));
                	return strlen(trim($signature)) ? true : false;
                }
			}

			return false;
		}

		/**
		 * Returns parsed poster (from current post) signature
		 *
		 * @param Array $params
		 * @return string
		 */
		function PostSignature($params)
		{
			$object =& $this->getObject($params);

			$post_helper =& $this->Application->recallObject('PostHelper');
			/* @var $post_helper PostHelper */

			$sub_blocks = Array (
				'smileys' => $params['smiley_render_as'],
				'bbcode' => $params['bbcode_render_as'],
			);

			$signature = $this->getUserSignature($object->GetDBField('CreatedById'));
			return $post_helper->parsePostBody($signature, $object->GetDBField('Options'), $sub_blocks);
		}

		/**
		 * Returns user signature (cached for all viewed posts on page)
		 *
		 * @param int $user_id
		 * @return string
		 */
		function getUserSignature($user_id)
		{
			static $user_signatures = null;

			$object =& $this->getObject();

			if (!isset($user_signatures)) {
				$poster_ids = array_unique($object->GetCol('CreatedById'));

				$sql = 'SELECT VariableValue, PortalUserId
						FROM '.TABLE_PREFIX.'PersistantSessionData
						WHERE PortalUserId IN ('.implode(',', $poster_ids).') AND VariableName = "my_signature"';
				$user_signatures = $this->Conn->GetCol($sql, 'PortalUserId');
			}

			$poster_id = $object->GetDBField('CreatedById');
			return isset($user_signatures[$poster_id]) ? $user_signatures[$poster_id] : '';
		}

		/**
		 * Creates link to individual post in topic
		 *
		 * @param Array $params
		 * @return string
		 */
		function PostLink($params)
		{
			$params['pass'] = 'm,bb,bb-post';

			return $this->Application->ProcessParsedTag('m', 'Link', $params);
		}

		function ReplyQuotedLink($params)
		{
			$object =& $this->getObject($params);

			$params['pass'] = 'm,bb';
			$params['reply_to'] = $object->GetID();

			return $this->Application->ProcessParsedTag('m', 'Link', $params);
		}

		/**
		 * Checks if user have one of required permissions
		 *
		 * @param Array $params
		 * @return bool
		 */
		function HasPermission($params)
		{
			static $category_path = null;

			if (!isset($category_path)) {
				// get topic category
				$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
				$parent_item =& $this->Application->recallObject($parent_prefix, null, Array ('raise_warnings' => 0));
				$category_path = $parent_item->isLoaded() ? $parent_item->GetDBField('ParentPath') : $this->Application->GetVar('m_cat_id');
			}

			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
			/* @var $perm_helper kPermissionsHelper */

			$params['raise_warnings'] = 0;
			$object =& $this->getObject($params);
			/* @var $object kDBItem */

			// 1. category restriction
			$params['cat_id'] = $category_path;

			// 2. owner restriction
			$is_owner = $object->GetDBField('CreatedById') == $this->Application->RecallVar('user_id');

			return $perm_helper->TagPermissionCheck($params, $is_owner);
		}

		function CategoryItemCount($params)
		{
			$count_helper =& $this->Application->recallObject('CountHelper');
			/* @var $count_helper kCountHelper */

			return $count_helper->CategoryItemCount('bb', $params, 'SUM(Posts)'); //  - COUNT(TopicId)
		}

		function ItemCount($params)
		{
			$count_helper =& $this->Application->recallObject('CountHelper');
			/* @var $count_helper kCountHelper */

			$today_only = isset($params['today']) && $params['today'];
			return $count_helper->ItemCount('bb', $today_only, 'SUM(Posts)'); // - COUNT(TopicId)
		}

		/**
		 * Preserve main item id in subitem pagination url
		 *
		 * @param Array $params
		 * @return string
		 */
		function PageLink($params)
		{
			$object =& $this->getObject($params);
			/* @var kDBList */

			$parent_info = $object->getLinkedInfo();
			if ($parent_info['ParentId'] > 0) {
				$params['pass'] = 'm,'.$this->getPrefixSpecial().','.$parent_info['ParentPrefix'];
			}
			return parent::PageLink($params);
		}
	}