<?php
/**
 * Event_handle_main.php - Library to run the template event handles. This can be used anywhere with the proper data.
 * 								It is currently called form Unitmain but it can be called anywhere with $data and $params.
 * 								This library can change the action (from edit to read) inside $params so make sure you reset action after this library.
 * 								Please look at Unitmain how this is done.
 *
 * @author $Author: dtong $
 * @version $Id: Event_handle_main.php,v 1.2 2011/03/24 09:37:16 dtong Exp $
 * @copyright Copyright (c) 2010, Tiller Software Co., Ltd.
*/

Class Event_handle_main {
	public $html_error_msg = '';
	private $CI = NULL;

	function run($data, $params) {
		$this->CI = & get_instance();
		$this->html_error_msg = '';

		//No handle config found so do nothing
		$handle_config = osa_value($data, '_event_handle', FALSE);
		if ( !$handle_config || !is_array($handle_config) || count($handle_config)<1 )
			return TRUE;
		//Single event - '_event_handle'=>array('_handle'=>'user_role', '_owner'=>TRUE)
		//Multi event - '_event_handle'=>array(array('_handle'=>'user_role', '_owner'=>TRUE), array('_handle'=>'dummy', 'param1'=>FALSE))
		//So, we put a single event in a array so the code to handle both is the same
		if ( array_key_exists('_handle', $handle_config) ) {
			$handle_config = array($handle_config);
		}
		$ret = TRUE; $error_flag=FALSE;
		//Always execute all the handles, will return false if anyone returns false
		foreach($handle_config as $one_handle) {
			if ( !($handlename = osa_value($one_handle, '_handle', FALSE))) {
				osa_errorlog(__METHOD__ . " - Template event handle syntax error.", $one_handle);
				$this->html_error_msg = osa_buildererror();
				return FALSE;
			}
			$handlename = "handle_{$handlename}";
			if (!@include_once("{$handlename}.php")) {
				osa_errorlog(__METHOD__ . " - Event handle class file {$handlename} does not exist", $one_handle);
				$this->html_error_msg = osa_buildererror();
				return FALSE;
			}
			//Objects are cached on the first initialization
			$handleobj = $this->CI->cms_cache->object_get($handlename);
			if ( empty($handleobj) ) {
				osa_errorlog(__METHOD__ . " - Event handle class {$handlename} does not exist", $one_handle);
				$this->html_error_msg = osa_buildererror();
				return FALSE;
			}
			if ( !$handleobj->reset($one_handle, $data, $params) ) {
				$this->html_error_msg = osa_buildererror();
				continue;
			}
			if ( !$handleobj->invoke() )
				$ret = FALSE;
			//If error condition happened in object then print error message to browser
			if ( $handleobj->error_flag )
				$error_flag = TRUE;
		} //foreach
		if ( $error_flag )
			$this->html_error_msg = osa_buildererror();
		return $ret;
	}
}