<?php 
/**
 * Manually Developed CI Controller
 *
 *
 * @package			AIR\controllers\Appregistrar
 * @version			V1.2.0
 * @copyright		2015, BizyCorp Internal Systems Development
 * @license			private, All rights reserved
 * @author			MRM Roshan <roshan@ekwa.com>
 * 
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
@session_start();
/**
 * Manually Developed CI Controller
 *
 * This controller facilitates the access of table countries
 *  
 * Usage:-
 *  
 *			function index(), default index funtion to list all AIR entries  
 *			function validate_remote_host(), To validate remote host 
 *			function validate_app(), To validate application
 *			function get_uaacs_feed_by_app_id(), To get uaacs application feed by app id 
 *			function get_calling_app_name(), To get calling app name
 *			function issueToken(), To issue token
 *			function generateToken(), To generate token for issuing
 *			function get_called_app_function_id(), To get called application function id
 * 			function getTimeStamp(), To get time stamp
 * 			function getHostIP(), To get host IP
 * 			function getUserId(), To get user id
 * 			function getRandomString(), To get random string 
 * 			function getAppId(), To get app id
 * 			function verify_token(), To verify given token 
 * 			function verify_user_access(), To verify user access
 *			function verify_permission(), To verify permission
 *			function verify_role(), To verify role
 *			function view_log(), To view log
 *			function get_user_ip(), To get user ip
 *			function get_jason(), To get json
 *			function get_related_links(), To get related AIR links
 *			function createDropdown(), To get dropdown listing with AIR linkagse
 *			function set_called_app_name(), To set caled application name
 *			function get_called_app_name(), To get caled application name
 *
 *
 *
 * @package			AIR\controllers\Appregistrar
 * @version			V1.2.0
 * @copyright		2015, BizyCorp Internal Systems Development
 * @license			private, All rights reserved
 * @author			MRM Roshan
 * @created			July 2014  
 * @uses			
 * @see 
 * @modified		28/04/2016 by MRM Roshan
 * @modification	1.Added set_called_app_name() and get_called_app_name() to identify called app function
 * 					2.Added log entry to identify uses and apps as unkonown if system could not identify them 
 */

class AppRegistrar extends CI_Controller {

	/**
	 * $debug
	 * 
	 * @var boolien
	 */
	public $debug = true;
	/**
	 * $progress
	 *  
	 * @var string
	 */	
	public $progress;
	/**
	 * $calling_app_id
	 * 
	 * @var int
	 */
	private $calling_app_id;
	/**
	 * $calling_app_name
	 * 
	 * @var string
	 */
	private $calling_app_name;
	/**
	 * $called_app_name
	 *
	 * @var string
	 */
	private $called_app_name;
	/**
	 * $calling_app_user_id
	 * 
	 * @var int
	 */
	private $calling_app_user_id;
	/**
	 * $called_app_role_id
	 * 
	 * @var int
	 */
	private $called_app_role_id;
	/**
	 * $calling_app_access_key
	 * 
	 * @var string
	 */
	private $calling_app_access_key;
	/**
	 * $calling_app_security_key
	 * 
	 * @var string
	 */
	private $calling_app_security_key;
	/**
	 * $calling_app_host
	 * 
	 * @var string
	 */
	private $calling_app_host;
	/**
	 * $calling_app_func_id
	 * 
	 * @var int
	 */
	private $calling_app_func_id;
	/**
	 * $integration_id
	 * 
	 * @var int
	 */
	private $integration_id;
	/**
	 * $called_app_id
	 * 
	 * @var int
	 */
	private $called_app_id;
	/**
	 * $called_app_access_key
	 * 
	 * @var string
	 */
	private $called_app_access_key;
	/**
	 * $called_app_security_key
	 * 
	 * @var string
	 */
	private $called_app_security_key;
	/**
	 * $appIntRegResult
	 * 
	 * @var object
	 */
	private $appIntRegResult;
	/**
	 * $url
	 * 
	 * @var string
	 */
	private $url;
	/**
	 * $jason_data
	 * 
	 * @var string
	 */
	private $jason_data;
	/**
	 * $tr_host
	 * 
	 * @var string
	 */
	private $tr_host;
	/**
	 * $log_obj
	 * 
	 * @var object
	 */
	private $log_obj;
	
	/**
	 * __construct()
	 * 
	 * This is where all models and library files are loaded
	 * 
	 * Constructor function
	 * 
	 */
	function __construct(){
		
		parent::__construct();
		$this->load->library('Uaacs_authentication');
		$this->load->model('Applications_model');		
		$this->load->model('Tokens_model');
		$this->load->model('AppIntegrator_model');
		@session_start();
		$_SESSION['auth'] = null;
		
		///init log objects
		$this->log_obj = new log_object();
		//access log file path
		$this->log_obj->set_path('./application/logs/access');
				
	}//end of function
	
	/**
	 * validate_remote_host($debug)
	 * 
	 * This function checks validity of remote host when a token is request or token verification call is made
	 * 
	 * @param string $debug
	 * @return boolean
	 */
	private function validate_remote_host($debug = false){
		
		if($debug)$this->progress .="<br>AappRegistrar/validate_remote_host() invoked";		
		if($this->debug) log_message('info',"<b>validate_remote_host() invoked:</b>");
		$request_app_ip = $this->get_user_ip();
		if($this->debug) log_message('info',"<b>validate_remote_host() calling-app-ip:$request_app_ip</b>");
		$this->calling_app_host = $request_app_ip;
		if($this->debug) log_message('info',"<b>appregistrar/validate_remote_host() this->calling-app_host:".$this->calling_app_host."</b>");
				
		$valid_hosts = array('127.0.0.1','103.247.48.51');	/// these ips should have ade//'localhost','bizydads.com','www.bizydads.com','ekwa.com','www.ekwa.com',	
		$is_valid = (in_array($request_app_ip, $valid_hosts))?true:false;		
		if($this->debug) log_message('info',"<b>validate_remote_host() host ip: $request_app_ip, isvalid: $is_valid</b>");				
		if($debug)$this->progress .="<br>AappRegistrar/validate_remote_host(): host ip: $request_app_ip, isvalid: $is_valid";
		//return $is_valid;
		return true;
	}
	
	/**
	 * validate_app($app_id,$app_type,$debug){
	 * 
	 * This function checks for validity of calling or called applications when a token request or token verification call is made
	 * 
	 * @param int $app_id
	 * @param string $app_type - 'called_app' or 'calling_app' 
	 * @param boolean $debug
	 * @return boolean
	 */
	private function validate_app($app_id,$app_type,$debug = false){
	
		if($debug) log_message('debug',"validate_app()function invoked.App_id:$app_id,App_type:$app_type");
		if($debug)$this->progress .="<br>AappRegistrar/validate_app invoked";
		if($debug)$this->progress .="<br>AappRegistrar/validate_app() vars:app_id:$app_id,app_type:$app_type,";
		
		switch ($app_type){
			
			case 'called_app':
				$key = array('called_app_id' => $app_id);
				$is_exists = $this->Applications_model->exists($key);				
				if($debug) log_message('info',"vallidate_app():called_app:is_exists:$is_exists");
				if($is_exists){
					$app_data = $this->Applications_model->get_app_data(array('called_app_id' => $app_id));
					$this->called_app_security_key = $app_data[0]['called_app_secret_key'];
					$this->called_app_access_key = $app_data[0]['called_app_access_key'];
					$return = true;
				}else{
					$return = false;
				}
				break;
			case 'calling_app':
				$key = array('calling_app_id' => $app_id);
				$is_exists = $this->Applications_model->exists($key);
				if($debug) log_message('info',"vallidate_app():calling_app:is_exists:$is_exists");
				if($is_exists){
					$app_data = $this->Applications_model->get_app_data(array('calling_app_id' => $app_id));
					$this->calling_app_security_key = $app_data[0]['calling_app_secret_key'];
					$this->calling_app_access_key = $app_data[0]['calling_app_access_key'];
					$return = true;
				}else{
					$return = false;
				}				
				break;
		}//end switch
		if($debug)$this->progress .="<br>AappRegistrar/validate_app() return value:$return";
		return $return;
		
	}//end of function
	
