<?
include_once('baseModelPMS.php');

class systemModel extends baseModelPMS {


	/* ********************************************************************************
	Get table size
	******************************************************************************** */

	function getlist_tabledata(){

		$listdata=array();

		$sql="Show table status";
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select welcome notes
	******************************************************************************** */

	function getlist_welcomenotes(){

		$listdata=array();

		$sql="Select * from foreword_details";
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select the last inserted welcome note
	******************************************************************************** */

	function getdata_welcomenote(){

		$data=array();

		$sql="Select * from foreword_details order by foreword_date DESC limit 0,1";
		$data=$this->getextendedrow($sql);
		return $data;
	}


	/* ********************************************************************************
	Select list of news items
	******************************************************************************** */

	function getlist_news(){

		$listdata=array();

		$sql="Select * from news_details order by news_date DESC";
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select a specific news item
	******************************************************************************** */

	function getdata_news($newspkey){

		$data=array();

		$sql="Select * from news_details where news_pkey='".$newspkey."'";
		$data=$this->getextendedrow($sql);
		return $data;
	}


	/* ********************************************************************************
	Select list of audit trail items
	******************************************************************************** */

	function getlist_audittrail($userpkey="",$startdate="",$starttime="",$enddate="",$endtime=""){

		$listdata=array();

		if ($startdate!="") {
			if ($starttime!="") {
				$fullstarttime=$startdate." ".$starttime.":00";
			} else {
				$fullstarttime=$startdate." 00:00:00";
			}
		} else {
			if ($starttime!="") {
				$fullstarttime=date('d-m-Y')." ".$starttime.":00";
			} else {
				$fullstarttime=date('d-m-Y H:i').":00";
			}
		}
		if ($enddate!="") {
			if ($endtime!="") {
				$fullendtime=$enddate." ".$endtime.":59";
			} else {
				$fullendtime=$enddate." 23:59:59";
			}
		} else {
			if ($endtime!="") {
				$fullendtime=date('d-m-Y')." ".$endtime.":59";
			} else {
				$fullendtime=date('d-m-Y H:i').":59";
			}
		}

		if (($startdate=="")&&($starttime=="")&&($enddate=="")&&($endtime=="")) {
			$sql="Select AT.*, GU.user_name from system_audittrail AT left join general_users GU on AT.audit_userpkey=GU.user_pkey where GU.user_pkey like '".$userpkey."%' order by AT.audit_datetime DESC LIMIT 100";
		} else {
			$sql="Select AT.*, GU.user_name from system_audittrail AT left join general_users GU on AT.audit_userpkey=GU.user_pkey where GU.user_pkey like '".$userpkey."%' and AT.audit_datetime>='".converttounixfull($fullstarttime)."' and AT.audit_datetime<='".converttounixfull($fullendtime)."' order by AT.audit_datetime DESC LIMIT 100";
		}
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select list of user activities (similar to audit trail)
	******************************************************************************** */

	function getlist_useractivities($userpkey="",$startdate,$enddate){

		$listdata=array();

		$sql="Select AT.*, GU.user_name from system_audittrail AT left join general_users GU on AT.audit_userpkey=GU.user_pkey where GU.user_pkey like '".$userpkey."%' and AT.audit_datetime>='".$startdate."' and AT.audit_datetime<='".$enddate."' order by AT.audit_datetime DESC";
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select list of user activities (by group!)
	******************************************************************************** */

	function getlist_groupactivities($grouppkey="",$startdate,$enddate){

		$listdata=array();

		$sql="Select AT.*, GU.user_name, SP.staff_name from system_audittrail AT left join general_users GU on AT.audit_userpkey=GU.user_pkey left join staff_profiles SP on GU.user_pkey=SP.staff_userpkey where GU.user_grouppkey like '".$grouppkey."%' and AT.audit_datetime>='".$startdate."' and AT.audit_datetime<='".$enddate."' order by AT.audit_datetime DESC";
		$listdata=$this->getextendedrows($sql);
		return $listdata;
	}


	/* ********************************************************************************
	Select a specific audit trail item
	******************************************************************************** */

	function getdata_audittrail($auditpkey){

		$data=array();

		$sql="Select AT.*, GU.user_name from system_audittrail AT left join general_users GU on AT.audit_userpkey=GU.user_pkey where AT.audit_pkey='".$auditpkey."'";
		$data=$this->getextendedrow($sql);
		return $data;
	}


	/* ********************************************************************************
	Select system settings
	******************************************************************************** */

	function getdata_systemsettings() {

		$tempdata=array();
		$listdata=array();

		$sql="Select * from system_settings";
		$tempdata=$this->getextendedrows($sql);
		foreach ($tempdata as $mydata) {
			$mysettingname=$mydata['system_settingname'];
			$listdata[$mysettingname]=$mydata['system_settingvalue'];
		}
		return $listdata;
	}


	/* FUNCTIONS TO INSERT RECORDS */


	/* ********************************************************************************
	Insert/Create a new foreword
	> 
	******************************************************************************** */

	function insertdata_foreword($foreword_pkey, $foreword_text, $foreword_background, $foreword_photo) {

		// convert params..
		$foreword_pkey=md5(microtime());
		$foreword_date=gettimestamp();

		// upload file (currently no caption or desc)..
		$backgroundpkey = image_uploadimage($_FILES['foreword_background']['name'],$_FILES['foreword_background']['tmp_name'],"","");
		$photopkey = image_uploadimage($_FILES['foreword_photo']['name'],$_FILES['foreword_photo']['tmp_name'],"","");

		// update..
		$sa = $this->add_data("Welcome Note [Add]", "foreword_details", "foreword_pkey, foreword_text, foreword_backgroundpkey, foreword_photopkey, foreword_date",
				"'".$foreword_pkey."','".$foreword_text.
				"','".$backgroundpkey."','".$photopkey."','".$foreword_date."'");

		// return result..
		if ($sa==1) {
			return $foreword_pkey;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Insert/Create a news item
	> 
	******************************************************************************** */

	function insertdata_news($news_pkey, $news_date, $news_title, $news_summary, $news_text, $news_picture, $news_alignment, $news_relatedurl) {

		// convert params..
		$news_pkey=md5(microtime());
		if ($news_date=="") { $realdate=gettimestamp(); } else { $realdate=converttounix($news_date); }
		if ($news_alignment=="left") { $realalignment = 1; } else { $realalignment = 2; }

		// upload file (currently no caption or desc)..
		$imagepkey = image_uploadimage($_FILES['news_picture']['name'],$_FILES['news_picture']['tmp_name'],"","");

		// update news..
		$sa = $this->add_data("News Item [Add]", "news_details", "news_pkey, news_date, news_title, news_summary, news_text, news_picture, news_picturealignment, news_relatedurl",
				"'".$news_pkey."','".$realdate."','".$news_title.
				"','".$news_summary."','".$news_text."','".$imagepkey."',".$realalignment.
				",'".$news_relatedurl."'");

		// return result..
		if ($sa==1) {
			return $news_pkey;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Insert/Create system settings (delete all first?)
	******************************************************************************** */

	function insertdata_systemsettings($fullsettings,$fullvalues) {

		// delete existing..
		$sa = $this->delete_data("System Settings [Delete]", "system_settings", "");

		// insert settings..
		$mysettings = explode("|",$fullsettings);
		$myvalues = explode("|",$fullvalues);
		$myindex = 0;

		foreach ($mysettings as $mysetting) {
			// convert to unix if date fields (this is a HACK!!)
			if ($mysetting=="system_gui_logincountdate") $myvalues[$myindex]=converttounix($myvalues[$myindex]);
			$sa = $this->add_data("System Settings [Add]", "system_settings", "system_settingname, system_settingvalue", "'".$mysetting."','".$myvalues[$myindex]."'");
			$myindex++;
		}

		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* FUNCTIONS TO UPDATE RECORDS */


	/* ********************************************************************************
	Update/Override an existing news item
	> 
	******************************************************************************** */

	function updatedata_news($news_pkey, $news_date, $news_title, $news_summary, $news_text, $news_picture, $news_alignment, $news_relatedurl) {

		// convert params..
		if ($news_date=="") { $realdate=gettimestamp(); } else { $realdate=converttounix($news_date); }
		if ($news_alignment=="left") { $realalignment = 1; } else { $realalignment = 2; }

		// upload file (currently no caption or desc)..
		$imagepkey = image_uploadimage($_FILES['news_picture']['name'],$_FILES['news_picture']['tmp_name'],"","");

		// update news..
		if ($imagepkey!="") {
			$sa = $this->update_data("News Item [Edit]", "news_details", 
				"news_date = '".$realdate.
				"', news_title = '".$news_title.
				"', news_summary = '".$news_summary.
				"', news_text = '".$news_text.
				"', news_picture = '".$imagepkey.
				"', news_picturealignment = ".$realalignment.
				", news_relatedurl = '".$news_relatedurl."'",
				"where news_pkey = '".$news_pkey."'");
		} else {
			$sa = $this->update_data("News Item [Edit]", "news_details", 
				"news_date = '".$realdate.
				"', news_title = '".$news_title.
				"', news_summary = '".$news_summary.
				"', news_text = '".$news_text.
				"', news_picturealignment = ".$realalignment.
				", news_relatedurl = '".$news_relatedurl."'",
				"where news_pkey = '".$news_pkey."'");
		}

		// return result..
		if ($sa==1) {
			return $news_pkey;
		} else {
			return false;
		}
	}


	/* FUNCTIONS TO DELETE RECORDS */


	/* ********************************************************************************
	Delete an existing news item
	> 
	******************************************************************************** */

	function deletedata_news($news_pkey) {

		// TODO: delete corresponding picture and picture record!!

		// delete news..
		$sa = $this->delete_data("News Item [Delete]", "news_details", "where news_pkey = '".$news_pkey."'");

		// return result..
		if ($sa==1) {
			return $news_pkey;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Delete audit trail items.. only called by cls_purge!
	>
	******************************************************************************** */

	function deletedata_audittrail($purge_time) {

		// delete.. (temporarily suspend userpkey)

		$mypkey=$_SESSION['Xuserpkey'];
		$_SESSION['Xuserpkey']="System";
		$sa = $this->delete_data("Audit Trail [Delete]", "system_audittrail", "where audit_datetime < ".$purge_time);
		$_SESSION['Xuserpkey']=$mypkey;

		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Delete all items in page_contents (and excerpts in page_details??)
	Only called by the purgedb function..
	>
	******************************************************************************** */

	function purgedata_db() {

		// delete news..
		$sa = $this->delete_data("Page Contents [Delete]", "page_content", "");

		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Delete a page from the database
	>
	******************************************************************************** */

	function purgepage_db($page_pkey, $userpkey) {

		// delete news..
		$sa = $this->delete_data("Page Contents [Delete]", "page_content", "where page_pkey='".$page_pkey."'");

		require_once('browserModel.php');
		$mybrowserModel = new browserModel;

		// update history..
		$sa2 = $mybrowserModel->insertdata_pagehistory($page_pkey, "", $userpkey, 6);

		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Delete all items in cache
	Only called by the purgecache function..
	>
	******************************************************************************** */

	function purgedata_cache() {

		$systemsettings_data = $this->getdata_systemsettings();

		$cachepath = $systemsettings_data['system_cache_path'];

		// get list of files..
		$cachefiles=array();
		$cachepath = rtrim($cachepath, "/")."/";
		if ($handle = opendir($cachepath)) {
			while (($file = readdir($handle)) !== false) {
				if (($file != ".") && ($file != "..")) {
					if (is_dir($cachepath.$file."/")) {
						$cachefiles[] = $file;
					}
				}
			}
			closedir($handle);
		}

		// check file modified time..
		foreach ($cachefiles as $cachefile) {
			// unlink($cachefile);
			$this->purge_dir($cachepath.$cachefile."/");
			// what about page_contents table?
		}

		$sa=1;
		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Delete a page from the cache
	> TODO: delete related pages
	******************************************************************************** */

	function purgepage_cache($page_pkey) {

		$systemsettings_data = $this->getdata_systemsettings();

		$cachepath = $systemsettings_data['system_cache_path'];

		// get list of files..
		$cachefiles=array();
		$cachepath = rtrim($cachepath, "/")."/";
		$cachefile = $cachepath.$page_pkey;
		// unlink($cachefile);
		$this->purge_dir($cachefile."/");

		$sa=1;
		// return result..
		if ($sa==1) {
			return true;
		} else {
			return false;
		}
	}


	/* ********************************************************************************
	Recursive function to delete directory and subdirs..
	******************************************************************************** */

	function purge_dir($dirpath) {

		$files = glob( $dirpath . '*', GLOB_MARK ); 
		foreach( $files as $file ){ 
			if( substr( $file, -1 ) == '/' ) 
				purge_dir( $file ); 
			else 
				unlink( $file ); 
		} 
		if (is_dir($dirpath)) rmdir( $dirpath ); 
    
	} 

}
?>
