<?php
/**
* @version	$Id: mailing_list_tp.php 14241 2011-03-16 20:24:35Z alex $
* @package	In-Portal
* @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 MailingListTagProcessor extends kDBTagProcessor {

		function PrintRecipients($params)
		{
			$object =& $this->getObject($params);
			/* @var $object kDBItem */

			$recipients = explode(';', $object->GetDBField('To'));

			// 1. group recipients by types
			$recipients_grouped = Array ();
			foreach ($recipients as $recipient) {
				if (strpos($recipient, '_') !== false) {
					list ($recipient_type, $recipient_id) = explode('_', $recipient);
				}
				else {
					$recipient_type = 'direct';
					$recipient_id = $recipient;
				}

				if (!array_key_exists($recipient_type, $recipients_grouped)) {
					$recipients_grouped[$recipient_type] = Array ();
				}

				$recipients_grouped[$recipient_type][] = $recipient_id;
			}

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

			// for each group convert ids to names
			$recpient_names = Array ();
			foreach ($recipients_grouped as $recipient_type => $group_recipients) {
				$recpient_names = array_merge($recpient_names, $mailing_list_helper->getRecipientNames($recipient_type, $group_recipients));
			}

			$ret = '';
			$recipient_count = count($recpient_names);
			$block_params = $this->prepareTagParams($params);
			$block_params['name'] = $params['render_as'];

			foreach ($recpient_names as $recipient_index => $recipient_name) {
				$block_params['recipient_name'] = $recipient_name;
				$block_params['not_last'] = $recipient_index < $recipient_count - 1;

				$ret .= $this->Application->ParseBlock($block_params);
			}

			return $ret;
		}

		function IsManualRecipient($params)
		{
			$external_call = $this->Application->GetVar('mailing_recipient_type');

			if ($external_call) {
				return false;
			}

			$object =& $this->getObject($params);
			/* @var $object kDBItem */

			return $object->IsNewItem();
		}
	}