	/**
	 * get_uaacs_feed_by_app_id($called_app_id,$app_type,$debug)
	 * 
	 * This function gets UAACS feed for a given app id from UAACS and return for further check ups 	
	 * 
	 * @param int $app_id
	 * @param string $app_type - 'calling_app' or 'called_app'
	 * @param boolien $debug
	 */
	public function get_uaacs_feed_by_app_id($app_id,$app_type,$debug = false){
			
		if($this->debug) log_message('debug',"appregistrar/uaacs_get_feed_data_by_called_app_id() invoked:");
		if($debug)$this->progress .="<br>AappRegistrar/get_uaacs_feed_by_app_id() invoked for $app_type";
		
		$url = UAACS_URL.'/API/APPAPI/index.php/main/app/t/'.$app_id.'/1/1/';
		if($debug)$this->progress .="<br>AappRegistrar/get_uaacs_feed_by_app_id() url:$url";
		$feedData =  get_contents_with_session($url);		
		$simpleXml = new SimpleXMLElement($feedData);
		
		if($app_type == 'calling_app'){
			$this->set_calling_app_name($simpleXml);
		}else{
			$this->set_called_app_name($simpleXml);
		}
		
		if($this->debug) log_message('debug',"appregistrar/uaacs_get_feed_data(),app_id:$app_id,app_type:$app_type,feedData :".$simpleXml);
							
		return $simpleXml;
		
	}//end of function
	
	
	/**
	 * set_calling_app_name($app_feed)
	 * 
	 * This function sets calling app name property after xpathing UAACS xml feed  
	 * 
	 * @param object $app_feed - UAACS feed
	 * @param int $app_id - application id
	 */
	private function set_calling_app_name($app_feed,$app_id=null){
		
		if(!empty($app_feed)){
			$this->calling_app_name = (string) $app_feed->xpath("//application/metadata/name")[0];
		}else{	
			$url = UAACS_URL.'/API/APPAPI/index.php/main/app/t/'.$app_id.'/1/1/';			
			$feedData =  get_contents_with_session($url);
			$simpleXml = new SimpleXMLElement($feedData);					
			$this->calling_app_name = (string) $simpleXml->xpath("//application/metadata/name")[0];		
		}	
		
	}

	/**
	 * get_calling_app_name()
	 *
	 * This function gets calling app name from calling app name property
	 *
	 * return string calling app name
	 */
	public function get_calling_app_name(){
		return $this->calling_app_name;
	}
	
	
	/**
	 * set_called_app_name($app_feed)
	 *
	 * This function sets called app name property after xpathing UAACS xml feed
	 *
	 * @param object $app_feed - UAACS feed
	 */
	private function set_called_app_name($app_feed){
		
		//if(!empty($app_feed->xpath("//application/metadata/name")[0])){
			$this->called_app_name = (string) $app_feed->xpath("//application/metadata/name")[0];
		//}else{
			//$this->called_app_name = 'Unknown called application';
		//}
	}
	
	/**
	 * get_called_app_name()
	 *
	 * This function gets called app name from calling app name property
	 *
	 * return string calling app name
	 */
	public function get_called_app_name(){
		return $this->called_app_name;
	}
	

	
	/**
	 * get_user_role_function_data($uaacs_feed,$calling_app_user_id,$debug){
	 * 
	 * This function processes UAACS feed object and returns user role/assigned function array on success. Otherwise return fals
	 * 
	 * @param object $uaacs_feed
	 * @param int $calling_app_user_id
	 * @param boolean $debug
	 * @return array|boolean 
	 */
	public function get_user_role_function_data($uaacs_feed,$calling_app_user_id,$debug = false){

		if($this->debug) log_message('debug',"appregistrar/get_user_role_function_data() invoked:");
		if($debug)$this->progress .="<br>AappRegistrar/get_user_role_function_data() invoked";
		
		$user = (array)$uaacs_feed->xpath("//users/user[@staff_id=$calling_app_user_id]");
		if($debug)$this->progress .="<br>AappRegistrar/get_user_role_function_data() user var:<pre>".print_r($user,true).'</pre>';
		
		$role_id_array = array();
		$role_function_array = array();
		
		if(!empty($user)){			

			//first get role ids
			$assigned_roles =(array) $uaacs_feed->xpath("//users/user[@staff_id=$calling_app_user_id]/assignedRoles/assignedRole");
			foreach($assigned_roles as $ar){			
				$ar = (array)$ar;
				$assigned_role_id = (int)$ar['@attributes']['assignedRoleId'];
				$role_id_array[] = $assigned_role_id;				
			}			
			
			//get function ids
			$function_ids =(array) $uaacs_feed->xpath("//users/user[@staff_id=$calling_app_user_id]/assignedRoles");
			$function_ids = (array)$function_ids;						
			$fnIds = (array)$function_ids[0]->assignedRole;
			$function_id_array = array();
			
			foreach($fnIds as $a=>$b){
				
				$func_ids = (!is_array($b))? $b:null;
				if(!empty($func_ids))	$function_id_array[] = $func_ids;
			}
					
			foreach($role_id_array as $ri){
				$i = 0;
				$role_function_array[$ri] = $function_id_array[$i];
				$i++;
			}
			
			if($this->debug) log_message('debug',"appregistrar/get_user_role_function_data(),role_function_array:".print_r($role_function_array,true));
			if($debug)$this->progress .="<br>AappRegistrar/get_user_role_function_data() role_function_array:<pre>".print_r($role_function_array,true).'</pre>';
			return $role_function_array;
				
		}else{
			
			return false;
		}
				
	}//end of function
	
