<?php
/**
 * handle_use_action_edit.php -
 *
 * Change the current action to edit if no additional parameter supplied.
 * If additonal param is supplied then additonal conditions are checked before switching to edit action.
 * Only one single param should be used at any time.
 * TODO: This only supports units and not goal or survey but don't think they need them, or not?
 *
 * @author $Author: dtong $
 * @version $Id: handle_use_action_edit.php,v 1.5 2011/06/02 07:57:30 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/

require_once('handle_base.php');

Class handle_use_action_edit extends handle_base {
	/*
	 * _mycourse - Allow read-only teachers to use editing mode with editing units.
	 * _editor - Allow editor teachers to use editing mode for published units.
	 * _admin - Allow admins to use editing mode for published units.
	 */
	Const HANDLE_PARAM_LIST = '_mycourse,_editor,_admin';

	function __construct() {
		parent::__construct();
		$this->CI->load->model('unit/unit_model');
	}

	function invoke() {
		$this->valid_handle_params(self::HANDLE_PARAM_LIST);
		if ( empty($this->courseid) ) {
			return FALSE;
		}
		$isadmin = $this->CI->access_model->checkaccess_any_noexit('admin_unit_write');
		$iseditor = osa_is_course_editor($this->courseid);

		if ( $this->handle_value('_mycourse') ) {
			if ( $isadmin || $iseditor ) {
				//Admin and editor can edit anyway so do nothing.
				return TRUE;
			}
			if ( !osa_is_mycourse($this->courseid) ) {
				//Non-course teachers can only read so this would be an published unit
				//so just return true and do nothing
				return TRUE;
			}
			//get_unit() uses caching so call as many times as you want :)
			if ( !($unit = $this->CI->unit_model->get_unit($this->unitid)) ) {
				echo osa_buildererror();
				return FALSE;
			}
			if ( $unit->status == CMS_UNIT_STATUS_EDIT ) {
				//Switch edit action if it is a edting unit, this is for read-only teachers since they will always
				//see a read-only editing unit. For course editors, this does not change anything
				$this->change_action2edit();
			}
			return TRUE;
		}

		//Check for courses edit access
		if ( $this->handle_value('_editor') ) {
			if ( !$iseditor && !$isadmin ) {
				return FALSE;
			}
		}

		if ( $this->handle_value('_admin') ) {
			if ( !$isadmin ) {
				return FALSE;
			}
		}

		//For admin and editors, always switch to edit mode even for a published unit.
		//Right now, only admin is using this for admin notes.
		$this->change_action2edit();

		return TRUE;
	}
}