<?php
/**
 * paging_user_role.php - Check user roles for unit pagining.
 *
 * @author $Author: dtong $
 * @version $Id: paging_user_role.php,v 1.2 2011/04/13 10:20:09 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/
require_once ('paging_base.php');

class paging_user_role extends paging_base {

	function __construct() {
		parent::__construct();
		$this->handle_param_list = array('_roles', '_owner');
	}

	function invoke() {
		//All handles have to do this
		if ( !$this->valid_params_checked ) {
			//handle data array contains invalid tags so return false and don't let the page number clickable
			return FALSE;
		}
		$userroles = osa_value($this->handle_check_array, '_roles', FALSE);
		//We piggy back on the unit event handle model.
		$this->CI->load->model('unit/event/handle_user_role_model');
		$user = & $this->CI->login_model->getLogin();
		if ( !$user ) {
			return FALSE;
		}

		//Check user roles
		if ( $userroles !== FALSE ) {
			if ( !$this->valid_role_string($userroles) ) {
				//Invalid _roles string
				osa_errorlog(__METHOD__ . " - Page number {$this->pagenumber} contains invalid _roles $userroles", $this->handle_check_array);
				return FALSE;
			}
			if ( $this->CI->handle_user_role_model->has_roles($user->id, $userroles) ) {
				return TRUE;
			}

			if ( $this->CI->access_model->checkaccess_any('admin_unit_write', FALSE, FALSE, FALSE) ||
				$this->CI->access_model->checkaccess_any('admin_unit_read', FALSE, FALSE, FALSE) ) {
				return TRUE;
			}
		}

		//Check owner
		$owner_role = osa_value($this->handle_check_array, '_owner', FALSE);
		if ( !empty($owner_role) && $owner_role ) {
			$table = $this->template_identifier; //template_identifier and table name are always the same
			$column = 'creatorid'; //Make sure all the tables to be created has this column
			return $this->CI->handle_user_role_model->is_owner($user->id, $this->unitid, $table, $column);
		}
		return FALSE;
	}

	//Function to make sure the role list from the template is valid
	private function valid_role_string($roles) {
		return preg_match('/^[123456789][,1234567890]*$/', $roles);
	}
}