	/**
	 issueToken($integration_id,$calling_app_id = 0,$called_app_id = 0,$calling_app_user_id = 0,$calling_app_func_id = 0,$debug = false)
	 * 
	 * This function accepts above parameters then verify url call and given values.
	 * It first performs remote host ip address then performs application id check
	 * Based on given values this function then obtains uaacs data feed from UAACS application then 
	 * store it in local database.Then proceed to generate token process.After obtaining the token 
	 * then outputs an xml feed.
	 * 
	 * @updated : Added codes to identify users and applications. If could not do so then to add log as unkonwn user and unkonwn application
	 * 			  MRMR 
	 * @update on: 28/04/2016	
	 * 
	 * ex: http://localhost/app_registrar/index.php/AppRegistrar/issueToken/109/91/239/241
	 * 
	 * @param int $integration_id 
	 * @param int $calling_app_id
	 * @param int $called_app_id
	 * @param int $calling_app_user_id
	 * @param int $calling_app_func_id
	 * @param boolean $debug
	 * @access public 
	 * @since 
	 * @modified           Jun 17, 2016 by Roshan Ruzaik <mrmroshan@yahoo.com>
	 * @modification        Fixed bug id 21885,21446
	 * @return token
	 */
	public function issueToken($integration_id,$calling_app_id = 0,$called_app_id = 0,$calling_app_user_id = 0,$calling_app_func_id = 0,$debug = false){
		
				
		//if($this->debug) log_message('debug',"appregistrar/issueToken()invoked:");
		if($debug)$this->progress .="<br>AappRegistrar/issueToken() invoked";
		
			$this->calling_app_id = $calling_app_id;
			$this->called_app_id = $called_app_id;
			$this->calling_app_user_id = $calling_app_user_id;
			$this->calling_app_func_id = $calling_app_func_id;
			$this->integration_id = $integration_id;
				
			//(!empty($this->calling_app_user_id) || $this->calling_app_user_id != 0)?
			
			if($debug)$this->progress .="<br>AappRegistrar/issueToken()/received parameters:
			integration id:$integration_id,
			calling_app_id:$calling_app_id,
			called_app_id:$called_app_id,
			calling_app_user_id:$calling_app_user_id,
			calling_app_function_id:$calling_app_func_id";
			
			
			//get staff listing for log purposes
			staff_object();
			$xmlObj = simplexml_load_string($_SESSION['staff_xml']);
			$staff = $xmlObj->xpath('//row [@id="'.$this->calling_app_user_id.'"]');
			$staffName =  (!empty($staff[0]->cell[1]))?$staff[0]->cell[1]:'Unknown User';
			$calling_app_name = $this->get_calling_app_name();
			if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';	
			
			$data = array();
			
			if($this->validate_remote_host()){
				
				//if($this->validate_calling_app($calling_app_id,$debug) && $this->validate_called_app($called_app_id,$debug)){
					if($this->validate_app($calling_app_id,'calling_app',$debug) ){
						
						if($this->validate_app($called_app_id,'called_app',$debug)){

							//check user has access permission for called app before issue a token
							$user_access_permission = $this->verify_user_access($calling_app_user_id,$called_app_id,'Called app',$debug);
							
							if($user_access_permission == 1){
							
							//obtain app Inte reg info from db									
							$this->appIntRegResult = $this->AppIntegrator_model->get_app_data(
									$this->integration_id,
									$this->calling_app_id,
									$this->called_app_id,
									$this->calling_app_func_id);
									
							if($debug)$this->progress .="<br>AappRegistrar/issue_Token() appIntRegResult var value:".(int)$this->appIntRegResult;
					
					
							//var_dump($this->appIntRegResult);exit;
							
							if(!empty($this->appIntRegResult)){

								$calling_app_uaacs_feed = $this->get_uaacs_feed_by_app_id($calling_app_id,'calling_app',$debug);
								$called_app_uaacs_feed = $this->get_uaacs_feed_by_app_id($called_app_id,'called_app',$debug);
								
								$user_role_function_data = $this->get_user_role_function_data($called_app_uaacs_feed,$calling_app_user_id,$debug);
								$user_role_function_data_json = json_encode($user_role_function_data);
									
								
								if($this->debug) log_message('debug',"<b>appregistrar/issueToken(),user_role_function_data_json value:</b>".print_r($user_role_function_data_json,true));
								if($debug)$this->progress .="<br>AappRegistrar/issue_Token() user_role_function_data_json value:</b>".print_r($user_role_function_data_json,true);
								
									
								if(!empty($user_role_function_data_json) && $user_role_function_data_json != false){
										
										$token = $this->generateToken($debug);
										$called_function_url_array = $this->prepare_called_app_url($debug);
										
										$save_data = array(
												'token' => $token,
												'uaacs_data' => $user_role_function_data_json,
												'calling_app_id' => $this->calling_app_id,
												'called_app_id' => $this->called_app_id,
												'calling_app_user_id' => $this->calling_app_user_id,
												'calling_app_host' => $this->calling_app_host,
												'date_time' => date("Y-m-d h:i:s"),
												'calling_app_func_id' => $this->calling_app_func_id
										);
										if($this->debug) log_message('debug',"<b>appregistrar/issueToken(),save_data values:".print_r($save_data,true)."</b>");
										
										if(!$this->Tokens_model->exists(array('token' =>$token))){
											$result = $this->Tokens_model->save_token_data($save_data);
											if($this->debug) log_message('info',"<b>appregistrar/issueToken(),token data saved:</b>");
										}
										$data['login'] = "SUCCESS";
										$data['token'] = "$token";
										$data['function_url'] = $called_function_url_array['url'];
										$data['function_url_method'] = $called_function_url_array['method'];
										$data['function_url_parameters'] = $called_function_url_array['parameters'];
										$data['function_url_qstrings'] = $called_function_url_array['qstrings'];
										$data['function_url_user_defined'] = $called_function_url_array['user_defined_qstrings'];
										$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
											
										
										//============== Access log============================================
									
										$calling_app_name = $this->get_calling_app_name();
										$this->log_obj->set_userDetails($staffName,' calling app user');
										$this->log_obj->set_otherDetails(
												array(
														'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:SUCCESS',
														'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
														login => SUCCESS <br>".
														" - token => ".$token .
														"<br> - function_url => " . $called_function_url_array['url'] .
														"<br> - function_url_method => " . $called_function_url_array['method'] .
														"<br> - function_url_parameters=>" .serialize($called_function_url_array['parameters']) .
														"<br> - function_url_qstrings =>" . serialize($called_function_url_array['qstrings']) .
														"<br> - function_url_user_defined =>" . $called_function_url_array['user_defined_qstrings']
												));
										$this->log_obj->init();
										//======================================================================
											
										$this->load->view('token_request_response',$data);							
								
								}else{
								
									$data['login'] = "FAIL";
									$data['code'] = "515";
									$data['msg'] = 'Error: UAACS data feed error!';
									$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
									
									//============== Access log============================================
									$calling_app_name = $this->get_calling_app_name();
									if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
									$this->log_obj->set_userDetails($staffName,' calling app user');									
									$this->log_obj->set_otherDetails(
											array(
										'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
										'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br> 
										login => FAIL <br>".
										"- Error Msg".$data['msg'].
										"<br>Received parameters:
										- integration id:$integration_id<br>
										- calling_app_id:$calling_app_id<br>
										- called_app_id:$called_app_id<br>
										- calling_app_user_id:$calling_app_user_id<br>
										- calling_app_function_id:$calling_app_func_id<br>"													
												));
									$this->log_obj->init();
									//======================================================================
									
									$this->load->view('token_request_response',$data);
								}//end if
								
							}else{
								
								$data['login'] = "FAIL";
								$data['code'] = "514";
								$data['msg'] = 'Error: AIR could not fetch details of given calling_app_id,called_app_id and calling_app_func_id!';
								$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
								
								//============== Access log============================================
								
								$this->set_calling_app_name(null,$calling_app_id);
								$calling_app_name = $this->get_calling_app_name();	
								if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
								if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
								$this->log_obj->set_userDetails($staffName,' calling app user');
								$this->log_obj->set_otherDetails(
										array(
										'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
										'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
										login => FAIL <br>".
										"- Error Msg".$data['msg'].
										"<br>Received parameters:
										- integration id:$integration_id<br>
										- calling_app_id:$calling_app_id<br>
										- called_app_id:$called_app_id<br>
										- calling_app_user_id:$calling_app_user_id<br>
										- calling_app_function_id:$calling_app_func_id<br>"													
												));
								$this->log_obj->init();
								//======================================================================
								
								$this->load->view('token_request_response',$data);
							}//end if					
							
							
							}else{
									
								$data['login'] = "FAIL";
								$data['code'] = "513";
								$data['msg'] = 'Error: You do not have access rights to called application!';
								$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
									
								//============== Access log============================================
								$this->set_calling_app_name(null,$calling_app_id);
								$calling_app_name = $this->get_calling_app_name();
								if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
								if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
								$this->log_obj->set_userDetails($staffName,' calling app user');
								$this->log_obj->set_otherDetails(
										array(
												'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
												'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
												login => FAIL <br>".
												"- Error Msg".$data['msg'].
												"<br>Received parameters:
												- integration id:$integration_id<br>
												- calling_app_id:$calling_app_id<br>
												- called_app_id:$called_app_id<br>
												- calling_app_user_id:$calling_app_user_id<br>
												- calling_app_function_id:$calling_app_func_id<br>"
										));
								$this->log_obj->init();
								//======================================================================
									
								$this->load->view('token_request_response',$data);
									
							}//end if permission
							
							
					}else{
							
						$data['login'] = "FAIL";
						$data['code'] = "512";
						$data['msg'] = 'Error: Unauthorized Called Application Call!';
						$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
						
						//============== Access log============================================
						$this->set_calling_app_name(null,$calling_app_id);
						$calling_app_name = $this->get_calling_app_name();
						if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
						$this->log_obj->set_userDetails($staffName,' calling app user');
						$this->log_obj->set_otherDetails(
								array(
										'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
										'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
										login => FAIL <br>".
										"- Error Msg".$data['msg'].
										"<br>Received parameters:
										- integration id:$integration_id<br>
										- calling_app_id:$calling_app_id<br>
										- called_app_id:$called_app_id<br>
										- calling_app_user_id:$calling_app_user_id<br>
										- calling_app_function_id:$calling_app_func_id<br>"													
									));
						$this->log_obj->init();
						//======================================================================
						
						$this->load->view('token_request_response',$data);							
							
					}//end if validate called application app
					
				}else {
					
					$data['login'] = "FAIL";
					$data['code'] = "511";
					$data['msg'] = 'Error: Unauthorized Calling Application Call!';
					$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
					
					//============== Access log============================================
					$this->set_calling_app_name(null,$calling_app_id);
					$calling_app_name = $this->get_calling_app_name();
					if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
					$this->log_obj->set_userDetails($staffName,' calling app user');
					$this->log_obj->set_otherDetails(
							array(
									'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
									'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
									login => FAIL <br>".
										"- Error Msg".$data['msg'].
										"<br>Received parameters:
										- integration id:$integration_id<br>
										- calling_app_id:$calling_app_id<br>
										- called_app_id:$called_app_id<br>
										- calling_app_user_id:$calling_app_user_id<br>
										- calling_app_function_id:$calling_app_func_id<br>"													
									));
					$this->log_obj->init();
					//======================================================================
					
					$this->load->view('token_request_response',$data);					
					
				}//end if validate calling application
				
			}else{

				$data['login'] = "FAIL";
				$data['code'] = "510";
				$data['msg'] = 'Error: Unauthorized Server Access!';
				$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
				
				//============== Access log============================================
				$this->set_calling_app_name(null,$calling_app_id);
				$calling_app_name = $this->get_calling_app_name();
				if(empty($calling_app_name)) $calling_app_name = 'Unknown calling application';
				$this->log_obj->set_userDetails($staffName,' calling app user');
				$this->log_obj->set_otherDetails(
						array(
								'Mode'=>'issue_token() is called by '.$calling_app_name .' and token response:FAIL',
								'Data'=> "received parameters:<br>
														- integration id:$integration_id<br>
														- calling_app_id:$calling_app_id<br>
														- called_app_id:$called_app_id<br>
														- calling_app_user_id:$calling_app_user_id<br>
														- calling_app_function_id:$calling_app_func_id<br>
								login => FAIL <br>".
										"- Error Msg".$data['msg'].
										"<br>Received parameters:
										- integration id:$integration_id<br>
										- calling_app_id:$calling_app_id<br>
										- called_app_id:$called_app_id<br>
										- calling_app_user_id:$calling_app_user_id<br>
										- calling_app_function_id:$calling_app_func_id<br>"													
						));
				$this->log_obj->init();
				//======================================================================
				
				$this->load->view('token_request_response',$data);
				
			}//end if validate host			
			
	}//end of function
	
	
	
