<?php
/**
 * Cms_security_type
 *
 * Security type check for full access with unit, goal, survey, system etc.
 * If you add a new template top-levle folder then you need to add new check for the foler here.
 * If a function here returns false it doesn't mean the user can't write, the caller (cms_security)
 * will start to use automic level security check instead.
 *
 * @author $Author: dtong $
 * @version $Id: Cms_security_type.php,v 1.2 2011/05/20 06:30:10 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/

class Cms_security_type {
	private $action;
	private $templateid;
	private $linkid;
	private $coreid;
	private $CI = NULL;

	function __construct() {
		$this->CI = & get_instance();
	}

	//This is a major system class so protect it from lazy coders...
	function __set($var, $value) {
		echo __METHOD__ . " - You are not allowed to set undeclared class property '$var', bye bye.";
		exit;
	}

	//templateid is ubd, myp, goal, course_desc, site_resources etc.
	function check($templateid, $action, $linkid=FALSE, $coreid=FALSE) {
		$this->action = $action;
		$this->templateid = $templateid;
		$this->linkid = $linkid;
		$this->coreid = $coreid;
		$function = "type_{$templateid}";
		if ( method_exists($this, $function) ) {
			return $this->$function();
		}
		$this->CI->load->library('cms/cms_template/cms_template');
		$folder = $this->CI->cms_template->filename_templateid($templateid);
		if ( $folder ) {
			$function = "type_{$folder}";
			if ( method_exists($this, $function) ) {
				return $this->$function();
			}
		}
		osa_log(__METHOD__, "Invalid template foler/id name {$templateid}.");
		return FALSE;
	}

	/*
	 * For all unit templates
	 */
	private function type_unit() {
		if ( !osa_is_int_one($this->coreid) ) {
			return FALSE;
		}
		if ( $this->action == CMS_ACTION_READ ) {
			return $this->CI->access_model->checkaccess_any_noexit('unit_read');
		}
		//Check for edit action
		if ( $this->CI->access_model->checkaccess_any_noexit('admin_unit_write') ) {
			return TRUE;
		}
		//osa_is_course_editor() also checks for admin_unit_write but like to place it above.
		if ( osa_is_course_editor($this->coreid) ) {
			return TRUE;
		}
		return FALSE;
	}

	/*
	 * For all goal templates
	 */
	private function type_goal() {
		$this->CI->load->model('goal/goal_model');
		return $this->CI->goal_model->is_edit_goal($this->linkid);
	}

	private function type_course_desc() {
		//Course description is same as unit template, courseid based.
		return $this->type_unit();
	}

	/*
	 * For all system templates
	 */
	private function type_system() {
		if ( $this->CI->access_model->checkaccess_any_noexit('admin_system_management') ) {
			return TRUE;
		}
		return FALSE;
	}

	/*
	 * For all survey templates
	 */
	private function type_survey() {
		return TRUE;
	}

}