<?php

	class EmailMessageHelper extends kHelper {

		/**
		 * Extracts Subject, Headers, Body fields from email message translation
		 *
		 * @param string $text
		 * @return Array
		 */
		function parseTemplate($text)
		{
			$ret = Array ('Subject' => '', 'Headers' => '', 'Body' => '');
			$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'] = implode("\n", $headers);

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

			// add "\n", that was lost before
			$ret['Body'] = implode("\n", $lines);

			return $ret;
		}

		/**
		 * Prepares email event content for language pack export
		 *
		 * @param Array $fields_hash
		 * @return string
		 */
		function buildTemplate($fields_hash)
		{
			if (!implode('', $fields_hash)) {
				return '';
			}

			$ret = array_key_exists('Headers', $fields_hash) ? $fields_hash['Headers'] : '';
			if ($ret) {
				$ret .= "\n";
			}

			$ret = $this->_removeTrailingCRLF($ret);
			$ret .= 'Subject: ' . $fields_hash['Subject'] . "\n\n";
			$ret .= $fields_hash['Body'];

			return $ret;
		}

		/**
		 * Remove trailing CR/LF chars from string
		 *
		 * @param string $string
		 * @return string
		 */
		function _removeTrailingCRLF($string)
		{
			return preg_replace('/(\n|\r)+/',"\\1",$string);
		}
	}