	/**
	 * generateToken()
	 * 
	 * This function generats token as per request. The token consists of following values 
	 * $token = "$calling_app_id-$called_app_id-$hostIp-$userId-$called_app_function_id-$timeStamp"	 * 
	 * This then be encripted and sent out
	 *  
	 * @param boolion $debug - true / false
	 * @return string $enctoken 
	 */
	private function generateToken($debug = false){
		
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() invoked";
		
		$timeStamp = $this->getTimeStamp();
		if($debug) log_message('debug',"appregistrar/generateToken(),timeStamp:".$timeStamp);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() timeStamp:$timeStamp";
		
		$userId = $this->getUserId();
		if($debug) log_message('debug',"appregistrar/generateToken(),userId:".$userId);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() userId:$userId";
		
		$hostIp = $this->getHostIP();
		if($debug) log_message('debug',"appregistrar/generateToken(),hostIp:".$hostIp);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() hostIp:$hostIp";
		
		$randomString = $this->getRandomString();
		if($debug) log_message('debug',"appregistrar/generateToken(),randomString:".$randomString);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken()randomString:$randomString";
		
		$calling_app_id = $this->calling_app_id;
		$called_app_id = $this->called_app_id;
		$called_app_function_id = $this->get_called_app_function_id();
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() called_app_function_id:$called_app_function_id";
		
		$token = "$calling_app_id-$called_app_id-$hostIp-$userId-$called_app_function_id-$timeStamp";//-$randomString
		//var_dump($token);exit;		
		if($debug) log_message('debug',"appregistrar/generateToken(),unencripted token:".$token);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() unencripted token:$token";
		
		$enc_token = base64_encode($token);
		if($debug) log_message('debug',"appregistrar/generateToken(),enc_token:".$enc_token);
		if($debug)$this->progress .="<br>AappRegistrar/generateToken() encripted token:$enc_token";
		return $enc_token;
				
	}//end of function
	
