<?php
/**
* @version	$Id: email_template_helper.php 15608 2012-11-06 17:21:28Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2011 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 kEmailTemplateHelper extends kHelper {

	/**
	 * Extracts Subject, Headers, Body fields from email message translation
	 *
	 * @param string|SimpleXMLElement $text
	 * @param string $message_type
	 * @return Array
	 */
	function parseTemplate($text, $message_type = '')
	{
		$ret = Array ('Subject' => '', 'Headers' => '', 'HtmlBody' => '', 'PlainTextBody' => '');

		if ( $message_type == '' ) {
			// this is v5+ e-mail event text as xml node
			foreach ($ret as $field => $value) {
				$node_name = strtoupper($field);
				$ret[$field] = (string)$text->$node_name;
			}

			return $ret;
		}

		$line_id = 1;
		$headers = Array();
		$lines = explode("\n", $text); // "\n" is lost in process

		foreach ($lines as $line_id => $line) {
			if ( strlen(trim($line)) == 0 || ($line == '.') ) {
				break;
			}

			$parts = explode(':', $line, 2);

			if ( strtolower($parts[0]) == 'subject' ) {
				$ret['Subject'] = trim($parts[1]);
			}
			else {
				$headers[] = $line;
			}
		}

		$ret['Headers'] = $headers ? implode("\n", $headers) : null; // it's null field

		$lines = array_slice($lines, $line_id + 1);

		// add "\n", that was lost before
		$ret[$message_type == 'html' ? 'HtmlBody' : 'PlainTextBody'] = implode("\n", $lines);

		return $ret;
	}

	/**
	 * Parses contents of given object field and sets error, when invalid in-portal tags found
	 * @param kDBItem $object
	 * @param string $field
	 * @return void
	 * @access public
	 */
	public function parseField($object, $field)
	{
		$this->Application->InitParser();

		try {
			$this->Application->Parser->CompileRaw($object->GetField($field), 'email_template');
		}
		catch (Exception $e) {
			if ( $this->Application->isDebugMode() ) {
				$this->Application->Debugger->appendHTML('<b style="color: red;">Error in Email Template:</b> ' . $e->getMessage() . ' (line: ' . $e->getLine() . ')');
			}

			$object->SetError($field, 'parsing_error');
		}
	}
}