<?

	require_once("class.dbconnection_v1_0.php");

/*	$globalSettings_backup = $globalSettings;
	require_once('mymanager_settings.php');
	$globalSettings = $globalSettings_backup;
*/

	class interChange_ContentCore {


		// Constructor
		// $mod_code	- The module code from the calling module.
		// $org_id	- The identifier from the calling organization.
		// $lng_code	- The ISO language code.
		function interChange_ContentCore($mod_code, $org_id, $lng_code, $pro_code){
			global $globalSettings;

			// Check variables
			if (!$mod_code)	die ("<b>Interchange:</b> no module code supplied");
			//2004-03-11 TK -> effen uit anders kunnen er geen XSL's worden geupload in de CE.
			//if (!$org_id)	die ("<b>Interchange:</b> no organization id supplied");
			if (!$lng_code)	die ("<b>Interchange:</b> no language code supplied");

			// Set defaults
			$this->_par_code			= 'AMGATE';
			$this->_pro_code    		= $pro_code;
			$this->_mod_code    		= strToUpper($mod_code);
			$this->_org_id	    		= $org_id;
			$this->_lng_code    		= strToLower($lng_code);

			// Get module settings
//			$this->_settings = &getModuleVariables(true, 'TICH0105');

			// Create database object
			$this->_db = new Connection($globalSettings->tich0105->db->connectionString, DB_TYPE_MYSQL);

			// Initialize content core (creates initial references to local objects)
			$this->_setContentCore('DCC', $this->_pro_code, $this->_org_id);

		}

		function _setContentCore($cc_code = null, $pro_code = null, $org_id = null) {
///			echo "_setContentCore($cc_code, $pro_code, $org_id)<br>";


			// Use local core
			if ($pro_code && $pro_code == $this->_pro_code) {
			
				if (!isset($this->_contentcore->pro_code) || $this->_contentcore->pro_code != $this->_pro_code) {

					$this->_contentcore->code = $cc_code;
					$this->_contentcore->pro_code = $this->_pro_code;
					$this->_contentcore->org_id = (is_numeric($org_id) ? $org_id : $this->_org_id);
					$this->_contentcore->db = &$this->_db;
					$this->_contentcore->settings = &$this->_settings;				

				}

			}
		}

		// function _setContentCoreByCC
		// This function sets the global variables _db_sel and _org_id_sel to the
		// selected content core, if not already set. Functions depending on this
		// information will automaticly use the right content core.
		// $content_core	-	The code of the content core (DCC) is the default content core.
		function _setContentCoreByCC ($content_core) {

			$this->_setContentCore($content_core);

		}

		// function _getControllerInformation
		// This function gets all controller information by storage identifcation information.
		// Controller information can not be acquired by uri, because multiple content controllers
		// can point to the same resource.
		// $tablename		-	Name of the table of the content user. Is used for controlling the resource.
		// $var_id			-	Id of the content user. Is used for controlling the resource (Optional when var_id is used).
		// $var_code			-	Code of the content user. Is used for controlling the resource (Optional when var_code is used).
		// $attribute		-	Name of the field in the table of the content user. Is used for controlling the resource.
		function &_getControllerInformation($tablename, $var_id = null, $var_code = null, $attribute = null) {

			// Get information from controller
			$rs = $this->_db->Query("
				select 
					* 
				from 
					tbl_ich_trc_resourcecontroller 
				where 
					trc_lng_code='".$this->_lng_code."' and 
					trc_pro_code='".$this->_pro_code."' and 
					trc_mod_code='".($tablename == "tbl_ich_links" || $tablename == "tbl_ich_trc_dossiers" ? $_SESSION["session_ich_version"] : $this->_mod_code)."' and 
					trc_org_id=".$this->_org_id." and 
					trc_tablename='".$tablename."' and 
					trc_attribute='".$attribute."' and 
					trc_var_id = '".($var_id ? $var_id : '')."' 
					".($var_code ? "and trc_var_code = '".sqlSafe($var_code, 50)."'" : ''));

			$result = $rs->Row();
			$rs->Close();

			// Return
			return $result;

		}

		// function newURI
		// This function returns a new URI (Unique Resource Identifier)
		function newURI(){

			$this->_db->Execute("INSERT INTO tbl_ich_trc_uri_sequence (seq_createdate) VALUES (current_timestamp)");
			$result = mysql_insert_id($this->_db->Connection);

			return $this->_par_code."_".$this->_pro_code."_".$this->_org_id."_TICH_R".$result.rand(1, 9999999999);
		}

		// function _setContentCoreByURI
		// This function sets the global variables _db_sel and _org_id_sel to the
		// content core where the URI belongs to. Functions depending on this
		// information will automaticly use the right content core.
		// $uri	-	The Unique Resource Identifier of a resource.
		function _setContentCoreByURI($uri) {

			$array = explode("_", $uri);
			$this->_setContentCore(null, $array[1], $array[2]);
			return $this->_contentcore->code;

		}

		// function _killController
		// This function removes a controller
		// $native_trc_id	-	Identifier of the native controller
		// $foreign_trc_id	-	Identifier of the foreign controller (Optional)
		// $uri				-	Unique identifier of the resource.
		function _killController($native_trc_id, $foreign_trc_id =null, $uri = null) {

			if ($native_trc_id) {

				// Delete native controller
				$this->_db->Execute("DELETE FROM tbl_ich_trc_resourcecontroller WHERE trc_id=".$native_trc_id);

				// Check for foreign controller
				if ($foreign_trc_id && $uri){

					// Set connection to the right content core
					$this->_setContentCoreByURI($uri);

					// Delete foreign controller
					$this->_contentcore->db->Execute("DELETE FROM tbl_ich_trc_resourcecontroller WHERE trc_id=".$foreign_trc_id);

				}

			}

		}

		// function _putControllerInformation
		// This function saves the content control data into the content core tables
		// $uri				-	Unique Recource Identifier
		// $trc_owner		-	Is the now inserted controller also the owner of the resource: Y | N
		// $trc_tablename	-	Name of the table of the content user. Is used for controlling the resource.
		// $trc_var_id		-	Id of the content user. Is used for controlling the resource (Optional when var_id is used).
		// $trc_var_code		-	Code of the content user. Is used for controlling the resource (Optional when var_code is used).
		// $trc_attribute	-	Name of the field in the table of the content user. Is used for controlling the resource.
		// $update			-	true | false - Should the controllers xsl style sheet be updated or should a new controller be inserted.
		// $uri_xsl			-	The Unique Recource Identifier of the XSL Style sheet.
		function _putControllerInformation($uri, $trc_owner, $trc_tablename, $trc_var_id, $trc_var_code, $trc_attribute, $update, $uri_xsl = null) {

			// Check if content is available
			if (!$uri) die("<B>Interchange: Storage terminated, no uri available</B>");

			// Get controller id
			$trc = $this->_getControllerInformation($trc_tablename, $trc_var_id, $trc_var_code, $trc_attribute);

			// Set the correct content core
			$this->_setContentCoreByURI($uri);

			// Controller types:
			// N - Native
			// D - Director
			// F - Foreign
			if (is_numeric($trc['TRC_ID'])) {

				$sql = "update 
							tbl_ich_trc_resourcecontroller 
						set 
							trc_xsl_uri = ".($uri_xsl ? "'".$uri_xsl."'" : "NULL")."
						where 
							trc_id = ".$trc['TRC_ID'];

				// Update Native controller
				$this->_db->Execute($sql);

				// Update Foreign controller (if exists)
				if ($this->_contentcore->pro_code != $this->_pro_code) $this->_contentcore->db->Execute($sql);

			} else {

				$sql = "
					insert into tbl_ich_trc_resourcecontroller (
						trc_createdate,
						trc_changedate,
						trc_mod_code,
						trc_pro_code,
						trc_cor_code,
						trc_type,
						trc_trc_id,
						trc_org_id,
						trc_lng_code,
						trc_rsc_uri,
						trc_xsl_uri,
						trc_owner,
						trc_tablename,
						trc_var_id,
						trc_var_code,
						trc_attribute
					) values (
						current_timestamp,
						current_timestamp,
						'".($trc_tablename == "tbl_ich_links" || $trc_tablename == "tbl_ich_trc_dossiers" ? $_SESSION["session_ich_version"] : $this->_mod_code)."',
						'".$this->_pro_code."',
						'".$this->_contentcore->code."',
						'%trc_type',
						%trc_trc_id,
						".$this->_org_id.",
						'".$this->_lng_code."',
						'".$uri."',
						".($uri_xsl ? "'".$uri_xsl."'" : "NULL").",
						'".($trc_owner ? $trc_owner : 'N')."',
						'".$trc_tablename."',
						'".$trc_var_id."',
						'".sqlSafe($trc_var_code, 50)."',
						'".$trc_attribute."')";
							
				// Check if controller is native or foreign
				if ($this->_contentcore->pro_code == $this->_pro_code) {

					// Create controller (Type N) in native content core
					$this->_db->Execute(preg_replace(array('/%trc_type/','/%trc_trc_id/'), array('N','NULL'), $sql));

				} else {

					// Create controller (Type F) in foreign content core
					$this->_contentcore->db->Execute(preg_replace(array('/%trc_type/','/%trc_trc_id/'), array('F','NULL'), $sql));

					// Create controller (Type D) in native content core
					$this->_db->Execute(preg_replace(array('/%trc_type/','/%trc_trc_id/'), array('D',$this->_contentcore->db->lastInsertID), $sql));

				}

			}

		}

		function _createSearchData($uri){

			// Get the resource information
			$rs = $this->_db->Query("select * from tbl_ich_trc_resources where rsc_uri = '".$uri."'");

			// Add meta data to result
			$result =  $rs->Row("RSC_TITLE")."\n";
			$result .= $rs->Row("RSC_NAME")."\n";
			$result .= $rs->Row("RSC_PUBLISHER")."\n";
			$result .= $rs->Row("RSC_CREATORS")."\n";
			$result .= $rs->Row("RSC_SUBJECT")."\n";
			$result .= $rs->Row("RSC_DESCRIPTION")."\n";
			$result .= $rs->Row("RSC_CONTRIBUTORS")."\n";
			$result .= $rs->Row("RSC_SOURCE")."\n";
			$result .= $rs->Row("RSC_REFERALS")."\n";
			$result .= $rs->Row("RSC_REMARKS")."\n";
			$result .= $rs->Row("RSC_RIGHTS")."\n";
			$result .= $rs->Row("RSC_SOURCE")."\n";
			$result .= $rs->Row("RSC_URI")."\n";

			// Add content to result
			switch ($rs->Row("RSC_ICO_MIMETYPE")) {

				case "text/html":
					$result .= strip_tags($rs->Row("RSC_DATA"));
					break;

				case "text/xml":

					preg_match_all('/(<!\[CDATA\[((.|\n|\r)*?)\]\]>)/i', $rs->Row("RSC_DATA"), $matches, PREG_SET_ORDER);
					foreach((array)$matches as $match) $result .= $match[2]."\n";
					break;

				case "text/plain":
					$result .= $rs->Row("RSC_DATA");
					break;

			}
			$rs->Close();

			// Delete old search data
			$this->_db->Execute("delete from tbl_ich_trc_search where src_rsc_uri='".$uri."'");

			// Create new search data
			$this->_db->Execute("insert into tbl_ich_trc_search values('".$uri."', '".sqlSafe($result)."')");

		}

		// function putResource
		// This function saves the content into the content core tables.
		// $data			-	An array with the fiels: title, category, type, size, name, data (only text), tmp_name (only file upload).
		// $tablename		-	Name of the table of the content user. Is used for controlling the resource.
		// $var_id			-	Id of the content user. Is used for controlling the resource (Optional when var_id is used).
		// $var_code		-	Code of the content user. Is used for controlling the resource (Optional when var_code is used).
		// $attribute		-	Name of the field in the table of the content user. Is used for controlling the resource.
		// $new_uri			-	The Unique Resource Identifier that should be used for the creation of this resource.
		function putResource($data, $tablename = null, $var_id = null, $var_code = null, $attribute = null, $uri = null, $lng_code_selected = null) {

			// NOTE: alle $this->_db's zouden in deze functie vervangen moeten worden met 
			// $this->_contentcore->db omdat je anders nooit een resource in een andere
			// cc kan stoppen of bewerken. waarom was dat niet zo?

			// Check required values
			if (!$var_id && !$var_code) die("<B>Interchange: Storage terminated, no id or code available</B>");
			if (!is_array($data)) return;

			// Set language code
			$lng_code = ($lng_code_selected ? $lng_code_selected : $this->_lng_code);

			// Get uri from a) controller, b) parameters, c) create new
			$trc = $this->_getControllerInformation($tablename, $var_id, $var_code, $attribute);
			$uri = ($trc["TRC_RSC_URI"] ? $trc["TRC_RSC_URI"] : ($uri ? $uri : $this->newURI()));

			// Get icon id
			$rs = $this->_db->Query("select ico_id from tbl_ich_trc_icons where ico_rsc_uri = '".$uri."'");
			$ico_id = $rs->Row('ico_id');
			$rs->Close();

			// Upload file
			if (isset($data["tmp_name"]) && $data["tmp_name"] && $data["size"] > 0) {

				$data["data"] = addslashes(file_get_contents($data["tmp_name"]));

				// Create thumbnail
				// NOTE! When saving an image in photoshop using the 'save as' function photoshop
				//       will add additional header information and the image won't be recognized
				//       by the imagecreatefrom... functions, so you'd best use 'save for web'.
				$img = null;
				switch ($data["type"]) {
				
		            case "image/jpeg": case "image/pjpeg":
		                $img = @imagecreatefromjpeg($data["tmp_name"]);
		                break;
						
		            case "image/png": case "image/x-png":
		                $img = @imagecreatefrompng($data["tmp_name"]);
		                break;

		            case "image/gif":
		                $img = @imagecreatefromgif($data["tmp_name"]);
		                break;

		        }
	
				// Create icon
				if ($img) {

					// Maximum thumbnail size
		            $thumb_width = 98;
		            $thumb_height = 98;

					// Original image size
					$data['width'] = imagesx($img);
		            $data['height'] = imagesy($img);

					// Check size
					if ($data['width'] < $thumb_width && $data['height'] < $thumb_height) {

						$thumb_width = $data['width'];
						$thumb_height = $data['height'];

					} else {
	
			            // Calculate by x or y
						if ($data['width'] >= $data['height']) $thumb_height = round(($data['height'] * $thumb_width) / $data['width']);
						else $thumb_width = round(($data['width'] * $thumb_height) / $data['height']);

					}

		            $thumb = imagecreate($thumb_width, $thumb_height);
		            imagecopyresized($thumb, $img, 0, 0, 0, 0, $thumb_width, $thumb_height, $data['width'], $data['height']);

					ob_start();
					imagepng($thumb);
					$filecontent = ob_get_clean();
					$filesize = strlen($filecontent);

					// Insert or update record
					if (is_numeric($ico_id)) {

						$this->_db->Execute("
							update 
								tbl_ich_trc_icons 
							set 
								ico_data = '".addslashes($filecontent)."', 
								ico_size = ".$filesize." 
							where 
								ico_id = ".$ico_id);

					} else {

						$this->_db->Execute("
							insert into tbl_ich_trc_icons (
								ico_createdate,
								ico_changedate,
								ico_grouptype,
								ico_mimetype,
								ico_data,
								ico_type,
								ico_name,
								ico_size,
								ico_description
							) values (
								current_timestamp, 
								current_timestamp, 
								'IMG',
								NULL, 
								'".addslashes($filecontent)."', 
								'image/x-png', 
								'icon.png', 
								".$filesize.", 
								''
							)");

						$ico_id = $this->_db->lastInsertID();

					}

		        }
							
			}

			$rs = $this->_db->Query("select rsc_uri from tbl_ich_trc_resources where rsc_uri = '".$uri."'");
			if ($rs->EOF()) {

				// Insert
				$this->_db->Execute("
					insert into tbl_ich_trc_resources (
						rsc_uri, 
						rsc_createdate, 
						rsc_changedate, 
						rsc_lng_code, 
						rsc_org_id, 
						rsc_cat_id, 
						rsc_name, 
						rsc_on_ftp, 
						rsc_ico_mimetype, 
						rsc_data, 
						rsc_size, 
						rsc_title,
						rsc_width,
						rsc_height
					) VALUES (
						'".$uri."',
						current_timestamp,
						current_timestamp,
						'".$lng_code."',
						".$this->_org_id.",
						".$data["category"].",
						'".sqlSafe($data["name"])."',
						'".(isset($data["ftp"]) && $data["ftp"] ? $data["ftp"] : 'N')."',
						'".$data["type"]."',
						'".$data["data"]."',
						".($data["size"] ? $data["size"] : strlen($data["data"])).",
						'".sqlSafe($data["title"], 100)."',
						".(isset($data["width"]) && $data["width"] ? $data["width"] : "NULL").",
						".(isset($data["height"]) && $data["height"] ? $data["height"] : "NULL")."
					)");

				// Delete old controller
				$this->_killController($trc["TRC_ID"]);

				// Create new controller
				$this->_putControllerInformation($uri, "Y", $tablename, $var_id, $var_code, $attribute, false);

			} else {

				// Update
				$upd_string = '';
				if (isset($data["category"]) && is_numeric($data["category"])) $upd_string .= "rsc_cat_id=".$data["category"];
				if (isset($data["name"]) && $data["name"]) $upd_string .= ($upd_string ? ',' : '')."rsc_name='".sqlSafe($data["name"])."'";
				if ($lng_code) $upd_string .= ($upd_string ? ',' : '')."rsc_lng_code='".$lng_code."'";
				if (isset($data["ftp"]) && $data["ftp"]) $upd_string .= ($upd_string ? ',' : '')."rsc_on_ftp='".$data["ftp"]."'";
				if (isset($data["type"]) && $data["type"]) $upd_string .= ($upd_string ? ',' : '')."rsc_ico_mimetype='".$data["type"]."'";
				if (isset($data["data"]) && $data["data"]) $upd_string .= ($upd_string ? ',' : '')."rsc_data='".$data["data"]."'";
				if (isset($data["size"]) && $data["size"]) $upd_string .= ($upd_string ? ',' : '')."rsc_size='".$data["size"]."'";
				if (isset($data["title"]) && $data["title"]) $upd_string .= ($upd_string ? ',' : '')."rsc_title='".sqlSafe($data["title"], 100)."'";
				if (isset($data["width"]) && $data["width"]) $upd_string .= ($upd_string ? ',' : '')."rsc_width=".$data["width"]."'";
				if (isset($data["height"]) && $data["height"]) $upd_string .= ($upd_string ? ',' : '')."rsc_height=".$data["height"]."'";

				if ($upd_string) $this->_db->Execute("update tbl_ich_trc_resources set ".$upd_string." where rsc_uri = '".$uri."'");

			}
			$rs->Close();

			// Update icon (the icon can't be inserted as an uri icon before the uri itself due to constraints)
			if (is_numeric($ico_id)) $this->_db->Execute("update tbl_ich_trc_icons set ico_rsc_uri = '".$uri."'".($data["title"] ? ", ico_description = '".sqlSafe($data["title"])."'" : "")." where ico_id = ".$ico_id);

			// Update search data
			$this->_createSearchData($uri);

			// Insert log record
			//    ^-- Why?
			if (isset($_SESSION["session_usr_id"]) && is_numeric($_SESSION["session_usr_id"])) {
				$this->_db->Execute("INSERT INTO tbl_ich_trc_logging (log_createdate, log_rsc_uri, log_usr_id) VALUES (current_timestamp, '".$uri."', ".$_SESSION["session_usr_id"].")");
			}

		}


  		// function putResourceMeta
  		// This function updates the information of a resource.
  		// The resource is identified by the Unique Recource Identifier.
  		// $uri				-	Unique Recource Identifier
  		// $meta				-	Array with fields:
		//						*   title (mandatory)
		//						*   creators
		//						*   subject
		//						*   description
		//						*   contributors
		//						*   publisher
		//						*   date
		//						*   source
		//						*   referals
		//						*   remarks
		//						*   rights
		//						*   authorization
		//						*   keywords
  		function putResourceMeta($uri,$meta){

//			if($uri && $meta["title"]){
			if($uri){

/*				// Get authorization
				$authorization = $meta["authorization"];
				$authorization = ($authorization=="Y" || $authorization=="N" ? $authorization : "N");
*/
				// Create fieldlength array
				$length["title"]		= 100;
				$length["creators"]		= 128;
				$length["subject"]		= 128;
				$length["description"]	= 254;
				$length["contributors"]	= 128;
				$length["publisher"]	= 50;
				$length["source"]		= 128;
				$length["remarks"]		= 128;
				$length["rights"]		= 254;
				$length["options"]		= 254;

				// Create update string
				foreach((array)$meta as $key => $val){

					$arr[] = "rsc_".$key."='".sqlSafe($val,$length[$key])."'";

				}
				$str = implode(",", (array)$arr);

				// Update the resource meta data
				if($str) $this->_db->Execute("UPDATE tbl_ich_trc_resources SET ".$str." WHERE rsc_uri='".$uri."'");

				// Set search data
				$this->_createSearchData($uri);

			}
		}	

		function _createWhere($org_id, $category_id, $lng_code, $content_group, $content_types=null, $search_criteria=null, $period_in_days=null, $keyword_code=null, $mod_code=null, $table_name=null, $options=null) {

			$where_src_crit = '';
			$where_src_auth = '';
			$where_src_and  = '';
			$where_type		= '';
			$where_date		= '';
			$where_keyword	= '';
			$where_options  = '';
			$where_cat		= '';
			
			// Mimetypes
			if ($content_types !== false) $where_type = " AND rsc_ico_mimetype IN ('".str_replace(":","','",$content_types)."')";

			// Search


			if($search_criteria){

				// Get the administrator groups of the user
				$groups = $this->_getAdministratorGroups();

//				$where_src = " AND (rsc_title LIKE '%".sqlSafe($search_criteria)."%' OR rsc_description LIKE '%".sqlSafe($search_criteria)."%' OR rsc_creators LIKE '%".sqlSafe($search_criteria)."%' OR rsc_subject LIKE '%".sqlSafe($search_criteria)."%' OR rsc_publisher LIKE '%".sqlSafe($search_criteria)."%' OR rsc_source LIKE '%".sqlSafe($search_criteria)."%')";
				$where_src_crit = " INNER JOIN tbl_ich_trc_search ON src_rsc_uri = rsc_uri AND src_data LIKE '%".sqlSafe($search_criteria)."%' ";
				$where_src_auth = " INNER JOIN tbl_ich_trc_categories ON rsc_cat_id = cat_id LEFT JOIN tbl_ich_authorizarions ON aut_var_code=rsc_cat_id AND aut_type='ADM' AND AUT_VAR_TABLENAME='tbl_ich_trc_categories' AND aut_item IN ('".implode("','",$groups)."') ";
				$where_src_and  = " AND (CAT_AUTH_ADMINGROUPS='N' OR aut_flags>0)";
			}

			// Date
			if($period_in_days){
				$where_date = " AND rsc_changedate > DATE_SUB(current_timestamp, INTERVAL ".$period_in_days." DAY)";
			}

			// Keyword
			if($keyword_code){
				$where_keyword = " AND rsc_keywords LIKE '%".$keyword_code."%'";
			}

			if ($options) {
				foreach ($options as $option_code => $option_state) {
					$where_options .= " AND rsc_options ".($option_state ? '' : 'NOT ')." LIKE '%".$option_code."%'";
				}
			}


			// Searching spans all categories
			if (!$search_criteria && is_numeric($category_id)) {
				$where_cat = " AND rsc_cat_id=".$category_id;
			}

			$query = "tbl_ich_trc_resources ".$where_src_crit;
//			$query = "tbl_ich_trc_resources LEFT JOIN tbl_ich_trc_authorizations ON aut_rsc_uri = rsc_uri AND aut_def_code = 'STM' ";
			if ($mod_code) $query .= "INNER JOIN tbl_ich_trc_resourcecontroller ON trc_rsc_uri = rsc_uri AND trc_mod_code = '".strToUpper($mod_code)."'".($table_name ? " AND trc_tablename='".$table_name."'" : "")." ";
//			$query .= "INNER JOIN tbl_ich_trc_icons on ico_mimetype = rsc_ico_mimetype and ico_grouptype = '".$content_group."' ";
			$query .= "INNER JOIN tbl_ich_trc_icons on ico_mimetype = rsc_ico_mimetype ".$where_src_auth;
//			$query .= "WHERE rsc_lng_code='".$lng_code."' AND rsc_org_id=".$org_id." ".$where_type.$where_src.$where_date.$where_keyword.$where_cat;
			$query .= "WHERE rsc_lng_code='".$lng_code."'".$where_src_and." AND rsc_org_id=".$org_id." ".$where_type.$where_date.$where_keyword.$where_cat.$where_options;

			// Return
			return $query;

		}

		// function killResource
		// This function removes the resource from the content core.
		// Only the controller is removerd if other controllers are still using the resource.
		// The resource is removed when all controllers are removed.
		// To remove one controller, all the controller information as it was created should
		// be given to identify the controller. If a group of controllers should be removerd,
		// the attribute can be obmitted.
		// $tablename		-	Name of the table of the content user. Is used for controlling the resource.
		// $var_id			-	Id of the content user. Is used for controlling the resource (Optional when var_id is used).
		// $var_code			-	Code of the content user. Is used for controlling the resource (Optional when var_code is used).
		// $attribute		-	Name of the field in the table of the content user. Is used for controlling the resource (Optional - If obmitted all controllers are removed, according to the other attributes).
		function killResource($tablename, $var_id="", $var_code="", $attribute=""){

error_log("killResource($tablename, $var_id, $var_code, $attribute)");

			if(!$var_id && !$var_code) die('<b>Interchange: Either $var_id or $var_code must be given...</b>');

			// Default values when empty
			$var_id 	= ($var_id							? " AND trc_var_id=".$var_id  					: "");
			$var_code 	= ($var_code						? " AND trc_var_code='".mysql_escape_string($var_code)."'" 	: "");
			$attribute	= ($attribute						? " AND trc_attribute='".$attribute."'" 		: "");
			$mod_code	= ($tablename == "tbl_ich_links" || $tablename == "tbl_ich_trc_dossiers" ? $_SESSION["session_ich_version"] : $this->_mod_code);

			// Get the controllers
			$rs = $this->_db->Query("SELECT * FROM tbl_ich_trc_resourcecontroller WHERE (trc_type='N' OR trc_type='D') AND trc_mod_code='".$mod_code."' AND trc_pro_code='".$this->_pro_code."' AND trc_org_id=".$this->_org_id." AND trc_tablename='".$tablename."'".$var_id.$var_code.$attribute);

			// Loop through the controllers
			while(!$rs->EOF()){

				// Delete controller
				$this->_killController($rs->Row("TRC_ID"),$rs->Row("TRC_TRC_ID"),$rs->Row("TRC_RSC_URI"));

				// Delete resource
				if($uri != $rs->Row("TRC_RSC_URI")) $this->_killResource($uri);

				// Set URI
				$uri = $rs->Row("TRC_RSC_URI");

				$rs->MoveNext();

			}
			$this->_killResource($uri);

			$rs->Close();

		}

		// function _killResource
		// This function removers a resource from the database, including the icon
		// $uri	-	Unique identifier from the resource
		function _killResource($uri) {

			$number_of_controllers = -1;

			if($uri){

				// Check if the uri is no an 404
				if (!preg_match("/_TICH_R[0-9]+:404[A-Z][A-Z]/", $uri)) {

					// Set the correct content core
					$this->_setContentCoreByURI($uri);

					// Count existing controllers
					$rs = $this->_contentcore->db->Query("SELECT COUNT(trc_id) AS number_of_controllers FROM tbl_ich_trc_resourcecontroller WHERE trc_rsc_uri='".$uri."' AND trc_type!='D'");
					$number_of_controllers = $rs->Row("number_of_controllers");
					$rs->Close();

					// Delete resource
					if($number_of_controllers==0){

						// Get resource information
						$rs = $this->_contentcore->db->Query("SELECT rsc_on_ftp, rsc_name FROM tbl_ich_trc_resources WHERE rsc_uri='".$uri."'");

						// Check if the resource is on the ftp server
						if($rs->Row("rsc_on_ftp")=="Y"){

							// Remove resource from ftp server
							$ftp = new ftp_resource($this->_contentcore->db, $this->_par_code, $this->_contentcore->pro_code, $this->_contentcore->org_id);
							$ftp->set_ftp2_connect_data($this->_settings['secure_ftp_server'], $this->_settings['secure_ftp_user'], $this->_settings['secure_ftp_pass']);
							$ftp->delete($uri,$rs->Row("rsc_name"),$this->_contentcore->pro_code,$this->_contentcore->org_id);

						}
						$rs->Close();

						$this->_contentcore->db->Execute("DELETE FROM tbl_ich_trc_icons WHERE ico_rsc_uri='".$uri."'");
						$this->_contentcore->db->Execute("DELETE FROM tbl_ich_authorizarions WHERE aut_var_code='".$uri."'");
						$this->_contentcore->db->Execute("DELETE FROM tbl_ich_trc_resources WHERE rsc_uri='".$uri."'");
						$this->_contentcore->db->Execute("DELETE FROM tbl_ich_trc_search WHERE src_rsc_uri='".$uri."'");

					}
				}
			} else {
			error_log('NO URI!!!');
			}

			// Return number of controllers
			return $number_of_controllers;
		}

		// function getURIs
		// This function returns all resources from the selected content core.
		// $content_core			-	The content core where the resources should come from.
		// $lng_code				-	The identifier of the language in which the uris are.
		// $category_id				-	The identifier of the category.
		// $content_group			-	Filter on content group as defined in the icon table.
		// $content_types			-	The content type(s) that will be selected. For multiple selection the types should be separated with ":" (Optional).
		// $search_criteria			-	Criteria to search through the content (Optional).
		// $period_in_days			-	The period back in days of where the resources should be changed in (Optional).
		// $keyword_code			-	The keyword code what should de selected with the resources (Optional).
		// $sort_order				-	The fieldname to sort on (Optional).
		// $sort_direction			-	The direction of the sort (Optional - default ASC).
		// $offset					-	Startpoint of the selection (Optional, default 0).
		// $limit					-	Limitation of the resultset returned (Optional, default 20).
		// $mod_code				-	The code of the module. Only the resources with a controller of the module are returned (Optional).
		// $tablename				-	The name of the table. Only the resources with a controller with this table name are returned (Optional). Works only when mod_code is given.
		function getURIs($content_core, $lng_code, $category_id, $content_group, $content_types, $search_criteria=null, $period_in_days=null, $keyword_code=null, $sort_order="rsc_title", $sort_direction="ASC", $offset=0, $limit=20, $mod_code=null, $tablename=null, $options=null){

			$result = array();

			// Set the selected content core ready for use
			$this->_setContentCoreByCC($content_core);

			$rs = $this->_contentcore->db->Query("
				select distinct
					rsc_uri as uri,
					rsc_cat_id as category,
					rsc_ico_mimetype as mimetype,
					rsc_title as title,
					rsc_description as description,
					rsc_creators as creator,
					rsc_rights as rights,
					rsc_width as width,
					rsc_height as height,
					rsc_publisher as publisher,
					rsc_source as source,
					rsc_size as size,
					rsc_options as options,
					unix_timestamp(rsc_createdate) as createdate,
					unix_timestamp(rsc_changedate) as changedate
				FROM
					".$this->_createWhere($this->_org_id, $category_id, $lng_code, $content_group, $content_types, $search_criteria, $period_in_days, $keyword_code, $mod_code, $tablename, $options)."
					".($sort_order ? "ORDER BY ".$sort_order." ".$sort_direction : ""), $offset, $limit);

//			echo $rs->QueryString;

			// Create result array
			while(!$rs->EOF()){
				$result[$rs->Row("uri")] = $rs->Row();
				$rs->MoveNext();
			}
			$rs->Close();

			// Return
			return (array)$result;
		}
	

		// function _getAdministratorGroups
		// This function get the administrator groups where the user is a member of.
		function _getAdministratorGroups(){
			global $g_obj_ti3a0365;
			$groups = array();

			if (is_numeric($_SESSION['session_usr_id'])) {

				/*$sql = "SELECT grp_id, grp_description 
						FROM tbl_i3a_group_admins, tbl_i3a_group_definitions 
						WHERE gam_grp_id = grp_id AND gam_usr_id= ".$_SESSION['session_usr_id']." ORDER BY lower(grp_description) ASC";*/

				$sql = "SELECT grp_id, grp_description 
						FROM tbl_i3a_group_members, tbl_i3a_group_definitions 
						WHERE mgp_grp_id = grp_id AND mgp_usr_id= ".$_SESSION['session_usr_id']." ORDER BY lower(grp_description) ASC";
							
				$rs = $g_obj_ti3a0365->query($sql);
				while ($r = $rs->row()) {
					$groups[$r['GRP_ID']] = $r['GRP_DESCRIPTION'];
					$rs->moveNext();
				}
				$rs->Close();
			}
			
			return array_keys($groups);

		}

		// function getAuthorizations
		// This function returns the authorization flags or an array with authorization flags when the var_code is obmitted.
		// $tablename	- The name of the table where the authorizations apply too.
		// $var_code	- The item in the table the autorization should apply too (Optional).
		function &getAuthorizations($tablename, $var_code=""){

			if($tablename){

				// Create where
				if($var_code) $where = " AND aut_var_code='".$var_code."'";

				// Module code
				$mod_code = ($tablename=="tbl_ich_trc_categories" ? "TICH0105" : $this->_mod_code);

				// Get the administrator groups of the user
				$groups = $this->_getAdministratorGroups();

				// Create items IN statement
				$in = implode("','",$groups);

				// Get the authorizations
				$rs = $this->_db->Query("SELECT aut_var_code, aut_flags FROM tbl_ich_authorizarions WHERE aut_mod_code='".$mod_code."' AND aut_type='ADM' AND aut_item IN ('".$in."') AND aut_var_tablename='".$tablename."'".$where);

				if($var_code){

					$result = $rs->Row('aut_flags');

				} else {

					while(!$rs->EOF()){

						$result[$rs->Row('aut_var_code')] = $rs->Row('aut_flags');
						$rs->MoveNext();

					}

				}

				// Return
				return $result;

			}
		}



		function getTypes($grouptypes) {

			if (is_array($grouptypes)) $grouptypes = implode("','", $grouptypes);
			else $grouptypes = str_replace(":", "','", $grouptypes);

			$rs = $this->_db->Query("select ICO_ID, ICO_MIMETYPE, ICO_DESCRIPTION, ICO_EDITOR_CODE, ICO_EDITOR_PAG_NEW, ICO_EDITOR_PAG_EDIT from tbl_ich_trc_icons where ico_grouptype in ('".$grouptypes."') and ico_rsc_uri is null order by ico_description asc");
			while (($result[] = $rs->Row())) $rs->MoveNext();
			$rs->Close();

			// Return result
			return (array)$result;

		}
		
	}

?>