function do_upload($tid) { global $nick; if ($_FILES['attachment-file']['size'] < 1) { return "File size is too small!"; } $file_name = $_FILES['attachment-file']['name']; $file_ext = strtolower(substr($file_name, -4)); if ($file_ext != ".jpg" && $file_ext != ".png" && $file_ext != ".pdf" && $file_ext != ".log" && $file_ext != ".txt") { return "You can only upload jpg/png/pdf/log/txt files!"; } $file_type = $_FILES['attachment-file']['type']; $file_size = $_FILES['attachment-file']['size']; $file_desc = "Attachment by " . $nick; if (!is_numeric($file_size)) { safe_die("Error! Invalid number in file size!"); } $query = squery("INSERT INTO karnaf_files(tid,file_name,file_type,file_desc,file_size,lastupd_time) VALUES(%d,'%s','%s','%s',%d,%d)", $tid, $file_name, $file_type, $file_desc, $file_size, time()); if (!$query) { return "SQL Error! Query failed on do_upload() function: " . mysql_error(); } $id = sql_insert_id(); $fn = KARNAF_UPLOAD_PATH . "/" . $tid; if (!file_exists($fn)) { if (!mkdir($fn)) { return "Can't create attachment directory!"; } } $fn .= "/" . $id . $file_ext; if (!copy($_FILES['attachment-file']['tmp_name'], $fn)) { return "Couldn't create attachment file!"; } return ""; }
function send_research_request() { # Insert a search request into the requests table. # Resolve resource types $rt = ""; $types = get_resource_types(); for ($n = 0; $n < count($types); $n++) { if (getval("resource" . $types[$n]["ref"], "") != "") { if ($rt != "") { $rt .= ", "; } $rt .= $types[$n]["ref"]; } } global $userref; $as_user = getvalescaped("as_user", $userref, true); # If userref submitted, use that, else use this user # Insert the request sql_query("insert into research_request(created,user,name,description,deadline,contact,email,finaluse,resource_types,noresources,shape)\n\tvalues (now(),'{$as_user}','" . getvalescaped("name", "") . "','" . getvalescaped("description", "") . "'," . (getvalescaped("deadline", "") == "" ? "null" : "'" . getvalescaped("deadline", "") . "'") . ",'" . getvalescaped("contact", "") . "','" . getvalescaped("email", "") . "','" . getvalescaped("finaluse", "") . "','" . $rt . "'," . (getvalescaped("noresources", "") == "" ? "null" : "'" . getvalescaped("noresources", "") . "'") . ",'" . getvalescaped("shape", "") . "')"); # E-mails a resource request (posted) to the team global $applicationname, $email_from, $baseurl, $email_notify, $username, $userfullname, $useremail, $lang; $templatevars['ref'] = sql_insert_id(); $templatevars['teamresearchurl'] = $baseurl . "/pages/team/team_research.php"; $templatevars['username'] = $username; $templatevars['userfullname'] = $userfullname; $templatevars['useremail'] = getvalescaped("email", $useremail); # Use provided e-mail (for anonymous access) or drop back to user email. $templatevars['url'] = $baseurl . "/pages/team/team_research_edit.php?ref=" . $templatevars['ref']; $message = "'{$username}' ({$userfullname} - {$useremail}) " . $lang["haspostedresearchrequest"] . ".\n\n"; $message .= $templatevars['teamresearchurl']; hook("modifyresearchrequestemail"); send_mail($email_notify, $applicationname . ": " . $lang["newresearchrequestwaiting"], $message, $useremail, "", "emailnewresearchrequestwaiting", $templatevars); }
function create_dash_tile($url, $link, $title, $reload_interval, $all_users, $default_order_by, $resource_count, $text = "", $delete = 1) { $rebuild_order = TRUE; # Validate Parameters if (empty($reload_interval) || !is_numeric($reload_interval)) { $reload_interval = 0; } $delete = $delete ? 1 : 0; $all_users = $all_users ? 1 : 0; if (!is_numeric($default_order_by)) { $default_order_by = append_default_position(); $rebuild_order = FALSE; } $resource_count = $resource_count ? 1 : 0; # De-Duplication of tiles on creation $existing = sql_query("SELECT ref FROM dash_tile WHERE url='" . $url . "' AND link='" . $link . "' AND title='" . escape_check($title) . "' AND txt='" . escape_check($text) . "' AND reload_interval_secs=" . $reload_interval . " AND all_users=" . $all_users . " AND resource_count=" . $resource_count); if (isset($existing[0]["ref"])) { $tile = $existing[0]["ref"]; $rebuild_order = FALSE; } else { $result = sql_query("INSERT INTO dash_tile (url,link,title,reload_interval_secs,all_users,default_order_by,resource_count,allow_delete,txt) VALUES ('" . $url . "','" . $link . "','" . escape_check($title) . "'," . $reload_interval . "," . $all_users . "," . $default_order_by . "," . $resource_count . "," . $delete . ",'" . escape_check($text) . "')"); $tile = sql_insert_id(); } # If tile already existed then this no reorder if ($rebuild_order) { reorder_default_dash(); } if ($all_users == 1) { sql_query("DELETE FROM user_dash_tile WHERE dash_tile=" . $tile); $result = sql_query("INSERT user_dash_tile (user,dash_tile,order_by) SELECT user.ref,'" . $tile . "',5 FROM user"); } return $tile; }
function create_fact($fact_type, $book_id, $fields) { sql_begin(); sql_pe("INSERT INTO facts\n VALUES (NULL, ?, ?, ?)", array($book_id, $user_id, $fact_type)); $fact_id = sql_insert_id(); add_field_values($fact_id, $fact_type, $fields); sql_commit(); }
/** * Creates a new template * * (static) */ function createNew($name, $desc) { global $manager; $manager->notify('PreAddTemplate', array('name' => &$name, 'description' => &$desc)); sql_query('INSERT INTO ' . sql_table('template_desc') . " (tdname, tddesc) VALUES ('" . sql_real_escape_string($name) . "','" . sql_real_escape_string($desc) . "')"); $newId = sql_insert_id(); $manager->notify('PostAddTemplate', array('templateid' => $newId, 'name' => $name, 'description' => $desc)); return $newId; }
function insert_room($idConference, $user_email, $display_name, $confkey, $audiovideosettings, $maxmikes, $maxparticipants, $startdate, $starthour, $startminute, $duration, $extra_conf) { $res->result = true; $res = $this->api_schedule_meeting($idConference, $user_email, $display_name, $confkey, $audiovideosettings, $maxmikes, $maxparticipants, $startdate, $starthour, $startminute, $duration, $extra_conf); if ($res && $res->result) { require_once _base_ . '/lib/lib.json.php'; $json = new Services_JSON(); //save in database the roomid for user login $insert_room = "\r\n\t\t\tINSERT INTO " . $this->_getRoomTable() . "\r\n\t\t\t( idConference,confkey,emailuser,displayname,audiovideosettings,maxmikes,schedule_info, extra_conf ) VALUES (\r\n\t\t\t\t'" . $idConference . "',\r\n\t\t\t\t'" . $confkey . "',\r\n\t\t\t\t'" . $user_email . "',\r\n\t\t\t\t'" . $display_name . "',\r\n\t\t\t\t'" . $audiovideosettings . "',\r\n\t\t\t\t'" . $maxmikes . "',\r\n\t\t\t\t'" . $json->encode($res->response) . "',\r\n\t\t\t\t'" . $json->encode($extra_conf) . "'\r\n\t\t\t)"; if (!sql_query($insert_room)) { return false; } return sql_insert_id(); } return false; }
function message_add($users, $text, $url = "", $owner = null, $notification_type = MESSAGE_ENUM_NOTIFICATION_TYPE_SCREEN, $ttl_seconds = MESSAGE_DEFAULT_TTL_SECONDS) { global $userref; $text = escape_check($text); $url = escape_check($url); if (!is_array($users)) { $users = array($users); } if (is_null($owner)) { $owner = $userref; } sql_query("INSERT INTO `message` (`owner`, `created`, `expires`, `message`, `url`) VALUES ({$owner}, NOW(), DATE_ADD(NOW(), INTERVAL {$ttl_seconds} SECOND), '{$text}', '{$url}')"); $message_ref = sql_insert_id(); foreach ($users as $user) { sql_query("INSERT INTO `user_message` (`user`, `message`) VALUES ({$user},{$message_ref})"); } }
function sql_transaction($lines = array(), $return_last_insert_id = TRUE) { //sql_rollback(); sql_begin(); if (!is_array($lines)) { $lines = array($lines); } foreach ($lines as $line) { $result = sql_query_dbg($line, true); } if (count($lines)) { if ($return_last_insert_id) { //we must get the insert id before commiting $ret = sql_insert_id(); } } sql_commit(); if (count($lines) && !$return_last_insert_id) { $ret = sql_affected_rows($result); } return $ret; }
function addCom($wcaid,$name,$birthday,$country,$gender,$importing=false,$id=0) { global $compstable; // $name = preg_replace("~[\\\\\"\;]~","",$name); $wcaid = strtoupper($wcaid); if ($wcaid && !preg_match("/^\d{4}[A-Z]{4}\d{2}$/",$wcaid)) return addCom_err("Invalid WCA id format",$wcaid,$name,$importing); if (!checkdate((int)substr($birthday,5,2),(int)substr($birthday,8,2),(int)substr($birthday,0,4))) return addCom_err("Invalid date [$birthday]",$wcaid,$name,$importing); $gender = strtolower($gender); if ($gender!="f" && $gender!="m") return addCom_err("Invalid gender",$wcaid,$name,$importing); // if ($wcaid && !$id) { $result = strict_query("SELECT * FROM $compstable WHERE WCAid=?", array($wcaid)); if (sql_num_rows($result)) return addCom_err("WCA id already exists",$wcaid,$name,$importing); } $result = strict_query("SELECT * FROM countries WHERE id=?", array($country)); if (!sql_num_rows($result)) return addCom_err("Invalid country: ".$country,$wcaid,$name,$importing); if (!$id) { $result = strict_query("SELECT * FROM $compstable WHERE name=? AND country_id=? AND birthday=?", array($name,$country,$birthday)); if (sql_num_rows($result)) return addCom_err("Competitor already inserted",$wcaid,$name,$importing); } // if ($id) strict_query("UPDATE $compstable SET WCAid=?, name=?, country_id=?, birthday=?, gender=? WHERE id=?", array($wcaid,$name,$country,$birthday,$gender,$id)); else strict_query("INSERT INTO $compstable SET WCAid=?, name=?, country_id=?, birthday=?, gender=?", array($wcaid,$name,$country,$birthday,$gender)); // return ($id?(int)$id:sql_insert_id()); }
if (!$enable_mapdisplay) { $tpl->error(ERROR_INVALID_OPERATION); } $sqlchecksum = sprintf('%u', crc32($cachesFilter . "\n" . $sqlFilter)); // check if query was already executed within the cache period $rsMapCache = sql("SELECT `result_id` FROM `map2_result` WHERE `sqlchecksum`='&1' AND DATE_ADD(`date_created`, INTERVAL '&2' SECOND)>NOW() AND `sqlquery`='&3'", $sqlchecksum, $opt['map']['maxcacheage'], $sqlFilter); if ($rMapCache = sql_fetch_assoc($rsMapCache)) { $resultId = $rMapCache['result_id']; sql("UPDATE `map2_result` SET `shared_counter`=`shared_counter`+1 WHERE `result_id`='" . ($resultId + 0) . "'"); } else { // ensure that query is performed without errors before reserving the result_id sql_temp_table_slave('tmpmapresult'); sql_slave("CREATE TEMPORARY TABLE &tmpmapresult (`cache_id` INT UNSIGNED NOT NULL, PRIMARY KEY (`cache_id`)) ENGINE=MEMORY"); sql_slave("INSERT INTO &tmpmapresult (`cache_id`) " . $sqlFilter); sql("INSERT INTO `map2_result` (`slave_id`, `sqlchecksum`, `sqlquery`, `date_created`, `date_lastqueried`) VALUES ('&1', '&2', '&3', NOW(), NOW())", $db['slave_id'], $sqlchecksum, $cachesFilter . "\n" . $sqlFilter); $resultId = sql_insert_id(); sql_slave("INSERT IGNORE INTO `map2_data` (`result_id`, `cache_id`) SELECT '&1', `cache_id` FROM &tmpmapresult", $resultId); sql_drop_temp_table_slave('tmpmapresult'); } sql_free_result($rsMapCache); if ($map2_bounds) { $rs = sql_slave("SELECT MIN(`latitude`) AS `lat_min`,\n\t\t MAX(`latitude`) AS `lat_max`,\n\t\t MIN(`longitude`) AS `lon_min`,\n\t\t MAX(`longitude`) AS `lon_max`\n FROM `map2_data`, `caches`\n\t WHERE `result_id`='&1'\n\t AND `caches`.`cache_id`=`map2_data`.`cache_id`", $resultId); if (($rBounds = sql_fetch_assoc($rs)) && $rBounds['lat_min'] !== null) { if ($rBounds['lat_min'] == $rBounds['lat_max'] && $rBounds['lon_min'] == $rBounds['lon_max']) { $halfwin = 0.02; $rBounds['lat_min'] -= $halfwin; $rBounds['lat_max'] += $halfwin; $rBounds['lon_min'] -= $halfwin; $rBounds['lon_max'] += $halfwin; } $bounds_param = "&lat_min=" . round($rBounds['lat_min'], 5) . "&lat_max=" . round($rBounds['lat_max'], 5) . '&lon_min=' . round($rBounds['lon_min'], 5) . '&lon_max=' . round($rBounds['lon_max'], 5);
function create_feed($name_in, $group_in, $type_in = 0, $desc_in = ''){ if($this->set == true){ return false; //We already have a feed established here } else { //Begin testing/cleaning block $name_in = escape($name_in); $desc_in = escape($desc_in); if(!is_numeric($group_in) || !is_numeric($type_in)){ $this->status = "Unknown Error"; //Aka they are playing with the post data! return false; } //End testing/cleaning block $sql = "INSERT INTO feed (name, group_id, type, description) VALUES ('$name_in', $group_in, $type_in, '$desc_in')"; $res = sql_query($sql); if($res){ $sql_id = sql_insert_id(); $this->id = $sql_id; $this->name = stripslashes($name_in); $this->description = stripslashes($desc_in); $this->group_id = $group_in; $this->type = $type_in; $this->set = true; $notify = new Notification(); $notify->notify('feed', $this->id, 'group', $this->group_id, 'new'); return true; } else { return false; } } }
$nb_erreur++; } } # there is no error in submited datas if ($nb_erreur == 0) { # case : new item to add if (!isset($_POST['id']) or empty($_POST['id'])) { $sql_add = sql_replace($sql['member']['insert_country'], $_POST); $sgbd = sql_connect(); $execution = sql_query($sql_add); if ($execution) { $page['L_message'] = $lang['member']['form_country_add_1']; } else { $page['L_message'] = $lang['member']['form_country_add_0']; } $page['value_id'] = sql_insert_id($sgbd); sql_close($sgbd); # si l'add vient d'une page pop, c'est que l'on vient d'un autre formulaire. # on va donc renvoyer l'information au formulaire parent if ($execution and isset($_GET['fen']) and $_GET['fen'] == "pop") { $page['pop'] = "1"; $page['nouveau_text'] = $_POST['name']; $page['nouveau_id'] = $page['value_id']; } } else { $sql_modification = sql_replace($sql['member']['edit_country'], $_POST); $sgbd = sql_connect(); if (sql_query($sql_modification) != false) { $page['L_message'] = $lang['member']['form_country_edit_1']; } else { $page['L_message'] = $lang['member']['form_country_edit_0'];
function add_smart_collection() { global $userref; $search = getvalescaped("addsmartcollection", ""); $restypes = getvalescaped("restypes", ""); if ($restypes == "Global") { $restypes = ""; } $archive = getvalescaped("archive", "", true); $starsearch = getvalescaped("starsearch", 0); // more compact search strings should work with get_search_title $searchstring = array(); if ($search != "") { $searchstring[] = "search={$search}"; } if ($restypes != "") { $searchstring[] = "restypes={$restypes}"; } if ($starsearch != "") { $searchstring[] = "starsearch={$starsearch}"; } if ($archive != 0) { $searchstring[] = "archive={$archive}"; } $searchstring = implode("&", $searchstring); if ($starsearch == "") { $starsearch = 0; } $newcollection = create_collection($userref, get_search_title($searchstring), 1); sql_query("insert into collection_savedsearch(collection,search,restypes,archive,starsearch) values ('{$newcollection}','" . $search . "','" . $restypes . "','" . $archive . "','" . $starsearch . "')"); $savedsearch = sql_insert_id(); sql_query("update collection set savedsearch='{$savedsearch}' where ref='{$newcollection}'"); set_user_collection($userref, $newcollection); }
$as_re_name = $reply_array['wr_name']; $as_re_mb = $reply_array['mb_id']; } else { $sql = " select max(wr_comment) as max_comment from {$write_table}\n where wr_parent = '{$wr_id}' and wr_is_comment = 1 "; $row = sql_fetch($sql); //$row[max_comment] -= 1; $row['max_comment'] += 1; $tmp_comment = $row['max_comment']; $tmp_comment_reply = ''; } //럭키포인트 $as_lucky = $board['as_lucky'] ? apms_lucky('', $bo_table, $wr_id) : 0; $wr_subject = get_text(stripslashes($wr['wr_subject'])); $sql = " insert into {$write_table}\n set ca_name = '" . addslashes($wr['ca_name']) . "',\n wr_option = '{$wr_secret}',\n wr_num = '{$wr['wr_num']}',\n wr_reply = '',\n wr_parent = '{$wr_id}',\n wr_is_comment = 1,\n wr_comment = '{$tmp_comment}',\n wr_comment_reply = '{$tmp_comment_reply}',\n wr_subject = '',\n wr_content = '{$wr_content}',\n mb_id = '{$mb_id}',\n wr_password = '******',\n wr_name = '{$wr_name}',\n wr_email = '{$wr_email}',\n wr_homepage = '{$wr_homepage}',\n wr_datetime = '" . G5_TIME_YMDHIS . "',\n wr_last = '',\n wr_ip = '{$_SERVER['REMOTE_ADDR']}',\n as_level = '{$as_level}',\n\t\t\t\t\t as_lucky = '{$as_lucky}',\n as_re_mb = '{$as_re_mb}',\n\t\t\t\t\t as_re_name = '{$as_re_name}',\n\t\t\t\t\t as_icon = '{$as_icon}',\n wr_1 = '{$wr_1}',\n wr_2 = '{$wr_2}',\n wr_3 = '{$wr_3}',\n wr_4 = '{$wr_4}',\n wr_5 = '{$wr_5}',\n wr_6 = '{$wr_6}',\n wr_7 = '{$wr_7}',\n wr_8 = '{$wr_8}',\n wr_9 = '{$wr_9}',\n wr_10 = '{$wr_10}' "; sql_query($sql); $comment_id = sql_insert_id(); // 원글에 댓글수 증가 & 마지막 시간 반영 sql_query(" update {$write_table} set wr_comment = wr_comment + 1, wr_last = '" . G5_TIME_YMDHIS . "' where wr_id = '{$wr_id}' "); sql_query(" update {$g5['board_new_table']} set as_comment = as_comment + 1 where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' ", false); // 새글 INSERT if ($is_new) { sql_query(" insert into {$g5['board_new_table']} ( bo_table, wr_id, wr_parent, bn_datetime, mb_id, as_lucky, as_re_mb ) values ( '{$bo_table}', '{$comment_id}', '{$wr_id}', '" . G5_TIME_YMDHIS . "', '{$member['mb_id']}', '{$as_lucky}', '{$as_re_mb}') "); } // 댓글 1 증가 sql_query(" update {$g5['board_table']} set bo_count_comment = bo_count_comment + 1 where bo_table = '{$bo_table}' "); // APMS : 내글반응 등록 if ($is_response) { apms_response('wr', 'comment', '', $bo_table, $wr_id, $wr_subject, $wr['mb_id'], $member['mb_id'], $wr_name, $comment_id); if ($response_flag == 'reply') { //대댓글일 때 $pre_comment = sql_fetch(" select mb_id from {$write_table} where wr_parent = '{$wr_id}' and wr_is_comment = 1 and wr_comment = '{$tmp_comment}' and wr_comment_reply = '" . substr($tmp_comment_reply, 0, -1) . "' ");
function populate_metadata_from_dump($id, $meta) { global $fields_title, $fields_embeddedequiv, $fields_type, $optionlists; // read in the metadata file and dump it into the right places in the database $metadump = file_get_contents($meta); // lazy solution: the resourcespace XML namespace is not formally defined // and thus the docs will not validate. For now we're just going to do some // regex magic to get rid of the namespaces alltogether. Fixme - would be // nice to make the metadump files validate $metadump = preg_replace('/([<\\/])([a-z0-9]+):/i', '$1$2', $metadump); $metadump = preg_replace('/(resourcespace):(resourceid="\\d+">)/i', '$1$2', $metadump); # Fix an issue whereby the resourcespace namespace is not defined. Add a fake namespace to the header. $metadump = str_replace("xmlns:dc", "xmlns:resourcespace='http://www.resourcespace.org' xmlns:dc", $metadump); $metadump = stripInvalidXml($metadump); //echo $metadump; $xml = new SimpleXMLElement($metadump); //print_r($xml); //echo "\n field ref for title is " . $xml->dctitle['rsfieldref'] . "\n"; foreach ($xml as $fieldxml) { if ($fieldxml == '') { continue; } $value = $fieldxml; $rsfieldtitle = $fieldxml['rsfieldtitle']; $rsembeddedequiv = $fieldxml['rsembeddedequiv']; $rsfieldref = $fieldxml['rsfieldref']; $rsfieldtype = $fieldxml['rsfieldtype']; echo "\n==========\n"; echo " rsfieldtitle: {$rsfieldtitle}\n"; echo " rsembeddedequiv: {$rsembeddedequiv}\n"; echo " rsfieldref: {$rsfieldref}\n"; echo " rsfieldtype: {$rsfieldtype}\n"; echo " value: {$value}\n"; $rsfieldtitle = escape_check($rsfieldtitle); $newid = sql_value("select ref value from resource_type_field where title = '{$rsfieldtitle}' and type = '{$rsfieldtype}'", 0); if ($newid > 0) { $finalid = $newid; } else { if ($rsfieldtype == '7') { // category trees are too complicated to construct, so we're going to treat them as text fields for now. $rsfieldtype = '1'; } $sql = "insert into resource_type_field (title,type,name) values ('{$rsfieldtitle}','{$rsfieldtype}','{$rsembeddedequiv}')"; $result = sql_query($sql); $finalid = sql_insert_id(); } if ($rsfieldtype == 2 || $rsfieldtype == 3) { if (!isset($optionlists[$finalid])) { $optionlists[$finalid] = array(); } if (!in_array($value, $optionlists[$finalid])) { $optionlists[$finalid][] = $value; } } $fields_title["{$rsfieldref}"] = $rsfieldtitle; $fields_embeddedequiv["{$rsfieldref}"] = $rsembeddedequiv; $fields_type["{$rsfieldref}"] = $rsfieldtype; $value = escape_check($value); $sql = "insert into resource_data (resource, resource_type_field, value) values ('{$id}','{$rsfieldref}','{$value}')"; sql_query($sql); } }
function ProcessFolder($folder) { #echo "<br>processing folder $folder"; global $syncdir, $nogo, $max, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $staticsync_alt_suffixes, $staticsync_alt_suffix_array, $file_minimum_age, $staticsync_run_timestamp; $collection = 0; echo "Processing Folder: {$folder}\n"; # List all files in this folder. $dh = opendir($folder); echo date('Y-m-d H:i:s '); echo "Reading from {$folder}\n"; while (($file = readdir($dh)) !== false) { // because of alternative processing, some files may disappear during the run // that's ok - just ignore it and move on if (!file_exists($folder . "/" . $file)) { echo date('Y-m-d H:i:s '); echo "File {$file} missing. Moving on.\n"; continue; } $filetype = filetype($folder . "/" . $file); $fullpath = $folder . "/" . $file; $shortpath = str_replace($syncdir . "/", "", $fullpath); if ($staticsync_mapped_category_tree) { $path_parts = explode("/", $shortpath); array_pop($path_parts); touch_category_tree_level($path_parts); } # -----FOLDERS------------- if (($filetype == "dir" || $filetype == "link") && $file != "." && $file != ".." && strpos($nogo, "[" . $file . "]") === false && strpos($file, $staticsync_alternatives_suffix) === false) { # Recurse #echo "\n$file : " . filemtime($folder . "/" . $file) . " > " . $lastsync; if (true || strlen($lastsync) == "" || filemtime($folder . "/" . $file) > $lastsync - 26000) { ProcessFolder($folder . "/" . $file); } } # -------FILES--------------- if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db" && !ss_is_alt($file)) { // we want to make sure we don't touch files that are too new // so check this if (time() - filectime($folder . "/" . $file) < $file_minimum_age) { echo date('Y-m-d H:i:s '); echo " {$file} too new -- skipping .\n"; //echo filectime($folder . "/" . $file) . " " . time() . "\n"; continue; } # Already exists? if (!in_array($shortpath, $done)) { $count++; if ($count > $max) { return true; } echo date('Y-m-d H:i:s '); echo "Processing file: {$fullpath}\n"; if ($collection == 0 && $staticsync_autotheme) { # Make a new collection for this folder. $e = explode("/", $shortpath); $theme = ucwords($e[0]); $name = count($e) == 1 ? "" : $e[count($e) - 2]; echo date('Y-m-d H:i:s '); echo "\nCollection {$name}, theme={$theme}"; $collection = sql_value("select ref value from collection where name='" . escape_check($name) . "' and theme='" . escape_check($theme) . "'", 0); if ($collection == 0) { sql_query("insert into collection (name,created,public,theme,allow_changes) values ('" . escape_check($name) . "',now(),1,'" . escape_check($theme) . "',0)"); $collection = sql_insert_id(); } } # Work out extension $extension = explode(".", $file); $extension = trim(strtolower($extension[count($extension) - 1])); // if coming from collections or la folders, assume these are the resource types if (stristr(strtolower($fullpath), 'collection services/curatorial')) { $type = 5; } elseif (stristr(strtolower($fullpath), 'collection services/conservation')) { $type = 5; } elseif (stristr(strtolower($fullpath), 'collection services/library_archives')) { $type = 6; } else { # Work out a resource type based on the extension. $type = $staticsync_extension_mapping_default; reset($staticsync_extension_mapping); foreach ($staticsync_extension_mapping as $rt => $extensions) { if ($rt == 5 or $rt == 6) { continue; } // we already eliminated those if (in_array($extension, $extensions)) { $type = $rt; } } } # Formulate a title if ($staticsync_title_includes_path) { $title = str_ireplace("." . $extension, "", str_replace("/", " - ", $shortpath)); $title = ucfirst(str_replace("_", " ", $title)); } else { $title = str_ireplace("." . $extension, "", $file); } # Import this file $r = import_resource($shortpath, $type, $title, $staticsync_ingest); if ($r !== false) { # Add to mapped category tree (if configured) if (isset($staticsync_mapped_category_tree)) { $basepath = ""; # Save tree position to category tree field # For each node level, expand it back to the root so the full path is stored. for ($n = 0; $n < count($path_parts); $n++) { if ($basepath != "") { $basepath .= "~"; } $basepath .= $path_parts[$n]; $path_parts[$n] = $basepath; } update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts)); #echo "update_field($r,$staticsync_mapped_category_tree," . "," . join(",",$path_parts) . ");\n"; } # StaticSync path / metadata mapping # Extract metadata from the file path as per $staticsync_mapfolders in config.php if (isset($staticsync_mapfolders)) { foreach ($staticsync_mapfolders as $mapfolder) { $match = $mapfolder["match"]; $field = $mapfolder["field"]; $level = $mapfolder["level"]; if (strpos("/" . $shortpath, $match) !== false) { # Match. Extract metadata. $path_parts = explode("/", $shortpath); if ($level < count($path_parts)) { # Save the value print_r($path_parts); $value = $path_parts[$level - 1]; update_field($r, $field, $value); echo " - Extracted metadata from path: {$value}\n"; } } } } // add the timestamp from this run to the keywords field to help retrieve this batch later $currentkeywords = sql_value("select value from resource_data where resource = '{$r}' and resource_type_field = '1'", ""); if (strlen($currentkeywords) > 0) { $currentkeywords .= ','; } update_field($r, 1, $currentkeywords . $staticsync_run_timestamp); if (function_exists('staticsync_local_functions')) { // if local cleanup functions have been defined, run them staticsync_local_functions($r); } # Add any alternative files $altpath = $fullpath . $staticsync_alternatives_suffix; if ($staticsync_ingest && file_exists($altpath)) { $adh = opendir($altpath); while (($altfile = readdir($adh)) !== false) { $filetype = filetype($altpath . "/" . $altfile); if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") { # Create alternative file global $lang; # Find extension $ext = explode(".", $altfile); $ext = $ext[count($ext) - 1]; $aref = add_alternative_file($r, $altfile, strtoupper($ext) . " " . $lang["file"], $altfile, $ext, filesize_unlimited($altpath . "/" . $altfile)); $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref); rename($altpath . "/" . $altfile, $path); # Move alternative file } } } # check for alt files that match suffix list if ($staticsync_alt_suffixes) { $ss_nametocheck = substr($file, 0, strlen($file) - strlen($extension) - 1); //review all files still in directory and see if they are alt files matching this one $althandle = opendir($folder); while (($altcandidate = readdir($althandle)) !== false) { if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") { # Find extension $ext = explode(".", $altcandidate); $ext = $ext[count($ext) - 1]; $altcandidate_name = substr($altcandidate, 0, strlen($altcandidate) - strlen($ext) - 1); $altcandidate_validated = false; foreach ($staticsync_alt_suffix_array as $sssuffix) { if ($altcandidate_name == $ss_nametocheck . $sssuffix) { $altcandidate_validated = true; $thisfilesuffix = $sssuffix; break; } } if ($altcandidate_validated) { echo date('Y-m-d H:i:s '); echo " Attaching {$altcandidate} as alternative.\n"; $filetype = filetype($folder . "/" . $altcandidate); # Create alternative file global $lang; if (preg_match("/^_VERSO[0-9]*/i", $thisfilesuffix)) { $alt_title = "Verso"; } elseif (preg_match("/^_DNG[0-9]*/i", $thisfilesuffix)) { $alt_title = "DNG"; } elseif (preg_match("/^_ORIG[0-9]*/i", $thisfilesuffix)) { $alt_title = "Original Scan"; } elseif (preg_match("/^_TPV[0-9]*/i", $thisfilesuffix)) { $alt_title = "Title Page Verso"; } elseif (preg_match("/^_TP[0-9]*/i", $thisfilesuffix)) { $alt_title = "Title Page"; } elseif (preg_match("/^_COV[0-9]*/i", $thisfilesuffix)) { $alt_title = "Cover"; } elseif (preg_match("/^_SCR[0-9]*/i", $thisfilesuffix)) { $alt_title = "Inscription"; } elseif (preg_match("/^_EX[0-9]*/i", $thisfilesuffix)) { $alt_title = "Enclosure"; } else { $alt_title = $altcandidate; } $aref = add_alternative_file($r, $alt_title, strtoupper($ext) . " " . $lang["file"], $altcandidate, $ext, filesize_unlimited($folder . "/" . $altcandidate)); $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref); rename($folder . "/" . $altcandidate, $path); # Move alternative file global $alternative_file_previews; if ($alternative_file_previews) { create_previews($r, false, $ext, false, false, $aref); } } } } } # Add to collection if ($staticsync_autotheme) { sql_query("insert into collection_resource(collection,resource,date_added) values ('{$collection}','{$r}',now())"); } // fix permissions // get directory to fix global $scramble_key; $permfixfolder = "/hne/rs/filestore/"; for ($n = 0; $n < strlen($r); $n++) { $permfixfolder .= substr($r, $n, 1); if ($n == strlen($r) - 1) { $permfixfolder .= "_" . substr(md5($r . "_" . $scramble_key), 0, 15); } $permfixfolder .= "/"; } exec("/bin/chown -R wwwrun {$permfixfolder}"); exec("/bin/chgrp -R www {$permfixfolder}"); } else { # Import failed - file still being uploaded? echo date('Y-m-d H:i:s '); echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?) \n"; } } else { # check modified date and update previews if necessary $filemod = filemtime($fullpath); if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) { # File has been modified since we last created previews. Create again. $rd = sql_query("select ref,has_image,file_modified,file_extension from resource where file_path='" . escape_check($shortpath) . "'"); if (count($rd) > 0) { $rd = $rd[0]; $rref = $rd["ref"]; echo date('Y-m-d H:i:s '); echo "Resource {$rref} has changed, regenerating previews: {$fullpath}\n"; create_previews($rref, false, $rd["file_extension"]); sql_query("update resource set file_modified=now() where ref='{$rref}'"); } } } } } }
function _executeInsert($query) { $res = null; if ($this->dbconn === NULL) { $res = sql_query($query); } else { $res = sql_query($query, $this->dbconn); } if (!$res) { return FALSE; } if ($this->dbconn === NULL) { return sql_insert_id(); } else { return sql_insert_id($this->dbconn); } }
} if (preg_match("/\\.(jpg|gif|png)\$/i", $_FILES['bn_img']['name'])) { @mkdir(G5_DATA_PATH . '/banner/' . $_POST['theme'] . '/', G5_DIR_PERMISSION); @chmod(G5_DATA_PATH . '/banner/' . $_POST['theme'] . '/', G5_DIR_PERMISSION); $dest_path = G5_DATA_PATH . '/banner/' . $_POST['theme'] . '/' . $file_name; move_uploaded_file($_FILES['bn_img']['tmp_name'], $dest_path); chmod($dest_path, G5_FILE_PERMISSION); if (file_exists($dest_path)) { $size = getimagesize($dest_path); $sql_common .= "bn_img = '" . $file_name . "',"; } } } if ($w == '') { sql_query(" insert into {$g5['eyoom_banner']} set {$sql_common} bn_regdt = '" . G5_TIME_YMDHIS . "'"); $bn_no = sql_insert_id(); $msg = "배너/광고를 추가하였습다."; } else { if ($w == 'u') { if ($del_bn_img) { $banner_file = G5_DATA_PATH . '/banner/' . $del_bn_img_name; if (file_exists($banner_file)) { @unlink($banner_file); } } $sql = " update {$g5['eyoom_banner']} set {$sql_common} bn_regdt=bn_regdt where bn_no = '{$bn_no}' "; sql_query($sql); $msg = "배너/광고를 정상적으로 수정하였습니다."; } else { alert('제대로 된 값이 넘어오지 않았습니다.'); }
function create_screen($name_in, $group_id_in, $location_in, $mac_hex_in, $width_in='', $height_in='', $template_id_in='', $type_in = 0, $latitude_in = 'NULL', $longitude_in = 'NULL'){ if($this->set){ return false; } else { //Begin testing/cleaning block $name_in = escape($name_in); $location_in = escape($location_in); $mac_hex_in = eregi_replace("[\s|:]", '', $mac_hex_in); $mac_address_in = hexdec($mac_hex_in); if(!is_numeric($group_id_in) || !is_numeric($width_in) || !is_numeric($height_in) || !is_numeric($template_id_in) || !is_numeric($type_in)){ return false; } if($latitude_in == ''){ $latitude_in = 'NULL'; } if($longitude_in == ''){ $longitude_in = 'NULL'; } if(($latitude_in != 'NULL' && $longitude_in != 'NULL') && (!is_numeric($latitude_in) && !is_numeric($longitude_in))){ return false; } //End testing/cleaning block $sql = "INSERT INTO `screen` (name, group_id, location, mac_address, width, height, template_id, type, latitude, longitude) VALUES ('$name_in', $group_id_in, '$location_in', '$mac_address_in', $width_in, $height_in, $template_id_in, $type_in, $latitude_in, $longitude_in)"; // print $sql; die; $res = sql_query($sql); if($res){ $sql_id = sql_insert_id(); $this->id = $sql_id; $this->name = stripslashes($name_in); $this->group_id = $group_id_in; $this->location = stripslashes($location_in); $this->mac_address = $mac_address_in; $this->mac_inhex = $mac_hex_in; $this->width = $width_in; $this->height = $height_in; $this->template_id = $template_id_in; $this->type = $type_in; $this->latitude = $latitude_in; $this->longitude = $longitude_in; $this->last_updated = 0; $this->set = true; $notify = new Notification(); $notify->notify('screen', $this->id, 'group', $this->group_id, 'new'); return true; } else { return false; } } }
} } # for merge, we update only non-empty data if ($value_list[$j] != '') { $field_value_list[$j] = $field_list[$j] . "='" . $value_list[$j] . "'"; } } if ($_POST['action'][$i] == "import") { # we add the match ksort($field_list); ksort($value_list); $var['field'] = implode(", ", $field_list); $var['values'] = "'" . implode("', '", $value_list) . "'"; $sql_import = sql_replace($sql['match']['import_match'], $var); sql_query($sql_import); $match_id = sql_insert_id($sgbd); } elseif ($_POST['action'][$i] == "merge") { # we merge the match with the one found (we update only the not empty field) $var['field_value'] = implode(", ", $field_value_list); $var['id'] = $_POST['match'][$i]; $sql_merge = sql_replace($sql['match']['merge_match'], $var); sql_query($sql_merge); } } sql_close($sgbd); $page['value_step'] = ''; $page['num_step'] = ''; $page['show_step_1'] = ''; $page['show_step_2'] = ''; $page['show_step_3'] = ''; $page['show_step_4'] = '';
function managed_collection_request($ref,$details,$ref_is_resource=false) { # Request mode 1 # Managed via the administrative interface # An e-mail is still sent. global $applicationname,$email_from,$baseurl,$email_notify,$username,$useremail,$userref,$lang,$request_senduserupdates; # Has a resource reference (instead of a collection reference) been passed? # Manage requests only work with collections. Create a collection containing only this resource. if ($ref_is_resource) { $c=create_collection($userref,$lang["request"] . " " . date("ymdHis")); add_resource_to_collection($ref,$c); $ref=$c; # Proceed as normal } # Fomulate e-mail text $message=""; reset ($_POST); foreach ($_POST as $key=>$value) { if (strpos($key,"_label")!==false) { # Add custom field $setting=trim($_POST[str_replace("_label","",$key)]); if ($setting!="") { $message.=$value . ": " . $setting . "\n\n"; } } } if (trim($details)!="") {$message.=$lang["requestreason"] . ": " . newlines($details) . "\n\n";} else {return false;} # Add custom fields $c=""; global $custom_request_fields,$custom_request_required; if (isset($custom_request_fields)) { $custom=explode(",",$custom_request_fields); # Required fields? if (isset($custom_request_required)) {$required=explode(",",$custom_request_required);} for ($n=0;$n<count($custom);$n++) { if (isset($required) && in_array($custom[$n],$required) && getval("custom" . $n,"")=="") { return false; # Required field was not set. } $message.=i18n_get_translated($custom[$n]) . ": " . getval("custom" . $n,"") . "\n\n"; } } # Create the request sql_query("insert into request(user,collection,created,request_mode,status,comments) values ('$userref','$ref',now(),1,0,'" . escape_check($message) . "')"); $request=sql_insert_id(); # Send the e-mail $userconfirmmessage = $lang["requestsenttext"]; $message=$lang["username"] . ": " . $username . "\n" . $message; $message.=$lang["viewrequesturl"] . ":\n$baseurl/?q=$request"; send_mail($email_notify,$applicationname . ": " . $lang["requestcollection"] . " - $ref",$message,$useremail); if ($request_senduserupdates){send_mail($useremail,$applicationname . ": " . $lang["requestsent"] . " - $ref",$userconfirmmessage,$email_from);} # Increment the request counter sql_query("update resource set request_count=request_count+1 where ref='$ref'"); return true; }
function add_alternative_file($resource,$name,$description="",$file_name="",$file_extension="",$file_size=0,$alt_type='') { sql_query("insert into resource_alt_files(resource,name,creation_date,description,file_name,file_extension,file_size,alt_type) values ('$resource','" . escape_check($name) . "',now(),'" . escape_check($description) . "','" . escape_check($file_name) . "','" . escape_check($file_extension) . "','" . escape_check($file_size) . "','" . escape_check($alt_type) . "')"); return sql_insert_id(); }
// set common variable options if (isset($_REQUEST['sortorder'])) { $options['sortorder'] = $_REQUEST['sortorder']; } if (isset($_REQUEST['creationdate'])) { $options['creationdate'] = $_REQUEST['creationdate']; } //========================================================= // 3. query caching //========================================================= $bRememberQuery = isset($_REQUEST['skipqueryid']) ? !$_REQUEST['skipqueryid'] : true; // This is used by the map, which implements its own query-caching. if ($bRememberQuery) { if ($queryid == 0 && $options['showresult'] != 0) { sql("INSERT INTO `queries` (`user_id`, `options`, `last_queried`) VALUES (0, '&1', NOW())", serialize($options)); $options['queryid'] = sql_insert_id(); } $cookie->set('lastqueryid', $options['queryid']); } // remove old queries (after 1 hour without use); // execute only every 50 search calls if (rand(1, 50) == 1) { sql("DELETE FROM `queries` WHERE `last_queried` < NOW() - INTERVAL 1 HOUR AND `user_id`=0"); } //========================================================= // 4. set defaults for new search options // which may not be present in a stored query //========================================================= if (!isset($options['orderRatingFirst'])) { $options['orderRatingFirst'] = false; }
} else { $category = ''; } if ($id) { $query = sprintf('update %s set name="%s",description="%s",category="%s", active=%d,listorder=%d,prefix = "%s", owner = %d where id=%d', $tables["list"], sql_escape($_POST["listname"]), sql_escape($_POST["description"]), sql_escape($_POST['category']), $_POST["active"], $_POST["listorder"], $_POST["prefix"], $_POST["owner"], $id); } else { $query = sprintf('insert into %s (name,description,entered,listorder,owner,prefix,active,category) values("%s","%s",now(),%d,%d,"%s",%d,"%s")', $tables["list"], sql_escape($_POST["listname"]), sql_escape($_POST["description"]), $_POST["listorder"], $_POST["owner"], sql_escape($_POST["prefix"]), $_POST["active"], sql_escape($category)); } # print $query; $result = Sql_Query($query); if (!$id) { $id = sql_insert_id(); $_SESSION['action_result'] = s('New list added') . ": {$id}"; $_SESSION['newlistid'] = $id; } else { $_SESSION['action_result'] = s('Changes saved'); } ## allow plugins to save their fields foreach ($GLOBALS['plugins'] as $plugin) { $result = $result && $plugin->processEditList($id); } print '<div class="actionresult">' . $_SESSION['action_result'] . '</div>'; if ($_GET['page'] == 'editlist') { print '<div class="actions">' . PageLinkButton('importsimple&list=' . $id, s('Add some subscribers')) . ' ' . PageLinkButton('editlist', s('Add another list')) . '</div>'; } unset($_SESSION['action_result']); return;
function new_user($newuser) { global $lang, $home_dash; # Username already exists? $c = sql_value("select count(*) value from user where username='******'", 0); if ($c > 0) { return false; } # Create a new user with username $newuser. Returns the created user reference. sql_query("insert into user(username) values ('" . escape_check($newuser) . "')"); $newref = sql_insert_id(); #Create Default Dash for the new user if ($home_dash) { include dirname(__FILE__) . "/dash_functions.php"; create_new_user_dash($newref); } # Create a collection for this user, the collection name is translated when displayed! $new = create_collection($newref, "My Collection", 0, 1); # Do not translate this string! # set this to be the user's current collection sql_query("update user set current_collection='{$new}' where ref='{$newref}'"); return $newref; }
/** * Creates a new category for this blog * * @param $catName * name of the new category. When empty, a name is generated automatically * (starting with newcat) * @param $catDescription * description of the new category. Defaults to 'New Category' * * @returns * the new category-id in case of success. * 0 on failure */ function createNewCategory($catName = '', $catDescription = _CREATED_NEW_CATEGORY_DESC) { global $member, $manager; if ($member->blogAdminRights($this->getID())) { // generate if ($catName == '') { $catName = _CREATED_NEW_CATEGORY_NAME; $i = 1; $res = sql_query('SELECT * FROM ' . sql_table('category') . " WHERE cname='" . $catName . $i . "' and cblog=" . $this->getID()); while (sql_num_rows($res) > 0) { $i++; $res = sql_query('SELECT * FROM ' . sql_table('category') . " WHERE cname='" . $catName . $i . "' and cblog=" . $this->getID()); } $catName = $catName . $i; } $manager->notify('PreAddCategory', array('blog' => &$this, 'name' => &$catName, 'description' => $catDescription)); $query = 'INSERT INTO ' . sql_table('category') . ' (cblog, cname, cdesc) VALUES (' . $this->getID() . ", '" . sql_real_escape_string($catName) . "', '" . sql_real_escape_string($catDescription) . "')"; sql_query($query); $catid = sql_insert_id(); $manager->notify('PostAddCategory', array('blog' => &$this, 'name' => $catName, 'description' => $catDescription, 'catid' => $catid)); return $catid; } else { return 0; } }
$sql_val[] = $area_defaults[$key] ? 1 : 0; } elseif ($field['nature'] == 'integer') { $sql_val[] = $area_defaults[$key]; } else { $sql_val[] = "'" . addslashes($area_defaults[$key]) . "'"; } } break; } } $sql = "INSERT INTO {$tbl_area} (" . implode(', ', $sql_col) . ") VALUES (" . implode(', ', $sql_val) . ")"; if (sql_command($sql) < 0) { trigger_error(sql_error(), E_USER_WARNING); fatal_error(TRUE, get_vocab("fatal_db_error")); } $area = sql_insert_id("{$tbl_area}", "id"); } // Release the mutex sql_mutex_unlock("{$tbl_area}"); } elseif ($type == "room") { // Truncate the name and description fields to the maximum length as a precaution. $name = substr($name, 0, $maxlength['room.room_name']); $description = substr($description, 0, $maxlength['room.description']); // Add SQL escaping $room_name_q = addslashes($name); $description_q = addslashes($description); if (empty($capacity)) { $capacity = 0; } // Acquire a mutex to lock out others who might be editing rooms if (!sql_mutex_lock("{$tbl_room}")) {
function ProcessFolder($folder, $version_dir, &$resource_array, &$resource_error) { global $lang, $syncdir, $nogo, $staticsync_max_files, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_folder_structure, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $theme_category_levels, $staticsync_defaultstate, $additional_archive_states, $staticsync_extension_mapping_append_values, $image_alternatives, $exclude_resize, $post_host, $media_endpoint, $image_required_height, $sync_bucket, $aws_key, $aws_secret_key; $collection = 0; echo "Processing Folder: {$folder}" . PHP_EOL; #$alt_path = get_resource_path(59, TRUE, '', FALSE, 'png', -1, 1, FALSE, '', 4); # List all files in this folder. $dh = opendir($folder); while (($file = readdir($dh)) !== false) { if ($file == '.' || $file == '..') { continue; } $filetype = filetype($folder . "/" . $file); $fullpath = $folder . "/" . $file; $shortpath = str_replace($syncdir . "/", '', $fullpath); # Work out extension $extension = explode(".", $file); if (count($extension) > 1) { $extension = trim(strtolower($extension[count($extension) - 1])); } else { //No extension $extension = ""; } if (strpos($fullpath, $nogo)) { echo "This directory is to be ignored." . PHP_EOL; continue; } if ($staticsync_mapped_category_tree) { $path_parts = explode("/", $shortpath); array_pop($path_parts); touch_category_tree_level($path_parts); } # -----FOLDERS------------- if (($filetype == "dir" || $filetype == "link") && strpos($nogo, "[{$file}]") === false && strpos($file, $staticsync_alternatives_suffix) === false) { # Get current version direcotries. if (preg_match("/[0-9]{2}-[0-9]{2}-[0-9]{4}\$/", $file)) { if (!in_array($file, $version_dir)) { array_push($version_dir, $file); } if (preg_match('/in_progress*/', $file)) { echo "The Barcode is still being processed." . PHP_EOL; continue; } } # Recurse ProcessFolder($folder . "/" . $file, $version_dir, $resource_array, $resource_error); } $psd_files = array(); if (preg_match('/images/', $fullpath)) { $path_array = explode('/', $fullpath); $psd_array = array_splice($path_array, 0, array_search('images', $path_array)); $psd_path = implode('/', $psd_array) . '/psd/'; $psd_files = array_diff(scandir($psd_path), array('..', '.')); foreach ($psd_files as $index => $psd_file) { $psd_files[$index] = pathinfo($psd_file, PATHINFO_FILENAME); } } # -------FILES--------------- if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") { /* Below Code Adapted from CMay's bug report */ global $banned_extensions; # Check to see if extension is banned, do not add if it is banned if (array_search($extension, $banned_extensions)) { continue; } /* Above Code Adapted from CMay's bug report */ $count++; if ($count > $staticsync_max_files) { return true; } $last_sync_date = sql_value("select value from sysvars where name = 'last_sync'", ""); $file_creation_date = date("Y-m-d H:i:s", filectime($fullpath)); if (isset($last_sync_date) && $last_sync_date > $file_creation_date) { echo "No new file found.." . PHP_EOL; continue; } # Already exists? if (!isset($done[$shortpath])) { echo "Processing file: {$fullpath}" . PHP_EOL; if ($collection == 0 && $staticsync_autotheme) { # Make a new collection for this folder. $e = explode("/", $shortpath); $theme = ucwords($e[0]); $themesql = "theme='" . ucwords(escape_check($e[0])) . "'"; $themecolumns = "theme"; $themevalues = "'" . ucwords(escape_check($e[0])) . "'"; if ($staticsync_folder_structure) { for ($x = 0; $x < count($e) - 1; $x++) { if ($x != 0) { $themeindex = $x + 1; if ($themeindex > $theme_category_levels) { $theme_category_levels = $themeindex; if ($x == count($e) - 2) { echo PHP_EOL . PHP_EOL . "UPDATE THEME_CATEGORY_LEVELS TO {$themeindex} IN CONFIG!!!!" . PHP_EOL . PHP_EOL; } } $th_name = ucwords(escape_check($e[$x])); $themesql .= " AND theme{$themeindex} = '{$th_name}'"; $themevalues .= ",'{$th_name}'"; $themecolumns .= ",theme{$themeindex}"; } } } $name = count($e) == 1 ? '' : $e[count($e) - 2]; echo "Collection {$name}, theme={$theme}" . PHP_EOL; $ul_username = $theme; $escaped_name = escape_check($name); $collection = sql_value("SELECT ref value FROM collection WHERE name='{$escaped_name}' AND {$themesql}", 0); if ($collection == 0) { sql_query("INSERT INTO collection (name,created,public,{$themecolumns},allow_changes)\n VALUES ('{$escaped_name}', NOW(), 1, {$themevalues}, 0)"); $collection = sql_insert_id(); } } # Work out a resource type based on the extension. $type = $staticsync_extension_mapping_default; reset($staticsync_extension_mapping); foreach ($staticsync_extension_mapping as $rt => $extensions) { if (in_array($extension, $extensions)) { $type = $rt; } } $modified_type = hook('modify_type', 'staticsync', array($type)); if (is_numeric($modified_type)) { $type = $modified_type; } # Formulate a title if ($staticsync_title_includes_path) { $title_find = array('/', '_', ".{$extension}"); $title_repl = array(' - ', ' ', ''); $title = ucfirst(str_ireplace($title_find, $title_repl, $shortpath)); } else { $title = str_ireplace(".{$extension}", '', $file); } $modified_title = hook('modify_title', 'staticsync', array($title)); if ($modified_title !== false) { $title = $modified_title; } # Import this file #$r = import_resource($shortpath, $type, $title, $staticsync_ingest); #Check for file name containing the psd. if (!empty($psd_files)) { $image_file_array = explode('/', $fullpath); $image_file = $image_file_array[count($image_file_array) - 1]; $image_psd_name = explode('_', $image_file)[0]; if (array_search($image_psd_name, $psd_files)) { #Image name is in right format. if (!validate_image_size($fullpath, $image_required_height)) { $resource_error['size'][$file] = $fullpath; } $r = import_resource($fullpath, $type, $title, $staticsync_ingest); sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n VALUES ('{$r}', (SELECT ref FROM resource_type_field WHERE name = 'logical_id'), '{$image_psd_name}')"); $original_filepath = sql_query("SELECT value FROM resource_data WHERE resource = '{$r}' AND\n resource_type_field = (SELECT ref FROM resource_type_field where name = 'original_filepath')"); if (isset($original_filepath)) { sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'original_filepath'), '{$fullpath}')"); } } else { echo "Filename '{$fullpath}' is not in right format.." . PHP_EOL; $resource_error['name'][$file] = $fullpath; continue; } } elseif (word_in_string($exclude_resize, explode('/', $fullpath))) { $r = import_resource($fullpath, $type, $title, $staticsync_ingest); } if ($r !== false) { array_push($resource_array, $r); # Create current version for resource. #print_r($version_dir); if (count($version_dir) == 1) { sql_query("INSERT into resource_data (resource,resource_type_field,value)\n VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'current'), 'TRUE')"); } $sync_status = sync_to_s3($syncdir, $sync_bucket, $aws_key, $aws_secret_key); if (!$sync_status) { echo "Failed to sync"; } # Add to mapped category tree (if configured) if (isset($staticsync_mapped_category_tree)) { $basepath = ''; # Save tree position to category tree field # For each node level, expand it back to the root so the full path is stored. for ($n = 0; $n < count($path_parts); $n++) { if ($basepath != '') { $basepath .= "~"; } $basepath .= $path_parts[$n]; $path_parts[$n] = $basepath; } update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts)); } #This is an override to add user data to the resouces if (!isset($userref)) { $ul_username = ucfirst(strtolower($ul_username)); $current_user_ref = sql_query("Select ref from user where username = '******' "); if (!empty($current_user_ref)) { $current_user_ref = $current_user_ref[0]['ref']; sql_query("UPDATE resource SET created_by='{$current_user_ref}' where ref = {$r}"); } } # default access level. This may be overridden by metadata mapping. $accessval = 0; # StaticSync path / metadata mapping # Extract metadata from the file path as per $staticsync_mapfolders in config.php if (isset($staticsync_mapfolders)) { foreach ($staticsync_mapfolders as $mapfolder) { $match = $mapfolder["match"]; $field = $mapfolder["field"]; $level = $mapfolder["level"]; if (strpos("/" . $shortpath, $match) !== false) { # Match. Extract metadata. $path_parts = explode("/", $shortpath); if ($level < count($path_parts)) { // special cases first. if ($field == 'access') { # access level is a special case # first determine if the value matches a defined access level $value = $path_parts[$level - 1]; for ($n = 0; $n < 3; $n++) { # if we get an exact match or a match except for case if ($value == $lang["access" . $n] || strtoupper($value) == strtoupper($lang['access' . $n])) { $accessval = $n; echo "Will set access level to " . $lang['access' . $n] . " ({$n})" . PHP_EOL; } } } else { if ($field == 'archive') { # archive level is a special case # first determin if the value matches a defined archive level $value = $mapfolder["archive"]; $archive_array = array_merge(array(-2, -1, 0, 1, 2, 3), $additional_archive_states); if (in_array($value, $archive_array)) { $archiveval = $value; echo "Will set archive level to " . $lang['status' . $value] . " ({$archiveval})" . PHP_EOL; } } else { # Save the value #print_r($path_parts); $value = $path_parts[$level - 1]; if ($staticsync_extension_mapping_append_values) { $given_value = $value; // append the values if possible...not used on dropdown, date, categroy tree, datetime, or radio buttons $field_info = get_resource_type_field($field); if (in_array($field['type'], array(0, 1, 2, 4, 5, 6, 7, 8))) { $old_value = sql_value("select value value from resource_data where resource={$r} and resource_type_field={$field}", ""); $value = append_field_value($field_info, $value, $old_value); } } update_field($r, $field, trim($value)); if (strtotime(trim($value))) { add_keyword_mappings($r, trim($value), $field, false, true); } else { add_keyword_mappings($r, trim($value), $field); } if ($staticsync_extension_mapping_append_values) { $value = $given_value; } echo " - Extracted metadata from path: {$value}" . PHP_EOL; } } } } } } #Resize only original images. if (!word_in_string($exclude_resize, explode('/', $fullpath))) { echo "Creating preview.."; create_previews($r, false, $extension, false, false, -1, false, $staticsync_ingest); } # update access level sql_query("UPDATE resource SET access = '{$accessval}',archive='{$staticsync_defaultstate}' WHERE ref = '{$r}'"); # Add any alternative files $altpath = $fullpath . $staticsync_alternatives_suffix; if ($staticsync_ingest && file_exists($altpath)) { $adh = opendir($altpath); while (($altfile = readdir($adh)) !== false) { $filetype = filetype($altpath . "/" . $altfile); if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") { # Create alternative file # Find extension $ext = explode(".", $altfile); $ext = $ext[count($ext) - 1]; $description = str_replace("?", strtoupper($ext), $lang["originalfileoftype"]); $file_size = filesize_unlimited($altpath . "/" . $altfile); $aref = add_alternative_file($r, $altfile, $description, $altfile, $ext, $file_size); $path = get_resource_path($r, true, '', true, $ext, -1, 1, false, '', $aref); rename($altpath . "/" . $altfile, $path); # Move alternative file } } } # Add to collection if ($staticsync_autotheme) { $test = ''; $test = sql_query("SELECT * FROM collection_resource WHERE collection='{$collection}' AND resource='{$r}'"); if (count($test) == 0) { sql_query("INSERT INTO collection_resource (collection, resource, date_added)\n VALUES ('{$collection}', '{$r}', NOW())"); } } } else { # Import failed - file still being uploaded? echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?)" . PHP_EOL; } } else { # check modified date and update previews if necessary $filemod = filemtime($fullpath); if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) { # File has been modified since we last created previews. Create again. $rd = sql_query("SELECT ref, has_image, file_modified, file_extension FROM resource\n WHERE file_path='" . escape_check($shortpath) . "'"); if (count($rd) > 0) { $rd = $rd[0]; $rref = $rd["ref"]; echo "Resource {$rref} has changed, regenerating previews: {$fullpath}" . PHP_EOL; extract_exif_comment($rref, $rd["file_extension"]); # extract text from documents (e.g. PDF, DOC). global $extracted_text_field; if (isset($extracted_text_field)) { if (isset($unoconv_path) && in_array($extension, $unoconv_extensions)) { // omit, since the unoconv process will do it during preview creation below } else { extract_text($rref, $extension); } } # Store original filename in field, if set global $filename_field; if (isset($filename_field)) { update_field($rref, $filename_field, $file); } create_previews($rref, false, $rd["file_extension"], false, false, -1, false, $staticsync_ingest); sql_query("UPDATE resource SET file_modified=NOW() WHERE ref='{$rref}'"); } } } } } }
exit("Access denied"); } # Should never arrive at this page without edit access if (getval("submitted", "") != "") { # Save license data # Construct expiry date $expires = getvalescaped("expires_year", "") . "-" . getvalescaped("expires_month", "") . "-" . getvalescaped("expires_day", ""); # Construct usage $license_usage = ""; if (isset($_POST["license_usage"])) { $license_usage = escape_check(join(", ", $_POST["license_usage"])); } if ($ref == "new") { # New record sql_query("insert into resource_license (resource,outbound,holder,license_usage,description,expires) values ('" . getvalescaped("resource", "") . "', '" . getvalescaped("outbound", "") . "', '" . getvalescaped("holder", "") . "', '{$license_usage}', '" . getvalescaped("description", "") . "', '{$expires}')"); $ref = sql_insert_id(); resource_log($resource, "", "", $lang["new_license"] . " " . $ref); } else { # Existing record sql_query("update resource_license set outbound='" . getvalescaped("outbound", "") . "',holder='" . getvalescaped("holder", "") . "', license_usage='{$license_usage}',description='" . getvalescaped("description", "") . "',expires='{$expires}' where ref='{$ref}' and resource='{$resource}'"); resource_log($resource, "", "", $lang["edit_license"] . " " . $ref); } redirect("pages/view.php?ref=" . $resource); } # Fetch license data if ($ref == "new") { # Set default values for the creation of a new record. $license = array("resource" => $resource, "outbound" => 1, "holder" => "", "license_usage" => "", "description" => "", "expires" => date("Y-m-d")); } else { $license = sql_query("select * from resource_license where ref='{$ref}'"); if (count($license) == 0) {
/** * Register a new consumer * @param string $consumer_class * @param string $consumer_file * @return int the id of the registered consumer, FALSE if error * @static * @access private **/ function _registerConsumer($consumer_class, $consumer_file) { $consumer_id = DoceboEventConsumer::getConsumerId($consumer_class); if ($consumer_id !== FALSE) { return $consumer_id; } else { $query = "INSERT INTO " . $GLOBALS['prefix_fw'] . "_event_consumer" . " (consumer_class, consumer_file) VALUES " . " ('" . $consumer_class . "','" . $consumer_file . "')"; $result = sql_query($query); if ($result) { return sql_insert_id(); } else { return FALSE; } } }