	/**
	 * prepare_called_app_url($debug=false)
	 *
	 * This function prepares called app url which was supplied at integrating the app via share_function.xml file
	 * 
	 * @param boolion $debug - true / false
	 * @return string
	 */
	private function prepare_called_app_url($debug = false){
		
		$para_array = json_decode ($this->appIntRegResult[0]->called_function_para,true);
		if($this->debug) log_message('debug',"<br><b>appregistrar/prepare_called_app_url() para_array value:</b>".print_r($para_array,true));
		if($debug)$this->progress .= "<br><b>appregistrar/prepare_called_app_url() para_array value:</b><pre>".print_r($para_array,true)."</pre>";
		//var_dump($para_array);exit;
		
		$url_first_part = null;
		$str = null;
		$url_qstring = null;
		$url = array('parameters' => null,'qstrings' => array(),'txtQstring' => null,'url_first_part' => null);
		
		foreach($para_array as $part ){			

			if(array_key_exists('url_first_part', $part)) {
				
				$url_string = $part['url_first_part'] ;
				$url_string = explode('@',$url_string);
				$url['method']= $url_string[0] ;//method
				$url['url']= $url_string[1] ;//actual url	
			}
			//make sure only <parameters> are prcessed in here
			if(array_key_exists('para_type', $part)){
					
				//if para_type is a parameter and not a qrystring
				if($part['para_type'] == 'parameter'){
	
					//$url['parameters'][] = $part['display_name'];
					//$url['parameters'][][$part['display_name']] = $part['value'];
					//parameters has no name as oppose to qstring.
					$url['parameters'][]= $part['value'];
				}else{					
					$url['qstrings'][$part['qvar_name']]= $part['value'];
				}
			}//end if		
			
			if(array_key_exists('txtQstring', $part)) {
	
				$url['user_defined_qstrings']=  $part['txtQstring'] ;
			}else{
				$url['user_defined_qstrings'] =  null ;
			}
		}
		
		if($debug)$this->progress .= "<b>appregistrar/prepare_called_app_url() url array value:</b><pre>".print_r($url,true)."</pre>";
		//var_dump($url);exit;		
		return $url;	
		
	}//end of funciton
	
	
	
	
	
	/**
	 * get_called_app_function_id()
	 * 
	 * This function returns called app function id
	 *  
	 * @return unknown
	 */
	private function get_called_app_function_id(){
		
		$called_app_func_id = $this->appIntRegResult[0]->called_app_function_id;
		return $called_app_func_id;
	}//end of function
	
	/**
	 * getTimeStamp()
	 * 
	 * This function returns date and only hrs value. It can include minits and seconds.
	 * but for the timebeing made available only hrs value along with date
	 * 
	 * @return string date
	 */	
	private function getTimeStamp(){
		
		return date("Y-m-d h:i:s");
	}//end of function
	
	/**
	 * getHostIP()
	 * 
	 * This function returns remote address
	 * 
	 * @return string remote address
	 */
	private function getHostIP(){
		
		return $_SERVER['REMOTE_ADDR'];
	}//end of function
	
	/**
	 * getUserId()
	 * 
	 * This function returns calling app user id
	 *  
	 * return int calling app user id
	 */
	private function getUserId(){
		
		return $this->calling_app_user_id ;
	}//end of function
	
	/**
	 *  getRandomString()
	 *  
	 *  This function returns a random string 
	 *  
	 *  return string  
	 */
	private function getRandomString(){
		
		return substr(str_shuffle(MD5(microtime())), 0, 10);
		
	}//end of function
	
	/**
	 * getAppId()
	 * 
	 * This function returns app id
	 * 
	 * return int
	 */
	private function getAppId(){
		
		return $this->app_id;
	}//end of function
	
	
	/**
	 * Function  verify_token ()
	 *
	 * @param string $debug
	 * @access public 
	 * @since 
	 * @modified           Jun 17, 2016 by Roshan Ruzaik <mrmroshan@yahoo.com>
	 * @modification Fixed bug id 21527,20497,21455        
	 * @return void
	 */
	public function verify_token($debug = false){
	
		if($this->debug) log_message('info',"<b>appregistrar/verify_token() invoded</b>");
		if($debug)$this->progress .="<br>AappRegistrar/verify_token() invoked";
		if($debug)$this->progress .="<br><b>Verify Token Response</b>";
		

		//get token
		$enc_token = (isset($_GET['token']))?$_GET['token']:null;
		$user_access_permission = 0;
				
		
		if($this->debug) log_message('info',"<b>appregistrar/verify_token(); enc_token value:$enc_token</b>");
		if($debug)$this->progress .="<br>AappRegistrar/verify_token() received token:$enc_token";
		
		if(!empty($enc_token) ){
			
			$token = base64_decode($enc_token);
			
			if($this->debug) log_message('info',"<b>appregistrar/verify_token();decrypted token value:$token</b>");
			if($debug)$this->progress .="<br>AappRegistrar/verify_token() decrypted token:$token";
			 
			//verify process
			$token_parts = explode('-', $token);		
			if(count($token_parts) == 8){

				$calling_app_id = $token_parts[0];
				$called_app_id = $token_parts[1];
				$calling_app_host_ip = $token_parts[2];
				$calling_app_user_id = $token_parts[3];
				$called_app_func_id = $token_parts[4];
				$time_stamp = $token_parts[5];
					
				//get called app name
				$this->get_uaacs_feed_by_app_id($called_app_id,'called_app');
				$called_app_name = $this->get_called_app_name();
				$called_app_name = (empty($called_app_name))?'Unknown called application':$called_app_name;
					
				//get staff listing for log purposes
				staff_object();
				$xmlObj = simplexml_load_string($_SESSION['staff_xml']);
				$staff = $xmlObj->xpath('//row [@id="'.$calling_app_user_id.'"]');
				$staffName = $staff[0]->cell[1];
				
				//============== Access log============================================
				$this->log_obj->set_userDetails($called_app_name,'Called app');
				$this->log_obj->set_otherDetails(
						array(
								'Mode'=>'Verify token request is made by '.$called_app_name,
								'Data'=> 'Calling app user:'.$staffName.': Supplied token to verify :'.$enc_token));
				$this->log_obj->init();
				//======================================================================
					
					
				//do the verification
					
				//validate calling app
				if($this->validate_app($calling_app_id,'calling_app',$debug)){
				
					if($this->validate_app($called_app_id,'called_app',$debug)){
							
						if($this->validate_remote_host()){
								
							if($this->Tokens_model->exists(array('token' => $enc_token))){
									
								if($this->debug) log_message('info',"<b>appregistrar/verify_token() token valid</b>");
								if($debug)$this->progress .="<br>AappRegistrar/verify_token() token existing in db and its valid";
				
								//cross check function id aginst uaacs_data
								$permission = (int)$this->verify_permission($enc_token,$debug);
								if($debug)$this->progress .="<br>AappRegistrar/verify_token() permission var value:$permission";
									
								if($permission == 1){
				
								// Following verify_role() is not necessary. Since we only get function id from called app and
								// there is no way of determining to select role by called app.
				
								//$role  = $this->verify_role($enc_token, $calling_app_user_id, $called_app_role_id);
								//$role = 1;
				
								$user_access_permission = $this->verify_user_access($calling_app_user_id,$called_app_id,'Called app',$debug);
									
								if($user_access_permission == 1){
									
								$data['validity'] = 'VALID';
								$data['code'] = 200;
									$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
										
								}else{
								if($this->debug) log_message('info',"<b>appregistrar/verify_token() error: role error</b>");
								$data['validity'] = 'INVALID';
									$data['code'] = "526";
										$data['errors'] = 'Error: You do not have access permission to called application!';
								$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
								}
				
								}else{
								if($this->debug) log_message('info',"<b>appregistrar/verify_token() error: Permission error</b>");
								$data['validity'] = 'INVALID';
								$data['code'] = "525";
								$data['errors'] = 'Error: No Permission';
								$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
								//var_dump($data);exit;
							}
				
								}else{
									
								if($this->debug) log_message('info',"<b>appregistrar/verify_token() error: non existing token</b>");
								$data['validity'] = 'INVALID';
									$data['code'] = "524";
											$data['errors'] = 'Error:non existing token';
							$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
								}
				
								}else{
				
										if($this->debug) log_message('info',"<b>appregistrar/verify_token() error:unauthorized host</b>");
										$data['validity'] = 'INVALID';
											$data['code'] = "523";
											$data['errors'] = 'Error:Unauthorized Host';
						$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
						}
						}else{
							
								if($this->debug) log_message('info',"<b>appregistrar/verify_token() error:invalid called app id</b>");
								$data['validity'] = 'INVALID';
								$data['code'] = "522";
								$data['errors'] = 'Error:Invalid Called App';
					$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
				
								}
				
				}else{
				
				if($this->debug) log_message('info',"<b>appregistrar/verify_token() error:invalid calling app id</b>");
				$data['validity'] = 'INVALID';
									$data['code'] = "521";
										$data['errors'] = 'Error:Invalid Calling App';
				$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
				
									}
										
									//============== Access log============================================
			$this->log_obj->set_userDetails('AIR','AIR Application');
			$this->log_obj->set_otherDetails(
									array(
									'Mode'=>'Token verification is done for called app:'.$called_app_name,
									'Data'=> 'token verification response: '.serialize($data)));
									$this->log_obj->init();
									//======================================================================
				
			}else{
				
				//	 check $token_parts == 8
				if($this->debug) log_message('info',"<b>appregistrar/verify_token() error: incorrect token error</b>");
				$data['validity'] = 'INVALID';
				$data['code'] = "528";
				$data['errors'] = 'Error: Given token is not valid!';
				$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
				//============== Access log============================================
				$this->log_obj->set_userDetails('Unknown call','Called app');
				$this->log_obj->set_otherDetails(
						array(
								'Mode'=>'Token verification call is made with incorrect token',
								'Data'=> 'Validity:'.$data['validity'].'-Code:'.$data['code'].'-Errors:'.$data['errors']));
				$this->log_obj->init();
				//======================================================================
				
			}

					
			
		}else{
			
			if($this->debug) log_message('info',"<b>appregistrar/verify_token() error:token was not provided </b>");
			$data['validity'] = 'INVALID';
			$data['code'] = "520";
			$data['errors'] = 'Error:Token was not provided';
			$data['debug'] = ($debug)?"<![CDATA[ ".$this->progress."]]>":null;
			
			//============== Access log============================================
			$this->log_obj->set_userDetails('Unknown call','Called app');
			$this->log_obj->set_otherDetails(
					array(
							'Mode'=>'Token verification call is made without a token',
							'Data'=> 'Validity:'.$data['validity'].'-Code:'.$data['code'].'-Errors:'.$data['errors']));
			$this->log_obj->init();
			//======================================================================
					
		}
		
		if($debug)$this->progress .="<br>AappRegistrar/verify_token() token validity data:".print_r($data,true);
		
		
		
		$this->load->view('token_verify_response',$data);
	
	}//end of function
	
