<?php
if (!isset($GLOBALS['vbulletin']->db))
{
	exit;
}

/**
* Class for displaying a vBulletin PM Attachment
*/
class vB_Attachment_Display_Single_vBForum_PrivateMessage extends vB_Attachment_Display_Single
{
	/**
	* Verify permissions of a single attachment
	*
	* @return	bool
	*/
	public function verify_attachment()
	{
		$selectsql = array(
			"pmtext.pmtextid",
			"pmtext.fromuserid AS userid",
		);

		$joinsql = array(
			"LEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pmtext.pmtextid = a.contentid)",
		);

		// This function sets $this->attachmentinfo with additional info as defined above
		if (!$this->verify_attachment_specific('vBForum_PrivateMessage', $selectsql, $joinsql))
		{
			return false;
		}

		if ($canviewcontent = ($this->registry->userinfo['userid'] == $this->attachmentinfo['userid']))
		{
			// We wrote the PM, of course we can view it
			return true;
		}

		if (!isset($this->attachmentinfo['pmtextid']) OR !$this->attachmentinfo['pmtextid'])
		{
			// This is a PM in progress
			return true;
		}

		// It's possible there's multiple recipients, and this is safer than checking touserarray in the pmtext table
		$pmusers = $this->registry->db->query_read_slave("
			SELECT userid
			FROM " . TABLE_PREFIX . "pm
			WHERE pmtextid = " . $this->attachmentinfo['pmtextid']
		);
		while ($pmuser = $this->registry->db->fetch_array($pmusers))
		{
			if ($pmuser['userid'] == $this->registry->userinfo['userid'])
			{
				// For performance reasons, we don't return true here 
				// 	since we want to free_result and unset
				$canviewcontent = true;
			}
		}
		unset($pmuser);
		$this->registry->db->free_result($pmusers);
		
		if (!$canviewcontent)
		{
			// Epic fail
			return false;
		}

		return true;
	}
}

/**
* Class for display of multiple vBulletin PM attachments
*
* @package 		vBulletin
* @version		$Revision: 29983 $
* @date 		$Date: 2009-03-20 16:22:30 -0700 (Fri, 20 Mar 2009) $
*
*/
class vB_Attachment_Display_Multiple_vBForum_PrivateMessage extends vB_Attachment_Display_Multiple
{
	/**
	* Constructor
	*
	* @param	vB_Registry
	* @param	integer			Unique id of this contenttype (forum post, blog entry, etc)
	*
	* @return	void
	*/
	public function __construct(&$registry, $contenttypeid)
	{
		parent::__construct($registry);
		$this->contenttypeid = $contenttypeid;

		if (
			!$this->registry->options['dbtech_vbsuper_pm_system_enabled'] OR
			!$this->registry->options['dbtech_vbsuper_pm_pmattach_enabled']
		)
		{
			$this->usable = false;
		}
	}

	/**
	* Return content specific information that relates to the ownership of attachments
	*
	* @param	array		List of attachmentids to query
	*
	* @return	void
	*/
	public function fetch_sql($attachmentids)
	{
		$selectsql = array(
			"pmtext.title, pmtext.pmtextid, IF(pmtext.fromuserid = {$this->registry->userinfo['userid']}, 1, 0) AS is_owner",
			"user.username",
		);

		$joinsql = array(
			"LEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pmtext.pmtextid = a.contentid)",
			"LEFT JOIN " . TABLE_PREFIX . "user AS user ON (a.userid = user.userid)",
		);

		return $this->fetch_sql_specific($attachmentids, $selectsql, $joinsql);
	}

	/**
	* Fetches the SQL to be queried as part of a UNION ALL of an attachment query, verifying read permissions
	*
	* @param	string	SQL WHERE criteria
	* @param	string	Contents of the SELECT portion of the main query
	*
	* @return	string
	*/
	protected function fetch_sql_ids($criteria, $selectfields)
	{	
		$joinsql = array(
			"INNER JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pmtext.pmtextid = a.contentid)",
			"LEFT JOIN " . TABLE_PREFIX . "user AS user ON (a.userid = user.userid)",
		);
	
		return $this->fetch_sql_ids_specific($this->contenttypeid, $criteria, $selectfields, $subwheresql, $joinsql);
	}

	/**
	* Formats $groupinfo content for display. The SQL fields in $groupinfo are set in fetch_sql() above
	*
	* @param	array		Entry information
	*
	* @return	array
	*/
	public function process_attachment_template($groupinfo, $showthumbs = false)
	{
		global $show, $vbphrase;

		$show['thumbnail'] = ($groupinfo['hasthumbnail'] == 1 AND $showthumbs);
		$show['inprogress'] = $groupinfo['inprogress'];

		$show['canmoderate'] = false;
		$show['candelete'] = false;
		if (
			$this->registry->options['dbtech_vbsuper_pm_pmattach_enabled']
				AND
			(
				$groupinfo['inprogress']
					OR
				$this->registry->userinfo['userid'] == $groupinfo['userid']
			)
		)
		{
			$show['candelete'] = true;
		}

		return array(
			'template' => 'group',
			'group'    => $groupinfo,
		);
	}

	/**
	* Return PM specific url to the owner an attachment
	*
	* @param	array		Content information
	*
	* @return	string
	*/
	protected function fetch_content_url_instance($contentinfo)
	{
		return "private.php?" . $this->registry->session->vars['sessionurl'] . 'pmid=' . $contentinfo['contentid'];
	}
}

