<?php
if (!defined('VB_ENTRY')) die('Access denied.');
/*======================================================================*\
   || #################################################################### ||
   || # vBulletin 5.0.0 Beta 10
   || # ---------------------------------------------------------------- # ||
   || # Copyright �2000-2012 vBulletin Solutions Inc. All Rights Reserved. ||
   || # This file may not be redistributed in whole or significant part. # ||
   || # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
   || # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
   || #################################################################### ||
   \*======================================================================*/


/**
 * vB_Api_Content_Channel
 *
 * @package vBApi
 * @author ebrown
 * @copyright Copyright (c) 2011
 * @version $Id$
 * @access public
 */
class vB_Api_Content_Channel extends vB_Api_Content
{
	//override in client- the text name
	protected $contenttype = 'vBForum_Channel';

	public static $topLevelChannels = array(
		'forum' => 'vbulletin-4ecbdf567f2c35.70389590',
		'blog' => 'vbulletin-4ecbdf567f3a38.99555305',
		'groups' => 'vbulletin-4ecbdf567f3a38.99555306',
		'special' => 'vbulletin-4ecbdf567f3341.44451100',
	);

	//The table for the type-specific data.
	protected $tablename = 'channel';

	//We need the primary key field name.
	protected $primarykey = 'nodeid';

	/** normal protector- protected to prevent direct instantiation **/
	protected function __construct()
	{
		parent::__construct();
		$this->library = vB_Library::instance('Content_Channel');
	}

	/**
	 * Returns a channel record based on its node id
	 *
	 * @param	into	Node ID
	 *
	 * @return	array	Channel information
	 */
	public function fetchChannelById($nodeid)
	{
		$nodeid = intval($nodeid);
		$nodes = $this->getContent($nodeid);
		$data = array();

		if (!$this->validate($data, self::ACTION_VIEW, $nodeid, array($nodes)))
		{
			throw new vB_Exception_Api('no_permission');
		}
		return $nodes[$nodeid];

	}

	/**
	 * Returns an array with bbcode options for the node.
	 * @param type $nodeId
	 */
	public function getBbcodeOptions($nodeId)
	{
		$record = $this->assertor->getRow('channel', array(
			vB_dB_Query::TYPE_KEY	=> vB_dB_Query::QUERY_SELECT,
			vB_dB_Query::CONDITIONS_KEY => array('nodeid' => $nodeId)
		));

		$result = array();

		$options = vB::getDatastore()->getValue('bf_misc_forumoptions');
		foreach($options AS $optionName => $optionVal)
		{
			$result[$optionName] = (bool)($record['options'] & $optionVal);
		}

		return $result;
	}

	/** get a blog icon
	*
	*	@param	int		the channel or nodeid
	*
	*	@return	mixed	the raw content of the image.
	***/
	function fetchChannelIcon($nodeid, $thumb)
	{

		if (!vB::getUserContext()->getChannelPermission('forumpermissions', 'canview', $nodeid))
		{
			return false;
		}

		$channel = $this->assertor->getRow('vBForum:channel', array('nodeid' => $nodeid));
		if ($channel['filedataid'])
		{
			$record = vB::getDbAssertor()->getRow('filedata', array(
				vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT,
				'filedataid' => $channel['filedataid']));

			if (!empty($record))
			{
				return vB_Image::instance()->loadFileData($record, $thumb, true);
			}
		}
		//If we don't have a valid custom icon, return the default.
		return false;
	}

	public function getContributors($nodeId)
	{
		$db = vB::getDbAssertor();

		$users = array();

		// fetch relevant usergroups
		$systemgroups = array();
		$usergroups = $db->assertQuery('vBForum:usergroup', array(
			vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT,
			'systemgroupid' => array(
				vB_Api_UserGroup::CHANNEL_OWNER_SYSGROUPID,
				vB_Api_UserGroup::CHANNEL_MODERATOR_SYSGROUPID,
				vB_Api_UserGroup::CHANNEL_MEMBER_SYSGROUPID,
				vB_Api_UserGroup::SG_OWNER_SYSGROUPID,
				vB_Api_UserGroup::SG_MODERATOR_SYSGROUPID,
				vB_Api_UserGroup::SG_MEMBER_SYSGROUPID
			)
		));
		foreach ($usergroups as $usergroup)
		{
			$systemgroups[$usergroup['systemgroupid']] = $usergroup['usergroupid'];
		}

		// fetch active contributors
		$active = $db->assertQuery('vBForum:fetchActiveChannelContributors', array('nodeid' => $nodeId));
		if ($active AND $active->valid())
		{
			foreach($active AS $a)
			{
				switch ($a['systemgroupid'])
				{
					case vB_Api_UserGroup::CHANNEL_OWNER_SYSGROUPID:
					case vB_Api_UserGroup::SG_OWNER_SYSGROUPID:
						$role = 'owner';
						break;
					case vB_Api_UserGroup::CHANNEL_MODERATOR_SYSGROUPID:
					case vB_Api_UserGroup::SG_MODERATOR_SYSGROUPID:
						$role = 'moderator';
						break;
					case vB_Api_UserGroup::CHANNEL_MEMBER_SYSGROUPID:
					case vB_Api_UserGroup::SG_MEMBER_SYSGROUPID:
						$role = 'member';
						break;
					default:
						continue;
				}

				if (!isset($users[$a['userid']]))
				{
					$users[$a['userid']] = vB_User::fetchUserinfo($a['userid'], array('avatar'));
				}

				$result['active'][$role][] = array(
					'usergroupid' => $a['usergroupid'],
					'user' => $users[$a['userid']],
				);
			}

		}

		// fetch pending contributors
		$pending = $db->assertQuery('vBForum:fetchPendingChannelContributors', array('nodeid' => $nodeId));
		if ($pending AND $pending->valid())
		{
			foreach($pending AS $p)
			{
				switch ($p['about'])
				{
					case vB_Api_Node::REQUEST_TAKE_OWNER:
					case vB_Api_Node::REQUEST_SG_TAKE_OWNER:
						$role = 'owner';
						$usergroupid = $systemgroups[vB_Api_UserGroup::CHANNEL_OWNER_SYSGROUPID];
						break;
					case vB_Api_Node::REQUEST_TAKE_MODERATOR:
					case vB_Api_Node::REQUEST_SG_TAKE_MODERATOR:
						$role = 'moderator';
						$usergroupid = $systemgroups[vB_Api_UserGroup::CHANNEL_MODERATOR_SYSGROUPID];
						break;
					default:
						continue;
				}

				if (!isset($users[$p['recipientid']]))
				{
					$users[$p['recipientid']] = vB_User::fetchUserinfo($p['recipientid'], array('avatar'));
				}

				$result['pending'][$role][] = array(
					'usergroupid' => $usergroupid,
					'user' => $users[$p['recipientid']],
				);
			}
		}

		return $result;
	}

	/**
	 *
	 * @param bool $makeCategory
	 * @param int $nodeId
	 * @return bool
	 */
	public function switchForumCategory($makeCategory, $nodeId)
	{
		return $this->library->switchForumCategory($makeCategory, $nodeId);
	}

	public function fetchTopLevelChannelIds()
	{
		$channels = array();
		$channels_res = vB::getDbAssertor()->assertQuery('vBForum:channel', array('guid' => self::$topLevelChannels));
		foreach ($channels_res as $channel)
		{
			$area = array_search($channel['guid'], self::$topLevelChannels);
			$channels[$area] = $channel['nodeid'];
		}
		return $channels;
	}
}