	/**
	 * verify_user_access($user_id,$app_id,$app_type,$debug = false)
	 * 
	 * This function cross checks with UAACS object for permissions with given user id and application id then
	 * return true/false    
	 * 
	 * @param int $user_id
	 * @param int $app_id
	 * @param string $app_type
	 * @param boolean $debug
	 * @return int - 0 or 1
	 */	
	function verify_user_access($user_id,$app_id,$app_type,$debug = false){
		

		if($debug)$this->progress .="<br>AappRegistrar/verify_user_access() invoked";
		if($debug) log_message('info',"<b>appregistrar/verify_permission() invoked</b>");
		
		$has_permission = 0;	
				
		if($debug) log_message('info',"<b>appregistrar/verify_permission() user id:$user_id</b>");
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() user id:$user_id";
		

		try {
			$app_uaacs_xml =  get_contents_with_session(UAACS_URL.'/API/APPAPI/index.php/main/app/t/'.$app_id.'/1/1/');				 
		}catch (Exception $e)  {
			show_error("Sorry! An error occoured while fetching XML feed data from server");
			exit;
		}			
			
			$app_uaacs_obj = simplexml_load_string($app_uaacs_xml);
			$users = $app_uaacs_obj->users;
			$users_arr = array();
			
			//var_dump($users->user[0]->attributes()->staff_id);exit;		
			
			foreach($users->user as $user){
				$users_arr[] = (int)$user->attributes()->staff_id;
			}		

			if(in_array($user_id,$users_arr)){
				$has_permission = 1;
			}
		
		return $has_permission;
		
	}//end of function
	
	/**
	 * verify_permission()
	 * 
	 * This function verifies permissions assigned to calling application user.
	 * 
	 * @param string $token - token value
	 * @param string $debug - true or fals
	 * @return number
	 */
	function verify_permission($token,$debug = false){
		
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() invoked";
		$found = 0;
		
		//decrypt and break token values to get called app function id
		$dec_token = base64_decode($token);
		if($debug) log_message('info',"AppRegistrar:verify_permission();decrypted token value:$dec_token");
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() decrypted token value:$dec_token";
		
		//verify process
		$token_parts = explode('-', $dec_token);
		$calling_app_id = $token_parts[0];
		$called_app_id = $token_parts[1];
		$calling_app_host_ip = $token_parts[2];
		$calling_app_user_id = $token_parts[3];
		$called_app_func_id = $token_parts[4];
		$time_stamp = $token_parts[5];
		
		
		if($debug) log_message('info',"<b>appregistrar/verify_permission() invoked</b>");
		if($debug) log_message('info',"<b>appregistrar/verify_permission() token:$token,function id:$called_app_func_id</b>");
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() token:$token,called app function id:$called_app_func_id";
		
		//retreve uaacs data associatd with the token
		$rst = $this->Tokens_model->get_uaacs_data($token);		
		if($debug) log_message('info',"<b>appregistrar/verify_permission();rst:</b>".print_r($rst,true));
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() token model results:".print_r($rst,true);
		$uaacs_data = $rst[0]['uaacs_data'];
		//var_dump($uaacs_data);exit;
		
		if($debug) log_message('info',"<b>appregistrar/verify_permission();uaacs_data:</b>$uaacs_data");
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() uaacs_data:$uaacs_data";
		
		//convert jason aray to assoc array
		$array_uaacs_data = json_decode($uaacs_data, true);
		//var_dump($array_uaacs_data);exit;
		
		if($debug) log_message('info',"<b>appregistrar/verify_permission();array_uaacs_data:</b>".print_r($array_uaacs_data,true));
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() uaacs data array:".print_r($array_uaacs_data,true);
		
		$role_array = array();
		$function_array = array();
		
		if(!empty($array_uaacs_data)){
			foreach($array_uaacs_data as $k => $v){
				$role_array [] = $k;
				$function_array = explode(',', $v);
			}
		}//end if
		$found = (int)in_array($called_app_func_id, $function_array);
		//var_dump($found);exit;
		
		if($debug)$this->progress .="<br>AappRegistrar/verify_permission() is function found:$found";
		
		return $found;
		
		
		/*
		$roles = (isset($array_uaacs_data['ROLE']))?$array_uaacs_data['ROLE']:null;
		$functions = (isset($array_uaacs_data['FUNCTION']))?$array_uaacs_data['FUNCTION']:null;
		 
		if($this->debug) log_message('info',"<b>appregistrar/verify_permission();role array:</b>".print_r($roles,true));
		if($this->debug) log_message('info',"<b>appregistrar/verify_permission();functions array:</b>".print_r($functions,true));
		
		//check if function id is existing inside uaacs data function list
		if(!empty($functions)){
			
			//$found = in_array($function_id, $functions);
			foreach($functions as $function){
				if($called_app_func_id == $function['FUNCTIONID']){
					$found = 1;
				}
			}
			if($this->debug) log_message('info',"<b>appregistrar/verify_permission();function id found result:</b>".print_r($found,true));
		}//end if
		*/
		
		
	}//end of function
	
