<?php
/**
 * resource.php
 *
 * Resource controller. For add, edit, update and delete from the template page.
 * Resources are the most widely used module in the system so make sure the code here is clean.
 *
 * @author $Author: dtong $
 * @version $Id: resource.php,v 1.77 2011/05/20 14:43:33 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
class Resource extends CI_Controller {
	private $uploadbox_width = '450px';
	// Should be more than 70 pixels. if less than this you will can't see upload queue list
	private $uploadbox_height = '160px';

	function __construct() {
		parent::__construct();
		osa_header_nocache();
		osa_load_lang('unit');
		if ( !$this->access_model->checkaccess_any('unit_read', FALSE, FALSE, FALSE) ) {
			//A  won't print to the client until this returns and an exist
			//would result in no output. So, just echo it here. Noticed the 3rd parameter in the load->view
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		$this->load->library('cms/cms_template/cms_template');
		$this->load->library('cms/cms_security');
		$this->load->model('unit/unit_model');
		$this->load->model('unit/resource_model');
		$this->load->helper('form');
	}

	/*
	 * For the non-unit resource add page.
	 * Rignt now, this is a special add function for ICT,GC and Tail only
	 * For new features, you should have a new table like goal or survey link with the resource table
	 *
	 * @param int $type
	 * 	This is the resource template type
	 * @param int $benchmarkid
	 * 	Right now, this is for ict, gc, and tail upload. This is the benchmark ID
	 * @param int $schoolid
	 * 	Right now, this is for ict, gc, and tail upload. This is the schoolid in user_role table.
	 */
	function addo($type, $benchmarkid, $schoolid, $role_type) {
		if ( !is_numeric($benchmarkid) )
			return;
		$this->_add_real(0, $type, FALSE, $benchmarkid, $schoolid, $role_type);
	}

	//For non-unit resource edit page
	function edito($type, $resid) {
		$this->_add_real(0, $type, $resid);
	}

	//For non-unit resource edit page and any type
	function editit($type, $resid, $schoolid, $role_type) {
		$this->_add_real(0, $type, $resid, FALSE, $schoolid, $role_type);
	}

	//The typical add resource from the unit page.
	function add($unitid, $type) {
		$this->_add_real($unitid, $type);
	}

	//Shows the resource popup edit page
	function edit($unitid, $type, $resid) {
		$this->_add_real($unitid, $type, $resid);
	}

	//This is a special function for one resource record per unit
	function one($unitid, $type) {
		$resobj = $this->resource_model->get_resource_single($unitid, $type);
		if ( $resobj )
			$this->_add_real($unitid, $type, $resobj->id);
		else
			$this->_add_real($unitid, $type);
	}

	/*
	 * This is the real funciton that does the actual add and edit. Called by many wrapper functions
	 * Handles both add and edit popup page. Shows the resource add popup page.
	 */
	private function _add_real($unitid, $type, $resid=FALSE, $benchmarkid=FALSE, $schoolid=FALSE, $role_type=FALSE) {
		//Only editors can run this
		/*
		$unit = new stdClass();
		if ( $unitid != 0 ){
			if ( ($templateid = $this->get_template_identifier($type)) == CMS_TEMPLATE_UNIT_IDENTIFIER ){
				//if (!($unit = $this->unit_model->check_unit_editaccess_iframe($unitid))) {
					//return;
				//}
				$unit = $this->unit_model->get_unit_any($unitid);
				if ( !$unit ) {
					$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_internalservererror')));
					return;
				}
			}
			else{
				//The following line will call cms_template->type_filename()
				//It is safe to do it here as long as all non-unit templates don't have conflict types
				$unit->template = $this->get_template_filename($type);
				$unit->courseid = 0;
			}
		}
		else {// ICT (unitid is zero)
			//TODO: Hack, for non-unit resoruces
			//Put type access check here
			//$unit->template= CMS_UBD_TEMPLATE;
			//Setting the template to fasle will get the default template from the factory
			$unit->template = FALSE;
			$unit->courseid = 0;
			$templateid = FALSE;
		}
		*/
		if ( !($unit = osa_get_unit_special($unitid, $type)) ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_internalservererror')));
			return;
		}
		//Check security, this works for all templates.
		if ( !$this->cms_security->validate(CMS_ACTION_EDIT,
					$this->get_template_filename($type), $unit->courseid, $unit->id, $type, $resid) ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_security_no_permission')));
			return;
		}

		$resource_use_unitid = $unitid;
		$refresh_unitid = FALSE;
		//Handle static resoruces
		if ( $static_unit = $this->check_static_resource($unit, $type) ) {
			//Always use the current unitid for stage refresh
			$refresh_unitid = $unitid;
			$unit = $static_unit;
			//Use this unitid for resource and related table data query.
			$resource_use_unitid = $static_unit->id;
			if ( $resid === FALSE ) {
				//For adding a new unit so just use the static unitid which is the unit groupid
				$unitid = $static_unit->id;
			}
		}

		$resobj = FALSE;
		if ( $resid !== FALSE ) {
			if ( !is_numeric($resid) ) {
				$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_internalservererror')));
				return;
			}
			$resobj = $this->resource_model->get_resource($resource_use_unitid,$resid);
			$this->load->library('unit/unitmain', array('action'=>CMS_ACTION_EDIT,'unitid'=>$unitid,
										'courseid'=>$unit->courseid,'unit_template'=>$unit->template));
		}
		else {
			$this->load->library('unit/unitmain', array('action'=>CMS_ACTION_ADD,'unitid'=>$unitid,
										'courseid'=>$unit->courseid,'unit_template'=>$unit->template));
		}

		$data = $this->unitmain->resource_popup_data($type, $unitid);
		if ( !$data ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_internalservererror')));
			osa_errorlog(__METHOD__ . " - Failed to get popup data for type:$type unit:$unitid");
			return;
		}
		$data->publicflag_extra_msg = '';
		if ( $this->cms_template->type_templateid($type) == CMS_TEMPLATE_UNIT_IDENTIFIER ) {
			$data->publicflag_extra_msg = lang('unit_makepublic_unit_type');
		}
		//Stage refresh url part
		$data->refresh_url_part = osa_stage_refresh_urlpart($type);
		$data->refresh_unitid = $refresh_unitid;
		$data->resobj = $resobj;
		$data->courseid = $unit->courseid;
		$data->unitid = $resource_use_unitid;
		$data->type = $type;
		$data->resid = ($resid ? $resid : '');
		$data->uploadfiles = FALSE;
		$data->benchmarkid = ($benchmarkid ? $benchmarkid : '');
		$data->schoolid = ($schoolid ? $schoolid : '');
		$data->role_type = $role_type;
		//TODO: Why is this hard coded with flag 5,6 and the type?? THIS HAS TO GO AWAY
		if ($type == CMS_ITSTANDARDS_RESOURCE_TYPE) {
			$data->_select_order = array(CMS_TEC_TYPE, CMS_LIB_TYPE);
			$data->_select_flag5 = TRUE;
			$data->_select_checkbox_type5 = TRUE;
			$data->_select_title5 = lang('target_technology');

			$data->_select_flag6 = TRUE;
			$data->_select_checkbox_type6 = TRUE;
			$data->_select_title6 = lang('target_library');
		}

		//Resource is public by default
		//If we are adding a new resource then use the _is_private_resource parameter if it is present
		//This logic is in the view
		$data->checkbox_default_value = TRUE;
		if ( (osa_value($data, '_is_private_resource', FALSE)) === TRUE )
			$data->checkbox_default_value = FALSE;

		if ( osa_value($data, '_upload_flag', FALSE) !== FALSE ) {
			$this->load->library('cms/osa_uploader', array('unitid'=>$resource_use_unitid, 'type'=>$type, 'courseid' => $unit->courseid));
			if ( ($upload_height = osa_value($data, '_upload_height', FALSE)) === FALSE ) {
				//$this->osa_uploader->set_height($upload_height);
				$upload_height = $this->uploadbox_height;
			}
			if ( ($upload_width = osa_value($data, '_upload_width', FALSE)) === FALSE ) {
				//$this->osa_uploader->set_width($upload_width);
				$upload_width = $this->uploadbox_width;
			}
			$data->unitid = $resource_use_unitid;
			$data->type = $type;
			$data->upload_height = $upload_height;
			$data->upload_width = $upload_width;
			// (issue: 128) dynamic upload queue list height (upload_queuelist_height)
			// if upload height equal or less than leftover value, set upload queue list height to 0
			// otherwise, upload queue list height = upload height - leftover value
			$upload_height_wihtoutpx = intval($upload_height); // parses a string and returns an integer
			$leftover = 50; //leftover space value. Calculate from remaining pixels between upload queue list height and upload box height
			$data->upload_queuelist_height = $upload_height_wihtoutpx;
			if ($upload_height_wihtoutpx <= $leftover) {
				$data->upload_queuelist_height = 0;
			}
			else {
				$data->upload_queuelist_height = $upload_height_wihtoutpx - $leftover;
			}

			if ( $resid !== FALSE ) {
				$data->uploadfiles = $this->resource_model->get_uploads_byresource($resid);
			}
			//Added this to fix a bug when doing multi-upload without a tmp folder pre-created race problem
			//So, whenever adding the resource from the unit page will create the upload tmp dir b4 actual uploads happen
			@osa_unituploaddir($this->config->item('cms_resource_uploadtmpfolder'), $unit->courseid, $resource_use_unitid, $type, TRUE);
		}
		$data->unit_template = $unit->template;
		//multi url
		if ( $resid !== FALSE ) {
			$data->res_urls = $this->resource_model->get_res_urls($resource_use_unitid,$type,$resid,TRUE);

		}
		$this->load->view('unit/unit_resadd_view', $data);
	}

	function deleteo($resid, $type) {
		//$unit = $this->unit_model->check_unit_editaccess($unitid);
		//Should do some type checking here
		if ( !$this->resource_model->delete(0,$resid,$type) ) {
			echo osa_ajaxmsg(lang('unit_failedtodeletedata'));
      	exit;
		}
	}

	//This is called form the unit body page so all ajax here
	//Deletes one resource
	//TODO: not checking for access if not unit template
	function delete($unitid, $resid, $type) {
		if ( !($unit = osa_get_unit_special($unitid, $type)) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//Check security, this works for all templates.
		if ( !$this->cms_security->validate(CMS_ACTION_EDIT,
					$this->get_template_filename($type), $unit->courseid, $unit->id, $type, $resid) ) {
			echo osa_ajaxmsg(lang('gen_security_no_permission'));
			exit;
		}
		/*
		$unit = FALSE;
		if ( $this->get_template_identifier($type) == CMS_TEMPLATE_UNIT_IDENTIFIER ){
			$unit = $this->unit_model->check_unit_editaccess($unitid);
		}
		*/
		//Handle static resoruces
		if ( $static_unit = $this->check_static_resource($unit, $type) ) {
			$unitid = $static_unit->id;
		}
		if ( !$this->resource_model->delete($unitid,$resid) ) {
			echo osa_ajaxmsg(lang('unit_failedtodeletedata'));
      	exit;
		}
	}

	//Does both edit/update and add to the database
	//Handles the submit from the resource add or edit page
	function updateres($unitid, $type) {
		$max_selects = $this->config->item('cms_max_selects');
		/*
		if ( $unitid != 0 ) {
			if ( $this->get_template_identifier($type) == CMS_TEMPLATE_UNIT_IDENTIFIER ){
				if (!($unit = $this->unit_model->check_unit_editaccess_iframe($unitid)))
					return;
			}
			else {
				//Need access check
				//The following line will call cms_template->type_filename()
				//It is safe to do it here as long as all non-unit templates don't have conflict types
				$unit->template = $this->get_template_filename($type);
				$unit->courseid = 0;
				$unit->id = $unitid;
			}
		}
		else {
			//TODO: Hack, for non-unit resoruces
			//Put type access check here
			$unit->id = 0;
			$unit->courseid = 0;
			//$unit->template = NULL;
			//Setting the template to fasle will get the default template from the factory
			$unit->template = FALSE;
		}*/
		if ( (!$unit = osa_get_unit_special($unitid, $type)) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		$orig_unitid = $unitid;
		//Handle static resoruces
		if ( $static_unit = $this->check_static_resource($unit, $type) ) {
			//This will cause the update to take place with the static unit resource
			$unit = $static_unit;
			$unitid = $static_unit->id;
		}

		$this->load->library('form_validation');
		$this->load->library('unit/unitmain', array('action'=>CMS_ACTION_ADD,'unitid'=>$unitid,
									'courseid'=>$unit->courseid,'unit_template'=>$unit->template));
		$resobj = $this->unitmain->get_resourceobj($type, $unitid);

		//////////////////////////////////////
		//Validation stuff
		$this->form_validation->set_rules('resid', '','trim');
		$this->form_validation->set_rules('ispublic', '','trim');
		/*
		$this->form_validation->set_rules('select1', '','trim');
		$this->form_validation->set_rules('select2', '','trim');
		$this->form_validation->set_rules('select3', '','trim');
		$this->form_validation->set_rules('select4', '','trim');
		$this->form_validation->set_rules('select5', '','trim');
		*/
		/*
		 * CI does not support return of array any more from version 2.0
		 * so, just get from $_REQUEST
		for ($i=1; $i<=$max_selects; $i++) {
			$this->form_validation->set_rules('select'.$i.'[]', '');
		}
		*/
		$this->form_validation->set_rules('benchmarkid', '','trim');
		$this->form_validation->set_rules('schoolid', '','trim');
		//Description box
		if ( $resobj->getval('_text_required') === TRUE )
			$this->form_validation->set_rules('text1', '','trim|required');
		else
			$this->form_validation->set_rules('text1', '','trim');

		//upload file name
		//uploadfilename now contains multiple filenames separate by ',' due to multiple upload change
		if ( $resobj->getval('_upload_flag') === TRUE ) {
			$this->form_validation->set_rules('uploadfilename', '','trim');
		}
		if ( $resobj->getval('_date_flag') === TRUE ) {
			$this->form_validation->set_rules('fielddate', '','trim');
		}
		if ( ! $this->form_validation->run() ) {
      	//Caused the client print an error window with the validation errors.
      	echo osa_ajaxmsg(lang('unit_missingforminput'));
      	exit;
      }

      $resid = set_value('resid');
		//Check security, this works for all templates.
		if ( !$this->cms_security->validate(CMS_ACTION_EDIT,
					$this->get_template_filename($type), $unit->courseid, $orig_unitid, $type, $resid) ) {
			echo osa_ajaxmsg(lang('gen_security_no_permission'));
			exit;
		}

      //multi url
     	$urls_data = $this->get_url_data();
      $uploadfilename = set_value('uploadfilename');

      $data = new stdClass;
      $has_upload = FALSE;
      $benchmarkid = FALSE; $schoolid = FALSE;
      //if we have a resource id then we know this is an edit and not adding a new one
      // if ( ($resid = set_value('resid'))!='' && is_numeric($resid) ) {
      if ( $resid != '' && is_numeric($resid) ) {
      	$data = $this->resource_model->get_resource($unitid, $resid);
      	if (!$data) {
      		$data = new stdClass;
      	}
      	else {
      		$has_upload = $this->resource_model->has_upload($data->id);
      	}
      }
      else {
      	//No resid so this means it is an add and not edit
      	//TODO: This is hard codeded logic that unitid 0 implese ICT...
	      if ( $unitid == 0 ) {
	      	$benchmarkid = set_value('benchmarkid');
	      	if ( !is_numeric($benchmarkid) ) {
	      		echo osa_ajaxmsg(lang('unit_missingforminput'));
	      		exit;
	      	}
	      	$schoolid = set_value('schoolid');
	      	if ( $schoolid == '' || !is_numeric($schoolid) )
	      		$schoolid = FALSE;
	      }
      }

      // $tmp_upload = osa_value($data, 'upload1', FALSE);
      //It is an upload resource page, but no url or upload so spit error
      //When user updates a resource without upload to replace the existing upload
      //then this will not run
      if ( $resobj->getval('_allow_no_uploadandselect') !== TRUE ) { //Allow just the title or not
      	$page_has_noselect = TRUE;
      	for($i=1; $i<=$max_selects; $i++) {
      		if ( $resobj->getval('_select_flag'.$i) !== FALSE ) {
      			$page_has_noselect = FALSE;
      			break;
      		}
      	}
	      if ( strlen($uploadfilename) <= 0 && count($urls_data['urls_add']) <= 0 && count($urls_data['urls_update']) <= 0 &&
	      	  $resobj->getval('_upload_flag') === TRUE &&
	      	  $resobj->getval('_url_flag')  === TRUE &&
	      	  //($tmp_upload === FALSE || is_null($tmp_upload) || $tmp_upload == '') &&
	      	  !$has_upload && $page_has_noselect) {
	      	  /*
	      	  $resobj->getval('_select_flag1') === FALSE && $resobj->getval('_select_flag2') === FALSE &&
	      	  $resobj->getval('_select_flag3') === FALSE && $resobj->getval('_select_flag4') === FALSE &&
	      	  $resobj->getval('_select_flag5') === FALSE) { */
	      	echo osa_ajaxmsg(lang('unit_missingforminput'));
	      	exit;
	      }
		}
      //////////////////////////////////////
		//Process the data after validation
      $hasData = FALSE;

      //Make public
      //DB default is true for all resources without this flag
     // if ( $resobj->getval('_upload_flag') === TRUE ) {
      if ( ($ispublic = set_value('ispublic')) == '1' )
      	$data->ispublic = 1;
      else
      	$data->ispublic = 0;
		//}

      //Description
      if ( ($text1 = set_value('text1')) != '' ) {
			//$data->text1 = $this->_text_newline_bug_hack($text1);
			$data->text1 = $text1;
			$hasData = TRUE;
      }
      //Drop down options, save the submitted selections and pass to the view
      $selections = array();
      for ( $i=1; $i<=$max_selects; $i++) {
      	$seltag = "select$i";
      	//We used to use the CI set_value() function to get the arrays but CI changed
      	//its code to not return arrays so get directly form REQUEST
      	$tmp_select = osa_value($_REQUEST, $seltag, false);
      	if ( is_array($tmp_select) )  {
      		$selections[$i] = $tmp_select;
      	}
      	/* This is the old code before the support of multiple selects on the upload popup
      	if ( $resobj->getval($selflag) !== FALSE && ($selvalue = set_value($seltag.'[]')) != '' &&
      			is_array($selvalue)) {
      			//is_array($selvalue) && $selvalue > 0) {
      		//value 0 is the "Choose..." option
      		//$data->$seltag = $selvalue;
      		$selections[$i] = $selvalue;
      	}
      	*/
      }
      if ( count($selections) > 0 ) {
      	$data->selects_data = $selections;
      	$hasData = TRUE;
      }

      //Upload file
      $origfile = FALSE;
      $realfile = FALSE;
      $tmpfile = FALSE;
      $tmpfilearray = array();
      $uploadarray = array();
      $upload_sep = CMS_UPLOAD_SEPARATOR;
      if (strlen($uploadfilename)>0) {
      	$upfiles = $uploadfilename;
      	$tmpfile = strtok($upfiles, $upload_sep);
      	//Create array of all tmp files for cleanup purpose
      	while ($tmpfile !== FALSE) {
      		//tmp upload files don't use the resid therefore all tmp upload file belonging to the same type
      		//would use the same directory. The reason is because no resid for new resource when doing actual upload
      		$tmpfile = $this->_escape_filename($tmpfile);
      		$tmpfile = osa_unituploaddir($this->config->item('cms_resource_uploadtmpfolder'),
	      				  $unit->courseid, $unitid, $type) . '/' . $tmpfile;
	      	$tmpfilearray[] = array('fullpath' => $tmpfile);
      		$tmpfile = strtok($upload_sep);
      	}

      	$uploadfilename = strtok($upfiles, $upload_sep);
      	//Loop thru the filenames and create an array containging all the filenames and their size
      	//The files will also be copied form the tmp folder to the actual unit/type folder
      	$tmpfilefolder = osa_unituploaddir($this->config->item('cms_resource_uploadtmpfolder'),
	      				$unit->courseid, $unitid, $type);
	      $realfilefolder = osa_unituploaddir($this->config->item('cms_resource_uploadfolder'),
	      				  		$unit->courseid, $unitid, $type, TRUE);
	      if ( !$tmpfilefolder || !$realfilefolder ) {
      		echo osa_ajaxmsg(lang('unit_upload_notcopied'));
      		exit;
      	}
      	while ($uploadfilename !== FALSE) {
	      	/*if ( !is_null($data->upload1) && $data->upload1 != '' ) {
	      		$origfile = $realfilefolder . '/' . $data->upload1;
	      		$deletefile = $realfilefolder . '/deleted/' . $data->upload1;
	      	}*/
      		$uploadfilename = $this->_escape_filename($uploadfilename);
	      	$tmpfile = $tmpfilefolder . '/' . $uploadfilename;

	      	//$data contains resource id if editing existing resource
	      	if ( property_exists($data, 'id') ) {
		      	$realfile = $realfilefolder . "/{$data->id}/{$uploadfilename}";
		      	$dupfile = $uploadfilename;
		      	while (TRUE) {
		      		if ( !is_file($realfile) ) {
		      			$uploadfilename = $dupfile;
		      			break;
		      		}
		      		$dupfile = 'Copy_' . $dupfile;
		      		$realfile = $realfilefolder . "/{$data->id}/{$dupfile}";
		      	}
	      	}

	      	if ( !is_file($tmpfile) ) {
	      		echo osa_ajaxmsg(lang('unit_upload_notfound'));
	      		exit;
	      	}
	      	/*if ( $origfile ) {
	      		if ( is_file($deletefile) ) {
	      			//unlink($deletefile);
	      			osa_rename($deletefile, $deletefile . '_' . time());
	      		}
	      		osa_rename($origfile, $deletefile);
	      	}*/
	      	//@chmod($tmpfile, 0111);
	      	//if (!osa_rename($tmpfile, $realfile)) {
	      		/*if ( $origfile && is_file($deletefile) )
	      			osa_rename($deletefile, $origfile);*/
	      		/*osa_deletefiles($uploadarray);
	      		osa_deletefiles($tmpfilearray);
	      		echo osa_ajaxmsg(lang('unit_upload_notcopied'));
	      		exit;
	      	}*/
	      	$filesize = filesize($tmpfile);
	      	//$data->uploadsize1 = $filesize;
	      	//$data->upload1 = $uploadfilename;
	      	//Can't assign actual file path until we have a resid, this is the case for add new resource
	      	$uploadarray[] = array('name' => $uploadfilename,'size' => $filesize,
	      							'tmpfile'=>$tmpfile, 'filepath_part'=>$realfilefolder);
	      		//'fullpath' => $realfile, 'size' => $filesize);
	      	$hasData = TRUE;
	      	$uploadfilename = strtok($upload_sep);
      	}
      }

      $deleteids = osa_get_dynpost_values('delfile', FALSE);
      $deletearray = array();
      if ($deleteids !== FALSE && is_numeric($resid) ) {
      	$uploadfolder = osa_unituploaddir($this->config->item('cms_resource_uploadfolder'),
	      				  		$unit->courseid, $unitid, $type, TRUE);
	      $delete_uploads = $this->resource_model->get_uploads_byids($deleteids, $resid);
	      if ($delete_uploads !== FALSE) {
	      	foreach ($delete_uploads as $upload) {
	      		//osa_deletefiles() uses fullpath index for file path
	      		$deletearray[] = array('fullpath'=>$uploadfolder . "/{$upload->resourceid}/{$upload->filename}");
	      	}
	      }
      }

      //////////////////////////////////////////////
      //Do insert or update now
      if ( $hasData ) {
      	$user = $this->login_model->getLogin();
      	$date = set_value('fielddate');
      	if (isset($date) && $date != FALSE)
      		 $data->date1 = $date;
			$data->unitid = $unit->id;
			$data->courseid = $unit->courseid;
			$data->creatorid = $user->id;
			$data->type = $type;
			if ( is_numeric($resid) ) { //do update becuase we have a resource id
				unset($data->id);
				unset($data->creatorid);
				if ( !$this->resource_model->update($data, $unitid, $resid, $uploadarray, $deleteids) ) {
					/*if ( $origfile )
						osa_rename($deletefile, $origfile);*/
					//osa_deletefiles($uploadarray);
					osa_deletefiles($tmpfilearray);
					echo osa_ajaxmsg(lang('unit_failedtoadddata'));
	      		exit;
				}
				//Move the files now, if error happens here then it will be out of sync with the database
				//Should move the file move into the Modle later. The same for insert below
				foreach($uploadarray as $tmpfile) {
					@osa_mkdir($tmpfile['filepath_part'] . "/{$resid}");
					@osa_rename($tmpfile['tmpfile'], $tmpfile['filepath_part'] . "/{$resid}/{$tmpfile['name']}");
				}
				//multi url
				$this->resource_model->update_res_urls($resid,$urls_data);
			}
			else { //do insert if no resource id
				if ( ($resid = $this->resource_model->insert($data, $uploadarray, $benchmarkid, $schoolid)) === FALSE ) {

					//Clean up uploaded file if insert fails
					/*if ( $realfile ) {
						if ( is_file($realfile) )
							unlink($realfile);
						if ( is_file($tmpfile) )
						unlink($tmpfile);
					}*/
					//osa_deletefiles($uploadarray);
					osa_deletefiles($tmpfilearray);
					echo osa_ajaxmsg(lang('unit_failedtoadddata'));
	      		exit;
				}
				//multi url
				$this->resource_model->insert_res_urls($resid,$urls_data);
				//Move the files now
				foreach($uploadarray as $tmpfile) {
					@osa_mkdir($tmpfile['filepath_part'] . "/{$resid}");
					@osa_rename($tmpfile['tmpfile'], $tmpfile['filepath_part'] . "/{$resid}/{$tmpfile['name']}");
				}
			}
      }
      //The only way we get here is becuase of no insert or update, or successful insert or update
      //So, we do file delete here if any. $deletearray has data only for update page
      osa_deletefiles($deletearray);
	}


	function oneread($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_internalservererror')));
			return;
		}
		if ( !($unit = $this->unit_model->get_unit_any($unitid) )) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_internalservererror')));
			return;
		}
		$this->load->model('course/course_model');
		if ( !$this->course_model->isMyCourse(FALSE, $unit->courseid) &&
			  !$this->access_model->checkaccess_any(array('admin_unit_write', 'admin_unit_read'),FALSE,FALSE,FALSE) ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_no_permission_ajaxmsg')));
			return;
		}

		$this->load->library('unit/unitmain', array('action'=>CMS_ACTION_READ,'unitid'=>$unitid, 'courseid'=>$unit->courseid));
		$resobj = $this->unitmain->get_resourceobj($type, $unitid);
		//$template = $resobj->template_data();
		if ( !$resobj ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('gen_internalservererror')));
			return;
		}

		$resourcedb = $this->resource_model->get_resource_single($unitid, $type);
		if ( !$resourcedb ) {
			$this->load->view('unit/unit_htmlerror_view', array('errormsg'=>$resobj->getval('_nodatamsg')));
			return;
		}
		$data->db = $resourcedb;
		$data->template = $resobj;
		if ( isset($resourcedb->id) && $resourcedb->id !== FALSE ) {
				$data->resobj = $this->resource_model->get_resource($unitid,$resourcedb->id);
				$data->uploadfiles = $this->resource_model->get_uploads_byresource($resourcedb->id);
				//multi url
				$data->res_urls = $this->resource_model->get_res_urls($unitid,$type,$resourcedb->id,TRUE);
		}
		$this->load->view('unit/unit_resread_view', $data);
	}

	//$cachebust does nothing except to fool the browser not to cache page
	function upload($unitid, $type, $cachebust='') {
		set_time_limit($this->config->item('cms_upload_timeout'));
		if ( $unitid != 0 ) {
			if ( $this->get_template_identifier($type) == CMS_TEMPLATE_UNIT_IDENTIFIER ){
				if (!($unit = $this->unit_model->check_unit_editaccess_iframe($unitid))) {
					$this->osa_uploader->error(lang('unit_upload_errormsg'));
					exit;
				}
			}
			else{
				$unit->courseid = 0;
			}
		}
		else {
			//Put type checking here
			$unit->id = 0;
			$unit->courseid = 0;
		}
		$this->load->library('cms/osa_uploader', array('unitid'=>$unitid, 'type'=>$type, 'courseid'=>$unit->courseid));
		$uploadfolder = osa_unituploaddir($this->config->item('cms_resource_uploadtmpfolder'), $unit->courseid, $unitid, $type, TRUE);
		if ( !$uploadfolder ) {
			$this->osa_uploader->error(lang('unit_upload_errormsg'));
			exit;
		}
		$ret = $this->osa_uploader->upload($uploadfolder);
		echo $ret;
		exit;
	}

	/*
	 * File download. Not direct download so we have some access restrictions
	 * Have to add code to check public access and user permission
	 * $filename is not really needed, but to make it diffcult for people to donwload anything they want
	 */
	//function file($courseid, $unitid, $type, $filename) {
	function file($uploadid, $filename_hash, $filename) {
		/*$dir = osa_unituploaddir($this->config->item('cms_resource_uploadfolder'),
					$courseid, $unitid, $type);
		if (!$dir)
			return;
			*/
		$fileinfo = $this->resource_model->download_info($uploadid);
		if ( $fileinfo === FALSE )
			return;
		//$filename= urldecode(trim($filename));
		//$filename = str_replace(CMS_PLUS_HACK_STR,'+', $filename);
		//Fix (issue: 85)
		$filename = $fileinfo->filename;
		if ( $filename_hash != osa_filename_hash($filename) ){
			return;
		}
		$filename = html_entity_decode(rawurldecode(trim($filename)));
		$dir = osa_unituploaddir_res($fileinfo);
		if ($dir === FALSE)
			return;
		$file = $dir . "/{$fileinfo->filename}";
		if (!is_file("$file")) {
			return;
		}
		 header("Content-type: application/force-download; charset: utf-8;");
	    header("Content-Transfer-Encoding: Binary");
	    header("Content-length: ".filesize($file));
	    //IE can't handle non-ebnglish filename so rely on the download URL to supply the filename and not here
	    //header("Content-disposition: attachment; filename=\"".basename($file)."\"");
	    header("Content-disposition: attachment");
	    readfile("$file");
	    exit;
		/*
		$dir="/path/to/file/";
		if (isset($_REQUEST["file"])) {
			$file=$dir.$_REQUEST["file"];
		    header("Content-type: application/force-download");
		    header("Content-Transfer-Encoding: Binary");
		    header("Content-length: ".filesize($file));
		    header("Content-disposition: attachment; filename=\"".basename($file)."\"");
		    readfile("$file");
		}
		else {
		    echo "No file selected";
		}
		*/
	}

	function _escape_filename($filename) {
		$mod_filename = html_entity_decode($filename, ENT_QUOTES);
		//osa_errorlog($mod_filename);
		return $mod_filename;
	}
	//multi url
	private function get_url_data(){
		$data = array();
      // loop  check box is true
      $urls_delete = array();
      $chk_urls = array();
      $_delurl = FALSE;
      if ( isset($_POST['delurl_']) ) {
      $_delurl = $_POST['delurl_'];
      }
      if ($_delurl){
	      foreach ($_delurl as $index=>$value) {
	      	if ( is_array($value))  {
		      	foreach ($value as $key=>$var){
		      		if ($var == 'on'){
		      			$chk_urls[]= $index;
		      			$urls_delete[] = $key;
		      		}
		      	}
	      	}
	      	else{
	      		if ($value == 'on'){
		      		$chk_urls[]= $index;
		      	}
	      	}
	      }
      }
		//loop urls
		$urls_add = array();
		$urls_update = array();
		$_urls = FALSE;
		if ( isset($_POST['url_']) ) {
	 	$_urls = $_POST['url_'];
		}
	 	if ( $_urls ){
	      foreach ($_urls as $index=>$value) {
	      	if(!in_array($index,$chk_urls)){
		      	if ( is_array($value))  {
		     			foreach ($value as $key=>$var){
		     				$urls_update[$key] = trim($var);
		     			}
		      	}
		      	else{
		      		if (isset($value) && $value != FALSE)
		      			$urls_add[] = trim($value);
		      	}
	      	}
	      }
	 	}

      $data['urls_add']= $urls_add;
      $data['urls_update']= $urls_update;
      $data['urls_delete']= $urls_delete;
      return $data;
	}

	//Function get template identifier by type.
	private function get_template_identifier($type) {
		if (!isset($type) && $type == FALSE){
			osa_errorlog(__METHOD__ . " -  Invalidate Type in Function get templateidentifier ", $type);
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		$templateid = $this->cms_template->type_templateid($type);
		if ( $templateid === FALSE ){
			osa_errorlog(__METHOD__ . " -  Invalidate template identifier in Function get templateidentifier ", $templateid);
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		return $templateid;
	}

	//Function get templatefilename by type.
	private function get_template_filename($type) {
		if (!isset($type) && $type == FALSE){
			osa_errorlog(__METHOD__ . " -  Invalidate Type in Function get templatefilename ", $type);
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		$filename = $this->cms_template->type_filename($type);
		if ( $filename === FALSE ){
			osa_errorlog(__METHOD__ . " -  Invalidate template filename in Function get templatefilename ", $filename);
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		return $filename;
	}

	//Checks for static type and returns the static unit DB row if there is one
	private function check_static_resource($unit, $type) {
		if ( !osa_is_int_one($type) || !$this->cms_template->is_static($type) ) {
			return FALSE;
		}
		if ( !is_object($unit) && !isset($unit->groupid) && osa_is_int_one($unit->groupid) ) {
			return FALSE;
		}
		return $this->unit_model->get_unit_any($unit->groupid);
	}

	/*
	//Function get template identifier sort by type.
	private function get_template_identifier_sort($type) {
		$this->load->library('cms/cms_template/cms_template');
		if (!isset($type) && $type == FALSE){
			osa_errorlog(__METHOD__ . " -  Invalidate Type in Function get templateidentifier ", $type);
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}
		return $this->cms_template->type_templateid($type);
	}
	*/

	//(issue: 84) Resource edit always adds new line
	//This fix will cause an text entry to never have a new line at the end. It is like running trim at the end everytime
/*
	private function _text_newline_bug_hack($text) {
		$bad_text = '&lt;br /&gt;';
		$bad_text_len = 12;
		$text_len = strlen($text);
		if ( $text_len <= ($bad_text_len+1) ) {
			return $text;
		}
		$last12 = strtolower(substr($text, $text_len-$bad_text_len, $text_len-1));
		if ( $last12 == $bad_text ) {
			return substr($text, 0, $text_len-$bad_text_len);
		}
		return $text;
	} */
}
?>