Example #1
0
function plugin_search_action()
{
    global $post, $vars;
    $_title_search = _('Search for word(s)');
    $_title_result = _('Search result of  $1');
    $_msg_searching = _('Key words are case-insenstive, and are searched for in all pages.');
    if (PLUGIN_SEARCH_DISABLE_GET_ACCESS) {
        $s_word = isset($post['word']) ? htmlspecialchars($post['word']) : '';
    } else {
        $s_word = isset($vars['word']) ? htmlspecialchars($vars['word']) : '';
    }
    if (strlen($s_word) > PLUGIN_SEARCH_MAX_LENGTH) {
        unset($vars['word']);
        // Stop using $_msg_word at lib/html.php
        die_message('Search words too long');
    }
    $type = isset($vars['type']) ? $vars['type'] : '';
    $base = isset($vars['base']) ? $vars['base'] : '';
    if ($s_word != '') {
        // Search
        $msg = str_replace('$1', $s_word, $_title_result);
        $body = do_search($vars['word'], $type, FALSE, $base);
    } else {
        // Init
        unset($vars['word']);
        // Stop using $_msg_word at lib/html.php
        $msg = $_title_search;
        $body = '<br />' . "\n" . $_msg_searching . "\n";
    }
    // Show search form
    $bases = $base == '' ? array() : array($base);
    $body .= plugin_search_search_form($s_word, $type, $bases);
    return array('msg' => $msg, 'body' => $body);
}
Example #2
0
function plugin_search_action()
{
    global $post, $vars, $_title_result, $_title_search, $_msg_searching;
    if (PLUGIN_SEARCH_DISABLE_GET_ACCESS) {
        $s_word = isset($post['word']) ? htmlsc($post['word']) : '';
    } else {
        $s_word = isset($vars['word']) ? htmlsc($vars['word']) : '';
    }
    if (strlen($s_word) > PLUGIN_SEARCH_MAX_LENGTH) {
        unset($vars['word']);
        // Stop using $_msg_word at lib/html.php
        die_message('Search words too long');
    }
    $type = isset($vars['type']) ? $vars['type'] : '';
    $base = isset($vars['base']) ? $vars['base'] : '';
    if ($s_word != '') {
        // Search
        $msg = str_replace('$1', $s_word, $_title_result);
        $body = do_search($vars['word'], $type, false, $base);
    } else {
        // Init
        unset($vars['word']);
        // Stop using $_msg_word at lib/html.php
        $msg = $_title_search;
        $body = '<br />' . "\n" . $_msg_searching . "\n";
    }
    // Show search form
    $bases = $base == '' ? array() : array($base);
    $body .= plugin_search_search_form($s_word, $type, $bases);
    return array('msg' => $msg, 'body' => $body);
}
Example #3
0
     // The order is not exactly the votes
     // but a time-decreasing function applied to the number of votes
     $sql = "select link_id, counter*(1-(unix_timestamp(now())-unix_timestamp(link_date))*0.5/172800) as value from links, link_clicks, sub_statuses where sub_statuses.id = " . SitesMgr::my_id() . " AND link_id = link AND status='published' and date > '{$min_date}' and link_clicks.id = link order by value desc limit 25";
 } else {
     /////
     // All the others
     /////
     // The link_status to search
     if (!empty($_REQUEST['status'])) {
         $status = $db->escape(clean_input_string(trim($_REQUEST['status'])));
     } else {
         // By default it searches on all
         if ($_REQUEST['q']) {
             $status = 'all';
             include mnminclude . 'search.php';
             $search_ids = do_search(true);
             if ($search_ids['ids']) {
                 $search = ' link_id in (' . implode(',', $search_ids['ids']) . ')';
             }
         } else {
             $status = 'published';
         }
     }
     switch ($status) {
         case 'published':
             $order_field = 'date';
             $link_date = 'date';
             $title = $site_info->name . ': ' . _('publicadas');
             break;
         case 'queued':
             $title = $site_info->name . ': ' . _('en cola');
 public function search_relations()
 {
     do_search(false, false, true);
 }
<div class="clearerleft"> </div>
</div>

<div class="Question">
<label><?php echo $lang["resourceid"]?></label><div class="Fixed"><?php echo $resource["ref"]?></div>
<div class="clearerleft"> </div>
</div>



<?php
// -------- Related Resources (must be able to search for this to work)
if ($share_resource_include_related && $enable_related_resources && checkperm("s") && ($k==""))
	{
		
	$result=do_search("!related" . $ref);
	if (count($result)>0) 
		{
		?>
		<div class="Question" id="sharerelatedresources">
		<label><?php echo $lang["sharerelatedresources"]?></label>
		<input type="hidden" name="sharerelatedresources" id="sharerelatedresourcesfield"  value="" >
		<div class="sharerelatedresources">
		<?php
	
			for ($n=0;$n<count($result);$n++)
				{
				$related_restype=$result[$n]["resource_type"];
				$related_restypes[]=$related_restype;
				}
			//reduce array to unique values
function is_collection_approved($collection)
{
    if (is_array($collection)) {
        $result = $collection;
    } else {
        $result = do_search("!collection" . $collection, "", "relevance", 0, -1, "desc", false, "", false, "");
    }
    if (!is_array($result) || count($result) == 0) {
        return true;
    }
    $collectionstates = array();
    global $collection_allow_not_approved_share;
    for ($n = 0; $n < count($result); $n++) {
        $archivestatus = $result[$n]["archive"];
        if ($archivestatus < 0 && !$collection_allow_not_approved_share) {
            return false;
        }
        $collectionstates[] = $archivestatus;
    }
    return array_unique($collectionstates);
}
Example #7
0
	<?php hook("purchase_extra_options"); ?>
	
	<?php if ($showbuy) { ?>
		<p><input type="submit" name="submit" value="&nbsp;&nbsp;&nbsp;<?php echo $lang["buynow"]?>&nbsp;&nbsp;&nbsp;"></p>
	<?php } ?>
	</form>
	</div>
	<?php
	}
else
	{
	# ----------------------------------- Show the PayPal integration instead ------------------------------------
	$pricing_discounted=$pricing; # Copy the pricing, which may be group specific
	include "../include/config.php"; # Reinclude the config so that $pricing is now the default, and we can work out group discounts
	
	$resources=do_search("!collection" . $usercollection);
	$n=1;
	$paypal="";
	$totalprice=0;
	$totalprice_ex_discount=0;
	foreach ($resources as $resource)
		{
		$sizes=get_image_sizes($resource["ref"]);
		$title=get_data_by_field($resource["ref"],$view_title_field);
		foreach ($sizes as $size)
			{
			if (getval("select_" . $resource["ref"],"")==$size["id"])
				{
				$name=$size["name"];
				$id=$size["id"];
				if ($id=="") {$id="hpr";}
<?php

//echo "testing sp2<br/>";
# Perform the search
if (!isset($collections)) {
    $collections = search_public_collections($search, "theme", "ASC", !$search_includes_themes, !$search_includes_public_collections, false);
}
if (substr($search, 0, 11) != "!collection" && $collections != "") {
    for ($n = 0; $n < count($collections); $n++) {
        $resources = do_search("!collection" . $collections[$n]['ref'], "", "relevance", "", 5);
        $hook_result = hook("process_search_results", "", array("result" => $resources, "search" => "!collection" . $collections[$n]['ref']));
        if ($hook_result !== false) {
            $resources = $hook_result;
        }
        $pub_url = "search.php?search=" . urlencode("!collection" . $collections[$n]["ref"]);
        if ($display == "thumbs") {
            ?>
		<div class="ResourcePanelShell" id="ResourceShell">
		<div class="ResourcePanel">
	
		<table  border="0" class="ResourceAlign"><?php 
            hook("publicresulttop");
            ?>
<tr><td>
		
		<div style="position: relative;height:140px;">
		<a onClick="return CentralSpaceLoad(this,true);" href="<?php 
            echo $pub_url;
            ?>
" title="<?php 
            echo htmlspecialchars(str_replace(array("\"", "'"), "", i18n_get_collection_name($collections[$n])));
				else {
					jQuery("#showresourcecount").hide();
				}
			});
		</script>
		<?php 
    if ($promoted_resource) {
        global $link, $view_title_field;
        $search_string = explode('?', $link);
        parse_str(str_replace("&amp;", "&", $search_string[1]), $search_string);
        $search = isset($search_string["search"]) ? $search_string["search"] : "";
        $restypes = isset($search_string["restypes"]) ? $search_string["restypes"] : "";
        $order_by = isset($search_string["order_by"]) ? $search_string["order_by"] : "";
        $archive = isset($search_string["archive"]) ? $search_string["archive"] : "";
        $sort = isset($search_string["sort"]) ? $search_string["sort"] : "";
        $resources = do_search($search, $restypes, $order_by, $archive, -1, $sort);
        ?>
			<div class="Question" id="promotedresource">
				<label for="promoted_image">
				<?php 
        echo $lang["dashtileimage"];
        ?>
</label>
				<select class="stdwidth" id="previewimage" name="promoted_image">
				<?php 
        foreach ($resources as $resource) {
            ?>
					<option value="<?php 
            echo htmlspecialchars($resource["ref"]);
            ?>
" <?php 
Example #10
0
/**
 * Define a custom search routine.
 *
 * This hook allows a module to perform searches on content it defines
 * (custom node types, users, or comments, for example) when a site search
 * is performed.
 *
 * Note that you can use form API to extend the search. You will need to use
 * hook_form_alter() to add any additional required form elements. You can
 * process their values on submission using a custom validation function.
 * You will need to merge any custom search values into the search keys
 * using a key:value syntax. This allows all search queries to have a clean
 * and permanent URL. See node_form_search_form_alter() for an example.
 *
 * The example given here is for node.module, which uses the indexed search
 * capabilities. To do this, node module also implements hook_update_index()
 * which is used to create and maintain the index.
 *
 * We call do_search() with the keys, the module name, and extra SQL fragments
 * to use when searching. See hook_update_index() for more information.
 *
 * @param $op
 *   A string defining which operation to perform:
 *   - 'admin': The hook should return a form array containing any fieldsets the
 *     module wants to add to the Search settings page at admin/settings/search.
 *   - 'name': The hook should return a translated name defining the type of
 *     items that are searched for with this module ('content', 'users', ...).
 *   - 'reset': The search index is going to be rebuilt. Modules which use
 *     hook_update_index() should update their indexing bookkeeping so that it
 *     starts from scratch the next time hook_update_index() is called.
 *   - 'search': The hook should perform a search using the keywords in $keys.
 *   - 'status': If the module implements hook_update_index(), it should return
 *     an array containing the following keys:
 *     - remaining: The amount of items that still need to be indexed.
 *     - total: The total amount of items (both indexed and unindexed).
 * @param $keys
 *   The search keywords as entered by the user.
 * @return
 *   This varies depending on the operation.
 *   - 'admin': The form array for the Search settings page at
 *     admin/settings/search.
 *   - 'name': The translated string of 'Content'.
 *   - 'reset': None.
 *   - 'search': An array of search results. To use the default search result
 *     display, each item should have the following keys':
 *     - 'link': Required. The URL of the found item.
 *     - 'type': The type of item.
 *     - 'title': Required. The name of the item.
 *     - 'user': The author of the item.
 *     - 'date': A timestamp when the item was last modified.
 *     - 'extra': An array of optional extra information items.
 *     - 'snippet': An excerpt or preview to show with the result (can be
 *     generated with search_excerpt()).
 *   - 'status': An associative array with the key-value pairs:
 *     - 'remaining': The number of items left to index.
 *     - 'total': The total number of items to index.
 *
 * @ingroup search
 */
function hook_search($op = 'search', $keys = NULL)
{
    switch ($op) {
        case 'name':
            return t('Content');
        case 'reset':
            db_query("UPDATE {search_dataset} SET reindex = %d WHERE type = 'node'", REQUEST_TIME);
            return;
        case 'status':
            $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
            $remaining = db_result(db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND d.sid IS NULL OR d.reindex <> 0"));
            return array('remaining' => $remaining, 'total' => $total);
        case 'admin':
            $form = array();
            // Output form for defining rank factor weights.
            $form['content_ranking'] = array('#type' => 'fieldset', '#title' => t('Content ranking'));
            $form['content_ranking']['#theme'] = 'node_search_admin';
            $form['content_ranking']['info'] = array('#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>');
            // Note: reversed to reflect that higher number = higher ranking.
            $options = drupal_map_assoc(range(0, 10));
            foreach (module_invoke_all('ranking') as $var => $values) {
                $form['content_ranking']['factors']['node_rank_' . $var] = array('#title' => $values['title'], '#type' => 'select', '#options' => $options, '#default_value' => variable_get('node_rank_' . $var, 0));
            }
            return $form;
        case 'search':
            // Build matching conditions
            list($join1, $where1) = _db_rewrite_sql();
            $arguments1 = array();
            $conditions1 = 'n.status = 1';
            if ($type = search_query_extract($keys, 'type')) {
                $types = array();
                foreach (explode(',', $type) as $t) {
                    $types[] = "n.type = '%s'";
                    $arguments1[] = $t;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $types) . ')';
                $keys = search_query_insert($keys, 'type');
            }
            if ($category = search_query_extract($keys, 'category')) {
                $categories = array();
                foreach (explode(',', $category) as $c) {
                    $categories[] = "tn.tid = %d";
                    $arguments1[] = $c;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $categories) . ')';
                $join1 .= ' INNER JOIN {taxonomy_term_node} tn ON n.vid = tn.vid';
                $keys = search_query_insert($keys, 'category');
            }
            if ($languages = search_query_extract($keys, 'language')) {
                $categories = array();
                foreach (explode(',', $languages) as $l) {
                    $categories[] = "n.language = '%s'";
                    $arguments1[] = $l;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $categories) . ')';
                $keys = search_query_insert($keys, 'language');
            }
            // Get the ranking expressions.
            $rankings = _node_rankings();
            // When all search factors are disabled (ie they have a weight of zero),
            // The default score is based only on keyword relevance.
            if ($rankings['total'] == 0) {
                $total = 1;
                $arguments2 = array();
                $join2 = '';
                $select2 = 'i.relevance AS score';
            } else {
                $total = $rankings['total'];
                $arguments2 = $rankings['arguments'];
                $join2 = implode(' ', $rankings['join']);
                $select2 = '(' . implode(' + ', $rankings['score']) . ') AS score';
            }
            // Do search.
            $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid ' . $join1, $conditions1 . (empty($where1) ? '' : ' AND ' . $where1), $arguments1, $select2, $join2, $arguments2);
            // Load results.
            $results = array();
            foreach ($find as $item) {
                // Build the node body.
                $node = node_load($item->sid);
                $node = node_build_content($node, 'search_result');
                $node->body = drupal_render($node->content);
                // Fetch comments for snippet.
                $node->body .= module_invoke('comment', 'node', $node, 'update_index');
                // Fetch terms for snippet.
                $node->body .= module_invoke('taxonomy', 'node', $node, 'update_index');
                $extra = module_invoke_all('node_search_result', $node);
                $results[] = array('link' => url('node/' . $item->sid, array('absolute' => TRUE)), 'type' => check_plain(node_type_get_name($node)), 'title' => $node->title, 'user' => theme('username', $node), 'date' => $node->changed, 'node' => $node, 'extra' => $extra, 'score' => $total ? $item->score / $total : 0, 'snippet' => search_excerpt($keys, $node->body));
            }
            return $results;
    }
}
Example #11
0
    $offset = getvalescaped("saved_offset", 0);
    setcookie("saved_offset", $offset);
    $order_by = getvalescaped("saved_order_by", "relevance");
    setcookie("saved_order_by", $order_by);
    $archive = getvalescaped("saved_archive", 0);
    setcookie("saved_archive", $archive);
}
$refs = array();
#echo "search=$search";
# Special query? Ignore restypes
if (strpos($search, "!") !== false) {
    $restypes = "";
}
# Story only? Display as list
#if ($restypes=="2") {$display="list";}
$result = do_search($search, $restypes, "relevance", $archive, 100, "desc", false, $starsearch);
//echo $result[0];
# Create a title for the feed
$searchstring = "search={$search}&restypes={$restypes}&archive={$archive}&starsearch={$starsearch}";
$feed_title = $applicationname . " - " . xml_entities(get_search_title($searchstring));
$r = new RSSFeed($feed_title, $baseurl, str_replace("%search%", xml_entities($searchstring), $lang["filtered_resource_update_for"]));
// rss fields can include any of thumbs, smallthumbs, list, xlthumbs display fields, or data_joins.
$all_field_info = get_fields_for_search_display($rss_fields);
$n = 0;
foreach ($rss_fields as $display_field) {
    # Find field in selected list
    for ($m = 0; $m < count($all_field_info); $m++) {
        if ($all_field_info[$m]["ref"] == $display_field) {
            $field_info = $all_field_info[$m];
            $df[$n]['ref'] = $display_field;
            $df[$n]['name'] = $field_info['name'];
Example #12
0
                    ?>
	    <?php 
                }
                /*end if a collection search and compact_style - action selector*/
                ?>
    
    <?php 
            }
        }
        ?>

    <?php 
        hook("beforesearchresults");
        # Archive link
        if ($archive == 0 && strpos($search, "!") === false && $archive_search) {
            $arcresults = do_search($search, $restypes, $order_by, 2, 0);
            if (is_array($arcresults)) {
                $arcresults = count($arcresults);
            } else {
                $arcresults = 0;
            }
            if ($arcresults > 0) {
                ?>
		<div class="SearchOptionNav"><a href="<?php 
                echo $baseurl_short;
                ?>
pages/search.php?search=<?php 
                echo urlencode($search);
                ?>
&amp;archive=2" onClick="return CentralSpaceLoad(this);">&gt;&nbsp;<?php 
                echo $lang["view"];
Example #13
0
#
# Api_search setup page
#
// Do the include and authorization checking ritual -- don't change this section.
include '../../../include/db.php';
include '../../../include/authenticate.php';
if (!checkperm('a')) {
    exit($lang['error-permissiondenied']);
}
include '../../../include/general.php';
include '../../../include/search_functions.php';
// Specify the name of this plugin and the heading to display for the page.
$plugin_name = 'api_search';
$plugin_page_heading = $lang['api_search_configuration'];
// Build the $page_def array of descriptions of each configuration variable the plugin uses.
$result = do_search('', '', 'relevance', 0, 1);
if (isset($result[0])) {
    $list = "";
    foreach ($result[0] as $key => $value) {
        $list .= $key . ", ";
    }
}
$list = rtrim(trim($list), ",");
$page_def[] = config_add_text_input('api_search_exclude_fields', $lang['api_search_exclude_fields']);
$page_def[] = config_add_html($lang['api_search_excludable_fields'] . ": {$list}");
// Do the page generation ritual -- don't change this section.
$upload_status = config_gen_setup_post($page_def, $plugin_name);
include '../../../include/header.php';
config_gen_setup_html($page_def, $plugin_name, $upload_status, $plugin_page_heading);
include '../../../include/footer.php';
 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();
     }
 }
#
#
#
#
#
#
#
#
#
# admin-employee-rem.php :: Remove employees from db
##
require "settings.php";
if (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "search":
            $OUTPUT = do_search();
            break;
        default:
            $OUTPUT = "Invalid use.";
    }
} else {
    $OUTPUT = get_search();
}
require "template.php";
##
# Functions
##
function get_search()
{
    $display = "\n\t\t\t<h2>Search for Training</h2>\n\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<form action='" . SELF . "' method=post>\n\t\t\t\t<input type=hidden name=key value='search'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Search String</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type=text name=search_string size='50'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type=submit value='Search'></td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t</table>\n\t\t";
    return $display;
Example #16
0
$tabcount = 0;
$fieldcount = 0;
$extra = "";
$used_tab_names = array();
$show_default_related_resources = TRUE;
for ($n = 0; $n < count($fields); $n++) {
    $displaycondition = check_view_display_condition($fields, $n);
    if ($displaycondition) {
        if (!hook("renderfield")) {
            display_field_data($fields[$n]);
        }
    }
}
// Option to display related resources of specified types along with metadata
if ($enable_related_resources && $show_default_related_resources) {
    $relatedresources = do_search("!related" . $ref);
    #build array of related resources' types
    $related_restypes = array();
    for ($n = 0; $n < count($relatedresources); $n++) {
        $related_restypes[] = $relatedresources[$n]['resource_type'];
    }
    #reduce extensions array to unique values
    $related_restypes = array_unique($related_restypes);
    $relatedtypes_shown = array();
    $related_resources_shown = 0;
    if (isset($related_type_show_with_data)) {
        # Render fields with display template before the list of related resources:
        echo $extra;
        foreach ($related_type_show_with_data as $rtype) {
            // Is this a resource type that needs to be displayed?
            if (!in_array($rtype, $related_type_show_with_data) || !in_array($rtype, $related_restypes) && !$related_type_upload_link) {
function is_collection_approved($collection)
		{
		if (is_array($collection)){$result=$collection;}
		else {
			$result=do_search("!collection" . $collection,"","relevance",0,-1,"desc",false,"",false,"");
			}	
		if (!is_array($result)){return true;}
		for ($n=0;$n<count($result);$n++)
			{
			$archivestatus=$result[$n]["archive"];
			if ($archivestatus<0) {return false;}
			}
		return true;
		}
Example #18
0
<?php

include "globals.php";
if (!$_GET) {
    $smarty->display("index.html");
    die;
} else {
    $result = do_search($_GET['keywords'], $_GET['start'], "uludag.org.tr");
    $result2 = do_search($_GET['keywords'], $_GET['start'], "pardus.org.tr");
    //echo "<pre>";
    //print_r(merge($result, $result2));
    //echo "</pre>";
    $smarty->assign("results", merge($result, $result2));
    $smarty->display("search.html");
    die;
}
function do_search($kw, $start, $domain)
{
    global $config;
    $searchString = $kw . ' site:liste.' . $domain;
    $google = new googleClient($config['core']['licensekey']);
    if ($start) {
        $st = $start;
    } else {
        $st = 0;
    }
    if ($google->search($searchString, $st)) {
        $result = $google->results;
    }
    $result->searchTime = round($result->searchTime, 2);
    for ($i = 0; $i < count($result->resultElements); $i++) {
Example #19
0
    $sql->close();
}
/*--------------------------------------------------*/
//########################################################################################################################
// MAIN
//########################################################################################################################
// action variable reserved for future use
//$action = (isset($_GET['action'])) ? $_GET['action'] : NULL;
// load language
$lang_mail = lang_mail();
$output .= '
          <div class="top">
            <h1>' . $lang_mail['mail_on'] . '</h1>
          </div>';
// we getting links to realm database and character database left behind by header
// header does not need them anymore, might as well reuse the link
$action = isset($_GET['action']) ? $_GET['action'] : NULL;
switch ($action) {
    case "do_search":
        do_search();
        break;
    case "search":
        search();
        break;
    default:
        do_search();
}
//unset($action);
unset($action_permission);
unset($lang_mail);
require_once 'footer.php';
$restypes = getvalescaped("restypes", "");
$page = getvalescaped("page", 1);
$alternative = getvalescaped("alternative", -1);
if (strpos($search, "!") !== false) {
    $restypes = "";
}
$default_sort = "DESC";
if (substr($order_by, 0, 5) == "field") {
    $default_sort = "ASC";
}
$sort = getval("sort", $default_sort);
$headerinsert = "\n\t <!--[if lt IE 7]><link rel='stylesheet' type='text/css' href='../css/ie.css'><![endif]-->\n";
if ($allow_reorder) {
    $result = do_search("!collection" . $colref);
} else {
    $result = do_search("!collection" . $colref, '', $order_by, $archive, -1, $sort);
}
$hook_result = hook("process_search_results", "all", array("result" => $result, "search" => $search));
if ($hook_result !== false) {
    $result = $hook_result;
}
include "../include/header.php";
if (substr($search, 0, 11) == "!collection") {
    $collection = substr($search, 11);
    $collection = explode(",", $collection);
    $collection = $collection[0];
    $collectiondata = get_collection($collection);
    if (!$collectiondata) {
        ?>
		<script>alert('<?php 
        echo $lang["error-collectionnotfound"];
Example #21
0
$default_sort = "DESC";
if (substr($order_by, 0, 5) == "field") {
    $default_sort = "ASC";
}
$sort = getval("sort", $default_sort);
# next / previous resource browsing
$go = getval("go", "");
if ($go != "") {
    $origref = $ref;
    # Store the reference of the resource before we move, in case we need to revert this.
    # Re-run the search and locate the next and previous records.
    $modified_result_set = hook("modifypagingresult");
    if ($modified_result_set) {
        $result = $modified_result_set;
    } else {
        $result = do_search($search, $restypes, $order_by, $archive, -1, $sort, false, $starsearch);
    }
    if (is_array($result)) {
        # Locate this resource
        $pos = -1;
        for ($n = 0; $n < count($result); $n++) {
            if ($result[$n]["ref"] == $ref) {
                $pos = $n;
            }
        }
        if ($pos != -1) {
            if ($go == "previous" && $pos > 0) {
                $ref = $result[$pos - 1]["ref"];
            }
            if ($go == "next" && $pos < $n - 1) {
                $ref = $result[$pos + 1]["ref"];
Example #22
0
	else
		{
		set_user_collection($userref,$col);
		}
	hook("postresearch");
	}
	
hook("processusercommand");
?>


<?php 
$searches=get_saved_searches($usercollection);

// Note that the full search is done initially. The time saved is due to content drawing and transfer.
$result=do_search("!collection" . $usercollection,"","relevance",0);
$count_result=count($result);


$hook_count=hook("countresult","",array($usercollection,$count_result));if (is_numeric($hook_count)) {$count_result=$hook_count;} # Allow count display to be overridden by a plugin (e.g. that adds it's own resources from elsewhere e.g. ResourceConnect).
$feedback=$cinfo["request_feedback"];



# E-commerce functionality. Work out total price, if $basket_stores_size is enabled so that they've already selected a suitable size.
$totalprice=0;
if (($userrequestmode==2 || $userrequestmode==3) && $basket_stores_size)
	{
	foreach ($result as $resource)
		{
		# For each resource in the collection, fetch the price (set in config.php, or config override for group specific pricing)
    } else {
        if ($sheetstyle == "thumbnails") {
            $pdf->Setx($topx);
            $pdf->Cell($cellsize[0], $bottomy - $topy + $imagesize + 0.2, '', 0, 0);
        }
    }
}
$deltay = 1;
do_contactsheet_sizing_calculations();
#Get data
$collectiondata = get_collection($collection);
if (is_numeric($order_by)) {
    $order_by = "field" . $order_by;
}
//debug("Contact Sheet Sort is $order_by $sort");
$result = do_search("!collection" . $collection, "", $order_by, 0, -1, $sort);
if ($sheetstyle == "thumbnails") {
    $getfields = $config_sheetthumb_fields;
} else {
    if ($sheetstyle == "list") {
        $getfields = $config_sheetlist_fields;
    } else {
        if ($sheetstyle == "single") {
            $getfields = $config_sheetsingle_fields;
        }
    }
}
$csf = "";
for ($m = 0; $m < count($getfields); $m++) {
    $csf_data = sql_query("select name,value_filter, type from resource_type_field where ref='{$getfields[$m]}'");
    $csf[$m]['name'] = $csf_data[0]['name'];
 function get_resource_access($resource)
 {
     # $resource may be a resource_data array from a search, in which case, many of the permissions checks are already done.
     # Returns the access that the currently logged-in user has to $resource.
     # Return values:
     # 0 = Full Access (download all sizes)
     # 1 = Restricted Access (download only those sizes that are set to allow restricted downloads)
     # 2 = Confidential (no access)
     # Load the 'global' access level set on the resource
     # In the case of a search, resource type and global,group and user access are passed through to this point, to avoid multiple unnecessary get_resource_data queries.
     # passthru signifies that this is the case, so that blank values in group or user access mean that there is no data to be found, so don't check again .
     $passthru = "no";
     // get_resource_data doesn't contain permissions, so fix for the case that such an array could be passed into this function unintentionally.
     if (is_array($resource) && !isset($resource['group_access']) && !isset($resource['user_access'])) {
         $resource = $resource['ref'];
     }
     if (!is_array($resource)) {
         $resourcedata = get_resource_data($resource, true);
     } else {
         $resourcedata = $resource;
         $passthru = "yes";
     }
     $ref = $resourcedata['ref'];
     $access = $resourcedata["access"];
     $resource_type = $resourcedata['resource_type'];
     // Set a couple of flags now that we can check later on if we need to check whether sharing is permitted based on whether access has been specifically granted to user/group
     global $customgroupaccess, $customuseraccess;
     $customgroupaccess = false;
     $customuseraccess = false;
     global $k;
     if ($k != "") {
         # External access - check how this was shared.
         $extaccess = sql_value("select access value from external_access_keys where resource=" . $ref . " and access_key='" . escape_check($k) . "' and (expires is null or expires>now())", -1);
         if ($extaccess != -1) {
             return $extaccess;
         }
     }
     global $uploader_view_override, $userref;
     if (checkperm("z" . $resourcedata['archive']) && !($uploader_view_override && $resourcedata['created_by'] == $userref)) {
         // User has no access to this archive state
         return 2;
     }
     if (checkperm("v")) {
         # Permission to access all resources
         # Always return 0
         return 0;
     }
     if ($access == 3) {
         $customgroupaccess = true;
         # Load custom access level
         if ($passthru == "no") {
             global $usergroup;
             $access = get_custom_access($resource, $usergroup);
         } else {
             $access = $resource['group_access'];
         }
     }
     if ($access == 1 && get_edit_access($ref, $resourcedata['archive'], false, $resourcedata)) {
         # If access is restricted and user has edit access, grant open access.
         $access = 0;
     }
     global $open_access_for_contributor;
     if ($open_access_for_contributor && $access == 1 && $resourcedata['created_by'] == $userref) {
         # If access is restricted and user has contributed resource, grant open access.
         $access = 0;
     }
     # Check for user-specific and group-specific access (overrides any other restriction)
     global $userref, $usergroup;
     if ($passthru == "no") {
         $userspecific = get_custom_access_user($resource, $userref);
         $groupspecific = get_custom_access($resource, $usergroup, false);
     } else {
         $userspecific = $resourcedata['user_access'];
         $groupspecific = $resourcedata['group_access'];
     }
     if ($userspecific != "") {
         $customuseraccess = true;
         return $userspecific;
     }
     if ($groupspecific != "") {
         $customgroupaccess = true;
         return $groupspecific;
     }
     if (checkperm('T' . $resource_type)) {
         // this resource type is always confidential/hidden for this user group
         return 2;
     }
     global $usersearchfilter, $search_filter_strict;
     if (trim($usersearchfilter) != "" && $search_filter_strict) {
         # A search filter has been set. Perform filter processing to establish if the user can view this resource.
         # Always load metadata, because the provided metadata may be missing fields due to permissions.
         /*
                         
                         # ***** OLD METHOD ***** - used filter_match() - required duplication and was very difficult to implement OR matching for the field name supporting OR across fields
                         
         $metadata=get_resource_field_data($ref,false,false);
         for ($n=0;$n<count($metadata);$n++)
         	{
         	$name=$metadata[$n]["name"];
         	$value=$metadata[$n]["value"];			
         	if ($name!="")
         		{
         		$match=filter_match($usersearchfilter,$name,$value);
                                         echo "<br />$name/$value = $match";
         		if ($match==1) {return 2;} # The match for this field was incorrect, always show as confidential in this event.
         		}
         	}
         	
         # Also check resource type	
         # Disabled until also implented in do_search() - future feature - syntax supported in edit filter only for now.
         /*
         $match=filter_match($usersearchfilter,"resource_type",$resource_type);
         if ($match==1) {return 2;} # The match for this field was incorrect, always show as confidential in this event.
         */
         # ***** NEW METHOD ***** - search for the resource, utilising the existing filter matching in do_search to avoid duplication.
         global $search_all_workflow_states;
         $search_all_workflow_states_cache = $search_all_workflow_states;
         $search_all_workflow_states = TRUE;
         $results = do_search("!resource" . $ref);
         $search_all_workflow_states = $search_all_workflow_states_cache;
         if (count($results) == 0) {
             return 2;
         }
         # Not found in results, so deny
     }
     if ($access == 0 && !checkperm("g") && !$customgroupaccess) {
         # User does not have the 'g' permission. Return restricted for active resources unless group has been granted overide access.
         $access = 1;
     }
     if ($access == 0 && checkperm('X' . $resource_type)) {
         // this resource type is always restricted for this user group
         $access = 1;
     }
     // Check derestrict filter
     global $userderestrictfilter;
     if ($access == 1 && trim($userderestrictfilter) != "") {
         # A filter has been set to derestrict access when certain metadata criteria are met
         if (!isset($metadata)) {
             #  load metadata if not already loaded
             $metadata = get_resource_field_data($ref, false, false);
         }
         $matchedfilter = false;
         for ($n = 0; $n < count($metadata); $n++) {
             $name = $metadata[$n]["name"];
             $value = $metadata[$n]["value"];
             if ($name != "") {
                 $match = filter_match($userderestrictfilter, $name, $value);
                 if ($match == 1) {
                     $matchedfilter = false;
                     break;
                 }
                 if ($match == 2) {
                     $matchedfilter = true;
                 }
             }
         }
         if ($matchedfilter) {
             $access = 0;
         }
     }
     return $access;
 }
Example #25
0
if ($transition > 0) {
    ?>
var embedslideshow_auto=true;
<?php 
} else {
    ?>
var embedslideshow_auto=false;
<?php 
}
?>
var timer;
</script>

<?php 
$page = 1;
$resources = do_search("!collection" . $ref);
foreach ($resources as $resource) {
    $file_path = get_resource_path($resource["ref"], true, $size, false, $resource["preview_extension"], -1, 1, $use_watermark);
    if (file_exists($file_path)) {
        $preview_path = get_resource_path($resource["ref"], false, $size, false, $resource["preview_extension"], -1, 1, $use_watermark);
    } else {
        # Fall back to 'pre' size
        $preview_path = get_resource_path($resource["ref"], false, "pre", false, $resource["preview_extension"], -1, 1, $use_watermark);
    }
    # sets height and width to display
    $ratio = $resource["thumb_width"] / $resource["thumb_height"];
    if ($ratio >= 1) {
        # Landscape image, width is the largest - scale the height
        $width = getvalescaped("width", "");
        $height = floor($width / $ratio);
    } else {
Example #26
0
}
$errors = array();
# The results of the save operation (e.g. required field messages)
# Disable auto save for upload forms - it's not appropriate.
if ($ref < 0) {
    $edit_autosave = false;
}
# next / previous resource browsing
$go = getval("go", "");
if ($go != "") {
    # Re-run the search and locate the next and previous records.
    $modified_result_set = hook("modifypagingresult");
    if ($modified_result_set) {
        $result = $modified_result_set;
    } else {
        $result = do_search($search, $restypes, $order_by, $archive, 240 + $offset + 1, $sort);
    }
    if (is_array($result)) {
        # Locate this resource
        $pos = -1;
        for ($n = 0; $n < count($result); $n++) {
            if ($result[$n]["ref"] == $ref) {
                $pos = $n;
            }
        }
        if ($pos != -1) {
            if ($go == "previous" && $pos > 0) {
                $ref = $result[$pos - 1]["ref"];
            }
            if ($go == "next" && $pos < $n - 1) {
                $ref = $result[$pos + 1]["ref"];
if ($purge != "" || $deleteall != "") {
    if ($purge != "") {
        $deletecollection = $purge;
    }
    if ($deleteall != "") {
        $deletecollection = $deleteall;
    }
    if (!function_exists("do_search")) {
        include "../include/search_functions.php";
    }
    if (!function_exists("delete_resource")) {
        include "../include/resource_functions.php";
    }
    # Delete all resources in collection
    if (!checkperm("D")) {
        $resources = do_search("!collection" . $deletecollection);
        for ($n = 0; $n < count($resources); $n++) {
            if (checkperm("e" . $resources[$n]["archive"])) {
                delete_resource($resources[$n]["ref"]);
                collection_log($deletecollection, "D", $resources[$n]["ref"]);
            }
        }
    }
    if ($purge != "") {
        # Delete collection
        delete_collection($purge);
        # Get count of collections
        $c = get_user_collections($userref);
        # If the user has just deleted the collection they were using, select a new collection
        if ($usercollection == $purge && count($c) > 0) {
            # Select the first collection in the dropdown box.
# Resolve resource types
$resource_types = get_resource_types();
$rtx = explode(",", getvalescaped("restypes", ""));
foreach ($rtx as $rt) {
    # Locate the resource type name in the local list.
    # We have to handle resource type names because the resource type numeric IDs could be different from system to system.
    foreach ($resource_types as $resource_type) {
        if ($resource_type["name"] == $rt) {
            if ($restypes != "") {
                $restypes .= ",";
            }
            $restypes .= $resource_type["ref"];
        }
    }
}
$results = do_search($search, $restypes, "relevance", 0, $pagesize + $offset, "desc", false, "", true);
# Search, ignoring filters (as fields are unlikely to match).
# The access key is used to sign all inbound queries, the remote system must therefore know the access key.
$access_key = md5("resourceconnect" . $scramble_key);
# Check the search query against the signature.
$expected_sign = md5($access_key . $search);
if ($sign != $expected_sign) {
    exit("<p>" . $lang["resourceconnect_error-not_signed_with_correct_key"] . "</p>");
}
if ($offset > count($results)) {
    while ($offset > count($results)) {
        $offset -= $pagesize;
    }
}
if ($offset < 0) {
    $offset = 0;
    ?>
">
<input type="hidden" name="collection" value="<?php 
    echo $collection;
    ?>
">

<?php 
    if ($feedback_resource_select) {
        ?>
<h2><?php 
        echo $lang["selectedresources"];
        ?>
:</h2><?php 
        # Show thumbnails and allow the user to select resources.
        $result = do_search("!collection" . $collection);
        for ($n = 0; $n < count($result); $n++) {
            $ref = $result[$n]["ref"];
            $access = get_resource_access($ref);
            $use_watermark = check_use_watermark($ref);
            $title = $ref . " : " . htmlspecialchars(tidy_trim(i18n_get_translated($result[$n]["field" . $view_title_field]), 60));
            if (isset($collection_feedback_display_field)) {
                $displaytitle = htmlspecialchars(get_data_by_field($ref, $collection_feedback_display_field));
            } else {
                $displaytitle = $title;
            }
            ?>
	
		<!--Resource Panel-->
		<div class="ResourcePanelShell" id="ResourceShell<?php 
            echo $ref;
Example #30
0
         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 != "") {
         $value = getvalescaped($key, "");
         $field = str_replace("field", "", $key);
         update_field($ref, $field, $value);
     }
 }
 $results = do_search("!list{$ref}", "", "relevance", $status);
 $modified_result = hook("modifyapisearchresult");
 if ($modified_result) {
     $results = $modified_result;
 }
 // this function in api_core
 $results = refine_api_resource_results($results);
 // return refs
 header('Content-type: application/json');
 if ($collection != "") {
     $result = array('collection' => $collection, 'resource' => $results);
 } else {
     $result = array('resource' => $results);
 }
 echo json_encode($result);
 // echo json without headers by default