Exemple #1
0
 public function updateResource()
 {
     $rid = $this->resourceId();
     // resource does not exist - create it
     if ($rid == 0) {
         $rid = create_resource($this->type);
     } else {
         update_resource_type($rid, $this->type);
     }
     foreach ($this->fields as $k => $v) {
         update_field($rid, $k, $v);
     }
     if (file_exists($this->filename)) {
         $extension = explode(".", $this->filename);
         if (count($extension) > 1) {
             $extension = trim(strtolower($extension[count($extension) - 1]));
         } else {
             $extension = "";
         }
         $path = get_resource_path($rid, true, "", true, $extension);
         copy($this->filename, $path);
         create_previews($rid, false, $extension);
         # add file extension
         sql_query("update resource set file_extension='" . escapeString($extension) . "' where ref='" . escapeString($rid) . "'");
     }
     # add resource to collection (if the collection exists)
     if ($this->collection != null) {
         $col_ref = sql_value("select ref as value from collection where name='" . escapeString($this->collection) . "'", 0);
         if (isset($col_ref)) {
             add_resource_to_collection($rid, $col_ref);
         }
     }
     # set access rights
     if ($this->access != null) {
         sql_query("update resource set access='" . escapeString($this->access) . "' where ref='" . escapeString($rid) . "'");
     }
 }
