<?php
/**
* @version	$Id: changes_formatter.php 14628 2011-10-04 09:36:30Z 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 kChangesFormatter extends kFormatter {

	/**
	 * Formats value of a given field
	 *
	 * @param string $value
	 * @param string $field_name
	 * @param kDBItem|kDBList $object
	 * @param string $format
	 * @return string
	 */
	function Format($value, $field_name, &$object, $format = null)
	{
		if ( is_null($value) ) {
			return '';
		}

		$changes = unserialize($value);

		$res = '';
		if ( !$changes ) {
			return '';
		}

		foreach ($changes as $field => $data) {
			$fld_translation = $this->Application->Phrase('la_fld_' . $field);

			// remove translation link (added in debug mode)
			$fld_translation = preg_replace('/<a href="(.*?)".*>(.*?)<\/a>/', '\\2', $fld_translation);

			if ( $fld_translation == '!' . strtoupper('la_fld_' . $field) . '!' ) {
				// when phrase is not translated use field name as label
				$fld_translation = $field;
			}

			if ( is_array($data) ) {
				if ( $format == 'auto_cut' ) {
					$data = array_map(Array (&$this, 'cutValue'), $data);
				}

				if ( array_key_exists('old', $data) && array_key_exists('new', $data) ) {
					$res .= "$fld_translation: {$data['old']} => {$data['new']}<br/>\n";
				}
				else {
					$res .= "$fld_translation: {$data['new']}<br/>\n";
				}
			}
			else {
				if ( $format == 'auto_cut' ) {
					$data = $this->cutValue($data);
				}

				$res .= "$fld_translation: {$data}<br/>\n";
			}
		}

		return $res;
	}

	function cutValue($data)
	{
		if ( strlen($data) > 200 ) {
			$data = substr($data, 0, 50) . ' ...';
		}

		return $data;
	}
}