	/**
	 * verify_role()
	 * 
	 * This function verifies user role for a given user id.
	 * 
	 * @param string $token - token value
	 * @param int $user_id - user id 
	 * @param int $role_id - role id
	 * @return number
	 */
	function verify_role($token,$user_id,$role_id){
		
		$found = 0;		
		if($this->debug) log_message('info',"<b>appregistrar/verify_role() invoked</b>");
		if($this->debug) log_message('info',"<b>appregistrar/verify_role() user id:$user_id,role id:$role_id invoked</b>");
		
		//retreve uaacs data associatd with the token
		$rst = $this->Tokens_model->get_uaacs_data($token);
		if($this->debug) log_message('info',"<b>appregistrar/verify_role();rst:</b>".print_r($rst,true));
		$uaacs_data = $rst[0]['uaacs_data'];
		
		if($this->debug) log_message('info',"<b>appregistrar/verify_role();uaacs_data:</b>$uaacs_data");
		
		//convert jason aray to assoc array
		$array_uaacs_data = json_decode($uaacs_data, true);
		
		if($this->debug) log_message('info',"<b>appregistrar/verify_role();array_uaacs_data:</b>".print_r($array_uaacs_data,true));
		$roles = (isset($array_uaacs_data['ROLE']))?$array_uaacs_data['ROLE']:null;
		
		if(!empty($roles)){
							
			foreach($roles as $role){
				if($role_id == $role['ROLEID']){
					$found = 1;
				}
			}
			if($this->debug) log_message('info',"<b>appregistrar/verify_role();role id found result:</b>".print_r($found,true));
		}//end if
		
		return $found;
		
	}//end of function
	
	/**
	 * view_log()
	 * 
	 * This function is to use as a debug message displayer
	 * 
	 */
	public function view_log(){
	
	$str = file_get_contents('application/logs/log-'.date('Y-m-d').'.php');
		$str = str_replace('DEBUG', '<BR>DEBUG', $str);
		$str = str_replace('INFO', '<BR>INFO', $str);
		$str = str_replace('ERROR', '<BR>ERROR', $str);
		$str = explode('<BR>', $str);
		
		//echo substr($str[], 0, 3);
		//var_dump($str);exit;
		
		foreach($str as $line){
			$ss = $line;
			if(substr($line, 0, 4) == 'INFO'){
				echo $ss.'<br>'; 		
			}
		
		}
	}
	