function copy_collection($copied, $current, $remove_existing = false)
{
    # Get all data from the collection to copy.
    $copied_collection = sql_query("select * from collection_resource where collection='{$copied}'", "");
    if ($remove_existing) {
        #delete all existing data in the current collection
        sql_query("delete from collection_resource where collection='{$current}'");
        collection_log($current, "R", 0);
    }
    #put all the copied collection records in
    foreach ($copied_collection as $col_resource) {
        # Use correct function so external sharing is honoured.
        add_resource_to_collection($col_resource['resource'], $current, true);
    }
}
     $file_size = @filesize_unlimited($path);
     # Save alternative file data.
     sql_query("update resource_alt_files set file_name='" . escape_check($plfilename) . "',file_extension='" . escape_check($extension) . "',file_size='" . $file_size . "',creation_date=now() where resource='{$alternative}' and ref='{$aref}'");
     if ($alternative_file_previews_batch) {
         create_previews($alternative, false, $extension, false, false, $aref);
     }
     echo "SUCCESS";
     exit;
 }
 if ($replace == "" && $replace_resource == "") {
     # Standard upload of a new resource
     $ref = copy_resource(0 - $userref);
     # Copy from user template
     # Add to collection?
     if ($collection_add != "") {
         add_resource_to_collection($ref, $collection_add);
     }
     # Log this
     daily_stat("Resource upload", $ref);
     resource_log($ref, "u", 0);
     $status = upload_file($ref, getval("no_exif", "") != "", false, getval('autorotate', '') != '');
     echo "SUCCESS: " . $ref;
     exit;
 } elseif ($replace == "" && $replace_resource != "") {
     # Replacing an existing resource file
     $status = upload_file($replace_resource, getval("no_exif", "") != "", false, getval('autorotate', '') != '');
     echo "SUCCESS: {$replace_resource}";
     exit;
 } else {
     # Overwrite an existing resource using the number from the filename.
     # Extract the number from the filename
function managed_collection_request($ref,$details,$ref_is_resource=false)
	{
	# Request mode 1
	# Managed via the administrative interface
	
	# An e-mail is still sent.
	global $applicationname,$email_from,$baseurl,$email_notify,$username,$useremail,$userref,$lang,$request_senduserupdates;

	# Has a resource reference (instead of a collection reference) been passed?
	# Manage requests only work with collections. Create a collection containing only this resource.
	if ($ref_is_resource)
		{
		$c=create_collection($userref,$lang["request"] . " " . date("ymdHis"));
		add_resource_to_collection($ref,$c);
		$ref=$c; # Proceed as normal
		}

	# Fomulate e-mail text
	$message="";
	reset ($_POST);
	foreach ($_POST as $key=>$value)
		{
		if (strpos($key,"_label")!==false)
			{
			# Add custom field
			$setting=trim($_POST[str_replace("_label","",$key)]);
			if ($setting!="")
				{
				$message.=$value . ": " . $setting . "\n\n";
				}
			}
		}
	if (trim($details)!="") {$message.=$lang["requestreason"] . ": " . newlines($details) . "\n\n";} else {return false;}
	
	# Add custom fields
	$c="";
	global $custom_request_fields,$custom_request_required;
	if (isset($custom_request_fields))
		{
		$custom=explode(",",$custom_request_fields);
	
		# Required fields?
		if (isset($custom_request_required)) {$required=explode(",",$custom_request_required);}
	
		for ($n=0;$n<count($custom);$n++)
			{
			if (isset($required) && in_array($custom[$n],$required) && getval("custom" . $n,"")=="")
				{
				return false; # Required field was not set.
				}
			
			$message.=i18n_get_translated($custom[$n]) . ": " . getval("custom" . $n,"") . "\n\n";
			}
		}
	
	# Create the request
	sql_query("insert into request(user,collection,created,request_mode,status,comments) values ('$userref','$ref',now(),1,0,'" . escape_check($message) . "')");
	$request=sql_insert_id();
	
	# Send the e-mail		
	$userconfirmmessage = $lang["requestsenttext"];
	$message=$lang["username"] . ": " . $username . "\n" . $message;
	$message.=$lang["viewrequesturl"] . ":\n$baseurl/?q=$request";
	send_mail($email_notify,$applicationname . ": " . $lang["requestcollection"] . " - $ref",$message,$useremail);
	if ($request_senduserupdates){send_mail($useremail,$applicationname . ": " . $lang["requestsent"] . " - $ref",$userconfirmmessage,$email_from);}	
	
	# Increment the request counter
	sql_query("update resource set request_count=request_count+1 where ref='$ref'");
	
	return true;
	}
Exemple #5
0
 if (isset($filename_field)) {
     $wait = update_field($ref, $filename_field, $_FILES['userfile']['name']);
 }
 // extract metadata
 $wait = extract_exif_comment($ref, $extension);
 $resource = get_resource_data($ref);
 //create previews
 if ($camera_autorotation) {
     AutoRotateImage($filepath);
 }
 $wait = create_previews($ref, false, $extension);
 // add resource to collection
 if ($collection != "") {
     $collection_exists = sql_value("select name value from collection where ref='" . escape_check($collection) . "'", "");
     if ($collection_exists != "") {
         if (!add_resource_to_collection($ref, $collection)) {
             header("HTTP/1.0 403 Forbidden.");
             echo "HTTP/1.0 403 Forbidden. Collection is not writable by this user.\n";
             exit;
         }
     } else {
         header("HTTP/1.0 403 Forbidden.");
         echo "HTTP/1.0 403 Forbidden. Collection does not exist.\n";
         exit;
     }
 }
 // make sure non-required fields get written. Note this behavior is somewhat different than in the system since these override extracted data
 reset($_POST);
 reset($_GET);
 foreach (array_merge($_GET, $_POST) as $key => $value) {
     if (substr($key, 0, 5) == "field" && $value != "") {
	$to_collection = getvalescaped('toCollection', '');

	if(strpos($add,",")>0)
		{
		$addarray=explode(",",$add);
		}
	else
		{
		$addarray[0]=$add;
		unset($add);
		}	
	foreach ($addarray as $add)
		{
		hook("preaddtocollection");
		#add to current collection
		if (add_resource_to_collection($add,($to_collection === '') ? $usercollection : $to_collection,false,getvalescaped("size",""))==false)
			{ ?>
			<script language="Javascript">alert("<?php echo $lang["cantmodifycollection"]?>");</script><?php
			}
		else
			{
			# Log this	
			daily_stat("Add resource to collection",$add);
		
			# Update resource/keyword kit count
			$search=getvalescaped("search","");
			if ((strpos($search,"!")===false) && ($search!="")) {update_resource_keyword_hitcount($add,$search);}
			hook("postaddtocollection");
			}
		}	
	# Show warning?
 function do_search($search, $restypes = "", $order_by = "relevance", $archive = 0, $fetchrows = -1, $sort = "desc", $access_override = false, $starsearch = 0, $ignore_filters = false, $return_disk_usage = false)
 {
     debug("search={$search} restypes={$restypes} archive={$archive}");
     # globals needed for hooks
     global $sql, $order, $select, $sql_join, $sql_filter, $orig_order, $checkbox_and, $collections_omit_archived, $search_sql_double_pass_mode;
     # Takes a search string $search, as provided by the user, and returns a results set
     # of matching resources.
     # If there are no matches, instead returns an array of suggested searches.
     # $restypes is optionally used to specify which resource types to search.
     # $access_override is used by smart collections, so that all all applicable resources can be judged regardless of the final access-based results
     # resolve $order_by to something meaningful in sql
     $orig_order = $order_by;
     global $date_field;
     $order = array("relevance" => "score {$sort}, user_rating {$sort}, hit_count {$sort}, field{$date_field} {$sort},r.ref {$sort}", "popularity" => "user_rating {$sort},hit_count {$sort},field{$date_field} {$sort},r.ref {$sort}", "rating" => "r.rating {$sort}, user_rating {$sort}, score {$sort},r.ref {$sort}", "date" => "field{$date_field} {$sort},r.ref {$sort}", "colour" => "has_image {$sort},image_blue {$sort},image_green {$sort},image_red {$sort},field{$date_field} {$sort},r.ref {$sort}", "country" => "country {$sort},r.ref {$sort}", "title" => "title {$sort},r.ref {$sort}", "file_path" => "file_path {$sort},r.ref {$sort}", "resourceid" => "r.ref {$sort}", "resourcetype" => "resource_type {$sort},r.ref {$sort}", "titleandcountry" => "title {$sort},country {$sort}", "random" => "RAND()");
     if (!in_array($order_by, $order) && substr($order_by, 0, 5) == "field") {
         $order[$order_by] = "{$order_by} {$sort}";
     }
     hook("modifyorderarray");
     # Recognise a quoted search, which is a search for an exact string
     $quoted_string = false;
     if (substr($search, 0, 1) == "\"" && substr($search, -1, 1) == "\"") {
         $quoted_string = true;
         $search = substr($search, 1, -1);
     }
     $order_by = $order[$order_by];
     $keywords = split_keywords($search);
     $search = trim($search);
     # -- Build up filter SQL that will be used for all queries
     $sql_filter = "";
     # append resource type filtering
     if ($restypes != "") {
         if ($sql_filter != "") {
             $sql_filter .= " and ";
         }
         $restypes_x = explode(",", $restypes);
         $sql_filter .= "resource_type in ('" . join("','", $restypes_x) . "')";
     }
     if ($starsearch != "" && $starsearch != 0) {
         if ($sql_filter != "") {
             $sql_filter .= " and ";
         }
         $sql_filter .= "user_rating >= '{$starsearch}'";
     }
     # If returning disk used by the resources in the search results ($return_disk_usage=true) then wrap the returned SQL in an outer query that sums disk usage.
     $sql_prefix = "";
     $sql_suffix = "";
     if ($return_disk_usage) {
         $sql_prefix = "select sum(disk_usage) total_disk_usage,count(*) total_resources from (";
         $sql_suffix = ") resourcelist";
     }
     # append resource type restrictions based on 'T' permission
     # look for all 'T' permissions and append to the SQL filter.
     global $userpermissions;
     $rtfilter = array();
     for ($n = 0; $n < count($userpermissions); $n++) {
         if (substr($userpermissions[$n], 0, 1) == "T") {
             $rt = substr($userpermissions[$n], 1);
             if (is_numeric($rt) && !$access_override) {
                 $rtfilter[] = $rt;
             }
         }
     }
     if (count($rtfilter) > 0) {
         if ($sql_filter != "") {
             $sql_filter .= " and ";
         }
         $sql_filter .= "resource_type not in (" . join(",", $rtfilter) . ")";
     }
     # append "use" access rights, do not show restricted resources unless admin
     if (!checkperm("v") && !$access_override) {
         if ($sql_filter != "") {
             $sql_filter .= " and ";
         }
         $sql_filter .= "r.access<>'2'";
     }
     # append archive searching (don't do this for collections or !listall, archived resources can still appear in these searches)
     if (substr($search, 0, 8) != "!listall" && substr($search, 0, 11) != "!collection" || $collections_omit_archived && !checkperm("e2")) {
         global $pending_review_visible_to_all;
         if ($archive == 0 && $pending_review_visible_to_all) {
             # If resources pending review are visible to all, when listing only active resources include
             # pending review (-1) resources too.
             if ($sql_filter != "") {
                 $sql_filter .= " and ";
             }
             $sql_filter .= "(archive='0' or archive=-1)";
         } else {
             # Append normal filtering.
             if ($sql_filter != "") {
                 $sql_filter .= " and ";
             }
             $sql_filter .= "archive='{$archive}'";
         }
     }
     # append ref filter - never return the batch upload template (negative refs)
     if ($sql_filter != "") {
         $sql_filter .= " and ";
     }
     $sql_filter .= "r.ref>0";
     # ------ Advanced 'custom' permissions, need to join to access table.
     $sql_join = "";
     global $k;
     if (!checkperm("v") && !$access_override) {
         global $usergroup;
         global $userref;
         # one extra join (rca2) is required for user specific permissions (enabling more intelligent watermarks in search view)
         # the original join is used to gather group access into the search query as well.
         $sql_join = " left outer join resource_custom_access rca2 on r.ref=rca2.resource and rca2.user='******'  and (rca2.user_expires is null or rca2.user_expires>now()) and rca2.access<>2  ";
         $sql_join .= " left outer join resource_custom_access rca on r.ref=rca.resource and rca.usergroup='{$usergroup}' and rca.access<>2 ";
         if ($sql_filter != "") {
             $sql_filter .= " and ";
         }
         # If rca.resource is null, then no matching custom access record was found
         # If r.access is also 3 (custom) then the user is not allowed access to this resource.
         # Note that it's normal for null to be returned if this is a resource with non custom permissions (r.access<>3).
         $sql_filter .= " not(rca.resource is null and r.access=3)";
     }
     # Join thumbs_display_fields to resource table
     $select = "r.ref, r.resource_type, r.has_image, r.is_transcoding, r.hit_count, r.creation_date, r.rating, r.user_rating, r.user_rating_count, r.user_rating_total, r.file_extension, r.preview_extension, r.image_red, r.image_green, r.image_blue, r.thumb_width, r.thumb_height, r.archive, r.access, r.colour_key, r.created_by, r.file_modified, r.file_checksum, r.request_count, r.new_hit_count, r.expiry_notification_sent, r.preview_tweaks, r.file_path ";
     $modified_select = hook("modifyselect");
     if ($modified_select) {
         $select .= $modified_select;
     }
     $modified_select2 = hook("modifyselect2");
     if ($modified_select2) {
         $select .= $modified_select2;
     }
     # Return disk usage for each resource if returning sum of disk usage.
     if ($return_disk_usage) {
         $select .= ",r.disk_usage";
     }
     # select group and user access rights if available, otherwise select null values so columns can still be used regardless
     # this makes group and user specific access available in the basic search query, which can then be passed through access functions
     # in order to eliminate many single queries.
     if (!checkperm("v") && !$access_override) {
         $select .= ",rca.access group_access,rca2.access user_access ";
     } else {
         $select .= ",null group_access, null user_access ";
     }
     # add 'joins' to select (adding them
     $joins = get_resource_table_joins();
     foreach ($joins as $datajoin) {
         $select .= ",r.field" . $datajoin . " ";
     }
     # Prepare SQL to add join table for all provided keywods
     $suggested = $keywords;
     # a suggested search
     $fullmatch = true;
     $c = 0;
     $t = "";
     $t2 = "";
     $score = "";
     $keysearch = true;
     # Do not process if a numeric search is provided (resource ID)
     global $config_search_for_number, $category_tree_search_use_and;
     if ($config_search_for_number && is_numeric($search)) {
         $keysearch = false;
     }
     if ($keysearch) {
         for ($n = 0; $n < count($keywords); $n++) {
             $keyword = $keywords[$n];
             if (substr($keyword, 0, 1) != "!") {
                 global $date_field;
                 $field = 0;
                 #echo "<li>$keyword<br/>";
                 if (strpos($keyword, ":") !== false && !$ignore_filters) {
                     $kw = explode(":", $keyword, 2);
                     if ($kw[0] == "day") {
                         if ($sql_filter != "") {
                             $sql_filter .= " and ";
                         }
                         $sql_filter .= "r.field{$date_field} like '____-__-" . $kw[1] . "%' ";
                     } elseif ($kw[0] == "month") {
                         if ($sql_filter != "") {
                             $sql_filter .= " and ";
                         }
                         $sql_filter .= "r.field{$date_field} like '____-" . $kw[1] . "%' ";
                     } elseif ($kw[0] == "year") {
                         if ($sql_filter != "") {
                             $sql_filter .= " and ";
                         }
                         $sql_filter .= "r.field{$date_field} like '" . $kw[1] . "%' ";
                     } else {
                         $ckeywords = explode(";", $kw[1]);
                         # Fetch field info
                         $fieldinfo = sql_query("select ref,type from resource_type_field where name='" . escape_check($kw[0]) . "'", 0);
                         if (count($fieldinfo) == 0) {
                             debug("Field short name not found.");
                             return false;
                         } else {
                             $fieldinfo = $fieldinfo[0];
                         }
                         # Special handling for dates
                         if ($fieldinfo["type"] == 4 || $fieldinfo["type"] == 6) {
                             $ckeywords = array(str_replace(" ", "-", $kw[1]));
                         }
                         $field = $fieldinfo["ref"];
                         #special SQL generation for category trees to use AND instead of OR
                         if ($fieldinfo["type"] == 7 && $category_tree_search_use_and || $fieldinfo["type"] == 2 && $checkbox_and) {
                             for ($m = 0; $m < count($ckeywords); $m++) {
                                 $keyref = resolve_keyword($ckeywords[$m]);
                                 if (!($keyref === false)) {
                                     $c++;
                                     # Add related keywords
                                     $related = get_related_keywords($keyref);
                                     $relatedsql = "";
                                     for ($r = 0; $r < count($related); $r++) {
                                         $relatedsql .= " or k" . $c . ".keyword='" . $related[$r] . "'";
                                     }
                                     # Form join
                                     //$sql_join.=" join (SELECT distinct k".$c.".resource,k".$c.".hit_count from resource_keyword k".$c." where k".$c.".keyword='$keyref' $relatedsql) t".$c." ";
                                     $sql_join .= " join resource_keyword k" . $c . " on k" . $c . ".resource=r.ref and k" . $c . ".resource_type_field='" . $field . "' and (k" . $c . ".keyword='{$keyref}' {$relatedsql})";
                                     if ($score != "") {
                                         $score .= "+";
                                     }
                                     $score .= "k" . $c . ".hit_count";
                                     # Log this
                                     daily_stat("Keyword usage", $keyref);
                                 }
                             }
                         } else {
                             $c++;
                             $sql_join .= " join resource_keyword k" . $c . " on k" . $c . ".resource=r.ref and k" . $c . ".resource_type_field='" . $field . "'";
                             if ($score != "") {
                                 $score .= "+";
                             }
                             $score .= "k" . $c . ".hit_count";
                             # work through all options in an OR approach for multiple selects on the same field
                             # where k.resource=type_field=$field and (k*.keyword=3 or k*.keyword=4) etc
                             $keyjoin = "";
                             for ($m = 0; $m < count($ckeywords); $m++) {
                                 $keyref = resolve_keyword($ckeywords[$m]);
                                 if ($keyref === false) {
                                     $keyref = -1;
                                 }
                                 if ($m != 0) {
                                     $keyjoin .= " OR ";
                                 }
                                 $keyjoin .= "k" . $c . ".keyword='{$keyref}'";
                                 # Also add related.
                                 $related = get_related_keywords($keyref);
                                 for ($o = 0; $o < count($related); $o++) {
                                     $keyjoin .= " OR k" . $c . ".keyword='" . $related[$o] . "'";
                                 }
                                 # Log this
                                 daily_stat("Keyword usage", $keyref);
                             }
                             if ($keyjoin != "") {
                                 $sql_join .= " and (" . $keyjoin . ")";
                             }
                         }
                     }
                 } else {
                     # Normal keyword (not tied to a field) - searches all fields
                     # If ignoring field specifications then remove them.
                     if (strpos($keyword, ":") !== false && $ignore_filters) {
                         $s = explode(":", $keyword);
                         $keyword = $s[1];
                     }
                     # Omit resources containing this keyword?
                     $omit = false;
                     if (substr($keyword, 0, 1) == "-") {
                         $omit = true;
                         $keyword = substr($keyword, 1);
                     }
                     global $noadd, $wildcard_always_applied;
                     if (in_array($keyword, $noadd)) {
                         $skipped_last = true;
                     } else {
                         # Handle wildcards
                         if (strpos($keyword, "*") !== false || $wildcard_always_applied) {
                             if ($wildcard_always_applied && strpos($keyword, "*") === false) {
                                 $keyword .= "*";
                             }
                             # Suffix asterisk if none supplied and using $wildcard_always_applied mode.
                             # Keyword contains a wildcard. Expand.
                             $c++;
                             global $use_temp_tables;
                             if (!$use_temp_tables) {
                                 global $wildcard_expand_limit;
                                 $wildcards = sql_array("select ref value from keyword where keyword like '" . escape_check(str_replace("*", "%", $keyword)) . "' order by hit_count desc limit " . $wildcard_expand_limit);
                                 # Form join
                                 if (!$omit) {
                                     # Include in query
                                     $sql_join .= " join resource_keyword k" . $c . " on k" . $c . ".resource=r.ref and k" . $c . ".keyword in ('" . join("','", $wildcards) . "')";
                                     $sql_exclude_fields = hook("excludefieldsfromkeywordsearch");
                                     if (!empty($sql_exclude_fields)) {
                                         $sql_join .= " and k" . $c . ".resource_type_field not in (" . $sql_exclude_fields . ")";
                                     }
                                 } else {
                                     # Exclude matching resources from query (omit feature)
                                     if ($sql_filter != "") {
                                         $sql_filter .= " and ";
                                     }
                                     $sql_filter .= "r.ref not in (select resource from resource_keyword where keyword in ('" . join("','", $wildcards) . "'))";
                                     # Filter out resources that do contain the keyword.
                                 }
                                 #echo $sql_join;
                             } else {
                                 //begin code for temporary table wildcard expansion
                                 // use a global counter to avoide temporary table naming collisions
                                 global $temptable_counter;
                                 if (!isset($temptable_counter)) {
                                     $temptable_counter = 0;
                                 }
                                 $temptable_counter++;
                                 $thetemptable = 'wcql' . $c . '_' . $temptable_counter;
                                 $sql_exclude_fields = hook("excludefieldsfromkeywordsearch");
                                 $temptable_exclude = '';
                                 if (!empty($sql_exclude_fields)) {
                                     $temptable_exclude = "and rk.resource_type_field not in (" . $sql_exclude_fields . ")";
                                 }
                                 sql_query("create temporary table {$thetemptable} (resource bigint unsigned)");
                                 sql_query("insert into {$thetemptable} select distinct r.ref from resource r\n                                                                        left join resource_keyword rk on r.ref = rk.resource {$temptable_exclude}\n                                                                        left join keyword k  on rk.keyword = k.ref\n                                                                        where k.keyword like '" . escape_check(str_replace("*", "%", $keyword)) . "'");
                                 if (!$omit) {
                                     # Include in query
                                     $sql_join .= " join {$thetemptable} on {$thetemptable}.resource = r.ref ";
                                 } else {
                                     # Exclude matching resources from query (omit feature)
                                     if ($sql_filter != "") {
                                         $sql_filter .= " and ";
                                     }
                                     $sql_filter .= "r.ref not in (select resource from {$thetemptable})";
                                     # Filter out resources that do contain the keyword.
                                 }
                             }
                         } else {
                             # Not a wildcard. Normal matching.
                             $keyref = resolve_keyword($keyword);
                             # Resolve keyword. Ignore any wildcards when resolving. We need wildcards to be present later but not here.
                             if ($keyref === false && !$omit) {
                                 $fullmatch = false;
                                 $soundex = resolve_soundex($keyword);
                                 if ($soundex === false) {
                                     # No keyword match, and no keywords sound like this word. Suggest dropping this word.
                                     $suggested[$n] = "";
                                 } else {
                                     # No keyword match, but there's a word that sounds like this word. Suggest this word instead.
                                     $suggested[$n] = "<i>" . $soundex . "</i>";
                                 }
                             } else {
                                 # Key match, add to query.
                                 $c++;
                                 # Add related keywords
                                 $related = get_related_keywords($keyref);
                                 $relatedsql = "";
                                 for ($m = 0; $m < count($related); $m++) {
                                     $relatedsql .= " or k" . $c . ".keyword='" . $related[$m] . "'";
                                 }
                                 # Form join
                                 global $use_temp_tables, $use_temp_tables_for_keyword_joins;
                                 if (substr($search, 0, 8) == "!related") {
                                     $use_temp_tables_for_keyword_joins = false;
                                 }
                                 // temp tables can't be used twice (unions)
                                 $sql_exclude_fields = hook("excludefieldsfromkeywordsearch");
                                 if (!$use_temp_tables_for_keyword_joins || !$use_temp_tables) {
                                     // Not using temporary tables
                                     # Quoted string support
                                     $positionsql = "";
                                     if ($quoted_string) {
                                         if ($c > 1) {
                                             $last_key_offset = 1;
                                             if (isset($skipped_last) && $skipped_last) {
                                                 $last_key_offset = 2;
                                             }
                                             # Support skipped keywords - if the last keyword was skipped (listed in $noadd), increase the allowed position from the previous keyword. Useful for quoted searches that contain $noadd words, e.g. "black and white" where "and" is a skipped keyword.
                                             $positionsql = "and k" . $c . ".position=k" . ($c - 1) . ".position+" . $last_key_offset;
                                         }
                                     }
                                     if (!empty($sql_exclude_fields)) {
                                         $sql_join .= " and k" . $c . ".resource_type_field not in (" . $sql_exclude_fields . ")";
                                     }
                                     if (!$omit) {
                                         # Include in query
                                         $sql_join .= " join resource_keyword k" . $c . " on k" . $c . ".resource=r.ref and (k" . $c . ".keyword='{$keyref}' {$relatedsql}) {$positionsql}";
                                         if ($score != "") {
                                             $score .= "+";
                                         }
                                         $score .= "k" . $c . ".hit_count";
                                     } else {
                                         # Exclude matching resources from query (omit feature)
                                         if ($sql_filter != "") {
                                             $sql_filter .= " and ";
                                         }
                                         $sql_filter .= "r.ref not in (select resource from resource_keyword where keyword='{$keyref}')";
                                         # Filter out resources that do contain the keyword.
                                     }
                                 } else {
                                     //use temp tables
                                     if (!isset($temptable_counter)) {
                                         $temptable_counter = 0;
                                     }
                                     $temptable_counter++;
                                     $jtemptable = 'jtt' . $c . '_' . $temptable_counter;
                                     sql_query("drop table IF EXISTS {$jtemptable} ", false);
                                     $exclude_sql = '';
                                     # Quoted string support
                                     $positionsql = "";
                                     if ($quoted_string) {
                                         if ($c > 1) {
                                             $last_key_offset = 1;
                                             if (isset($skipped_last) && $skipped_last) {
                                                 $last_key_offset = 2;
                                             }
                                             # Support skipped keywords - if the last keyword was skipped (listed in $noadd), increase the allowed position from the previous keyword. Useful for quoted searches that contain $noadd words, e.g. "black and white" where "and" is a skipped keyword.
                                             $positionsql = "and {$jtemptable}.position=" . 'jtt' . ($c - 1) . '_' . ($temptable_counter - 1) . ".position+" . $last_key_offset;
                                         }
                                     }
                                     if (!empty($sql_exclude_fields)) {
                                         $exclude_sql = "and k" . $c . ".resource_type_field not in (" . $sql_exclude_fields . ")";
                                     }
                                     $test = sql_query("create temporary table {$jtemptable} SELECT distinct k" . $c . ".resource,k" . $c . ".hit_count,k" . $c . ".position from \tresource_keyword k" . $c . " where (k" . $c . ".keyword='{$keyref}' {$relatedsql})  {$exclude_sql}");
                                     if (!$omit) {
                                         # Include in query
                                         $sql_join .= " join {$jtemptable} on {$jtemptable}.resource = r.ref {$positionsql}";
                                         if ($score != "") {
                                             $score .= "+";
                                         }
                                         $score .= $jtemptable . ".hit_count";
                                     } else {
                                         # Exclude matching resources from query (omit feature)
                                         if ($sql_filter != "") {
                                             $sql_filter .= " and ";
                                         }
                                         $sql_filter .= "r.ref not in (select resource from {$jtemptable})";
                                         # Filter out resources that do contain the keyword.
                                     }
                                 }
                                 # Log this
                                 daily_stat("Keyword usage", $keyref);
                             }
                         }
                         $skipped_last = false;
                     }
                 }
             }
         }
     }
     # Could not match on provided keywords? Attempt to return some suggestions.
     if ($fullmatch == false) {
         if ($suggested == $keywords) {
             # Nothing different to suggest.
             debug("No alternative keywords to suggest.");
             return "";
         } else {
             # Suggest alternative spellings/sound-a-likes
             $suggest = "";
             if (strpos($search, ",") === false) {
                 $suggestjoin = " ";
             } else {
                 $suggestjoin = ", ";
             }
             for ($n = 0; $n < count($suggested); $n++) {
                 if ($suggested[$n] != "") {
                     if ($suggest != "") {
                         $suggest .= $suggestjoin;
                     }
                     $suggest .= $suggested[$n];
                 }
             }
             debug("Suggesting {$suggest}");
             return $suggest;
         }
     }
     # Some useful debug.
     #echo("keywordjoin=" . $sql_join);
     #echo("<br>Filter=" . $sql_filter);
     #echo("<br>Search=" . $search);
     hook("additionalsqlfilter");
     # ------ Search filtering: If search_filter is specified on the user group, then we must always apply this filter.
     global $usersearchfilter;
     $sf = explode(";", $usersearchfilter);
     if (strlen($usersearchfilter) > 0) {
         for ($n = 0; $n < count($sf); $n++) {
             $s = explode("=", $sf[$n]);
             if (count($s) != 2) {
                 exit("Search filter is not correctly configured for this user group.");
             }
             # Find field(s) - multiple fields can be returned to support several fields with the same name.
             $f = sql_array("select ref value from resource_type_field where name='" . escape_check($s[0]) . "'");
             if (count($f) == 0) {
                 exit("Field(s) with short name '" . $s[0] . "' not found in user group search filter.");
             }
             # Find keyword(s)
             $ks = explode("|", strtolower(escape_check($s[1])));
             $modifiedsearchfilter = hook("modifysearchfilter");
             if ($modifiedsearchfilter) {
                 $ks = $modifiedsearchfilter;
             }
             $kw = sql_array("select ref value from keyword where keyword in ('" . join("','", $ks) . "')");
             #if (count($k)==0) {exit ("At least one of keyword(s) '" . join("', '",$ks) . "' not found in user group search filter.");}
             $sql_join .= " join resource_keyword filter" . $n . " on r.ref=filter" . $n . ".resource and filter" . $n . ".resource_type_field in ('" . join("','", $f) . "') and filter" . $n . ".keyword in ('" . join("','", $kw) . "') ";
         }
     }
     $userownfilter = hook("userownfilter");
     if ($userownfilter) {
         $sql_join .= $userownfilter;
     }
     # Handle numeric searches when $config_search_for_number=false, i.e. perform a normal search but include matches for resource ID first
     global $config_search_for_number;
     if (!$config_search_for_number && is_numeric($search)) {
         # Always show exact resource matches first.
         $order_by = "(r.ref='" . $search . "') desc," . $order_by;
     }
     # --------------------------------------------------------------------------------
     # Special Searches (start with an exclamation mark)
     # --------------------------------------------------------------------------------
     # Can only search for resources that belong to themes
     if (checkperm("J")) {
         $sql_join .= " join collection_resource jcr on jcr.resource=r.ref join collection jc on jcr.collection=jc.ref and length(jc.theme)>0 ";
     }
     # ------ Special searches ------
     # View Last
     if (substr($search, 0, 5) == "!last") {
         # Replace r2.ref with r.ref for the alternative query used here.
         $order_by = str_replace("r.ref", "r2.ref", $order_by);
         if ($orig_order == "relevance") {
             $order_by = "r2.ref desc";
         }
         # Extract the number of records to produce
         $last = explode(",", $search);
         $last = str_replace("!last", "", $last[0]);
         if (!is_numeric($last)) {
             $last = 1000;
         }
         # 'Last' must be a number. SQL injection filter.
         # Fix the order by for this query (special case due to inner query)
         $order_by = str_replace("r.rating", "rating", $order_by);
         return sql_query($sql_prefix . "select distinct *,r2.hit_count score from (select {$select} from resource r {$sql_join}  where {$sql_filter} order by ref desc limit {$last} ) r2 order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # View Resources With No Downloads
     if (substr($search, 0, 12) == "!nodownloads") {
         if ($orig_order == "relevance") {
             $order_by = "ref desc";
         }
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where {$sql_filter} and ref not in (select distinct object_ref from daily_stat where activity_type='Resource download') order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # Duplicate Resources (based on file_checksum)
     if (substr($search, 0, 11) == "!duplicates") {
         // old code disabled due to performance issues
         //return sql_query("select distinct r.hit_count score, $select from resource r $sql_join  where $sql_filter and file_checksum in (select file_checksum from (select file_checksum,count(*) dupecount from resource group by file_checksum) r2 where r2.dupecount>1) order by file_checksum",false,$fetchrows);
         // new code relies on MySQL temporary tables being enabled, as well as checksums
         // if either is not turned on, just give up.
         global $use_temp_tables;
         global $file_checksums;
         if ($use_temp_tables && $file_checksums) {
             global $temptable_counter;
             if (!isset($temptable_counter)) {
                 $temptable_counter = 0;
             }
             $temptable_counter++;
             $thetemptable = 'dupehashx' . '_' . $temptable_counter;
             $dupequery = "select distinct r.hit_count score, {$select} from resource r {$sql_join} join {$thetemptable} on r.file_checksum = {$thetemptable}.hash where {$sql_filter} order by file_checksum";
             sql_query("create temporary table {$thetemptable} (`hash` varchar(255) NOT NULL,`hashcount` int(10) default NULL, KEY `Index 1` (`hash`))", false);
             sql_query("insert into {$thetemptable} select file_checksum, count(file_checksum) from resource where archive = 0 and ref > 0 and file_checksum <> '' and file_checksum is not null group by file_checksum having count(file_checksum) > 1", false);
             $duperesult = sql_query($dupequery, false, $fetchrows);
             return $duperesult;
         } else {
             return false;
         }
     }
     # View Collection
     if (substr($search, 0, 11) == "!collection") {
         if ($orig_order == "relevance") {
             $order_by = "c.sortorder asc,c.date_added desc,r.ref";
         }
         $colcustperm = $sql_join;
         if (getval("k", "") != "") {
             $sql_filter = "ref>0";
         }
         # Special case if a key has been provided.
         # Extract the collection number
         $collection = explode(" ", $search);
         $collection = str_replace("!collection", "", $collection[0]);
         $collection = explode(",", $collection);
         // just get the number
         $collection = $collection[0];
         # smart collections update
         global $allow_smart_collections;
         if ($allow_smart_collections) {
             $smartsearch_ref = sql_value("select savedsearch value from collection where ref={$collection}", "");
             if ($smartsearch_ref != "") {
                 $smartsearch = sql_query("select * from collection_savedsearch where ref={$smartsearch_ref}");
                 if (isset($smartsearch[0]['search'])) {
                     $smartsearch = $smartsearch[0];
                     $results = do_search($smartsearch['search'], $smartsearch['restypes'], "relevance", $smartsearch['archive'], -1, "desc", true, $smartsearch['starsearch']);
                     # results is a list of the current search without any restrictions
                     # we need to compare against the current collection contents to minimize inserts and deletions
                     $current = sql_query("select resource from collection_resource where collection={$collection}");
                     $current_contents = array();
                     $results_contents = array();
                     if (!empty($current)) {
                         foreach ($current as $current_item) {
                             $current_contents[] = $current_item['resource'];
                         }
                     }
                     if (!empty($results) && is_array($results)) {
                         foreach ($results as $results_item) {
                             $results_contents[] = $results_item['ref'];
                         }
                     }
                     for ($n = 0; $n < count($results_contents); $n++) {
                         if (!in_array($results_contents[$n], $current_contents)) {
                             add_resource_to_collection($results_contents[$n], $collection, true);
                         }
                     }
                     for ($n = 0; $n < count($current_contents); $n++) {
                         if (!in_array($current_contents[$n], $results_contents)) {
                             remove_resource_from_collection($current_contents[$n], $collection, true);
                         }
                     }
                 }
             }
         }
         return sql_query($sql_prefix . "select distinct c.date_added,c.comment,c.purchase_size,c.purchase_complete,r.hit_count score,length(c.comment) commentset, {$select} from resource r  join collection_resource c on r.ref=c.resource {$colcustperm}  where c.collection='" . $collection . "' and {$sql_filter} group by r.ref order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # View Related
     if (substr($search, 0, 8) == "!related") {
         # Extract the resource number
         $resource = explode(" ", $search);
         $resource = str_replace("!related", "", $resource[0]);
         $order_by = str_replace("r.", "", $order_by);
         # UNION below doesn't like table aliases in the order by.
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r join resource_related t on (t.related=r.ref and t.resource='" . $resource . "') {$sql_join}  where 1=1 and {$sql_filter} group by r.ref \n\t\tUNION\n\t\tselect distinct r.hit_count score, {$select} from resource r join resource_related t on (t.resource=r.ref and t.related='" . $resource . "') {$sql_join}  where 1=1 and {$sql_filter} group by r.ref \n\t\torder by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # Geographic search
     if (substr($search, 0, 4) == "!geo") {
         $geo = explode("t", str_replace(array("m", "p"), array("-", "."), substr($search, 4)));
         # Specially encoded string to avoid keyword splitting
         $bl = explode("b", $geo[0]);
         $tr = explode("b", $geo[1]);
         $sql = "select r.hit_count score, {$select} from resource r {$sql_join} where \n\n\t\t\t\t\tgeo_lat > '" . escape_check($bl[0]) . "'\n              and   geo_lat < '" . escape_check($tr[0]) . "'\t\t\n              and   geo_long > '" . escape_check($bl[1]) . "'\t\t\n              and   geo_long < '" . escape_check($tr[1]) . "'\t\t\n                          \n\t\t and {$sql_filter} group by r.ref order by {$order_by}";
         return sql_query($sql_prefix . $sql . $sql_suffix, false, $fetchrows);
     }
     # Colour search
     if (substr($search, 0, 7) == "!colour") {
         $colour = explode(" ", $search);
         $colour = str_replace("!colour", "", $colour[0]);
         $sql = "select r.hit_count score, {$select} from resource r {$sql_join}\n\t\t\t\twhere \n\t\t\t\t\tcolour_key like '" . escape_check($colour) . "%'\n              \tor  colour_key like '_" . escape_check($colour) . "%'\n                          \n\t\t and {$sql_filter} group by r.ref order by {$order_by}";
         return sql_query($sql_prefix . $sql . $sql_suffix, false, $fetchrows);
     }
     # Similar to a colour
     if (substr($search, 0, 4) == "!rgb") {
         $rgb = explode(":", $search);
         $rgb = explode(",", $rgb[1]);
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where has_image=1 and {$sql_filter} group by r.ref order by (abs(image_red-" . $rgb[0] . ")+abs(image_green-" . $rgb[1] . ")+abs(image_blue-" . $rgb[2] . ")) asc limit 500" . $sql_suffix, false, $fetchrows);
     }
     # Similar to a colour by key
     if (substr($search, 0, 10) == "!colourkey") {
         # Extract the colour key
         $colourkey = explode(" ", $search);
         $colourkey = str_replace("!colourkey", "", $colourkey[0]);
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where has_image=1 and left(colour_key,4)='" . $colourkey . "' and {$sql_filter} group by r.ref" . $sql_suffix, false, $fetchrows);
     }
     global $config_search_for_number;
     if ($config_search_for_number && is_numeric($search) || substr($search, 0, 9) == "!resource") {
         $theref = escape_check($search);
         $theref = preg_replace("/[^0-9]/", "", $theref);
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where r.ref='{$theref}' and {$sql_filter} group by r.ref" . $sql_suffix);
     }
     # Searching for pending archive
     if (substr($search, 0, 15) == "!archivepending") {
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where archive=1 and ref>0 group by r.ref order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     if (substr($search, 0, 12) == "!userpending") {
         if ($orig_order == "rating") {
             $order_by = "request_count desc," . $order_by;
         }
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where archive=-1 and ref>0 group by r.ref order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # View Contributions
     if (substr($search, 0, 14) == "!contributions") {
         global $userref;
         # Extract the user ref
         $cuser = explode(" ", $search);
         $cuser = str_replace("!contributions", "", $cuser[0]);
         if ($userref == $cuser) {
             $sql_filter = "archive='{$archive}'";
             $sql_join = "";
         }
         # Disable permissions when viewing your own contributions - only restriction is the archive status
         $select = str_replace(",rca.access group_access,rca2.access user_access ", ",null group_access, null user_access ", $select);
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where created_by='" . $cuser . "' and r.ref > 0 and {$sql_filter} group by r.ref order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # Search for resources with images
     if ($search == "!images") {
         return sql_query($sql_prefix . "select distinct r.hit_count score, {$select} from resource r {$sql_join}  where has_image=1 group by r.ref order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # Search for resources not used in Collections
     if (substr($search, 0, 7) == "!unused") {
         return sql_query($sql_prefix . "SELECT distinct {$select} FROM resource r {$sql_join}  where r.ref>0 and r.ref not in (select c.resource from collection_resource c) and {$sql_filter}" . $sql_suffix, false, $fetchrows);
     }
     # Search for a list of resources
     # !listall = archive state is not applied as a filter to the list of resources.
     if (substr($search, 0, 5) == "!list") {
         $resources = explode(" ", $search);
         if (substr($search, 0, 8) == "!listall") {
             $resources = str_replace("!listall", "", $resources[0]);
         } else {
             $resources = str_replace("!list", "", $resources[0]);
         }
         $resources = explode(",", $resources);
         // separate out any additional keywords
         $resources = escape_check($resources[0]);
         if (strlen(trim($resources)) == 0) {
             $resources = "where r.ref IS NULL";
         } else {
             $resources = "where (r.ref='" . str_replace(":", "' OR r.ref='", $resources) . "')";
         }
         return sql_query($sql_prefix . "SELECT distinct r.hit_count score, {$select} FROM resource r {$sql_join} {$resources} and {$sql_filter} order by {$order_by}" . $sql_suffix, false, $fetchrows);
     }
     # Within this hook implementation, set the value of the global $sql variable:
     # Since there will only be one special search executed at a time, only one of the
     # hook implementations will set the value.  So, you know that the value set
     # will always be the correct one (unless two plugins use the same !<type> value).
     $sql = "";
     hook("addspecialsearch");
     if ($sql != "") {
         debug("Addspecialsearch hook returned useful results.");
         return sql_query($sql_prefix . $sql . $sql_suffix, false, $fetchrows);
     }
     # -------------------------------------------------------------------------------------
     # Standard Searches
     # -------------------------------------------------------------------------------------
     # We've reached this far without returning.
     # This must be a standard (non-special) search.
     # Construct and perform the standard search query.
     #$sql="";
     if ($sql_filter != "") {
         if ($sql != "") {
             $sql .= " and ";
         }
         $sql .= $sql_filter;
     }
     # Append custom permissions
     $t .= $sql_join;
     if ($score == "") {
         $score = "r.hit_count";
     }
     # In case score hasn't been set (i.e. empty search)
     global $max_results;
     if ($t2 != "" && $sql != "") {
         $sql = " and " . $sql;
     }
     # Compile final SQL
     # Performance enhancement - set return limit to number of rows required
     if ($search_sql_double_pass_mode && $fetchrows != -1) {
         $max_results = $fetchrows;
     }
     $results_sql = $sql_prefix . "select distinct {$score} score, {$select} from resource r" . $t . "  where {$t2} {$sql} group by r.ref order by {$order_by} limit {$max_results}" . $sql_suffix;
     # Debug
     debug("\n" . $results_sql);
     # Execute query
     $result = sql_query($results_sql, false, $fetchrows);
     # Performance improvement - perform a second count-only query and pad the result array as necessary
     if ($search_sql_double_pass_mode && count($result) > 0 && count($result) >= $max_results) {
         $count_sql = "select count(distinct r.ref) value from resource r" . $t . "  where {$t2} {$sql}";
         $count = sql_value($count_sql, 0);
         $result = array_pad($result, $count, 0);
     }
     debug("Search found " . count($result) . " results");
     if (count($result) > 0) {
         return $result;
     }
     # (temp) - no suggestion for field-specific searching for now - TO DO: modify function below to support this
     if (strpos($search, ":") !== false) {
         return "";
     }
     # All keywords resolved OK, but there were no matches
     # Remove keywords, least used first, until we get results.
     $lsql = "";
     $omitmatch = false;
     for ($n = 0; $n < count($keywords); $n++) {
         if (substr($keywords[$n], 0, 1) == "-") {
             $omitmatch = true;
             $omit = $keywords[$n];
         }
         if ($lsql != "") {
             $lsql .= " or ";
         }
         $lsql .= "keyword='" . escape_check($keywords[$n]) . "'";
     }
     if ($omitmatch) {
         return trim_spaces(str_replace(" " . $omit . " ", " ", " " . join(" ", $keywords) . " "));
     }
     if ($lsql != "") {
         $least = sql_value("select keyword value from keyword where {$lsql} order by hit_count asc limit 1", "");
         return trim_spaces(str_replace(" " . $least . " ", " ", " " . join(" ", $keywords) . " "));
     } else {
         return array();
     }
 }
function managed_collection_request($ref, $details, $ref_is_resource = false)
{
    # Request mode 1
    # Managed via the administrative interface
    # An e-mail is still sent.
    global $applicationname, $email_from, $baseurl, $email_notify, $username, $useremail, $userref, $lang, $request_senduserupdates, $watermark, $filename_field, $view_title_field, $access, $resource_type_request_emails;
    # Has a resource reference (instead of a collection reference) been passed?
    # Manage requests only work with collections. Create a collection containing only this resource.
    if ($ref_is_resource) {
        $admin_mail_template = "emailresourcerequest";
        $user_mail_template = "emailuserresourcerequest";
        $resourcedata = get_resource_data($ref);
        $templatevars['thumbnail'] = get_resource_path($ref, true, "thm", false, "jpg", $scramble = -1, $page = 1, $watermark ? $access == 1 ? true : false : false);
        if (!file_exists($templatevars['thumbnail'])) {
            $templatevars['thumbnail'] = "../gfx/" . get_nopreview_icon($resourcedata["resource_type"], $resourcedata["file_extension"], false);
        }
        $templatevars['url'] = $baseurl . "/?r=" . $ref;
        if (isset($filename_field)) {
            $templatevars["filename"] = $lang["fieldtitle-original_filename"] . ": " . get_data_by_field($ref, $filename_field);
        }
        if (isset($resourcedata["field" . $view_title_field])) {
            $templatevars["title"] = $resourcedata["field" . $view_title_field];
        }
        $c = create_collection($userref, $lang["request"] . " " . date("ymdHis"));
        add_resource_to_collection($ref, $c);
        $ref = $c;
        # Proceed as normal
    } else {
        $admin_mail_template = "emailcollectionrequest";
        $user_mail_template = "emailusercollectionrequest";
        $collectiondata = get_collection($ref);
        $templatevars['url'] = $baseurl . "/?c=" . $ref;
        if (isset($collectiondata["name"])) {
            $templatevars["title"] = $collectiondata["name"];
        }
    }
    # Fomulate e-mail text
    $templatevars['username'] = $username;
    $templatevars["useremail"] = $useremail;
    $userdata = get_user($userref);
    $templatevars["fullname"] = $userdata["fullname"];
    $message = "";
    reset($_POST);
    foreach ($_POST as $key => $value) {
        if (strpos($key, "_label") !== false) {
            # Add custom field
            $setting = trim($_POST[str_replace("_label", "", $key)]);
            if ($setting != "") {
                $message .= $value . ": " . $setting . "\n\n";
            }
        }
    }
    if (trim($details) != "") {
        $message .= $lang["requestreason"] . ": " . newlines($details) . "\n\n";
    } else {
        return false;
    }
    # Add custom fields
    $c = "";
    global $custom_request_fields, $custom_request_required;
    if (isset($custom_request_fields)) {
        $custom = explode(",", $custom_request_fields);
        # Required fields?
        if (isset($custom_request_required)) {
            $required = explode(",", $custom_request_required);
        }
        for ($n = 0; $n < count($custom); $n++) {
            if (isset($required) && in_array($custom[$n], $required) && getval("custom" . $n, "") == "") {
                return false;
                # Required field was not set.
            }
            $message .= i18n_get_translated($custom[$n]) . ": " . getval("custom" . $n, "") . "\n\n";
        }
    }
    # Create the request
    sql_query("insert into request(user,collection,created,request_mode,status,comments) values ('{$userref}','{$ref}',now(),1,0,'" . escape_check($message) . "')");
    $request = sql_insert_id();
    $templatevars["request_id"] = $request;
    $templatevars["requesturl"] = $baseurl . "/?q=" . $request;
    $templatevars["requestreason"] = $message;
    hook("afterrequestcreate", "", array($request));
    # Check if alternative request email notification address is set, only valid if collection contains resources of the same type
    $admin_notify_email = $email_notify;
    if (isset($resource_type_request_emails)) {
        $requestrestypes = array_unique(sql_array("select r.resource_type as value from collection_resource cr left join resource r on cr.resource=r.ref where cr.collection='{$ref}'"));
        if (count($requestrestypes) == 1 && isset($resource_type_request_emails[$requestrestypes[0]])) {
            $admin_notify_email = $resource_type_request_emails[$requestrestypes[0]];
        }
    }
    # Send the e-mail
    $userconfirmmessage = $lang["requestsenttext"] . "<br /><br />{$message}<br /><br />" . $lang["clicktoviewresource"] . "<br />{$baseurl}/?c={$ref}";
    $message = $lang["user_made_request"] . "<br /><br />" . $lang["username"] . ": " . $username . "<br />{$message}<br /><br />";
    $message .= $lang["clicktoviewresource"] . "<br />{$baseurl}/?q={$request}";
    send_mail($admin_notify_email, $applicationname . ": " . $lang["requestcollection"] . " - {$ref}", $message, $useremail, $useremail, $admin_mail_template, $templatevars);
    if ($request_senduserupdates) {
        send_mail($useremail, $applicationname . ": " . $lang["requestsent"] . " - {$ref}", $userconfirmmessage, $email_from, $email_notify, $user_mail_template, $templatevars);
    }
    # Increment the request counter
    sql_query("update resource set request_count=request_count+1 where ref='{$ref}'");
    return true;
}
function HookImagestreamUpload_pluploadInitialuploadprocessing()
{
    #Support for uploading multi files as zip
    global $config_windows, $id, $targetDir, $resource_type, $imagestream_restypes, $imagestream_transitiontime, $zipcommand, $use_zip_extension, $userref, $session_hash, $filename, $filename_field, $collection_add, $archiver, $zipcommand, $ffmpeg_fullpath, $ffmpeg_preview_extension, $ffmpeg_preview_options, $ffmpeg_preview_min_height, $ffmpeg_preview_max_height, $ffmpeg_preview_min_width, $ffmpeg_preview_max_width, $lang, $collection_download_settings, $archiver_listfile_argument;
    $ffmpeg_fullpath = get_utility_path("ffmpeg");
    debug("DEBUG: Imagestream - checking restype: " . $resource_type . $imagestream_restypes);
    if (in_array($resource_type, $imagestream_restypes)) {
        debug("DEBUG: Imagestream - uploading file");
        #Check that we have an archiver configured
        $archiver_fullpath = get_utility_path("archiver");
        if (!isset($zipcommand) && !$use_zip_extension) {
            if ($archiver_fullpath == false) {
                exit($lang["archiver-utility-not-found"]);
            }
        }
        echo print_r($_POST) . print_r($_GET);
        if (getval("lastqueued", "")) {
            debug("DEBUG: Imagestream - last queued file");
            $ref = copy_resource(0 - $userref);
            # Copy from user template
            debug("DEBUG: Imagestream - creating resource: " . $ref);
            # Create the zip file
            $imagestreamzippath = get_resource_path($ref, true, "", true, "zip");
            if ($use_zip_extension) {
                $zip = new ZipArchive();
                $zip->open($imagestreamzippath, ZIPARCHIVE::CREATE);
            }
            $deletion_array = array();
            debug("DEBUG: opening directory: " . $targetDir);
            $imagestream_files = opendir($targetDir);
            $imagestream_workingfiles = get_temp_dir() . DIRECTORY_SEPARATOR . "plupload" . DIRECTORY_SEPARATOR . $session_hash . "workingfiles";
            if (!file_exists($imagestream_workingfiles)) {
                if ($config_windows) {
                    @mkdir($imagestream_workingfiles);
                } else {
                    @mkdir($imagestream_workingfiles, 0777, true);
                }
            }
            $filenumber = 00;
            $imagestream_filelist = array();
            while ($imagestream_filelist[] = readdir($imagestream_files)) {
                sort($imagestream_filelist);
            }
            closedir($imagestream_files);
            $imageindex = 1;
            foreach ($imagestream_filelist as $imagestream_file) {
                if ($imagestream_file != '.' && $imagestream_file != '..') {
                    $filenumber = sprintf("%03d", $filenumber);
                    $deletion_array[] = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file;
                    if (!$use_zip_extension) {
                        $imagestreamcmd_file = get_temp_dir(false, $id) . "/imagestreamzipcmd" . $imagestream_file . ".txt";
                        $fh = fopen($imagestreamcmd_file, 'w') or die("can't open file");
                        fwrite($fh, $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . "\r\n");
                        fclose($fh);
                        $deletion_array[] = $imagestreamcmd_file;
                    }
                    if ($use_zip_extension) {
                        debug("DEBUG: Imagestream - adding filename: " . $imagestream_file);
                        debug("DEBUG: using zip PHP extension, set up zip at : " . $imagestreamzippath);
                        $zip->addFile($imagestream_file);
                        debug(" Added files number : " . $zip->numFiles);
                        $wait = $zip->close();
                        debug("DEBUG: closed zip");
                    } else {
                        if ($archiver_fullpath) {
                            debug("DEBUG: using archiver, running command: \r\n" . $archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestream_file));
                            run_command($archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestreamcmd_file));
                        } else {
                            if (!$use_zip_extension) {
                                if ($config_windows) {
                                    debug("DEBUG: using zip command: . {$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                } else {
                                    # Pipe the command file, containing the filenames, to the executable.
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " -@ < " . escapeshellarg($imagestreamcmd_file));
                                }
                            }
                        }
                    }
                    #Create a JPEG if not already in that format
                    $imagestream_file_parts = explode('.', $imagestream_file);
                    $imagestream_file_ext = $imagestream_file_parts[count($imagestream_file_parts) - 1];
                    $imagestream_file_noext = basename($imagestream_file, $imagestream_file_ext);
                    global $imagemagick_path, $imagemagick_quality;
                    $icc_transform_complete = false;
                    # Camera RAW images need prefix
                    if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $imagestream_file_ext, $rawext)) {
                        $prefix = $rawext[0] . ':';
                    }
                    # Locate imagemagick.
                    $convert_fullpath = get_utility_path("im-convert");
                    if ($convert_fullpath == false) {
                        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'.");
                    }
                    $prefix = '';
                    if ($prefix == "cr2:" || $prefix == "nef:") {
                        $flatten = "";
                    } else {
                        $flatten = "-flatten";
                    }
                    $command = $convert_fullpath . ' ' . escapeshellarg($targetDir . DIRECTORY_SEPARATOR . $imagestream_file) . ' +matte ' . $flatten . ' -quality ' . $imagemagick_quality;
                    # EXPERIMENTAL CODE TO USE EXISTING ICC PROFILE IF PRESENT
                    global $icc_extraction, $icc_preview_profile, $icc_preview_options, $ffmpeg_supported_extensions;
                    if ($icc_extraction) {
                        $iccpath = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . '.icc';
                        if (!file_exists($iccpath) && !isset($iccfound) && $extension != "pdf" && !in_array($imagestream_file_ext, $ffmpeg_supported_extensions)) {
                            // extracted profile doesn't exist. Try extracting.
                            if (extract_icc_profile($ref, $imagestream_file_ext)) {
                                $iccfound = true;
                            } else {
                                $iccfound = false;
                            }
                        }
                    }
                    if ($icc_extraction && file_exists($iccpath) && !$icc_transform_complete) {
                        // we have an extracted ICC profile, so use it as source
                        $targetprofile = dirname(__FILE__) . '/../iccprofiles/' . $icc_preview_profile;
                        $profile = " +profile \"*\" -profile {$iccpath} {$icc_preview_options} -profile {$targetprofile} +profile \"*\" ";
                        $icc_transform_complete = true;
                    } else {
                        // use existing strategy for color profiles
                        # Preserve colour profiles? (omit for smaller sizes)
                        $profile = "+profile \"*\" -colorspace RGB";
                        # By default, strip the colour profiles ('+' is remove the profile, confusingly)
                        #if ($imagemagick_preserve_profiles && $id!="thm" && $id!="col" && $id!="pre" && $id!="scr") {$profile="";}
                    }
                    $runcommand = $command . " +matte {$profile} " . escapeshellarg($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                    $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg";
                    $output = run_command($runcommand);
                    debug("processed file" . $filenumber . ": " . $imagestream_file . "\r\n");
                    debug("Image index: " . $imageindex . ". file count: " . count($imagestream_filelist));
                    if ($filenumber == 00) {
                        $snapshotsize = getimagesize($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                        list($width, $height) = $snapshotsize;
                        # Frame size must be a multiple of two
                        if ($width % 2) {
                            $width++;
                        }
                        if ($height % 2) {
                            $height++;
                        }
                    }
                    if ($imageindex == count($imagestream_filelist) - 1) {
                        $additionalfile = $filenumber + 1;
                        $additionalfile = sprintf("%03d", $additionalfile);
                        copy($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg", $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg");
                        $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg";
                    }
                    $filenumber++;
                }
                #end of loop for each uploadedfile
                $imageindex++;
            }
            #Add the resource and move this zip file, set extension
            # Add to collection?
            if ($collection_add != "") {
                add_resource_to_collection($ref, $collection_add);
            }
            # Log this
            daily_stat("Resource upload", $ref);
            resource_log($ref, "u", 0);
            #Change this!!!!!!!!!!!
            #$status=upload_file($ref,true,false,false));
            if (!$config_windows) {
                @chmod($imagestreamzippath, 0777);
            }
            # Store extension in the database and update file modified time.
            sql_query("update resource set file_extension='zip',preview_extension='zip',file_modified=now(), has_image=0 where ref='{$ref}'");
            #update_field($ref,$filename_field,$filename);
            update_disk_usage($ref);
            # create the mp4 version
            # Add a new alternative file
            $aref = add_alternative_file($ref, "MP4 version");
            $imagestreamqtfile = get_resource_path($ref, true, "", false, "mp4", -1, 1, false, "", $aref);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
            echo "Running command: " . $shell_exec_cmd;
            if ($config_windows) {
                $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow MP4 video");
            if (!$config_windows) {
                @chmod($imagestreamqtfile, 0777);
            }
            $file_size = @filesize_unlimited($imagestreamqtfile);
            # Save alternative file data.
            sql_query("update resource_alt_files set file_name='quicktime.mp4',file_extension='mp4',file_size='" . $file_size . "',creation_date=now() where resource='{$ref}' and ref='{$aref}'");
            #create the FLV preview as per normal video processing if possible?
            if ($height < $ffmpeg_preview_min_height) {
                $height = $ffmpeg_preview_min_height;
            }
            if ($width < $ffmpeg_preview_min_width) {
                $width = $ffmpeg_preview_min_width;
            }
            if ($height > $ffmpeg_preview_max_height) {
                $width = ceil($width * ($ffmpeg_preview_max_height / $height));
                $height = $ffmpeg_preview_max_height;
            }
            if ($width > $ffmpeg_preview_max_width) {
                $height = ceil($height * ($ffmpeg_preview_max_width / $width));
                $width = $ffmpeg_preview_max_width;
            }
            $flvzippreviewfile = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -i " . $imagestreamqtfile . " {$ffmpeg_preview_options} -s {$width}x{$height} " . $flvzippreviewfile;
            debug("Running command: " . $shell_exec_cmd);
            if ($config_windows) {
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow FLV video");
            if (!$config_windows) {
                @chmod($flvzippreviewfile, 0777);
            }
            #Tidy up
            rcRmdir($imagestream_workingfiles);
            rcRmdir($targetDir);
            foreach ($deletion_array as $tmpfile) {
                debug("\r\nDEBUG: Deleting: " . $tmpfile);
                delete_exif_tmpfile($tmpfile);
            }
            echo "SUCCESS";
            #return true;
            exit;
        } else {
            echo "SUCCESS";
            exit;
        }
        return true;
    } else {
        return false;
    }
}
function HookVideo_spliceViewAfterresourceactions()
{
    global $videosplice_resourcetype, $resource, $lang, $config_windows, $resourcetoolsGT;
    if ($resource["resource_type"] != $videosplice_resourcetype) {
        return false;
    }
    # Not the right type.
    if (getval("video_splice_cut_from_hours", "") != "") {
        # Process actions
        $error = "";
        # Receive input
        $fh = getvalescaped("video_splice_cut_from_hours", "");
        $fm = getvalescaped("video_splice_cut_from_minutes", "");
        $fs = getvalescaped("video_splice_cut_from_seconds", "");
        $th = getvalescaped("video_splice_cut_to_hours", "");
        $tm = getvalescaped("video_splice_cut_to_minutes", "");
        $ts = getvalescaped("video_splice_cut_to_seconds", "");
        $preview = getvalescaped("preview", "") != "";
        # Calculate a duration, as needed by FFMPEG
        $from_seconds = $fh * 60 * 60 + $fm * 60 + $fs;
        $to_seconds = $th * 60 * 60 + $tm * 60 + $ts;
        $seconds = $to_seconds - $from_seconds;
        # Any problems?
        if ($seconds <= 0) {
            $error = $lang["error-from_time_after_to_time"];
        }
        # Convert seconds to HH:MM:SS as required by FFmpeg.
        $dh = floor($seconds / (60 * 60));
        $dm = floor(($seconds - $dh * 60 * 60) / 60);
        $ds = floor($seconds - $dh * 60 * 60 - $dm * 60);
        # Show error message if necessary
        if ($error != "") {
            ?>
			<script type="text/javascript">
			alert("<?php 
            echo $error;
            ?>
");
			</script>
			<?php 
        } else {
            # Process video.
            $ss = $fh . ":" . $fm . ":" . $fs;
            $t = str_pad($dh, 2, "0", STR_PAD_LEFT) . ":" . str_pad($dm, 2, "0", STR_PAD_LEFT) . ":" . str_pad($ds, 2, "0", STR_PAD_LEFT);
            # Establish FFMPEG location.
            $ffmpeg_fullpath = get_utility_path("ffmpeg");
            # Work out source/destination
            global $ffmpeg_preview_extension, $ref;
            if (file_exists(get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension))) {
                $source = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension, -1, 1, false, "", -1, false);
            } else {
                $source = get_resource_path($ref, true, "", false, $ffmpeg_preview_extension, -1, 1, false, "", -1, false);
            }
            # Preview only?
            global $userref;
            if ($preview) {
                # Preview only.
                $target = get_temp_dir() . "/video_splice_preview_" . $userref . "." . $ffmpeg_preview_extension;
            } else {
                # Not a preview. Create a new resource.
                $newref = copy_resource($ref);
                $target = get_resource_path($newref, true, "", true, $ffmpeg_preview_extension, -1, 1, false, "", -1, false);
                # Set parent resource field details.
                global $videosplice_parent_field;
                update_field($newref, $videosplice_parent_field, $ref . ": " . $resource["field8"] . " [{$fh}:{$fm}:{$fs} - {$th}:{$tm}:{$ts}]");
                # Set created_by, archive and extension
                sql_query("update resource set created_by='{$userref}',archive=-2,file_extension='" . $ffmpeg_preview_extension . "' where ref='{$newref}'");
            }
            # Unlink the target
            if (file_exists($target)) {
                unlink($target);
            }
            if ($config_windows) {
                # Windows systems have a hard time with the long paths used for video generation.
                $target_ext = strrchr($target, '.');
                $source_ext = strrchr($source, '.');
                $target_temp = get_temp_dir() . "/vs_t" . $newref . $target_ext;
                $target_temp = str_replace("/", "\\", $target_temp);
                $source_temp = get_temp_dir() . "/vs_s" . $ref . $source_ext;
                $source_temp = str_replace("/", "\\", $source_temp);
                copy($source, $source_temp);
                $shell_exec_cmd = $ffmpeg_fullpath . " -y -i " . escapeshellarg($source_temp) . " -ss {$ss} -t {$t} " . escapeshellarg($target_temp);
                $output = exec($shell_exec_cmd);
                rename($target_temp, $target);
                unlink($source_temp);
            } else {
                $shell_exec_cmd = $ffmpeg_fullpath . " -y -i " . escapeshellarg($source) . " -ss {$ss} -t {$t} " . escapeshellarg($target);
                $output = exec($shell_exec_cmd);
            }
            #echo "<p>" . $shell_exec_cmd . "</p>";
            # Generate preview/thumbs if not in preview mode
            if (!$preview) {
                include_once "../include/image_processing.php";
                create_previews($newref, false, $ffmpeg_preview_extension);
                # Add the resource to the user's collection.
                global $usercollection, $baseurl;
                add_resource_to_collection($newref, $usercollection);
                ?>
				<script type="text/javascript">
				top.collections.location.href="<?php 
                echo $baseurl;
                ?>
/pages/collections.php?nc=<?php 
                echo time();
                ?>
";
				</script>
				<?php 
            }
        }
    }
    ?>
<li><a href="#" onClick="
if (document.getElementById('videocut').style.display=='block') {document.getElementById('videocut').style.display='none';} else {document.getElementById('videocut').style.display='block';} return false;"><?php 
    echo ($resourcetoolsGT ? "&gt; " : "") . $lang["action-cut"];
    ?>
</a></li>
<form id="videocut" style="<?php 
    if (!(isset($preview) && $preview)) {
        ?>
display:none;<?php 
    }
    ?>
padding:10px 0 3px 0;" method="post">

<table>
<tr>
<td><?php 
    echo $lang["from-time"];
    ?>
</td>
<td><?php 
    echo $lang["hh"];
    ?>
<select name="video_splice_cut_from_hours">
<?php 
    for ($n = 0; $n < 100; $n++) {
        ?>
<option <?php 
        if (isset($fh) && $fh == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
<td><?php 
    echo $lang["mm"];
    ?>
<select name="video_splice_cut_from_minutes">
<?php 
    for ($n = 0; $n < 60; $n++) {
        ?>
<option <?php 
        if (isset($fm) && $fm == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
<td><?php 
    echo $lang["ss"];
    ?>
<select name="video_splice_cut_from_seconds">
<?php 
    for ($n = 0; $n < 60; $n++) {
        ?>
<option <?php 
        if (isset($fs) && $fs == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
</tr>

<tr>
<td><?php 
    echo $lang["to-time"];
    ?>
</td>
<td><?php 
    echo $lang["hh"];
    ?>
<select name="video_splice_cut_to_hours">
<?php 
    for ($n = 0; $n < 100; $n++) {
        ?>
<option <?php 
        if (isset($th) && $th == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
<td><?php 
    echo $lang["mm"];
    ?>
<select name="video_splice_cut_to_minutes">
<?php 
    for ($n = 0; $n < 60; $n++) {
        ?>
<option <?php 
        if (isset($tm) && $tm == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
<td><?php 
    echo $lang["ss"];
    ?>
<select name="video_splice_cut_to_seconds">
<?php 
    for ($n = 0; $n < 60; $n++) {
        ?>
<option <?php 
        if (isset($ts) && $ts == $n) {
            ?>
selected<?php 
        }
        ?>
><?php 
        echo str_pad($n, 2, "0", STR_PAD_LEFT);
        ?>
</option><?php 
    }
    ?>
</select></td>
</tr>

<tr><td colspan=4 align="center">
<input type="submit" name="preview" value="<?php 
    echo $lang["action-preview"];
    ?>
" style="width:40%;">
&nbsp;&nbsp;
<input type="submit" name="cut" value="<?php 
    echo $lang["action-cut"];
    ?>
" style="width:40%;">
</td></tr>

</table>

<?php 
    if (isset($preview) && $preview) {
        # Show the preview
        # Work out a colour theme
        global $userfixedtheme;
        $theme = isset($userfixedtheme) && $userfixedtheme != "" ? $userfixedtheme : getval("colourcss", "greyblu");
        $colour = "505050";
        if ($theme == "greyblu") {
            $colour = "446693";
        }
        global $baseurl;
        # Embedded preview player
        ?>
	<p align="center">
	<object type="application/x-shockwave-flash" data="../lib/flashplayer/player_flv_maxi.swf" width="240" height="135">
    <param name="allowFullScreen" value="true" />
	
     <param name="movie" value="../lib/flashplayer/player_flv_maxi.swf" />
     <param name="FlashVars" value="flv=<?php 
        echo convert_path_to_url($target);
        ?>
&amp;width=240&amp;height=135&amp;margin=0&amp;buffer=10&amp;showvolume=0&amp;volume=200&amp;showtime=0&amp;autoplay=1&amp;autoload=1&amp;showfullscreen=0&amp;showstop=0&amp;playercolor=<?php 
        echo $colour;
        ?>
" />
	</object>
	</p>
	<?php 
    }
    ?>



</form>

	<?php 
    return true;
}
             $counter++;
             if ($counter >= $result_limit && $result_limit != -1) {
                 break;
             }
         }
     }
 }
 //echo "Comparing results...";
 $results_contents_add = array_values(array_diff($results_contents, $current_contents));
 $current_contents_remove = array_values(array_diff($current_contents, $results_contents));
 $count_results = count($results_contents_add);
 if ($count_results > 0) {
     # Add any new resources
     debug("smart_collections_async : Adding {$count_results} resources to collection...");
     for ($n = 0; $n < $count_results; $n++) {
         add_resource_to_collection($results_contents_add[$n], $collection, true);
     }
 }
 $count_contents = count($current_contents_remove);
 if ($count_contents > 0) {
     # Remove any resources no longer present.
     debug("smart_collections_async : Removing {$count_contents} resources...");
     for ($n = 0; $n < $count_contents; $n++) {
         remove_resource_from_collection($current_contents_remove[$n], $collection, true);
     }
 }
 $endTime = microtime(true);
 $elapsed = $endTime - $startTime;
 if (RUNNING_ASYNC) {
     debug("smart_collections_async : {$elapsed} seconds for " . $smartsearch['search']);
 }
function managed_collection_request($ref, $details, $ref_is_resource = false)
{
    # Request mode 1
    # Managed via the administrative interface
    # An e-mail is still sent.
    global $applicationname, $email_from, $baseurl, $email_notify, $username, $useremail, $userref, $lang, $request_senduserupdates, $watermark, $filename_field, $view_title_field, $access, $resource_type_request_emails, $manage_request_admin;
    # Has a resource reference (instead of a collection reference) been passed?
    # Manage requests only work with collections. Create a collection containing only this resource.
    if ($ref_is_resource) {
        $admin_mail_template = "emailresourcerequest";
        $user_mail_template = "emailuserresourcerequest";
        $resourcedata = get_resource_data($ref);
        $templatevars['thumbnail'] = get_resource_path($ref, true, "thm", false, "jpg", $scramble = -1, $page = 1, $watermark ? $access == 1 ? true : false : false);
        # Allow alternative configuration settings for this resource type
        resource_type_config_override($resourcedata['resource_type']);
        if (!file_exists($templatevars['thumbnail'])) {
            $templatevars['thumbnail'] = "../gfx/" . get_nopreview_icon($resourcedata["resource_type"], $resourcedata["file_extension"], false);
        }
        $templatevars['url'] = $baseurl . "/?r=" . $ref;
        if (isset($filename_field)) {
            $templatevars["filename"] = $lang["fieldtitle-original_filename"] . ": " . get_data_by_field($ref, $filename_field);
        }
        if (isset($resourcedata["field" . $view_title_field])) {
            $templatevars["title"] = $resourcedata["field" . $view_title_field];
        }
        $c = create_collection($userref, $lang["request"] . " " . date("ymdHis"));
        add_resource_to_collection($ref, $c);
        $ref = $c;
        # Proceed as normal
    } else {
        $admin_mail_template = "emailcollectionrequest";
        $user_mail_template = "emailusercollectionrequest";
        $collectiondata = get_collection($ref);
        $templatevars['url'] = $baseurl . "/?c=" . $ref;
        if (isset($collectiondata["name"])) {
            $templatevars["title"] = $collectiondata["name"];
        }
    }
    # Fomulate e-mail text
    $templatevars['username'] = $username;
    $templatevars["useremail"] = $useremail;
    $userdata = get_user($userref);
    $templatevars["fullname"] = $userdata["fullname"];
    $message = "";
    reset($_POST);
    foreach ($_POST as $key => $value) {
        if (strpos($key, "_label") !== false) {
            # Add custom field
            $setting = trim($_POST[str_replace("_label", "", $key)]);
            if ($setting != "") {
                $message .= $value . ": " . $setting . "\n\n";
            }
        }
    }
    if (trim($details) != "") {
        $message .= $lang["requestreason"] . ": " . newlines($details) . "\n\n";
    } else {
        return false;
    }
    # Add custom fields
    $c = "";
    global $custom_request_fields, $custom_request_required;
    if (isset($custom_request_fields)) {
        $custom = explode(",", $custom_request_fields);
        # Required fields?
        if (isset($custom_request_required)) {
            $required = explode(",", $custom_request_required);
        }
        for ($n = 0; $n < count($custom); $n++) {
            if (isset($required) && in_array($custom[$n], $required) && getval("custom" . $n, "") == "") {
                return false;
                # Required field was not set.
            }
            $message .= i18n_get_translated($custom[$n]) . ": " . getval("custom" . $n, "") . "\n\n";
        }
    }
    # Create the request
    global $request_query;
    $request_query = "insert into request(user,collection,created,request_mode,status,comments) values ('{$userref}','{$ref}',now(),1,0,'" . escape_check($message) . "')";
    global $notify_manage_request_admin, $assigned_to_user;
    $notify_manage_request_admin = false;
    // Manage individual requests of resources:
    hook('autoassign_individual_requests', '', array($userref, $ref, $message, isset($collectiondata)));
    if (isset($manage_request_admin) && !isset($collectiondata)) {
        $query = sprintf("\n                    SELECT DISTINCT r.resource_type AS value\n                      FROM collection_resource AS cr\n                INNER JOIN resource r ON cr.resource = r.ref\n                     WHERE cr.collection = '%s';\n            ", $ref);
        $request_resource_type = sql_value($query, 0);
        if ($request_resource_type != 0 && array_key_exists($request_resource_type, $manage_request_admin)) {
            $request_query = sprintf("\n                    INSERT INTO request(\n                                            user,\n                                            collection,\n                                            created,\n                                            request_mode,\n                                            `status`,\n                                            comments,\n                                            assigned_to\n                                       )\n                         VALUES (\n                                     '%s',\n                                     '%s',\n                                     NOW(),\n                                     1,\n                                     0,\n                                     '%s',\n                                     '%s'\n                                );\n                ", $userref, $ref, escape_check($message), $manage_request_admin[$request_resource_type]);
            $assigned_to_user = get_user($manage_request_admin[$request_resource_type]);
            $notify_manage_request_admin = true;
        }
    }
    // Manage collection requests:
    hook('autoassign_collection_requests', '', array($userref, isset($collectiondata) ? $collectiondata : array(), $message, isset($collectiondata)));
    if (isset($manage_request_admin) && isset($collectiondata)) {
        $all_r_types = get_resource_types();
        foreach ($all_r_types as $r_type) {
            $all_resource_types[] = $r_type['ref'];
        }
        $resources = get_collection_resources($collectiondata['ref']);
        // Get distinct resource types found in this collection:
        $resource_types = array();
        $collection_resources_by_type = array();
        foreach ($resources as $resource_id) {
            $resource_data = get_resource_data($resource_id);
            $resource_types[$resource_id] = $resource_data['resource_type'];
            // Create a list of resource IDs based on type to separate them into different collections:
            $collection_resources_by_type[$resource_data['resource_type']][] = $resource_id;
        }
        // Split into collections based on resource type:
        foreach ($collection_resources_by_type as $collection_type => $collection_resources) {
            // Store all resources of unmanaged type in one collection which will be sent to the system administrator:
            if (!isset($manage_request_admin[$collection_type])) {
                $collections['not_managed'] = create_collection($userref, $collectiondata['name'] . ' for unmanaged types');
                foreach ($collection_resources as $collection_resource_id) {
                    add_resource_to_collection($collection_resource_id, $collections['not_managed']);
                }
                continue;
            }
            $collections[$collection_type] = create_collection($userref, $collectiondata['name'] . ' for type ' . $collection_type);
            foreach ($collection_resources as $collection_resource_id) {
                add_resource_to_collection($collection_resource_id, $collections[$collection_type]);
            }
        }
        if (isset($collections) && count($collections) > 1) {
            foreach ($collections as $request_resource_type => $collection_id) {
                $assigned_to = '';
                $assigned_to_user['email'] = $email_notify;
                if (array_key_exists($request_resource_type, $manage_request_admin)) {
                    $assigned_to = $manage_request_admin[$request_resource_type];
                    $assigned_to_user = get_user($manage_request_admin[$request_resource_type]);
                }
                $request_query = sprintf("\n                        INSERT INTO request(\n                                                user,\n                                                collection,\n                                                created,\n                                                request_mode,\n                                                `status`,\n                                                comments,\n                                                assigned_to\n                                           )\n                             VALUES (\n                                         '%s',\n                                         '%s',\n                                         NOW(),\n                                         1,\n                                         0,\n                                         '%s',\n                                         '%s'\n                                    );\n                    ", $userref, $collection_id, escape_check($message), $assigned_to);
                if (trim($assigned_to) == '') {
                    $request_query = sprintf("\n                        INSERT INTO request(\n                                                user,\n                                                collection,\n                                                created,\n                                                request_mode,\n                                                `status`,\n                                                comments\n                                           )\n                             VALUES (\n                                         '%s',\n                                         '%s',\n                                         NOW(),\n                                         1,\n                                         0,\n                                         '%s'\n                                    );\n                    ", $userref, $collection_id, escape_check($message));
                }
                sql_query($request_query);
                $request = sql_insert_id();
                // Send the mail:
                $email_message = $lang['requestassignedtoyoumail'] . "\n\n" . $baseurl . "/?q=" . $request . "\n";
                send_mail($assigned_to_user['email'], $applicationname . ': ' . $lang['requestassignedtoyou'], $email_message);
                unset($email_message);
            }
            $notify_manage_request_admin = false;
        } else {
            $ref = implode('', $collections);
        }
    }
    if (hook('bypass_end_managed_collection_request', '', array(!isset($collectiondata), $ref, $request_query, $message, $templatevars, $assigned_to_user, $admin_mail_template, $user_mail_template))) {
        return true;
    }
    sql_query($request_query);
    $request = sql_insert_id();
    $templatevars["request_id"] = $request;
    $templatevars["requesturl"] = $baseurl . "/?q=" . $request;
    $templatevars["requestreason"] = $message;
    hook("afterrequestcreate", "", array($request));
    # Automatically notify the admin who was assigned the request:
    if (isset($manage_request_admin) && $notify_manage_request_admin) {
        $message = $lang['requestassignedtoyoumail'] . "\n\n" . $baseurl . "/?q=" . $request . "\n";
        send_mail($assigned_to_user['email'], $applicationname . ': ' . $lang['requestassignedtoyou'], $message);
    }
    # Check if alternative request email notification address is set, only valid if collection contains resources of the same type
    $admin_notify_email = $email_notify;
    if (isset($resource_type_request_emails)) {
        $requestrestypes = array_unique(sql_array("select r.resource_type as value from collection_resource cr left join resource r on cr.resource=r.ref where cr.collection='{$ref}'"));
        if (count($requestrestypes) == 1 && isset($resource_type_request_emails[$requestrestypes[0]])) {
            $admin_notify_email = $resource_type_request_emails[$requestrestypes[0]];
        }
    }
    # Send the e-mail
    $userconfirmmessage = $lang["requestsenttext"] . "<br /><br />{$message}<br /><br />" . $lang["clicktoviewresource"] . "<br />{$baseurl}/?c={$ref}";
    $message = $lang["user_made_request"] . "<br /><br />" . $lang["username"] . ": " . $username . "<br />{$message}<br /><br />";
    $message .= $lang["clicktoviewresource"] . "<br />{$baseurl}/?q={$request}";
    send_mail($admin_notify_email, $applicationname . ": " . $lang["requestcollection"] . " - {$ref}", $message, $useremail, $useremail, $admin_mail_template, $templatevars);
    if ($request_senduserupdates) {
        send_mail($useremail, $applicationname . ": " . $lang["requestsent"] . " - {$ref}", $userconfirmmessage, $email_from, $email_notify, $user_mail_template, $templatevars);
    }
    # Increment the request counter
    sql_query("update resource set request_count=request_count+1 where ref='{$ref}'");
    return true;
}
function csv_upload_process($filename, &$meta, $resource_types, &$messages, $override = "", $max_error_count = 100, $processcsv = false)
{
    // echo "csv_upload_process(" . $filename . ", Resource types: ";
    // foreach($resource_types as $restype) {echo $restype. ", ";}
    // echo "Override:" . $override . "<br>";
    // if($processcsv){echo "Processing CSV file<br>";}
    $file = fopen($filename, 'r');
    $line_count = 0;
    if (($header = fgetcsv($file)) == false) {
        array_push($messages, "No header found");
        fclose($file);
        return false;
    }
    for ($i = 0; $i < count($header); $i++) {
        $header[$i] = strtoupper($header[$i]);
    }
    # ----- start of header row checks -----
    $resource_types_allowed = array();
    $resource_type_filter = getvalescaped("resource_type", "", true);
    if (getvalescaped("add_to_collection", "") != "") {
        include dirname(__FILE__) . "/../../../include/collections_functions.php";
        global $usercollection;
        $add_to_collection = true;
    } else {
        $add_to_collection = false;
    }
    foreach (array_keys($resource_types) as $resource_type) {
        if (!isset($meta[$resource_type])) {
            continue;
        }
        $missing_fields = array();
        foreach ($meta[$resource_type] as $field_name => $field_attributes) {
            if ($override != "" && $resource_type_filter != $resource_type && $resource_type != 0) {
                continue;
            }
            if ($field_attributes['required'] && array_search($field_name, $header) === false) {
                $meta[$resource_type][$field_name]['missing'] = true;
                array_push($missing_fields, $meta[$resource_type][$field_name]['nicename']);
            }
        }
        //if (count($missing_fields)==0 || $override==0 || ($override=="" || ($override==0 && $resource_type==$resource_type_filter)))
        if ($override == 0 || count($missing_fields) == 0 && ($override == "" || $resource_type == $resource_type_filter)) {
            array_push($messages, "Info: Found correct field headers for resource_type {$resource_type}({$resource_types[$resource_type]})");
            array_push($resource_types_allowed, $resource_type);
        } else {
            array_push($messages, "Warning: resource_type {$resource_type}({$resource_types[$resource_type]}) has missing field headers (" . implode(",", $missing_fields) . ") and will be ignored");
        }
    }
    if ($override != "" && array_search($resource_type_filter, $resource_types_allowed) === false) {
        array_push($messages, "Error: override resource_type {$resource_type_filter}({$resource_types[$resource_type_filter]}) not found or headers are incomplete");
        fclose($file);
        return false;
    } else {
        if ($override != "") {
            array_push($messages, "Info: Override resource_type {$resource_type_filter}({$resource_types[$resource_type_filter]}) is valid");
        }
    }
    if (count($header) == count(array_unique($header))) {
        array_push($messages, "Info: No duplicate header fields found");
    } else {
        array_push($messages, "Error: duplicate header fields found");
        fclose($file);
        return false;
    }
    # ----- end of header row checks, process each of the rows checking data -----
    $resource_type_index = array_search("RESOURCE_TYPE", $header);
    // index of column that contains the resource type
    $error_count = 0;
    echo "Processing " . count($header) . " columns<br>";
    while (($line = fgetcsv($file)) !== false && $error_count < $max_error_count) {
        $line_count++;
        if (!$processcsv && count($line) != count($header)) {
            array_push($messages, "Error: Incorrect number of columns(" . count($line) . ") found on line " . $line_count . " (should be " . count($header) . ")");
            $error_count++;
            continue;
        }
        // important! this is where the override happens
        if ($resource_type_index !== false && $override != 1) {
            $resource_type = $line[$resource_type_index];
            if ($override === 0 && $resource_type_filter != $resource_type) {
                continue;
            }
            // User has selected to only import a specific resource type
        } else {
            $resource_type = $resource_type_filter;
        }
        //echo "Resource type: " . $resource_type . "<br>";
        if (array_search($resource_type, $resource_types_allowed) === false) {
            if ($processcsv) {
                array_push($messages, "Skipping resource type " . $resource_type);
            }
            continue;
        }
        if ($processcsv) {
            // Create the new resource
            $newref = create_resource($resource_type);
            array_push($messages, "Created new resource: #" . $newref . " (" . $resource_types[$resource_type] . ")");
            if ($add_to_collection) {
                add_resource_to_collection($newref, $usercollection);
            }
        }
        $cell_count = -1;
        global $additional_archive_states;
        $valid_archive_states = array_merge(array(-2, -1, 0, 1, 2, 3), $additional_archive_states);
        // Now process the actual data
        foreach ($header as $field_name) {
            if ($field_name == "RESOURCE_TYPE") {
                $cell_count++;
                continue;
            }
            //echo "Getting data for " . $field_name . "<br>";
            $cell_count++;
            $cell_value = trim($line[$cell_count]);
            // important! we trim values, as options may contain a space after the comma
            //echo "Found value for " . $field_name . ": " . $cell_value . "<br>";
            if ($field_name == "ACCESS" && $processcsv) {
                //echo "Checking access<br>";
                $selectedaccess = in_array(getvalescaped("access", "", true), array(0, 1, 2)) ? getvalescaped("access", "", true) : "default";
                // Must be a valid access value
                if ($selectedaccess == "default") {
                    continue 2;
                }
                // Ignore this and the system will use default
                $cellaccess = in_array($cell_value, array(0, 1, 2)) ? $cell_value : "";
                // value from CSV
                $accessaction = getvalescaped("access_action", "", true);
                // Do we always override or only use the user selected value if missing or invalid CSV value
                if ($accessaction == 2 || $cellaccess == "") {
                    $access = $selectedaccess;
                } else {
                    $access = $cellaccess;
                }
                // use the cell value
                //echo "Updating the resource access: " . $access . "<br>";
                sql_query("update resource set access='{$access}' where ref='{$newref}'");
                continue;
            }
            if ($field_name == "STATUS" && $processcsv) {
                //echo "Checking status<br>";
                $selectedarchivestatus = in_array(getvalescaped("status", "", true), $valid_archive_states) ? getvalescaped("status", "", true) : "default";
                // Must be a valid status value
                if ($selectedarchivestatus == "default") {
                    continue 2;
                }
                // Ignore this and the system will use default
                $cellarchivestatus = in_array($cell_value, $valid_archive_states) ? $cell_value : "";
                // value from CSV
                $statusaction = getvalescaped("status_action", "", true);
                // Do we always override or only use the user selected value if missing or invalid CSV value
                if ($statusaction == 2 || $cellarchivestatus == "") {
                    $status = $selectedarchivestatus;
                } else {
                    $status = $cellarchivestatus;
                }
                // use the cell value
                //echo "Updating the resource archive status: " . $status . "<br>";
                update_archive_status($newref, $status);
                continue;
            }
            if (!isset($meta[$resource_type][$field_name])) {
                if (isset($meta[0][$field_name])) {
                    $field_resource_type = 0;
                } else {
                    //echo "Field not found : " . $field_name . "<br>";
                    continue;
                }
            } else {
                $field_resource_type = $resource_type;
            }
            if (!($field_name == "ACCESS" || $field_name == "RESOURCE_TYPE" || $field_name == "STATUS")) {
                // Check for multiple options
                if (strpos($cell_value, ",") > 0 && count($meta[$field_resource_type][$field_name]['options']) > 0 && !in_array($meta[$field_resource_type][$field_name]['type'], array(3, 12))) {
                    $cell_values = explode(",", $cell_value);
                } else {
                    // Make single value into a dummy array
                    $cell_values = array($cell_value);
                }
                $update_dynamic_field = false;
                if ($meta[$field_resource_type][$field_name]['required']) {
                    if ($cell_value == null or $cell_value == "") {
                        array_push($messages, "Error: Empty value for \"{$field_name}\" required field not allowed - found on line {$line_count}");
                        $error_count++;
                        continue;
                    }
                    foreach ($cell_values as $cell_actual_value) {
                        if (count($meta[$field_resource_type][$field_name]['options']) > 0 && array_search($cell_actual_value, $meta[$field_resource_type][$field_name]['options']) === false) {
                            if ($meta[$field_resource_type][$field_name]['type'] == 9) {
                                // Need to add to options table
                                $meta[$field_resource_type][$field_name]['options'][] = trim($cell_actual_value);
                                $update_dynamic_field = true;
                            } else {
                                array_push($messages, "Error: Value \"{$cell_actual_value}\" not found in lookup for \"{$field_name}\" required field - found on line {$line_count}");
                                $error_count++;
                                continue;
                            }
                        }
                    }
                } else {
                    if ($cell_value == null or $cell_value == "") {
                        continue;
                    }
                    foreach ($cell_values as $cell_actual_value) {
                        if (count($meta[$field_resource_type][$field_name]['options']) > 0 && array_search(trim($cell_actual_value), $meta[$field_resource_type][$field_name]['options']) === false) {
                            if ($meta[$field_resource_type][$field_name]['type'] == 9) {
                                // Need to add to options table
                                $meta[$field_resource_type][$field_name]['options'][] = trim($cell_actual_value);
                                $update_dynamic_field = true;
                                array_push($messages, "Adding option for field " . $meta[$field_resource_type][$field_name]['remote_ref'] . ": " . $cell_actual_value);
                            } else {
                                array_push($messages, "Error: Value \"{$cell_actual_value}\" not found in lookup for \"{$field_name}\" field - found on line {$line_count}");
                                $error_count++;
                                continue;
                            }
                        }
                    }
                }
                if ($processcsv) {
                    // Prefix value with comma as this is required for indexing and rendering selected options
                    if (in_array($meta[$field_resource_type][$field_name]['type'], array(2, 3, 7, 9, 12)) && substr($cell_value, 0, 1) != ',') {
                        $cell_value = ',' . $cell_value;
                    }
                    update_field($newref, $meta[$field_resource_type][$field_name]['remote_ref'], $cell_value);
                    if ($meta[$field_resource_type][$field_name]['type'] == 9 && $update_dynamic_field) {
                        debug("updating dynamic field options for field " . $field_name);
                        sql_query("update resource_type_field set options='," . escape_check(implode(",", $meta[$field_resource_type][$field_name]['options'])) . "' where ref='" . $meta[$field_resource_type][$field_name]['remote_ref'] . "'");
                    }
                }
            }
            ob_flush();
        }
        // end of cell loop
        // Set archive state if no header found in CSV
        if ($processcsv && !in_array("STATUS", $header)) {
            $selectedarchivestatus = in_array(getvalescaped("status", ""), $valid_archive_states) ? getvalescaped("status", "") : "default";
            // Must be a valid status value
            if ($selectedarchivestatus != "default") {
                update_archive_status($newref, $selectedarchivestatus);
            }
        }
        // Set access if no header found in CSV
        if ($processcsv && !in_array("ACCESS", $header)) {
            $selectedaccess = in_array(getvalescaped("access", "", true), array(0, 1, 2)) ? getvalescaped("access", "", true) : "default";
            // Must be a valid access value
            if ($selectedaccess != "default") {
                sql_query("update resource set access='{$selectedaccess}' where ref='{$newref}'");
            }
        }
    }
    // end of loop through lines
    fclose($file);
    if ($line_count == 1 && !$processcsv) {
        array_push($messages, "Error: No lines of data found in file");
    }
    if ($error_count > 0) {
        if ($error_count == $max_error_count) {
            array_push($messages, "Warning: Showing first {$max_error_count} data validation errors only - more may exist");
        }
        return false;
    }
    array_push($messages, "Info: data successfully validated");
    return true;
}
function HookAutoassign_mrequestsAllAutoassign_collection_requests($user_ref, $collection_data, $message, $manage_collection_request)
{
    global $manage_request_admin, $assigned_to_user, $email_notify, $lang, $baseurl, $applicationname, $request_query, $notify_manage_request_admin;
    // Do not process this any further as this should only handle collection requests
    if (!$manage_collection_request) {
        return false;
    }
    $resources = get_collection_resources($collection_data['ref']);
    $mapped_fields = get_mapped_fields();
    $collection_resources_by_assigned_user = array();
    $collections = array();
    // Build the collections map between asigned user and resources the collection should contain
    foreach ($resources as $resource) {
        $resource_data = get_resource_field_data($resource);
        $assigned_administrator = 0;
        $resource_not_assigned = true;
        foreach ($resource_data as $r_data) {
            if (in_array($r_data['ref'], $mapped_fields)) {
                $assigned_administrator = get_mapped_user_by_field($r_data['ref'], $r_data['value']);
                if ($assigned_administrator === 0) {
                    $collection_resources_by_assigned_user['not_managed'][] = $resource;
                } else {
                    $collection_resources_by_assigned_user[$assigned_administrator][] = $resource;
                }
                $resource_not_assigned = false;
                break;
            }
        }
        if ($resource_not_assigned && !isset($manage_request_admin)) {
            $collection_resources_by_assigned_user['not_managed'][] = $resource;
        }
    }
    // Create collections based on who is supposed to handle the request
    foreach ($collection_resources_by_assigned_user as $assigned_user_id => $collection_resources) {
        if ($assigned_user_id === 'not_managed') {
            $collections['not_managed'] = create_collection($user_ref, $collection_data['name'] . ' request for unmanaged resources');
            foreach ($collection_resources as $collection_resource_id) {
                add_resource_to_collection($collection_resource_id, $collections['not_managed']);
            }
            continue;
        }
        $user = get_user($assigned_user_id);
        $collections[$assigned_user_id] = create_collection($user_ref, $collection_data['name'] . ' request - managed by ' . $user['email']);
        foreach ($collection_resources as $collection_resource_id) {
            add_resource_to_collection($collection_resource_id, $collections[$assigned_user_id]);
        }
        // Attach assigned admin to this collection
        add_collection($user['ref'], $collections[$assigned_user_id]);
    }
    if (!empty($collections)) {
        foreach ($collections as $assigned_to => $collection_id) {
            $assigned_to_user = get_user($assigned_to);
            $request_query = sprintf("\n                    INSERT INTO request(\n                                            user,\n                                            collection,\n                                            created,\n                                            request_mode,\n                                            `status`,\n                                            comments,\n                                            assigned_to\n                                       )\n                         VALUES (\n                                     '%s',  # user\n                                     '%s',  # collection\n                                     NOW(), # created\n                                     1,     # request_mode\n                                     0,     # status\n                                     '%s',  # comments\n                                     '%s'   # assigned_to\n                                );\n                ", $user_ref, $collection_id, escape_check($message), $assigned_to);
            if ($assigned_to === 'not_managed' || !$assigned_to_user) {
                $assigned_to_user['email'] = $email_notify;
                $request_query = sprintf("\n                        INSERT INTO request(\n                                                user,\n                                                collection,\n                                                created,\n                                                request_mode,\n                                                `status`,\n                                                comments\n                                           )\n                             VALUES (\n                                         '%s',  # user\n                                         '%s',  # collection\n                                         NOW(), # created\n                                         1,     # request_mode\n                                         0,     # status\n                                         '%s'   # comments\n                                    );\n                    ", $user_ref, $collection_id, escape_check($message), $assigned_to);
            }
            sql_query($request_query);
            $request = sql_insert_id();
            // Send the mail:
            $email_message = $lang['requestassignedtoyoumail'] . "\n\n" . $baseurl . "/?q=" . $request . "\n";
            send_mail($assigned_to_user['email'], $applicationname . ': ' . $lang['requestassignedtoyou'], $email_message);
            unset($email_message);
        }
        $notify_manage_request_admin = false;
    }
    // If we've got this far, make sure auto assigning managed requests based on resource types won't overwrite this
    unset($manage_request_admin);
    return true;
}
echo htmlspecialchars($collection);
?>
';</script>
<?php 
$add = getvalescaped("add", "");
if ($add != "") {
    if (strpos($add, ",") > 0) {
        $addarray = explode(",", $add);
    } else {
        $addarray[0] = $add;
        unset($add);
    }
    foreach ($addarray as $add) {
        hook("preaddtocollection");
        #add to current collection
        if (add_resource_to_collection($add, $usercollection, false, getvalescaped("size", "")) == false) {
            ?>
			<script language="Javascript">alert("<?php 
            echo $lang["cantmodifycollection"];
            ?>
");</script><?php 
        } else {
            # Log this
            daily_stat("Add resource to collection", $add);
            # Update resource/keyword kit count
            $search = getvalescaped("search", "");
            if (strpos($search, "!") === false && $search != "") {
                update_resource_keyword_hitcount($add, $search);
            }
            hook("postaddtocollection");
        }
		{
		if($sharing_related)
			{
			// User has chosen to include related resources, so treat as sharing a new collection
			$relatedshares=explode(",",getvalescaped("sharerelatedresources",""));
			}
		// Create new collection
		$allow_changes=(getval("allow_changes","")!=""?1:0);
		$sharedcollection=create_collection($userref,i18n_get_translated($resource["field".$view_title_field]) . " Share " . nicedate(date("Y-m-d H:i:s")),$allow_changes);
		
		add_resource_to_collection($ref,$sharedcollection);
		if($sharing_related)
			{
			foreach($relatedshares as $relatedshare)
				{
				add_resource_to_collection($relatedshare,$sharedcollection);
				}			
			}
			
		$errors=email_collection($sharedcollection,i18n_get_collection_name($sharedcollection),$userfullname,$users,$message,false,$access,$expires,$user_email,$from_name,$cc,false,"","",$list_recipients,$add_internal_access);
		// Hide from drop down by default
		show_hide_collection($sharedcollection, false, $userref);
		
		if ($errors=="")
			{
			// Log this	
			// fix for bomb on multiple collections, daily stat object ref must be a single number.
			$crefs=explode(",",$ref);
			foreach ($crefs as $cref){		
				daily_stat("E-mailed collection",$cref);
			}
	# Move the file
	$destination=get_resource_path($r,true,"",true,$file['extension']);	
	$result=rename($temp_dir."/".$file['filename'],$destination);  echo "Moving file to filestore \r\n";
	chmod($destination,0777);

	# get file metadata 
	extract_exif_comment($r,$file['extension']); echo "Extracting Metadata... \r\n";
	
	# Ensure folder is created, then create previews.
	get_resource_path($r,false,"pre",true,$file['extension']);
					
	if ($build_collection){
		# Add Resource to Collection
		echo "Adding Resource $r to Collection $collection \r\n";
		add_resource_to_collection($r,$collection,true);
	}
					
	# Generate previews/thumbnails (if configured i.e if not completed by offline process 'create_previews.php')
	global $enable_thumbnail_creation_on_upload;
	if ($enable_thumbnail_creation_on_upload) {
		create_previews($r,false,$file['extension']); 
		echo "Creating Previews... \r\n";
	}
		 
	if (!$build_collection && $checkmail_confirm){
		email_resource($r,$subject,$applicationname,$fromusername,$lang['yourresourcehasbeenuploaded'],0,$expires="",$fromaddress,$applicationname);
		echo "Email Confirmation sent. \r\n";
	}

	if ($checkmail_purge){$delete=true;}
        if ($k == "") {
            set_user_collection($userref, $collection);
        }
        $usercollection = $collection;
    }
    hook("postchangecollection");
}
if (hook("modifyusercollection")) {
    $usercollection = hook("modifyusercollection");
}
# Process adding of items
$add = getvalescaped("add", "");
if ($add != "") {
    hook("preaddtocollection");
    #add to current collection
    if (add_resource_to_collection($add, $usercollection) == false) {
        ?>
<script type="text/javascript">alert("<?php 
        echo $lang["cantmodifycollection"];
        ?>
");</script><?php 
    }
    # Log this
    daily_stat("Add resource to collection", $add);
    # update resource/keyword kit count
    $search = getvalescaped("search", "");
    if (strpos($search, "!") === false && $search != "") {
        update_resource_keyword_hitcount($add, $search);
    }
    hook("postaddtocollection");
}