<?php
class AccessController extends CApplicationComponent {
	/**
	*check privilage based on URL or privilage id
	*usage: isAllowed()
	* isAllowed('createPost')
	*/
	public function isAllowed($privilageName=null){
		$userId = '';
		if(Yii::App()->user->isGuest){
				$userId = 'guest'; 
				return false;
			}
		else
			$userId = Yii::App()->user->id;
			
		//echo "bla".$userId."hmm" ;
		if($privilageName === null){
			$_controllerId = Yii::App()->controller->id;
			$_actionId = Yii::App()->controller->action->id;
			if(isset(Yii::App()->controller->module)){
				$_moduleId = Yii::App()->controller->module->id;
			}else{
				$_moduleId = Yii::app()->params['mainModuleId'];
			}
			//echo "-a- u:".$userId." m:".$_moduleId." c:".$_controllerId." i:".$_actionId." ";
			return $this->checkAccessByUrl($userId, $_moduleId,$_controllerId, $_actionId);
		}else{
			//echo " -b- ";
			return $this->checkAccessByPrivilageName($userId, $privilageName);
		}
		return false;
	}
	public function checkAccessByUrl($userId, $moduleId, $controllerId, $actionId){
		//echo "userid:". $userId;
		//get privilage name based on URL
		$privilage = Privilage::model()->findByAttributes(array(
		'sys_m_module_id' => $moduleId,
		'sys_m_controller_id' => $controllerId,
		'action' => $actionId,
		));
		//check users privilage from database
		if($privilage !== null){
		//echo " masuk ";
			return $this->checkAccessByPrivilageId($userId, $privilage->sys_m_privilage_id);
			}
		return false;
	}
	//check by global privilage
	public function checkAccessByPrivilageId($userId, $privilageId){
		//echo "baru ".$privilageId. " ".$userId;
		//$id =101;
		$roles = UserRole::model()->findAll(array("condition"=>"user_id =  $userId",));
		if($roles != NULL){	
			//$roles=UserRole::model()->findByAttributes(array('user_id' => $userId));
			//echo $roles->role_id;
			//$semArr = CHtml::listData($roles, 'user_id', 'role_id');
			 foreach ($roles as $role) {
					$myrole=$role->sys_m_role_id;
					$privilages = RolePrivilage::model()->findAll(array("condition"=>"sys_m_role_id =  $myrole",));
					 foreach ($privilages as $privilage) {  
					 //echo "ini priv ".$privilage->sys_m_privilage_id;
						if ($privilage->sys_m_privilage_id == $privilageId)
							{return true;}
					 }
			}			
		}
		//echo "false";
			//exit;
		return false;
	}
}
?>