	/**
	 * get_user_ip()
	 * 
	 * This function return user ip
	 * 
	 * http://stackoverflow.com/questions/15699101/get-the-client-ip-address-using-php
	 * 
	 * @return string user ip
	 */
	private function get_user_ip() {
		
		if($this->debug) log_message('info',"<b>appregistrar/get_user_ip() invoked:</b>");
		
		$ipaddress = '';
		if (isset($_SERVER['HTTP_CLIENT_IP']))
			$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if(isset($_SERVER['HTTP_X_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		else if(isset($_SERVER['HTTP_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_FORWARDED'];
		else if(isset($_SERVER['REMOTE_ADDR']))
			$ipaddress = $_SERVER['REMOTE_ADDR'];
		else
			$ipaddress = 'UNKNOWN';
		
		if($this->debug) log_message('info',"<b>appregistrar/issueToken(),ipaddress:$ipaddress</b>");
		
		return $ipaddress;
		
	}//end of function
	
	/**
	 * get_jason()
	 * 
	 * This function echos json string from uaacs feed for given appid,app role,and calling app user id
	 * 
	 * @param int $calling_app_id
	 * @param int $called_app_role_id
	 * @param int $calling_app_user_id
	 */
	public function get_jason($calling_app_id,$called_app_role_id,$calling_app_user_id){
		
		$feedData = file_get_contents("http://kindersigns.org/uaacs_feed.php?appid=$calling_app_id&roleid=$called_app_role_id&uid=$calling_app_user_id");
		$fileContents = str_replace(array("\n", "\r", "\t"), '', $feedData);
		$fileContents = trim(str_replace('"', "'", $fileContents));
		$simpleXml = simplexml_load_string($fileContents);
		$json = json_encode($simpleXml);
		echo $json;
	} 
	
	/**
	 * get_related_links($calling_app_id=0,$calling_app_function_id=0,$debug=false)
	 *
	 * This function gets all realted linkages for a given calling app id and calling  app function id
	 *	 
	 * @param number $calling_app_id
	 * @param number $calling_app_function_id
	 * @param boolion $debug - true / false 
	 */
	public function get_related_links($calling_app_id=0,$calling_app_function_id=0,$debug=false){
	
		$searchobj_array = array();
	
		$search_obj1= array(
				'search_field' => 'calling_app_id',
				'search_text' => $calling_app_id,
				'query_method'=>'equal');
			
		array_push($searchobj_array, $search_obj1);
	
		$search_obj2= array(
				'search_field' => 'calling_app_function_id',
				'search_text' => $calling_app_function_id,
				'query_method'=>'equal');
		array_push($searchobj_array, $search_obj2);
	
		$data['dataset'] = $this->AppIntegrator_model->get_data(array(
				'search'=>$searchobj_array,
				'selection'=>'ar_applications.integration_id,
							  ar_applications.intergration_name,
							  ar_applications.calling_app_id,
							  ar_applications.calling_app_function_id,
							  ar_applications.called_app_id,
							  ar_applications.called_app_function_id',
				'limit' => 100,
				'offset'=> 0,
				'order_by'=>array('ar_applications.integration_id'=>'Asc')));
	
		$wrapped_data['data'] = $data;
		$this->load->view('related_ai_gridfeed',$wrapped_data);
	
	}//end of function
	
	/**
	 *	createDropdown()
	 *
	 *	createDropdown is the component function. Its main functionality is to produce a dropdown with pre populated table data
	 *
	 *  Parameter list :-
	 *
	 *   $data['selectByValue']  => null   - preselection of list items by value
	 *   $data['selectBYText']   => null   - preselection of list items by Text
	 *   $data['filterBy']       => null   - filter data set by a field or list
	 *   $data['outFormat']      => 'html' - Format of the output like HTML,XML Etc
	 *   $data['isMultiple']     => false  - is the drop down with multi select capable
	 *   $data['sort']           => 'asc'  - sort list text Ascending or Descending
	 *   $data['optionsOnly']    => false  - Specify the controller that output only <options> values
	 *
	 *    Usage :-
	 *
	 *    1) Format for internal functional call by passing data array
	 *
	 *    $data = array('selectByValue' => null,
	 *					'selectBYText' => null,
	 *					'outFormat' => 'html' ,
	 *					'isMultiple' => false,
	 *					'sort' => 'asc',
	 *					'optionsOnly' => false,
	 *					'filterBy' => array(
	 *									'search_field' => 'T.status',
	 *									'search_text' => '0',
	 *									'query_method'=>'equal',
	 *									'order_by' => 'asc'
	 *									)
	 *						)
	 *
	 *    2) Format of external call by URL
	 *
	 *    http://.../index.php/task_master/createDropdown/?sbv=null&sbt=null&format=html&multiple=false&sort=asc&filterby=status-0-equal
	 *
	 *    Description of parameter list,
	 *
	 *    sbv - selectByValue  => null
	 *    sbt - selectBYText   => null
	 *    format - outFormat   => 'html'
	 *    multiple - isMultiple=> false
	 *    sort - sort          => 'asc'
	 *    filterby - filterBy  => null
	 *    optionsOnly - options only listing
	 *    
	 *    @param array $data data array to create dropdown
	 *
	 */
	public function createDropdown($data = false){
	
			
		$dataset = null;
		$selectByValue = null;
		$selectBYText = null;
		$outFormat = 'html' ;
		$isMultiple = null;
		$sort = null;
		$sort_array = array('ar_applications.integration_id' => 'ASC');
		$filterBy = null;
		$searchobj_array = null;
		$optionsOnly = false;
		$limit = null;
		$offset = null;
	
			
		/*
		 *	first check wether the call is internal(ie:internal function call) or external(ie:url call)
			*	to do this we can check $data variable.if this variable is an array it means its an internal call
			*	if $data is 'false' it means its an external call.
			*/
	
		if(is_array($data)){
	
			/*
			 * this is an internal call. so construct the search obj with passed array parameeters.
				* extract the data and pass on to the view
				*/
	
	
			$selectByValue = isset($data['selectByValue'])?$data['selectByValue']:null;
			$selectBYText = isset($data['selectBYText'])?$data['selectBYText']:null;
			$outFormat = isset($data['outFormat'])?$data['outFormat']:null;
			$isMultiple = isset($data['isMultiple'])?$data['isMultiple']:false;
			$sort = isset($data['sort'])?$data['sort']:'rpt_reports.tp_name=ASC';
			$filterBy = isset($data['filterBy'])?$data['filterBy']:null;
			$optionsOnly = isset($data['optionsOnly'])?$data['optionsOnly']:false;
			$limit = isset($data['limit'])?$data['limit']:null;
			$offset = isset($data['offset'])?$data['offset']:null;
	
		}else{
	
			/*
			 * this is an external url call. So process $_GET or $_POST parameeter values and using
				* these values construct search obj and fetch data for combo box
				*/
			if(count($_POST)>0 || count($_GET)>0){
					
				$myParams = count($_POST)>0? $_POST:$_GET;
	
				$selectByValue = isset($myParams['sbv'])? $myParams['sbv']:null ;
				$selectByValue = (!empty($selectByValue))?$selectByValue:null; // set default values if not supplied.
	
				$selectBYText = isset($myParams['sbt'])?$myParams['sbt']:null;
				$selectBYText = (!empty($selectBYText))?$selectBYText:null;
					
				$outFormat = isset($myParams['format'])?$myParams['format']:null;
				$outFormat = ($outFormat != 'html' && !empty($outFormat))?$outFormat:'html';
					
				$isMultiple = isset($myParams['multiple'])?$myParams['multiple']:null;
				$isMultiple = ($isMultiple == 'true')?true:false;
					
				$sort = isset($myParams['sort'])?$myParams['sort']:'ar_applications.integration_id=ASC';
				//$sort = ($sort == 'desc')?'desc':'asc';
					
				$filterBy_string = isset($myParams['filterby'])? $myParams['filterby']:null;
				$filterBy_string = (!empty($filterBy_string))?$filterBy_string:null;
					
				$optionsOnly = isset($myParams['optionsonly'])? $myParams['optionsonly']:false;
				$optionsOnly = ($optionsOnly == 'true')? true:false;
	
				$limit = isset($myParams['limit'])? $myParams['limit']:null;
				$limit = ($limit != null)? $limit:null;
	
				$offset = isset($myParams['offset'])? $myParams['offset']:null;
				$offset = ($offset != null)? $offset:null;
	
	
					
				if(!empty($filterBy_string)){
	
					$fieldPara = explode(',',$filterBy_string);
	
					foreach ($fieldPara as $val )   {
						$split =  explode('=',$val);
						$filterBy[$split[0]]= $split[1];
					}
	
				}else{
	
					$filterBy = null;
				}
	
				if (!empty($sort)){
	
					$sortPara = explode(',',$sort);
					foreach ($sortPara as $val )   {
						$split =  explode('=',$val);
						$sort_array[$split[0]]= $split[1];
					}
				}
					
			}
		}//end of param check and config
	
		// Construct search object if present
	
		If ($filterBy){
	
			$searchobj_array = array();
	
			foreach($filterBy as $key => $val){
					
				$search_text = $val; //search text
				$query_method = substr(strrchr($key, "_"), 1);
				$pos = strrpos($key, '_');
				$field = substr($key, 0, $pos);
				$search_obj = array(
						'search_field' => $field,
						'search_text'  => $search_text,
						'query_method' => $query_method
				);
	
				array_push($searchobj_array, $search_obj);
			}
		}//end if
	
		//Construct selection list. (Fixed)
		$selection =
			'ar_applications.integration_id,
			 ar_applications.intergration_name,
			 ar_applications.calling_app_id';
	
		// Fetch data from model
	
		$dataset = $this->AppIntegrator_model->get_data(array(
				'search' => $searchobj_array,
				'selection' => $selection,
				'limit' => $limit,
				'offset'=>$offset,
				'order_by' => $sort_array));
	
		//var_dump($dataset); for debug
			
		// Construct data structure for view
			
		$wrapped_data['data']['dataset'] = $dataset;
		$wrapped_data['selectByValue'] = $selectByValue;
		$wrapped_data['selectByText'] = $selectBYText;
		$wrapped_data['outFormat'] = $outFormat;
		$wrapped_data['isMultiple'] = $isMultiple;
		$wrapped_data['optionsOnly'] = $optionsOnly;
			
	
		// load view file with assigned data array
	
		$this->load->view('ai_dropdown',$wrapped_data);
			
	}//End of Function createDropdown
	
}//end of class
/* End of file appregistrar.php */
/* Location: ./application/controllers/appregistrar.php */