<?php

/**
 * Class file for audit helper used for decoding audit logs.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfAuditHelper Class
 *
 * Class to provide decoding for audit trail logging.
 *
 * @package clearFusionCMS
 */
class cfAuditHelper {

	/**
	 * Convert the raw data to a human readable message.
	 *
	 * @param array $data The audit data.
	 * @return string The message string.
	 */
	function getMessage($data) {
		return sprintf(__('Action performed on object %1d in module %2s.', 'cfBackend'), $data['cid'], $data['module']);
	}

	/**
	 * Print the data as JSON but without the escaped strings to allow for each copy and paste.
	 *
	 * @param array $data The audit record to print the data from.
	 * @return string The formatted output string.
	 */
	function printData($data) {
		if(!empty($data['previous'])) {
			return $this->_printData(json_decode($data['previous'], true));
		}
		else
			return '';
	}

	/**
	 * Print the data as JSON but without the escaped strings to allow for each copy and paste.
	 *
	 * @param array $data The data to print.
	 * @param int $depth The current indentation depth.
	 * @return string The formatted output string.
	 */
	protected function _printData($data, $depth = 0) {
		if(!array($data))
			return '';

		$txt = [];
		foreach($data as $k => $v) {
			$s = str_repeat("\t", $depth + 1) . "\"$k\": ";
			if(is_array($v)) {
				$txt[] = $s . $this->_printData($v, $depth + 1);
			}
			else if(is_bool($v)) {
				$txt[] = $s . ($v ? 'true' : 'false');
			}
			else if(is_numeric($v)) {
				$txt[] = $s . $v;
			}
			else {
				$txt[] = $s . "\"$v\"";
			}
		}

		return "{\n" . implode(",\n", $txt) . "\n" . str_repeat("\t", $depth) . '}';
	}

	/**
	 * Test if the event has additional data i.e. view more is applicable.
	 *
	 * @param array $data The audit log data.
	 * @return bool true if event has additional data; else false.
	 */
	function hasAdditionalData($data) {
		return true;
	}
}
