function HookAction_datesPagestoolscron_copy_hitcountAddplugincronjob() { global $lang, $action_dates_restrictfield, $action_dates_deletefield, $resource_deletion_state, $action_dates_reallydelete, $action_dates_email_admin_days, $email_notify, $email_from, $applicationname; $allowable_fields = sql_array("select ref as value from resource_type_field where type in (4,6,10)"); # Check that this is a valid date field to use if (in_array($action_dates_restrictfield, $allowable_fields)) { $restrict_resources = sql_query("select resource, value from resource_data where resource_type_field = '{$action_dates_restrictfield}'"); $emailrefs = array(); foreach ($restrict_resources as $resource) { $ref = $resource["resource"]; if ($action_dates_email_admin_days != "") { $action_dates_email_admin_seconds = intval($action_dates_email_admin_days) * 60 * 60 * 24; if (time() >= strtotime($resource["value"]) - $action_dates_email_admin_seconds && time() <= strtotime($resource["value"]) - $action_dates_email_admin_seconds + 86400) { $emailrefs[] = $ref; } } if (time() >= strtotime($resource["value"])) { # Restrict access to the resource as date has been reached $existing_access = sql_value("select access as value from resource where ref='{$ref}'", ""); if ($existing_access == 0) { echo "restricting resource " . $ref . "\r\n"; sql_query("update resource set access=1 where ref='{$ref}'"); resource_log($ref, 'a', '', $lang['action_dates_restrict_logtext'], $existing_access, 1); } } } if (count($emailrefs) > 0) { global $baseurl; # Send email as the date is within the specified number of days $subject = $lang['action_dates_email_subject']; $message = str_replace("%%DAYS", $action_dates_email_admin_days, $lang['action_dates_email_text']) . "\r\n"; $message .= $baseurl . "?r=" . implode("\r\n" . $baseurl . "?r=", $emailrefs) . "\r\n"; $templatevars['message'] = $message; echo "Sending email to " . $email_notify . "\r\n"; send_mail($email_notify, $subject, $message, $applicationname, $email_from, "emailexpiredresources", $templatevars, $applicationname); } } if (in_array($action_dates_deletefield, $allowable_fields)) { $delete_resources = sql_query("select resource, value from resource_data where resource_type_field = '{$action_dates_deletefield}'"); foreach ($delete_resources as $resource) { $ref = $resource["resource"]; if (time() >= strtotime($resource["value"])) { # Delete the resource as date has been reached echo "deleting resource " . $ref . "\r\n"; if ($action_dates_reallydelete) { delete_resource($ref); } else { if (!isset($resource_deletion_state)) { $resource_deletion_state = 3; } sql_query("update resource set archive='" . $resource_deletion_state . "' where ref='" . $ref . "'"); } # Remove the resource from any collections sql_query("delete from collection_resource where resource='{$ref}'"); resource_log($ref, 'x', '', $lang['action_dates_delete_logtext']); } } } }
function HookGrant_editEditeditbeforeheader() { global $ref, $baseurl, $usergroup, $grant_edit_groups, $collection; // Do we have access to do any of this, or is it a template if (!in_array($usergroup, $grant_edit_groups) || $ref < 0) { return; } // Check for Ajax POST to delete users $grant_edit_action = getvalescaped("grant_edit_action", ""); if ($grant_edit_action != "") { if ($grant_edit_action == "delete") { $remove_user = escape_check(getvalescaped("remove_user", "", TRUE)); if ($remove_user != "") { sql_query("delete from grant_edit where resource='{$ref}' and user={$remove_user}"); exit("SUCCESS"); } } exit("FAILED"); } # If 'users' is specified (i.e. access is private) then rebuild users list $users = getvalescaped("users", false); if ($users != false) { # Build a new list and insert $users = resolve_userlist_groups($users); $ulist = array_unique(trim_array(explode(",", $users))); $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')"); if (count($urefs) > 0) { $inserttext = array(); $grant_edit_expiry = getvalescaped("grant_edit_expiry", ""); foreach ($urefs as $uref) { if ($grant_edit_expiry != "") { $inserttext[] = $uref . ",'" . $grant_edit_expiry . "'"; } else { $inserttext[] = $uref . ",NULL"; } } if ($collection != "") { global $items; foreach ($items as $collection_resource) { sql_query("delete from grant_edit where resource='{$collection_resource}' and user in (" . implode(",", $urefs) . ")"); sql_query("insert into grant_edit(resource,user,expiry) values ({$collection_resource}," . join("),(" . $collection_resource . ",", $inserttext) . ")"); #log this global $lang; resource_log($collection_resource, 's', "", "Grant Edit - " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never'])); } } else { sql_query("delete from grant_edit where resource='{$ref}' and user in (" . implode(",", $urefs) . ")"); sql_query("insert into grant_edit(resource,user,expiry) values ({$ref}," . join("),(" . $ref . ",", $inserttext) . ")"); #log this global $lang; resource_log($ref, 's', "", "Grant Edit - " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never'])); } } } return true; }
function HookAction_datesPagestoolscron_copy_hitcountAddplugincronjob() { global $lang, $action_dates_restrictfield,$action_dates_deletefield, $resource_deletion_state, $action_dates_reallydelete; $allowable_fields=sql_array("select ref as value from resource_type_field where type in (4,6,10)"); # Check that this is a valid date field to use if(in_array($action_dates_restrictfield, $allowable_fields)) { $restrict_resources=sql_query("select resource, value from resource_data where resource_type_field = '$action_dates_restrictfield'"); foreach ($restrict_resources as $resource) { $ref=$resource["resource"]; if (time()>=strtotime($resource["value"])) { # Restrict access to the resource as date has been reached $existing_access=sql_value("select access as value from resource where ref='$ref'",""); if($existing_access==0) # Only apply to resources that are currently open { echo "restricting resource " . $ref ."\r\n"; sql_query("update resource set access=1 where ref='$ref'"); resource_log($ref,'a','',$lang['action_dates_restrict_logtext'],$existing_access,1); } } } } if(in_array($action_dates_deletefield, $allowable_fields)) { $delete_resources=sql_query("select resource, value from resource_data where resource_type_field = '$action_dates_deletefield'"); foreach ($delete_resources as $resource) { $ref=$resource["resource"]; if (time()>=strtotime($resource["value"])) { # Delete the resource as date has been reached echo "deleting resource " . $ref ."\r\n"; if ($action_dates_reallydelete) { delete_resource($ref); } else { if (!isset($resource_deletion_state)){$resource_deletion_state=3;} sql_query("update resource set archive='" . $resource_deletion_state . "' where ref='" . $ref . "'"); } # Remove the resource from any collections sql_query("delete from collection_resource where resource='$ref'"); resource_log($ref,'x','',$lang['action_dates_delete_logtext']); } } } }
function check_defensio_comment() { global $pixelpost_db_prefix, $cfgrow, $parent_id, $message, $ip, $name, $url, $email; $defensio_conf = sql_array("SELECT * FROM {$pixelpost_db_prefix}defensio"); // the following code tries to get the full addon path. $filename = basename(__FILE__, ".php"); $query = "SELECT `addon_name` FROM `{$pixelpost_db_prefix}addons` WHERE `addon_name` LIKE '%" . $filename . "%'"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)) { $addon_path = $row[0]; } $pos = strpos($addon_path, "/"); if ($pos === false) { $addon_path = null; } else { $addon_path = substr($addon_path, 0, $pos); } $defensio_conf['addon_path'] = "addons/" . $addon_path; // build $comment array used for testing. $comment = array(); $comment['owner-url'] = $defensio_conf['blog']; $comment['user-ip'] = $ip; $comment['comment_post_ID'] = $parent_id; $comment['permalink'] = $defensio_conf['blog'] . "index.php?showimage=" . $parent_id; $comment['comment-type'] = 'comment'; $comment['comment-author'] = $name; $comment['comment-content'] = $message; $comment['comment-author-email'] = $email; $comment['comment-author-url'] = $url; $comment['referrer'] = $_SERVER['HTTP_REFERER']; //$comment['trusted-user'] = '******'; // get the date/time of the original posting $query = "SELECT `datetime` FROM `{$pixelpost_db_prefix}pixelpost` WHERE `id` = '" . $parent_id . "'"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) == 1) { // check comment while ($row = mysql_fetch_array($result)) { $comment['article-date'] = gmdate("Y/m/d", $row[0]); } defensio_check_comment_front($defensio_conf, $comment); } else { // trying to comment on a non-existent blog post header("HTTP/1.0 404 Not Found"); header("Status: 404 File Not Found!"); echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><HTML><HEAD>\n<TITLE>404 Not Found</TITLE>\n</HEAD><BODY>\n<H1>Not Found</H1>\nThe comment could not be accepted because the blogpost doesn't exists.<P>\n<P>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.\n</BODY></HTML>"; exit; } }
function getThemeList($parents = array()) { if (count($parents) == 0) { // just retrieve all the top level themes $sql = "select distinct theme as value from collection where theme is not null and theme <> '' order by theme"; } else { // we were passed an array of parents, so we need to narrow our search for ($i = 1; $i < count($parents) + 1; $i++) { if ($i == 1) { $searchfield = 'theme'; } else { $searchfield = "theme{$i}"; } $whereclause = "{$searchfield} = '" . escape_check($parents[$i - 1]) . "' "; } $sql = "select distinct theme{$i} as value from collection where {$whereclause} and theme{$i} is not null and theme{$i} <> '' order by theme{$i}"; //echo $sql; } $result = sql_array($sql); return $result; }
public function getFeed($who, $limit = 50, $offset = 0) { if (!is_array($who)) { $who = array($who); } $who_array = $who; foreach ($who_array as $who) { if ($who_csv) { $who_csv .= ','; } $who_csv .= "'{$who}'"; } // return a distinct field in a table with an order by $where = "who in ( {$who_csv} )"; $order_by = 'news_who.insert_time desc'; $person_id = PERSON_ID ? PERSON_ID : 0; $sql = "\n SELECT news_item_id FROM (\n SELECT DISTINCT ON (q.news_item_id) news_item_id, row FROM (\n SELECT\n news_who.news_item_id,\n row_number() OVER (ORDER BY {$order_by}) AS row\n FROM news_who\n LEFT JOIN news_hide on news_hide.news_item_id = news_who.news_item_id\n and news_hide.person_id = {$person_id}\n and news_hide.active = 1\n LEFT JOIN news_item on news_item.id = news_who.news_item_id\n WHERE news_who.active = 1\n AND news_item.active = 1\n AND news_hide.id is null\n AND {$where}\n ORDER BY {$order_by}\n OFFSET {$offset}\n LIMIT {$limit}\n ) AS q\n ) AS fin ORDER BY row"; //print_pre($sql); elapsed('before news query'); $arr = sql_array($sql); elapsed('after news query'); return $arr; }
function get_theme_image($themes=array()) { # Returns an array of resource references that can be used as theme category images. global $theme_images_number; global $theme_category_levels; # First try to find resources that have been specifically chosen using the option on the collection comments page. $sql="select r.ref value from collection c join collection_resource cr on c.ref=cr.collection join resource r on cr.resource=r.ref where c.theme='" . escape_check($themes[0]) . "' "; for ($n=2;$n<=count($themes)+1;$n++){ if (isset($themes[$n-1])){ $sql.=" and theme".$n."='" . escape_check($themes[$n-1]) . "' "; } else { if ($n<=$theme_category_levels){ $sql.=" and (theme".$n."='' or theme".$n." is null) "; } } } $sql.=" and r.has_image=1 and cr.use_as_theme_thumbnail=1 order by r.ref desc"; $chosen=sql_array($sql,0); if (count($chosen)>0) {return $chosen;} # No chosen images? Manually choose a single image based on hit counts. $sql="select r.ref value from collection c join collection_resource cr on c.ref=cr.collection join resource r on cr.resource=r.ref where c.theme='" . escape_check($themes[0]) . "' "; for ($n=2;$n<=count($themes)+1;$n++){ if (isset($themes[$n-1])){ $sql.=" and theme".$n."='" . escape_check($themes[$n-1]) . "' "; } else { if ($n<=$theme_category_levels){ $sql.=" and (theme".$n."='' or theme".$n." is null) "; } } } $sql.=" and r.has_image=1 order by r.hit_count desc limit " . $theme_images_number; $images=sql_array($sql,0); $tmp = hook("getthemeimage", "", array($themes)); if($tmp!==false and is_array($tmp) and count($tmp)>0) $images = $tmp; if (count($images)>0) {return $images;} return false; }
function display_field_data($field, $valueonly = false, $fixedwidth = 452) { global $ref, $fieldcount, $tabcount, $show_expiry_warning, $access, $tabname, $search, $extra, $lang, $used_tab_names, $related_type_show_with_data, $show_default_related_resources; $value = $field["value"]; $modified_field = hook("beforeviewdisplayfielddata_processing", "", array($field)); if ($modified_field) { $field = $modified_field; } # Handle expiry fields if (!$valueonly && $field["type"] == 6 && $value != "" && $value <= date("Y-m-d H:i") && $show_expiry_warning) { $extra .= "<div class=\"RecordStory\"> <h1>" . $lang["warningexpired"] . "</h1><p>" . $lang["warningexpiredtext"] . "</p><p id=\"WarningOK\"><a href=\"#\" onClick=\"document.getElementById('RecordDownload').style.display='block';document.getElementById('WarningOK').style.display='none';\">" . $lang["warningexpiredok"] . "</a></p></div><style>#RecordDownload {display:none;}</style>"; } if ($value != "" && $value != "," && $field["display_field"] == 1 && ($access == 0 || $access == 1 && !$field["hide_when_restricted"])) { if (!$valueonly) { $title = htmlspecialchars(str_replace("Keywords - ", "", $field["title"])); } else { $title = ""; } //if ($field["type"]==4 || $field["type"]==6) {$value=NiceDate($value,false,true);} # Value formatting if ($field["type"] == 2 || $field["type"] == 7 || $field["type"] == 9) { $i18n_split_keywords = true; } else { $i18n_split_keywords = false; } $value = i18n_get_translated($value, $i18n_split_keywords); if ($field["type"] == 2 || $field["type"] == 3 || $field["type"] == 7 || $field["type"] == 9) { $value = TidyList($value); } $value_unformatted = $value; # store unformatted value for replacement also if ($field["type"] != 8 || $field["type"] == 8 && $value == strip_tags($value)) { $value = nl2br(htmlspecialchars($value)); } $modified_value = hook('display_field_modified_value', '', array($field)); if ($modified_value) { $value = $modified_value['value']; } # draw new tab panel? if (!$valueonly && $tabname != $field["tab_name"] && $fieldcount > 0) { $resource_type_tab_names = sql_array('SELECT tab_name as value FROM resource_type', ''); $resource_type_tab_names = array_filter($resource_type_tab_names); # Display related resources on this tab, if set: if (isset($related_type_show_with_data)) { # NOTE: the resource type tab name and the current tab you are on need to be the same: if (in_array($tabname, $resource_type_tab_names)) { if (($key = array_search($tabname, $resource_type_tab_names)) !== false) { # Fields with display template should be rendered before the related resources list: echo $extra; $extra = ''; include '../include/related_resources.php'; unset($resource_type_tab_names[$key]); $show_default_related_resources = FALSE; } } } $tabcount++; # Also display the custom formatted data $extra at the bottom of this tab panel. ?> <div class="clearerleft"> </div><?php echo $extra; ?> </div></div><div class="TabbedPanel StyledTabbedPanel" style="display:none;" id="tab<?php echo $tabcount; ?> "><div><?php $extra = ""; } $tabname = $field["tab_name"]; $used_tab_names[] = $tabname; $used_tab_names = array_unique($used_tab_names); $fieldcount++; if (!$valueonly && trim($field["display_template"]) != "") { # Process the value using a plugin $plugin = "../plugins/value_filter_" . $field["name"] . ".php"; if ($field['value_filter'] != "") { eval($field['value_filter']); } else { if (file_exists($plugin)) { include $plugin; } else { if ($field["type"] == 4 || $field["type"] == 6) { $value = NiceDate($value, false, true); } } } # Highlight keywords $value = highlightkeywords($value, $search, $field["partial_index"], $field["name"], $field["keywords_index"]); # Use a display template to render this field $template = $field["display_template"]; $template = str_replace("[title]", $title, $template); $template = str_replace("[value]", $value, $template); $template = str_replace("[value_unformatted]", $value_unformatted, $template); $template = str_replace("[ref]", $ref, $template); $extra .= $template; } else { #There is a value in this field, but we also need to check again for a current-language value after the i18n_get_translated() function was called, to avoid drawing empty fields if ($value != "") { # Draw this field normally. # value filter plugin should be used regardless of whether a display template is used. $plugin = "../plugins/value_filter_" . $field["name"] . ".php"; if ($field['value_filter'] != "") { eval($field['value_filter']); } else { if (file_exists($plugin)) { include $plugin; } else { if ($field["type"] == 4 || $field["type"] == 6) { $value = NiceDate($value, false, true); } } } # Highlight keywords $value = highlightkeywords($value, $search, $field["partial_index"], $field["name"], $field["keywords_index"]); ?> <div <?php if (!$valueonly) { echo "class=\"itemNarrow\""; } elseif (isset($fixedwidth)) { echo "style=\"width:" . $fixedwidth . "px\""; } ?> > <h3><?php echo $title; ?> </h3><p><?php echo $value; ?> </p></div><?php } } } }
} $archive = getvalescaped("archive", ""); if ($archive != "" && checkperm('e' . $archive)) { $status = $archive; } else { if (checkperm("c")) { $status = 0; } else { if (checkperm("d")) { $status = -2; } } } # Else, set status to Pending Submission. // check required fields $required_fields = sql_array("select ref value from resource_type_field where required=1 and (resource_type='{$resource_type}' or resource_type='0')"); $missing_fields = false; $error_message = ""; foreach ($required_fields as $required_field) { $value = getvalescaped("field" . $required_field, ""); if ($value == '') { $fieldname = i18n_get_translated(sql_value("select title value from resource_type_field where ref='{$required_field}'", "")); $options = sql_value("select options value from resource_type_field where ref='{$required_field}'", ""); $type = sql_value("select type value from resource_type_field where ref='{$required_field}'", ""); if ($options != "" && ($type == 3 || $type == 2)) { $optionstring = "Allowed Values: " . ltrim(implode("\n", explode(",", $options)), ",") . "\n"; } else { $optionstring = ""; } $error_message .= "{$fieldname} is required. Use field{$required_field}=[string] as a parameter. {$optionstring}\n"; $missing_fields = true;
function update_disk_usage_cron() { # Update disk usage for all resources that have not yet been updated or have not been updated in the past 30 days. # Limit to a reasonable amount so that this process is spread over several cron intervals for large data sets. $resources=sql_array("select ref value from resource where ref>0 and disk_usage_last_updated is null or datediff(now(),disk_usage_last_updated)>30 limit 20000"); foreach ($resources as $resource) { update_disk_usage($resource); } }
sql_query("delete from resource_keyword where resource not in (select ref from resource)"); echo sql_affected_rows() . " orphaned resource-keyword relationships deleted.<br/><br/>"; sql_query("delete from keyword where ref not in (select keyword from resource_keyword) and ref not in (select keyword from keyword_related) and ref not in (select related from keyword_related) and ref not in (select keyword from collection_keyword)"); echo sql_affected_rows() . " unused keywords deleted.<br/><br/>"; sql_query("delete from resource_alt_files where resource not in (select ref from resource)"); echo sql_affected_rows() . " orphaned alternative files deleted.<br/><br/>"; sql_query("delete from resource_custom_access where resource not in (select ref from resource) or (user not in (select ref from user) and usergroup not in (select ref from usergroup))"); echo sql_affected_rows() . " orphaned resource custom access rows deleted.<br/><br/>"; sql_query("delete from resource_dimensions where resource not in (select ref from resource)"); echo sql_affected_rows() . " orphaned resource dimension rows deleted.<br/><br/>"; sql_query("delete from resource_log where resource<>0 and resource not in (select ref from resource)"); echo sql_affected_rows() . " orphaned resource log rows deleted.<br/><br/>"; sql_query("delete from resource_related where resource not in (select ref from resource) or related not in (select ref from resource)"); echo sql_affected_rows() . " orphaned resource related rows deleted.<br/><br/>"; sql_query("delete from resource_type_field where resource_type<>999 and resource_type<>0 and resource_type not in (select ref from resource_type)"); echo sql_affected_rows() . " orphaned fields deleted.<br/><br/>"; sql_query("delete from user_collection where user not in (select ref from user) or collection not in (select ref from collection)"); echo sql_affected_rows() . " orphaned user-collection relationships deleted.<br/><br/>"; sql_query("delete from resource_data where resource not in (select ref from resource) or resource_type_field not in (select ref from resource_type_field)"); echo sql_affected_rows() . " orphaned resource data rows deleted.<br/><br/>"; # Clean out and resource data that is set for fields not applicable to a given resource type. $r = get_resource_types(); for ($n = 0; $n < count($r); $n++) { $rt = $r[$n]["ref"]; $fields = sql_array("select ref value from resource_type_field where resource_type=0 or resource_type=999 or resource_type='" . $rt . "'"); if (count($fields) > 0) { sql_query("delete from resource_data where resource in (select ref from resource where resource_type='{$rt}') and resource_type_field not in (" . join(",", $fields) . ")"); echo sql_affected_rows() . " orphaned resource data rows deleted for resource type {$rt}.<br/><br/>"; } } hook("dbprune");
sql_query("DELETE FROM resource_keyword WHERE resource NOT IN (SELECT ref FROM resource)"); echo number_format(sql_affected_rows()) . " orphaned resource-keyword relationships deleted." . $newline; sql_query("DELETE FROM keyword WHERE ref NOT IN (SELECT keyword FROM resource_keyword) AND ref NOT IN (SELECT keyword FROM keyword_related) AND ref NOT IN (SELECT related FROM keyword_related) AND ref NOT IN (SELECT keyword FROM collection_keyword)"); echo number_format(sql_affected_rows()) . " unused keywords deleted." . $newline; sql_query("DELETE FROM resource_alt_files WHERE resource NOT IN (SELECT ref FROM resource)"); echo number_format(sql_affected_rows()) . " orphaned alternative files deleted." . $newline; sql_query("DELETE FROM resource_custom_access WHERE resource NOT IN (SELECT ref FROM resource) OR (user NOT IN (SELECT ref FROM user) AND usergroup NOT IN (SELECT ref FROM usergroup))"); echo number_format(sql_affected_rows()) . " orphaned resource custom access rows deleted." . $newline; sql_query("DELETE FROM resource_dimensions WHERE resource NOT IN (SELECT ref FROM resource)"); echo number_format(sql_affected_rows()) . " orphaned resource dimension rows deleted." . $newline; sql_query("DELETE FROM resource_log WHERE resource<>0 AND resource NOT IN (SELECT ref FROM resource)"); echo number_format(sql_affected_rows()) . " orphaned resource log rows deleted." . $newline; sql_query("DELETE FROM resource_related WHERE resource NOT IN (SELECT ref FROM resource) OR related NOT IN (SELECT ref FROM resource)"); echo number_format(sql_affected_rows()) . " orphaned resource related rows deleted." . $newline; sql_query("DELETE FROM resource_type_field WHERE resource_type<>999 AND resource_type<>0 AND resource_type NOT IN (SELECT ref FROM resource_type)"); echo number_format(sql_affected_rows()) . " orphaned fields deleted." . $newline; sql_query("DELETE FROM user_collection WHERE user NOT IN (SELECT ref FROM user) OR collection NOT IN (SELECT ref FROM collection)"); echo number_format(sql_affected_rows()) . " orphaned user-collection relationships deleted." . $newline; sql_query("DELETE FROM resource_data WHERE resource NOT IN (SELECT ref FROM resource) OR resource_type_field NOT IN (SELECT ref FROM resource_type_field)"); echo number_format(sql_affected_rows()) . " orphaned resource data rows deleted." . $newline; # Clean out and resource data that is set for fields not applicable to a given resource type. $r = get_resource_types(); for ($n = 0; $n < count($r); $n++) { $rt = $r[$n]["ref"]; $fields = sql_array("SELECT ref value FROM resource_type_field WHERE resource_type=0 OR resource_type=999 OR resource_type='" . $rt . "'"); if (count($fields) > 0) { sql_query("DELETE FROM resource_data WHERE resource in (SELECT ref FROM resource WHERE resource_type='{$rt}') AND resource_type_field NOT IN (" . join(",", $fields) . ")"); echo number_format(sql_affected_rows()) . " orphaned resource data rows deleted for resource type {$rt}." . $newline; } } hook("dbprune");
$repetidos = repetidos($conexion, "nombre_categoria", strtoupper($_POST['nombre_categoria']), "categoria", "g", "", ""); if ($repetidos == 'true') { $data = "1"; /// este dato ya existe; } else { $sql = "insert into categoria values ('{$id}','" . strtoupper($_POST['nombre_categoria']) . "','{$fecha}','1')"; $guardar = guardarSql($conexion, $sql); $sql_nuevo = "select (id_categoria,nombre_categoria,fecha_creacion,estado) from categoria where id_categoria = '{$id}'"; $sql_nuevo = sql_array($conexion, $sql_nuevo); auditoria_sistema($conexion, 'categoria', $id_user, 'Insert', $id, $fecha_larga, $fecha, $sql_nuevo, ''); $data = "2"; } } else { if ($_POST['oper'] == "edit") { $repetidos = repetidos($conexion, "nombre_categoria", strtoupper($_POST['nombre_categoria']), "categoria", "m", $_POST['id'], "id_categoria"); if ($repetidos == 'true') { $data = "1"; /// este dato ya existe; } else { $sql_anterior = "select (id_categoria,nombre_categoria,fecha_creacion,estado) from categoria where id_categoria = '{$_POST['id']}'"; $sql_anterior = sql_array($conexion, $sql_anterior); $sql = "update categoria set nombre_categoria = '" . strtoupper($_POST['nombre_categoria']) . "', fecha_creacion = '{$fecha}' where id_categoria = '{$_POST['id']}'"; $guardar = guardarSql($conexion, $sql); $sql_nuevo = "select (id_categoria,nombre_categoria,fecha_creacion,estado) from categoria where id_categoria = '{$_POST['id']}'"; $sql_nuevo = sql_array($conexion, $sql_nuevo); auditoria_sistema($conexion, 'categoria', $id_user, 'Update', $_POST['id'], $fecha_larga, $fecha, $sql_nuevo, $sql_anterior); $data = "3"; } } } echo $data;
$moderate_where = " and publish='no' "; $moderate_where2 = " WHERE publish='no' "; } if (isset($_GET['show']) and $_GET['show'] == 'published') { $moderate_where = " and publish='yes' "; $moderate_where2 = " WHERE publish='yes' "; } $order_by = " ORDER BY id DESC "; // the $moderate_where and $order_by statements can now be overridden by using an addon and the following workspace: // new workspace added! For correct page number with other buttons eval_addon_admin_workspace_menu('pages_commentbuttons'); // count comments! $commentnumb = sql_array("select count(*) as count from " . $pixelpost_db_prefix . "comments" . $moderate_where2); $pixelpost_commentnumb = $commentnumb['count']; // get the number of comments in moderation $commentnumb_moderation = sql_array("select count(*) as count from " . $pixelpost_db_prefix . "comments WHERE publish='no' "); // display submenu echo "<div id='submenu'>"; $submenucssclass = 'notselected'; if (!isset($_GET['show']) || $_GET['show'] == 'published') { $submenucssclass = 'selectedsubmenu'; } if (isset($_GET['commentsview'])) { $submenucssclass = 'notselected'; } echo "<a href='index.php?view=comments&show=published' class='" . $submenucssclass . "'>" . $admin_lang_cmnt_submenu1 . "</a>\n"; $submenucssclass = 'notselected'; echo "|"; if (isset($_GET['show']) && $_GET['show'] == 'masked') { $submenucssclass = 'selectedsubmenu'; }
} } else { exit("Unknown argv: " . $argv[1]); } } } # Check for a process lock if (is_process_lock("staticsync")) { echo 'Process lock is in place. Deferring.' . PHP_EOL; echo 'To clear the lock after a failed run use --clearlock flag.' . PHP_EOL; exit; } set_process_lock("staticsync"); echo "Preloading data... "; $count = 0; $done = sql_array("SELECT file_path value FROM resource WHERE LENGTH(file_path)>0 AND file_path LIKE '%/%'"); $done = array_flip($done); # Load all modification times into an array for speed $modtimes = array(); $resource_modified_times = sql_query("SELECT file_modified, file_path FROM resource WHERE archive=0 AND LENGTH(file_path) > 0"); foreach ($resource_modified_times as $rmd) { $modtimes[$rmd["file_path"]] = $rmd["file_modified"]; } $lastsync = sql_value("SELECT value FROM sysvars WHERE name='lastsync'", ""); $lastsync = strlen($lastsync) > 0 ? strtotime($lastsync) : ''; echo "done." . PHP_EOL; echo "Looking for changes..." . PHP_EOL; # Pre-load the category tree, if configured. if (isset($staticsync_mapped_category_tree)) { $field = get_field($staticsync_mapped_category_tree); $tree = explode("\n", trim($field["options"]));
$restype_sort = getvalescaped("restype_sort", "asc"); $url_params = array("ref" => $ref, "restype_order_by" => $restype_order_by, "restype_sort" => $restype_sort); $url = generateURL($baseurl . "/pages/admin/admin_resource_type_edit.php", $url_params); $backurl = getvalescaped("backurl", ""); if ($backurl == "") { $backurl = $baseurl . "/pages/admin/admin_resource_types.php?ref=" . $ref; } if (getval("save", "") != "") { # Save resource type data sql_query("update resource_type set name='" . $name . "',config_options='" . $config_options . "', allowed_extensions='" . $allowed_extensions . "',tab_name='" . $tab . "' where ref='{$ref}'"); redirect(generateURL($baseurl_short . "pages/admin/admin_resource_types.php", $url_params)); } if (getval("delete", "") != "") { $targettype = getvalescaped("targettype", ""); # Check for resources of this type $affectedresources = sql_array("select ref value from resource where resource_type='{$ref}' and ref>0", 0); if (count($affectedresources) > 0 && $targettype == "") { //User needs to confirm a new resource type $confirm_delete = true; } else { //If we have a target type, move the current resources to the new resource type if ($targettype != "" && $targettype != $ref) { include "../../include/resource_functions.php"; foreach ($affectedresources as $affectedresource) { update_resource_type($affectedresource, $targettype); } } // Delete the resource type sql_query("delete from resource_type where ref='{$ref}'"); redirect(generateURL($baseurl_short . "pages/admin/admin_resource_types.php", $url_params)); }
$query = "SELECT id FROM {$pixelpost_db_prefix}ping LIMIT 1"; if (!mysql_query($query)) { $query = "CREATE TABLE {$pixelpost_db_prefix}ping (\n\t\t id INT(11) NOT NULL auto_increment,\n\t\t pinglist MEDIUMTEXT NOT NULL default '',\n\t\t PRIMARY KEY (id)\n\t\t)"; mysql_query($query); } // Update the ban list if the form is called if (isset($_POST['pinglistupdate']) && isset($_POST['pinglist'])) { $pinglist = str_replace("\r\n", "\n", $_POST['pinglist']); $pinglist = str_replace("\r", "\n", $pinglist); if (version_compare(phpversion(), "4.3.0") == "-1") { $pinglist = mysql_escape_string($pinglist); } else { $pinglist = mysql_real_escape_string($pinglist); } $query = "SELECT COUNT( * ) FROM {$pixelpost_db_prefix}ping"; $row = sql_array($query); if ($row[0] == 1) { $query = "UPDATE {$pixelpost_db_prefix}ping SET pinglist='{$pinglist}' LIMIT 1"; } else { $query = "INSERT INTO {$pixelpost_db_prefix}ping VALUES ( NULL, '{$pinglist}')"; } mysql_query($query) or die(mysql_error()); } // Get the ban list $query = "SELECT pinglist FROM {$pixelpost_db_prefix}ping LIMIT 1"; $result = mysql_query($query) or die(mysql_error()); if ($row = mysql_fetch_row($result)) { $pinglist = $row[0]; $pinglistarray = explode("\n", $pinglist); } else { $pinglist = '';
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(); } }
redirect($backurl); } } } # Fetch user data $user = get_user($ref); if ($user["usergroup"] == 3 && $usergroup != 3) { redirect($baseurl_short . "login.php?error=error-permissions-login&url=" . urlencode($url)); } if (checkperm("U") && $user["usergroup"] != "") { if ($U_perm_strict) { $sql = "where find_in_set('" . $usergroup . "',parent)"; } else { $sql = "where (ref='{$usergroup}' or find_in_set('" . $usergroup . "',parent))"; } $validgroups = sql_array("select ref value from usergroup {$sql}"); if (!in_array($user["usergroup"], $validgroups)) { redirect($baseurl_short . "login.php?error=error-permissions-login&url=" . urlencode($url)); exit; } } include "../../include/header.php"; # Log in as this user? if (getval("loginas", "") != "") { # Log in as this user # A user key must be generated to enable login using the MD5 hash as the password. ?> <form method="post" action="<?php echo $baseurl_short; ?> login.php" id="autologin">
DrawOption("d", $lang["can_create_resources_and_upload_files-general_users"]); DrawOption("D", $lang["can_delete_resources"], true); DrawOption("i", $lang["can_manage_archive_resources"]); DrawOption("n", $lang["can_tag_resources_using_speed_tagging"]); ?><tr><td colspan=3 class="permheader"><?php echo $lang["themes_and_collections"] ?></td></tr><?php DrawOption("b", $lang["enable_bottom_collection_bar"], true); DrawOption("h", $lang["can_publish_collections_as_themes"]); # ------------ Access to theme categories DrawOption("j*", $lang["can_see_all_theme_categories"], false, true); $themes=sql_array("select distinct theme value from collection where length(theme)>0 order by theme"); foreach ($themes as $theme) { if (!in_array("j*",$permissions)) { DrawOption("j" . $theme, " - " . $lang["can_see_theme_category"] . " '" . i18n_get_translated($theme) . "'", false); } else { # Add it to the 'done' list so it is discarded. $permissions_done[]="j" . $theme; } } DrawOption("J", $lang["display_only_resources_within_accessible_themes"]);
if (isset($_GET['advancedview']) and $_GET['advancedview'] == '' or isset($_GET['advancedview']) and $_GET['advancedview'] == 'general') { if (isset($_GET['optaction']) and $_GET['optaction'] == 'updateadv_gen') { /** * Update: * updatethumbnailpath, updateimagepath, * display sort, display order * * @advanced * */ sql_query("\n\t\t\tUPDATE `" . $pixelpost_db_prefix . "config` SET\n\t\t\t`thumbnailpath`\t\t= '" . clean($_POST['new_thumbnail_path']) . "',\n\t\t\t`imagepath`\t\t\t= '" . clean($_POST['new_image_path']) . "',\n\t\t\t`timestamp`\t\t\t= '" . clean($_POST['timestamp']) . "',\n\t\t\t`display_sort_by`\t= '" . clean($_POST['display_sort_by']) . "',\n\t\t\t`display_order`\t\t= '" . clean($_POST['display_order']) . "'\n\t\t\t"); /** * Refresh the settings * */ $cfgrow = sql_array("SELECT * FROM `" . $pixelpost_db_prefix . "config`"); } // END updateadv_gen } // END advanced / general //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //// //// ADVANCED LOCALIZATION OPTIONS SQL //// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// if (isset($_GET['advancedview']) and $_GET['advancedview'] == '' or isset($_GET['advancedview']) and $_GET['advancedview'] == 'localization') { if (isset($_GET['optaction']) and $_GET['optaction'] == 'updateadv_local' and !isset($_POST['delete'])) { /** * Clean the posted variables.
$tpl = replace_exif_tags($language_full, $image_exif, $tpl); } else { $tpl = replace_exif_tags_null($tpl); } } else { require_once 'includes/functions_exif.php'; $tpl = replace_exif_tags_null($tpl); } /** * Build a string with all comments. * Only perform this code when the user has commenting enabled * */ if (isset($_GET['x']) && $_GET['x'] == "" or isset($_GET['popup']) && $_GET['popup'] == "comment") { $comment_id = isset($_POST['parent_id']) ? intval($_POST['parent_id']) : ''; $comments_result = sql_array("SELECT `comments` FROM `" . $pixelpost_db_prefix . "pixelpost` WHERE `id` = '" . $comment_id . "'"); $cmnt_setting = pullout($comments_result['comments']); if ($cmnt_setting == 'F') { die('Die you SPAMMER!!'); } } // visitor information in comments $vinfo_name = ""; $vinfo_url = ""; $vinfo_email = ""; if (isset($_COOKIE['visitorinfo'])) { list($vinfo_name, $vinfo_url, $vinfo_email) = split("%", $_COOKIE['visitorinfo']); } $tpl = ereg_replace("<VINFO_NAME>", $vinfo_name, $tpl); $tpl = ereg_replace("<VINFO_URL>", $vinfo_url, $tpl); $tpl = ereg_replace("<VINFO_EMAIL>", $vinfo_email, $tpl);
$aql = "{$tablename} { * }"; $aql_data = aql::profile($aql, $id); if ($aql_data) { ?> <p id="instruction" style="font-size: 2em; font-family: Arial, Helveitca, Sans-serif; color: Blue; margin-bottom: 5px;"> <span style="color: Crimson; font-weight: bold;">Crtl+Click</span> on a field you want to edit... <small style="color:red; font-size:0.9em;">Be careful with those that have HTML content!</small> </p> <?php print_a($aql_data); elapsed('before getting cols'); $column_name = $tablename . "_id"; $sql = "SELECT\n a.table_name\n FROM information_schema.columns a,\n information_schema.columns b,\n information_schema.columns c\n WHERE a.table_name = b.table_name\n and a.table_name = c.table_name\n and b.column_name = 'id'\n and c.column_name = 'active'\n and a.column_name = '{$column_name}'"; $cols = sql_array($sql); if ($cols) { echo '<hr />'; foreach ($cols as $col) { $count = aql::count("{$col['table_name']} { where {$column_name} = '{$id}' }"); if ($count) { ?> <p> <a href="/dev/ide/<?php echo $col['table_name']; ?> /<?php echo $column_name; ?> /<?php echo $id;
$filter_not = true; $filterfield = substr($filterfield, 0, -1); # Strip off the exclamation mark. } # 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($filterfield) . "'"); if (count($f) == 0) { exit("Field(s) with short name '" . $filterfield . "' 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.");} if (!$filter_not) { # Standard operation ('=' syntax) $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) . "') "; } else { # Inverted NOT operation ('!=' syntax) if ($sql_filter != "") { $sql_filter .= " and "; } $sql_filter .= "r.ref not in (select resource from resource_keyword where resource_type_field in ('" . join("','", $f) . "') and keyword in ('" . join("','", $kw) . "'))"; # Filter out resources that do contain the keyword(s) } } } # Fetch a resource
function get_session_collections($rs_session, $userref = "", $create = false) { $extrasql = ""; if ($userref != "") { $extrasql = "and user='******'"; } $collectionrefs = sql_array("select ref value from collection where session_id='" . $rs_session . "' " . $extrasql, ""); if (count($collectionrefs) < 1 && $create) { $collectionrefs[0] = create_collection($userref, "My Collection", 0, 1); # Do not translate this string! } return $collectionrefs; }
function delete_resources_in_collection($collection) { global $resource_deletion_state; // Always find all resources in deleted state and delete them permanently: // Note: when resource_deletion_state is null it will find all resources in collection and delete them permanently $query = sprintf("\n\t\t\t\tSELECT ref AS value\n\t\t\t\t FROM resource\n\t\t\tINNER JOIN collection_resource ON collection_resource.resource = resource.ref AND collection_resource.collection = '%s'\n\t\t\t\t %s;\n\t", $collection, isset($resource_deletion_state) ? "WHERE archive = '" . $resource_deletion_state . "'" : ''); $resources_in_deleted_state = array(); $resources_in_deleted_state = sql_array($query); if (!empty($resources_in_deleted_state)) { foreach ($resources_in_deleted_state as $resource_in_deleted_state) { delete_resource($resource_in_deleted_state); } collection_log($collection, 'D', '', 'Resource ' . $resource_in_deleted_state . ' deleted permanently.'); } // Create a comma separated list of all resources remaining in this collection: $resources = sql_array("SELECT resource AS value FROM collection_resource WHERE collection = '" . $collection . "';"); $resources = implode(',', $resources); // If all resources had their state the same as resource_deletion_state, stop here: // Note: when resource_deletion_state is null it will always stop here if (empty($resources)) { return TRUE; } // Delete (ie. move to resource_deletion_state set in config): if (isset($resource_deletion_state)) { $query = sprintf("\n\t\t\t\t UPDATE resource\n\t\t\t\tINNER JOIN collection_resource ON collection_resource.resource = resource.ref AND collection_resource.collection = '%s'\n\t\t\t\t SET archive = '%s';\n\t\t", $collection, $resource_deletion_state); sql_query($query); collection_log($collection, 'D', '', 'All resources of this collection have been deleted by moving them to state ' . $resource_deletion_state); $query = sprintf("\n\t\t\t\tDELETE FROM collection_resource \n\t\t\t\t WHERE resource IN (%s);\n\t\t", $resources); sql_query($query); } return TRUE; }
function notify_resource_change($resource) { debug("notify_resource_change " . $resource); global $notify_on_resource_change_days; // Check to see if we need to notify users of this change if ($notify_on_resource_change_days == 0 || !is_int($notify_on_resource_change_days)) { return false; } debug("notify_resource_change - checking for users that have downloaded this resource " . $resource); $download_users = sql_array("select u.email value from resource_log rl left join user u on rl.user=u.ref where rl.type='d' and rl.resource={$resource} and u.email<>'' and datediff(now(),date)<'{$notify_on_resource_change_days}'", ""); if (count($download_users > 0)) { global $applicationname, $lang, $baseurl; foreach ($download_users as $download_user) { if ($download_user != "") { //send_mail($email,$subject,$message,$from="",$reply_to="",$html_template="",$templatevars=null,$from_name="",$cc="",$bcc="") send_mail($download_user, $applicationname . ": " . $lang["notify_resource_change_email_subject"], str_replace(array("[days]", "[url]"), array($notify_on_resource_change_days, $baseurl . "/?r=" . $resource), $lang["notify_resource_change_email"]), "", "", array("days" => $notify_on_resource_change_days, "url" => $baseurl . "/?r=" . $resource)); } } } }
$staticsync_run_timestamp = "SSTS" . time(); echo date('Y-m-d H:i:s '); echo "Timestamp for this run is {$staticsync_run_timestamp}\n"; set_time_limit(60 * 60 * 40); # Check for a process lock if (is_process_lock("staticsync")) { echo date('Y-m-d H:i:s '); echo "Process lock found. Deferring."; exit("Process lock is in place. Deferring."); } set_process_lock("staticsync"); echo date('Y-m-d H:i:s '); echo "Preloading data..."; $max = 350; $count = 0; $done = sql_array("select file_path value from resource where archive=0 and length(file_path)>0 and file_path like '%/%'"); # Load all modification times into an array for speed $modtimes = array(); $rd = sql_query("select ref,file_modified,file_path from resource where archive=0 and length(file_path)>0"); for ($n = 0; $n < count($rd); $n++) { $modtimes[$rd[$n]["file_path"]] = $rd[$n]["file_modified"]; } $lastsync = sql_value("select value from sysvars where name='lastsync'", ""); if (strlen($lastsync) > 0) { $lastsync = strtotime($lastsync); } else { $lastsync = ""; } echo "...done. Looking for changes..."; # Pre-load the category tree, if configured. if (isset($staticsync_mapped_category_tree)) {
// current date+time $from_date = mktime(0, 0, 0, gmdate("m", time() + 3600 * $cfgrow['timezone']), gmdate("d", time() + 3600 * $cfgrow['timezone']) - 7, gmdate("Y", time() + 3600 * $cfgrow['timezone'])); $from_date = strftime("%Y-%m-%d", $from_date); $from_date = "{$from_date} 00:00:00"; $referer = ""; $query = mysql_query("select distinct referer from " . $pixelpost_db_prefix . "visitors where (referer!='') AND (datetime>'{$from_date}')"); while (list($nreferer) = mysql_fetch_row($query)) { $nreferer = htmlentities($nreferer); $referer .= "!" . $nreferer; } $referer = split("!", $referer); $ref_biglist = ""; foreach ($referer as $value) { if ($value != "") { $value = mysql_real_escape_string($value); $row = sql_array("select count(*) as count from " . $pixelpost_db_prefix . "visitors where (referer='{$value}') AND (datetime>'{$from_date}')"); $refnumb = $row['count']; $ref_biglist .= "{$refnumb}@{$value}!"; } } $ref_biglist = split("!", $ref_biglist); rsort($ref_biglist, SORT_NUMERIC); foreach ($ref_biglist as $value) { @(list($numb, $referer) = explode("@", $value)); if ($numb > "0") { if ($numb < "10") { $numb = "0{$numb}"; } $referername = $referer; $length = strlen($referername); if ($length > 50) {
function get_section_list($page) { return sql_array("select name value from site_text where page='{$page}' and name<>'introtext' order by name"); }