// #######################################################################
// ############################# STORAGE #################################
// #######################################################################

/**
* Class for storing a vBulletin PM attachment
*
* @package 		vBulletin
* @version		$Revision: 29983 $
* @date 		$Date: 2009-03-20 16:22:30 -0700 (Fri, 20 Mar 2009) $
*
*/
class vB_Attachment_Store_vBForum_PrivateMessage extends vB_Attachment_Store
{
	/**
	*	Groupinfo
	*
	* @var	array
	*/
	protected $groupinfo = array();

	/**
	*	Override the vboption for thumbnails
	*
	* @var	boolean
	*/
	public $forcethumbnail = true;

	/**
	* Given an attachmentid, retrieve values that verify_permissions needs
	*
	* @param	int	Attachmentid
	*
	* @return	array
	*/
	public function fetch_associated_contentinfo($attachmentid)
	{
		return $this->registry->db->query_first("
			SELECT
				pmtext.pmtextid
			FROM " . TABLE_PREFIX . "attachment AS a
			INNER JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pmtext.pmtextid = a.contentid)
			WHERE
				a.attachmentid = " . intval($attachmentid) . "
		");
	}

	/**
	* Verifies permissions to attach content to PMs
	*
	* @param	array	Contenttype information - bypass reading environment settings
	*
	* @return	boolean
	*/
	public function verify_permissions($info = array())
	{
		global $show;

		if ($info['pmtextid'])
		{
			$this->values['pmtextid'] = $info['pmtextid'];
		}
		else
		{
			$this->values['pmtextid'] = intval($this->values['pmtextid']);
		}
		
		if (
			!$this->registry->options['dbtech_vbsuper_pm_system_enabled'] OR
			!$this->registry->options['dbtech_vbsuper_pm_pmattach_enabled']
		)
		{
			return false;
		}

		return true;
	}

	/**
	* Verify amount of attachments has not exceed maximum number based on permissions for albums
	*
	* @param	array		Attachment information
	*
	* @return	bool	true if we are under the limit
	*/
	protected function verify_max_attachments($attachment)
	{
		return true;
	}
}

/**
* Class for deleting a vBulletin group attachment
*
* @package 		vBulletin
* @version		$Revision: 29983 $
* @date 		$Date: 2009-03-20 16:22:30 -0700 (Fri, 20 Mar 2009) $
*
*/
class vB_Attachment_Dm_vBForum_PrivateMessage extends vB_Attachment_Dm
{
	/**
	* pre_approve function - extend if the contenttype needs to do anything
	*
	* @param	array		list of moderated attachment ids to approve
	* @param	boolean	verify permission to approve
	*
	* @return	boolean
	*/
	public function pre_approve($list, $checkperms = true)
	{
		@ignore_user_abort(true);

		// init lists
		$this->lists = array(
			'textlist'   => array(),
		);

		if ($checkperms)
		{
			// Verify that we have permission to view these attachmentids
			$attachmultiple = new vB_Attachment_Display_Multiple($this->registry);
			$attachments = $attachmultiple->fetch_results("a.attachmentid IN (" . implode(", ", $list) . ")");

			if (count($list) != count($attachments))
			{
				return false;
			}
		}
		$ids = $this->registry->db->query_read("
			SELECT
				a.attachmentid, a.userid, IF(a.contentid = 0, 1, 0) AS inprogress, a.caption,
				pmtext.title, pmtext.pmtextid, IF(pmtext.fromuserid = {$this->registry->userinfo['userid']}, 1, 0) AS is_owner,
				user.username
			FROM " . TABLE_PREFIX . "attachment AS a
			LEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (a.contentid = pmtext.pmtextid)
			LEFT JOIN " . TABLE_PREFIX . "user AS user ON (a.userid = user.userid)
			WHERE
				a.attachmentid IN (" . implode(", ", $list) . ")
		");
		while ($id = $this->registry->db->fetch_array($ids))
		{
			if ($checkperms AND !$id['is_owner'])
			{
				return false;
			}

			if ($id['pmtextid'])
			{
				$this->lists['textlist']["{$id['pmtextid']}"]["{$id['attachmentid']}"] = 1;
			}
		}
		return true;
	}
}

class vB_Attachment_Upload_Displaybit_vBForum_PrivateMessage extends vB_Attachment_Upload_Displaybit
{
	/**
	*	Parses the appropiate template for contenttype that is to be updated on the calling window during an upload
	*
	* @param	array	Attachment information
	* @param	array	Values array pertaining to contenttype
	* @param	boolean	Disable template comments
	* @return	string
	*/
	public function process_display_template($attach, $values = array(), $disablecomment = true)
	{
		$attach['extension'] = strtolower(file_extension($attach['filename']));
		$attach['filename']  = fetch_censored_text(htmlspecialchars_uni($attach['filename'], false));
		$attach['filesize']  = vb_number_format($attach['filesize'], 1, true);
		$attach['imgpath']   = $this->fetch_imgpath($attach['extension']);

		$templater = vB_Template::create('newpost_attachmentbit');
			$templater->register('attach', $attach);
		return $templater->render($disablecomment);
	}
}

/*======================================================================*\
|| ####################################################################
|| # Downloaded: 19:29, Wed Apr 17th 2013
|| # CVS: $RCSfile$ - $Revision: 29983 $
|| ####################################################################
\*======================================================================*/
?>