function saveRecordHML($filename) { global $recID, $outFullName; $hml = loadRemoteURLContent($filename); if ($hml) { $xml = new DOMDocument(); $xml->loadXML($hml); // convert to xml if (!$xml) { returnXMLErrorMsgPage("unable to generate valid hml for {$filename}"); } else { if ($outFullName) { $text = $xml->saveXML(); $ret = file_put_contents($outFullName, $text); if (!$ret) { returnXMLErrorMsgPage("output of {$outFullName} failed to write"); } else { if ($ret < strlen($text)) { returnXMLErrorMsgPage("output of {$outFullName} wrote {$ret} bytes of " . strlen($text)); } else { // success output the contents of the saved file file $text = file_get_contents($outFullName); } } echo $text; } else { echo $xml->saveXML(); //should never get here. } } } }
<input id="dbName" name="dbName" type="hidden"> <input id="dbTitle" name="dbTitle" type="hidden"> <input id="dbPrefix" name="dbPrefix" type="hidden"> </form> </div> <script type="text/javascript"> var registeredDBs = []; <?php require_once dirname(__FILE__) . '/../../common/php/dbMySqlWrappers.php'; require_once dirname(__FILE__) . "/../../common/config/initialise.php"; mysql_connection_insert(DATABASE); // Connect to the current database // Send request to getRegisteredDBs on the master Heurist index server, to get all registered databases and their URLs $reg_url = HEURIST_INDEX_BASE_URL . "admin/structure/getRegisteredDBs.php?t=11"; //HEURIST_INDEX_BASE_URL POINTS TO HEURISTSCHOLAR.ORG $data = loadRemoteURLContent($reg_url); if ($data) { // If data has been successfully received, write it to a javascript array, leave out own DB if found $res = mysql_query("select sys_dbRegisteredID from sysIdentification where `sys_ID`='1'"); if ($res) { $row = mysql_fetch_row($res); $ownDBID = $row[0]; echo 'var ownDBname = "' . $ownDBID . '";' . "\n"; } else { $ownDBID = 0; } $data = json_decode($data); foreach ($data as $registeredDB) { if ($ownDBID != $registeredDB->rec_ID) { if (array_key_exists('version', $registeredDB) && ($registeredDB->version == null || $registeredDB->version < HEURIST_DBVERSION)) { continue;
* * @author Stephen White * @copyright (C) 2005-2016 University of Sydney * @link http://HeuristNetwork.org * @version 3.1.0 * @license http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0 * @package Heurist academic knowledge management system * @subpackage Viewer/Transforms * @uses HEURIST_FILESTORE_DIR */ require_once dirname(__FILE__) . '/../../common/connect/applyCredentials.php'; require_once dirname(__FILE__) . '/../../records/files/fileUtils.php'; $style = @$_REQUEST['style']; define("SAVE_URI", "disabled"); if (preg_match("/(http:\\/\\/|\\/)/", $style)) { $data = loadRemoteURLContent($style); if ($data) { header('Content-type: text/xml; charset=utf-8'); echo $data; } return; /*****DEBUG****/ $handle = fopen($style, "rb"); $contents = stream_get_contents($handle); fclose($handle); header('Content-type: text/xml; charset=utf-8'); echo $contents; return; } else { if (is_dir(HEURIST_FILESTORE_DIR)) { if (is_dir(HEURIST_FILESTORE_DIR . 'xsl-templates')) {
//this is request from outside - redirect to master index $reg_url = HEURIST_INDEX_BASE_URL . "admin/setup/dbproperties/getRegisteredDBs.php?t=11&db=Heurist_Master_Index"; if ($is_named) { $reg_url = $reg_url . '&named=1'; } if ($is_curated) { $reg_url = $reg_url . '&curated=1'; } //get json array of registered databases $data = loadRemoteURLContentSpecial($reg_url); //without proxy if ($data) { $registeredDBs = json_decode($data); if (!is_array($registeredDBs)) { if (defined("HEURIST_HTTP_PROXY")) { $data = loadRemoteURLContent($reg_url, false); //false = USE PROXY if ($data) { $registeredDBs = json_decode($data); if (!is_array($data)) { $registeredDBs = array(); } } } } } } else { // this is a connection on the same server as the master index mysql_connection_select("hdb_Heurist_Master_Index"); //except specified databases if (@$_REQUEST['exclude']) {
function registerDatabase() { $heuristDBname = rawurlencode(HEURIST_DBNAME); global $dbID, $dbName, $ownerGrpID, $indexdb_user_id, $usrEmail, $usrPassword, $usrName, $usrFirstName, $usrLastName, $dbDescription; $serverURL = HEURIST_BASE_URL . "?db=" . $heuristDBname; $usrEmail = rawurlencode($usrEmail); $usrName = rawurlencode($usrName); $usrFirstName = rawurlencode($usrFirstName); $usrLastName = rawurlencode($usrLastName); $usrPassword = rawurlencode($usrPassword); $dbDescriptionEncoded = rawurlencode($dbDescription); $reg_url = HEURIST_INDEX_BASE_URL . "admin/setup/getNextDBRegistrationID.php" . // TODO: Change to HEURIST_INDEX_BASE_URL "?db=H3MasterIndex&serverURL=" . $serverURL . "&dbReg=" . $heuristDBname . "&dbVer=" . HEURIST_DBVERSION . "&dbTitle=" . $dbDescriptionEncoded . "&usrPassword="******"&usrName=" . $usrName . "&usrFirstName=" . $usrFirstName . "&usrLastName=" . $usrLastName . "&usrEmail=".$usrEmail; $data = loadRemoteURLContent($reg_url); if ($data) { $dbID = intval($data); } if ($dbID == 0) { // Unable to allocate a new database identifier $decodedData = explode(',', $data); $errorMsg = $decodedData[0]; error_log ('registerDB.php had problem allocating a database identifier from the Heurist index, dbID. Error: '.$data); $msg = "Problem allocating a database identifier from the Heurist index.\n" . "Please contact <a href=mailto:info@heuristscholar.org>Heurist developers</a> for advice"; echo $msg . "<br />"; return; } else if($dbID == -1) { // old title update function, should no longer be called $res = mysql_query("update sysIdentification set `sys_dbDescription`='$dbDescription' where `sys_ID`='1'"); echo "<div class='input-row'><div class='input-header-cell'>Database description (updated):</div><div class='input-cell'>". $dbDescription."</div></div>"; } else { // We have got a new dbID, set the assigned dbID in sysIdentification $res = mysql_query("update sysIdentification set `sys_dbRegisteredID`='$dbID', `sys_dbDescription`='$dbDescription' where `sys_ID`='1'"); if($res) { echo "<div class='input-row'><div class='input-header-cell'>Database:</div><div class='input-cell'>".DATABASE."</div></div>"; echo "<div class='input-row'><div class='input-header-cell'>Registration successful, database ID allocated is</div><div class='input-cell'>" . $dbID . "</div></div>"; echo "<div class='input-row'><div class='input-header-cell'></div><div class='input-cell'>Basic description: " . $dbDescription . "</div></div>"; $url = HEURIST_INDEX_BASE_URL."records/edit/editRecord.html?recID=".$dbID."&db=H3MasterIndex"; echo "<div class='input-row'><div class='input-header-cell'>Collection metadata:</div><div class='input-cell'> <a href=$url target=_blank>Click here to edit</a> (login - if asked - as yourself) </div></div>"; ?> <script> // automatically call H3MasterIndix metadata edit form for this database window.open("<?=$url?>",'_blank'); </script> <? } else { error_log ('Unable to write database identification record, dbID is '.$dbID); $msg = "<div class=wrap><div id=errorMsg><span>Unable to write database identification record</span>this database might be incorrectly set up<br />Please contact <a href=mailto:info@heuristscholar.org>Heurist developers</a> for advice</div></div>"; echo $msg; return; } // unable to write db identification record } // successful new DB ID } // registerDatabase()
function loadRemoteFile($filename) { $file_content = loadRemoteURLContent($filename, true); if (!$file_content) { returnXMLErrorMsgPage("Error loading remote file '{$filename}'"); } return $file_content; }
/** * copy file from another h3 instance and register it * * @param mixed $src_fileid - file id in source db * @return int - file id in destionation db, null - if copy and registration are failed */ function copyRemoteFile($src_fileid) { global $sourcedbname, $dbPrefix, $db_prefix; $sourcedb = $db_prefix . $sourcedbname; $_src_HEURIST_UPLOAD_DIR = HEURIST_UPLOAD_ROOT . $sourcedbname . '/'; $res = mysql_query("select * from {$sourcedb}.`recUploadedFiles` where ulf_ID=" . $src_fileid); if (mysql_num_rows($res) != 1) { print "<div style='color:red;'>no entry for file id#" . $src_fileid . "</div>"; return null; // nothing returned if parameter does not match one and only one row } $file = mysql_fetch_assoc($res); $need_copy = false; $externalFile = false; if ($file['ulf_FileName']) { $filename = $file['ulf_FilePath'] . $file['ulf_FileName']; // post 18/11/11 proper file path and name $need_copy = $file['ulf_FilePath'] == $_src_HEURIST_UPLOAD_DIR; } else { if ($file['ulf_ExternalFileReference']) { $filename = $file['ulf_ExternalFileReference']; // post 18/11/11 proper file path and name $need_copy = false; $externalFile = true; } else { $filename = $_src_HEURIST_UPLOAD_DIR . $file['ulf_ID']; // pre 18/11/11 - bare numbers as names, just use file ID $need_copy = true; } } if (!$externalFile && !file_exists($filename)) { //check if this file is remote print "<div style='color:red;'>File {$filename} not found. Can't register file</div>"; ob_flush(); flush(); // flush to screen return null; } if (false && $externalFile) { //@todo - copy external file and save $data = loadRemoteURLContent($filename); if (!$data) { print "<div style='color:red;'>Error. Can't download {$filename}. Can't register URL</div>"; ob_flush(); flush(); // flush to screen return null; } } if ($need_copy) { $newfilename = HEURIST_UPLOAD_DIR . $file['ulf_OrigFileName']; //if file in source upload dirtectiry copy it to destionation upload directory if (!copy($filename, $newfilename)) { print "<div style='color:red;'>Can't copy file {$fielname} to " . HEURIST_UPLOAD_DIR . "</div>"; ob_flush(); flush(); // flush to screen return null; } $filename = $newfilename; } //returns new file id in dest database if ($externalFile) { $jsonData = json_encode(array('remoteURL' => $filename, 'ext' => $file['ulf_MimeExt'], 'params' => $file['ulf_Parameters'] ? $file['ulf_Parameters'] : null)); $ret = register_external($jsonData, null, false); } else { $ret = register_file($filename, null, false); } if (intval($ret) > 0) { return $ret; } else { print "<div style='color:red;'>Can't register file " . $filename . "</div>"; ob_flush(); flush(); // flush to screen return null; } }
// TODO: check that this points at the correct reference database $source_db_id = '2'; //MAGIC NUMBER - ID of H3CoreDefinitions db in Heurist_System_Index database $source_db_name = 'H3CoreDefinitions'; $source_db_prefix = 'hdb_'; $source_url = "http://heuristscholar.org/h3/admin/structure/getDBStructure.php?db=" . $source_db_name . (@$source_db_prefix ? "&prefix=" . $source_db_prefix : ""); // parameters were ?prefix=hdb_&db=H3CoreDefinitions"; } else { $source_db_id = $_REQUEST["dbID"]; $source_db_name = $_REQUEST["dbName"]; $source_db_prefix = @$_REQUEST["dbPrefix"] && @$_REQUEST["dbPrefix"] != "" ? @$_REQUEST["dbPrefix"] : null; $source_url = $_REQUEST["dbURL"] . "admin/structure/getDBStructure.php?db=" . $source_db_name . (@$source_db_prefix ? "&prefix=" . $source_db_prefix : ""); } /*****DEBUG****/ //error_log("source url ".print_r($source_url,true)); $data = loadRemoteURLContent($source_url); if (!$data || substr($data, 0, 6) == "unable") { unlockDatabase(); die("<br>Source database <b> {$source_db_id} : {$source_db_prefix}{$source_db_name} </b>could not be accessed <p>URL to structure service: <a href={$source_url} target=_blank>{$source_url}</a> <p>Server may be offline"); } } // getting data from source database for import of definitions to an existing database // Split received data into data sets for one table defined by >>StartData>> and >>EndData>> markers. $startToken = ">>StartData>>"; // also defined in getDBStructure.php $splittedData = split($startToken, $data); $tableNumber = 1; if ($isExistingDB) { preg_match("/Database Version:\\s*(\\d+)\\.(\\d+)(?:\\.(\\d+))*/", $data, $sourceDBVersion); // $sourceDBVersion[0] = version string, 1, 2, 3 = ,major, minor, sub versions preg_match("/Vsn:\\s*(\\d+)\\.(\\d+)(?:\\.(\\d+))*/", "Vsn: " . HEURIST_DBVERSION, $thisDBVersion);
function makeFileContentNode($file) { $filename = $file['URL']; if ($file['mimeType'] === "application/xml") { // && file_exists($filename)) { if ($file['origName'] !== "_remote" && file_exists($filename)) { $xml = simplexml_load_file($filename); if (!$xml) { makeTag('error', null, " Error while attemping to read {$filename} ."); return; } $xml = $xml->asXML(); } else { $xml = loadRemoteURLContent($filename); if (!$xml) { makeTag('error', null, " Error while attemping to read {$filename} ."); return; } } //embedding so remove any xml element $content = preg_replace("/^\\<\\?xml[^\\?]+\\?\\>/", "", $xml); //embedding so remove any DOCTYPE TODO saw need to validate first then this is fine. also perhaps attribute with type and ID $content = preg_replace("/\\<\\!DOCTYPE[^\\[]+\\s*\\[\\s*(?:(?:\\<--)?\\s*\\<[^\\>]+\\>\\s*(?:--\\>)?)*\\s*\\]\\>/", "", $content, 1); if (preg_match("/\\<\\!DOCTYPE/", $content)) { $content = preg_replace("/\\<\\!DOCTYPE[^\\>]+\\>/", "", $content, 1); } $parser = xml_parser_create(); $ret = xml_parse_into_struct($parser, $content, $vals, $index); if ($ret == 0) { makeTag('error', null, "Invalid XML - " . xml_error_string(xml_get_error_code($parser))); xml_parser_free($parser); return; } if ($content) { makeTag('content', array("type" => "xml"), $content, true, false); } return; } }
/** * * * @param mixed $filedata */ function downloadViaProxy($filename, $mimeType, $url, $bypassProxy = true) { if (!file_exists($filename)) { // || filemtime($filename)<time()-(86400*30)) $rawdata = loadRemoteURLContent($url, $bypassProxy); saveAsFile($rawdata, $filename); /* if ($raw) { if(file_exists($filename)){ unlink($filename); } $fp = fopen($filename, "w"); //$fp = fopen($filename, "x"); fwrite($fp, $raw); //fflush($fp); // need to insert this line for proper output when tile is first requestet fclose($fp); } */ } if (file_exists($filename)) { downloadFile($mimeType, $filename); } }
/** * download image from given url * * @param mixed $remote_url * @return resource */ function get_remote_image($remote_url) { $img = null; $data = loadRemoteURLContent($remote_url, false); //from fileUtils.php if ($data) { $img = imagecreatefromstring($data); } return $img; }
/** * copy file from another vsn 3 instance and register it * * @param mixed $src_fileid - file id in source db * @return int - file id in destionation db, null - if copy and registration are failed */ function copyRemoteFile($src_fileid) { global $sourcedbname, $dbPrefix, $db_prefix; $sourcedb = $db_prefix . $sourcedbname; $_src_HEURIST_FILESTORE_DIR = HEURIST_UPLOAD_ROOT . $sourcedbname . '/'; $_src_HEURIST_FILES_DIR = HEURIST_UPLOAD_ROOT . $sourcedbname . '/file_uploads/'; $res = mysql_query("select * from {$sourcedb}.`recUploadedFiles` where ulf_ID=" . $src_fileid); if (mysql_num_rows($res) != 1) { print "<div style='color:red;'>no entry (or multiple entries)for file id#" . $src_fileid . "</div>"; return null; // nothing returned if parameter does not match one and only one row } $file = mysql_fetch_assoc($res); $need_copy = false; $externalFile = false; if (@$file['ulf_FilePath'] || @$file['ulf_FileName']) { $path = @$file['ulf_FilePath'] . @$file['ulf_FileName']; //add database media storage folder for relative paths //$filename = resolveFilePath($filename); //the same as in resolveFilePath($filename); however instead of consts uses source db folders if ($path && !file_exists($path)) { chdir($_src_HEURIST_FILESTORE_DIR); // relatively db root HEURIST_FILESTORE_DIR $fpath = realpath($path); if (file_exists($fpath)) { $filename = $fpath; } else { chdir($_src_HEURIST_FILES_DIR); // relatively file_uploads $fpath = realpath($path); if (file_exists($fpath)) { $filename = $fpath; } else { //special case to support absolute path on file server if (strpos($path, '/srv/HEURIST_FILESTORE/') === 0) { $fpath = str_replace('/srv/HEURIST_FILESTORE/', HEURIST_UPLOAD_ROOT, $path); if (file_exists($fpath)) { $filename = $fpath; } } } } } else { $filename = $path; } $need_copy = true; } else { if ($file['ulf_ExternalFileReference']) { $filename = $file['ulf_ExternalFileReference']; // post 18/11/11 proper file path and name $need_copy = false; $externalFile = true; } else { $filename = $_src_HEURIST_FILESTORE_DIR . $file['ulf_ID']; // pre 18/11/11 - bare numbers as names, just use file ID $need_copy = true; } } if (!$externalFile && !file_exists($filename)) { //check if this file is remote print "<div style='color:red;'>File {$filename} not found. Can't register file</div>"; ob_flush(); flush(); // flush to screen return null; } if (false && $externalFile) { //@todo - copy external file and save $data = loadRemoteURLContent($filename); if (!$data) { print "<div style='color:red;'>Error. Can't download {$filename}. Can't register URL</div>"; ob_flush(); flush(); // flush to screen return null; } } if ($need_copy) { $newfilename = HEURIST_FILES_DIR . $file['ulf_OrigFileName']; //if file in source upload dirtectiry copy it to destionation upload directory if (!copy($filename, $newfilename)) { print "<div style='color:red;'>Can't copy file {$fielname} to " . HEURIST_FILES_DIR . "</div>"; ob_flush(); flush(); // flush to screen return null; } $filename = $newfilename; } //returns new file id in dest database if ($externalFile) { $jsonData = json_encode(array('remoteURL' => $filename, 'ext' => $file['ulf_MimeExt'], 'params' => $file['ulf_Parameters'] ? $file['ulf_Parameters'] : null)); $ret = register_external($jsonData, null, false); } else { $ret = register_file($filename, null, false); } if (intval($ret) > 0) { return $ret; } else { print "<div style='color:red;'>Can't register file " . $filename . "</div>"; ob_flush(); flush(); // flush to screen return null; } }
</guid> </item> <?php } // 0 1 2 3 4 5 6 7 $squery = "select distinct rec_ID, rec_URL, rec_Title, rec_ScratchPad, rec_RecTypeID, rec_Modified, rec_Added, " . "b.dtl_Value, c.dtl_Value "; $joinTable = " left join recDetails b on (b.dtl_RecID=rec_ID and b.dtl_DetailTypeID=" . (defined('DT_SHORT_SUMMARY') ? DT_SHORT_SUMMARY : "0") . ") left join recDetails c on (c.dtl_RecID=rec_ID and c.dtl_DetailTypeID=" . (defined('DT_CREATOR') ? DT_CREATOR : "0") . ") "; if (true || @$_REQUEST['rules']) { //search with h4 search engine $h4way = true; //$_REQUEST['idonly'] = 1; //$_REQUEST['vo'] = 'h3'; //$result = recordSearch($system, $_REQUEST, false, false, $PUBONLY); $url = HEURIST_BASE_URL . "hserver/controller/record_search.php?" . $_SERVER["QUERY_STRING"] . "&detail=ids&vo=h3"; //call heurist $reclist = loadRemoteURLContent($url); $reclist = json_decode($reclist, true); $reccount = @$reclist['resultCount']; if (@$reclist['error'] != null) { print 'Error: ' . $reclist['error']; printCloseTags(); return; } if (!($reccount > 0)) { print 'Empty result set'; printCloseTags(); return; } $reclist = explode(",", $reclist['recIDs']); } else { $h4way = false;
/** * Returns array of mapobjects $mapobjects = array( "records"=>$geoRecords, "geoObjects"=>$geoObjects, "cntWithGeo"=>$cnt_geo, "cntWithTime"=>$cnt_time, "layers"=>$layers); */ function getMapObjects($request) { $imagelayerRT = defined('RT_IMAGE_SOURCE') ? RT_IMAGE_SOURCE : 0; $KMLlayerRT = defined('RT_KML_SOURCE') ? RT_KML_SOURCE : 0; mysql_connection_select(DATABASE); if (array_key_exists('layers', $request)) { //special mode - load ALL image layers and kml records only - for general drop down list on map $request['ver'] = "1"; $request['q'] = "type:" . $imagelayerRT; if ($KMLlayerRT) { $request['q'] = $request['q'] . "," . $KMLlayerRT; } $search_type = BOTH; } else { if (!@$request['q'] || @$request['ver'] && intval(@$request['ver']) < SEARCH_VERSION) { construct_legacy_search(); // migration path } if (@$request['w'] && ($request['w'] == 'B' || $request['w'] == 'bookmark')) { $search_type = BOOKMARK; } else { $search_type = BOTH; } // all records } if (!array_key_exists("limit", $request)) { //not defined $limit = intval(@$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']["display-preferences"]['smarty-output-limit']); if (!$limit || $limit < 1) { $limit = 1000; //default limit in dispPreferences } $request["limit"] = $limit; //force limit } // find all matching records $cols = "rec_ID as bibID, rec_RecTypeID as rectype, rec_Title as title, rec_URL as URL"; $query = REQUEST_to_query("select {$cols} ", $search_type, $request); $res = mysql_query($query); if (mysql_error()) { print mysql_error(); } $records = array(); $bibIDs = array(); $imageLayers = array(); // list of ids of map image layers $geoObjects = array(); // coordinates $geoBibIDs = array(); // list of id of records that have geo references while ($bib = mysql_fetch_assoc($res)) { $bibID = $bib["bibID"]; if (!$bibID) { continue; } $records[$bibID] = $bib; array_push($bibIDs, $bibID); if ($bib["rectype"] == $imagelayerRT) { //map image layer array_push($imageLayers, $bibID); $geoBibIDs[$bibID] = $bibID; } } foreach ($bibIDs as $bibID) { //0 DT_SHORT_SUMMARY //1 DT_EXTENDED_DESCRIPTION //2 - record URL //3 DT_FILE_RESOURCE //REMOVED 4 DT_LOGO_IMAGE //REMOVED 5 DT_THUMBNAIL //REMOVED 6 DT_IMAGES //4 7 DT_MAP_IMAGE_LAYER_REFERENCE //5 8 DT_KML //6 9 DT_KML_FILE //7 10 record type //d.dtl_UploadedFileID,e.dtl_UploadedFileID,f.dtl_UploadedFileID, // 0 1 2 3 4 imagelayer 5 kmltext 6 kmlfile 7 8 $squery = "select a.dtl_Value, b.dtl_Value, rec_URL, c.dtl_UploadedFileID, g.dtl_Value, h.dtl_Value, i.dtl_UploadedFileID, rec_RecTypeID, rec_Title, j.dtl_Value\n from Records\n left join recDetails a on a.dtl_RecID=rec_ID and a.dtl_DetailTypeID=" . (defined('DT_SHORT_SUMMARY') ? DT_SHORT_SUMMARY : "0") . " left join recDetails b on b.dtl_RecID=rec_ID and b.dtl_DetailTypeID=" . (defined('DT_EXTENDED_DESCRIPTION') ? DT_EXTENDED_DESCRIPTION : "0") . " left join recDetails c on c.dtl_RecID=rec_ID and c.dtl_DetailTypeID=" . (defined('DT_FILE_RESOURCE') ? DT_FILE_RESOURCE : "0") . " left join recDetails g on g.dtl_RecID=rec_ID and g.dtl_DetailTypeID=" . (defined('DT_MAP_IMAGE_LAYER_REFERENCE') ? DT_MAP_IMAGE_LAYER_REFERENCE : "0") . " left join recDetails h on h.dtl_RecID=rec_ID and h.dtl_DetailTypeID=" . (defined('DT_KML') ? DT_KML : "0") . " left join recDetails i on i.dtl_RecID=rec_ID and i.dtl_DetailTypeID=" . (defined('DT_KML_FILE') ? DT_KML_FILE : "0") . " left join recDetails j on j.dtl_RecID=rec_ID and j.dtl_DetailTypeID=" . (defined('DT_SHOW_IN_MAP_BG_LIST') ? DT_SHOW_IN_MAP_BG_LIST : "0") . " where rec_ID={$bibID}"; $res = mysql_query($squery); $row = mysql_fetch_row($res); if ($row) { $records[$bibID]["recID"] = $bibID; $records[$bibID]["rectype"] = $row[7]; $records[$bibID]["description"] = $row[0] ? $row[0] : ($row[1] ? $row[1] : ""); $records[$bibID]["url"] = $row[2]; //($row[2] ? "'".$row[2]."' target='_blank'" :"'javascript:void(0);'"); //'javascript:{this.href="'+$row[2]+'"}' : 'javascript:{return false;}');//javascript:void(0)}'); $records[$bibID]["icon_url"] = HEURIST_ICON_URL . $row[7] . ".png"; $thumb_url = getThumbnailURL($bibID); //function from uploadFile.php if ($thumb_url == "") { //if thumb not defined - use rectype default thumb $thumb_url = HEURIST_ICON_URL . "thumb/th_" . $row[7] . ".png"; } $records[$bibID]["thumb_url"] = $thumb_url; if ($row[4] && is_numeric($row[4]) && !in_array($row[4], $imageLayers)) { //DT_MAP_IMAGE_LAYER_REFERENCE array_push($imageLayers, $row[4]); } $kml_path = getKmlFilePath($row[3]); //DT_FILE_RESOURCE // removed by SAW as DT_KML_FILE changed from a file base type to blocktext // if($kml_path==null){ // $kml_path = getKmlFilePath($row[6]); //DT_KML_FILE // } if ($kml_path != null) { array_push($geoObjects, array("bibID" => $bibID, "type" => "kmlfile", "fileid" => $kml_path, "title" => $row[8], "isbackground" => $row[9])); $geoBibIDs[$bibID] = $bibID; } else { if ($row[5]) { //DT_KML dtl_value contains KML saw TODO: modify to check that text is valid KML. array_push($geoObjects, array("bibID" => $bibID, "type" => "kml", "recid" => $bibID, "title" => $row[8])); $geoBibIDs[$bibID] = $bibID; } } } } //for if ($bibIDs && count($bibIDs) > 0) { // Find the records that actually have any geographic data to plot $res = mysql_query("select dtl_RecID, dtl_Value, AsWKT(dtl_Geo), AsWKT(envelope(dtl_Geo)) from recDetails where dtl_Geo is not null and dtl_RecID in (" . join(",", $bibIDs) . ")"); if (mysql_error()) { } if ($res) { while ($val = mysql_fetch_row($res)) { // get the bounding box if (preg_match("/POLYGON\\(\\((\\S+)\\s+(\\S+),\\s*(\\S+)\\s+(\\S+),\\s*(\\S+)\\s+(\\S+),\\s*(\\S+)\\s+(\\S+),\\s*\\S+\\s+\\S+\\)\\)/i", $val[3], $matches)) { $bbox = array("w" => floatval($matches[1]), "s" => floatval($matches[2]), "e" => floatval($matches[5]), "n" => floatval($matches[6])); } else { $bbox = null; } $geoobj = parseValueFromDb($val[0], $val[1], $val[2], $bbox); if ($geoobj) { array_push($geoObjects, $geoobj); $geoBibIDs[$val[0]] = $val[0]; } } } } //$bibIDs!=null // some records may contain reference to map image layer record (dettype 588), // but we may have such records in search result as well rectype=$imagelayerRT if ($bibIDs && count($bibIDs) > 0) { $squery = "select rec_ID from Records\n where rec_ID in (" . join(",", $bibIDs) . ") and rec_RecTypeID={$imagelayerRT}"; $res = mysql_query($squery); if ($res) { while ($val = mysql_fetch_row($res)) { array_push($imageLayers, $val[0]); $geoBibIDs[$val[0]] = $val[0]; } } } $layers = array(); //find image layers if (count($imageLayers) > 0) { $squery = "select rec_ID, a.dtl_Value as title," . " (select trm_Label from defTerms where trm_ID=b.dtl_Value) as type," . " c.dtl_Value as url," . " (select trm_Label from defTerms where trm_ID=d.dtl_Value) as mime_type," . " e.dtl_Value as min_zoom, f.dtl_Value as max_zoom, g.dtl_Value as copyright, j.dtl_Value as isbackground" . " from Records" . " left join recDetails a on a.dtl_RecID=rec_ID and a.dtl_DetailTypeID=" . (defined('DT_SHORT_NAME') ? DT_SHORT_NAME : "0") . " left join recDetails b on b.dtl_RecID=rec_ID and b.dtl_DetailTypeID=" . (defined('DT_MAP_IMAGE_LAYER_SCHEMA') ? DT_MAP_IMAGE_LAYER_SCHEMA : "0") . " left join recDetails c on c.dtl_RecID=rec_ID and c.dtl_DetailTypeID=" . (defined('DT_SERVICE_URL') ? DT_SERVICE_URL : "0") . " left join recDetails d on d.dtl_RecID=rec_ID and d.dtl_DetailTypeID=" . (defined('DT_MIME_TYPE') ? DT_MIME_TYPE : "0") . " left join recDetails e on e.dtl_RecID=rec_ID and e.dtl_DetailTypeID=" . (defined('DT_MINMUM_ZOOM_LEVEL') ? DT_MINMUM_ZOOM_LEVEL : "0") . " left join recDetails f on f.dtl_RecID=rec_ID and f.dtl_DetailTypeID=" . (defined('DT_MAXIMUM_ZOOM_LEVEL') ? DT_MAXIMUM_ZOOM_LEVEL : "0") . " left join recDetails g on g.dtl_RecID=rec_ID and g.dtl_DetailTypeID=" . (defined('DT_ALTERNATE_NAME') ? DT_ALTERNATE_NAME : "0") . " left join recDetails j on j.dtl_RecID=rec_ID and j.dtl_DetailTypeID=" . (defined('DT_SHOW_IN_MAP_BG_LIST') ? DT_SHOW_IN_MAP_BG_LIST : "0") . " where rec_ID in (" . join(",", $imageLayers) . ")"; $res = mysql_query($squery); while ($rec = mysql_fetch_assoc($res)) { //find the extent for image layer if ($rec['type'] == "maptiler") { $manifest_file = $rec['url'] . "tilemapresource.xml"; } else { if ($rec['type'] == "virtual earth") { $manifest_file = $rec['url'] . "MapCruncherMetadata.xml"; } else { $rec['error'] = "Wrong or non supported map type " . $rec['type']; } } if (!$rec['url']) { $rec['error'] = "URL is not defined for image layer"; } else { if ($manifest_file) { if (file_exists($manifest_file)) { $manifest = simplexml_load_file($manifest_file); } else { $content = loadRemoteURLContent($manifest_file, false); $manifest = simplexml_load_string($content); } if ($manifest == null || is_string($manifest)) { //manifest not found $rec['error'] = "Cannot load manifest file image layer. " . $manifest_file; } else { if ($rec['type'] == "maptiler") { foreach ($manifest->children() as $f_gen) { if ($f_gen->getName() == "BoundingBox") { $arr = $f_gen->attributes(); $rec['extent'] = $arr['miny'] . ',' . $arr['minx'] . ',' . $arr['maxy'] . ',' . $arr['maxx']; //warning!!! wrong labels in these manifests!!!! break; } } } else { $rect = findXMLelement($manifest, 0, array("LayerList", "Layer", "SourceMapRecordList", "SourceMapRecord", "MapRectangle")); if ($rect) { $rec['extent'] = ""; foreach ($rect->children() as $pnt) { $arr = $pnt->attributes(); $lon = $arr['lon']; $lat = $arr['lat']; $rec['extent'] = $rec['extent'] . $lon . "," . $lat . ","; } //$rec['extent'] = $sw['lon'].','.$sw['lat'].','.$ne['lon'].','.$ne['lat']; } } if (!array_key_exists('extent', $rec)) { $rec['error'] = "Cannot find bounds parameters in manifest file"; } } } } if (!$rec['max_zoom']) { $rec['max_zoom'] = 19; } array_push($layers, $rec); } } //count($imageLayers)>0 $timeObjects = array(); if (!@$request['layers']) { // Find time extents -- must have at least a start time (end time is optional) // check for specific details first //saw TODO; modify this for handle durations with a start or end date if (defined('DT_START_DATE') && defined('DT_END_DATE') && $bibIDs && count($bibIDs) > 0) { $squery = "select START.dtl_RecID, START.dtl_Value, END.dtl_Value " . "from recDetails START left join recDetails END on START.dtl_RecID=END.dtl_RecID " . "and END.dtl_DetailTypeID=" . DT_END_DATE . " where START.dtl_DetailTypeID=" . DT_START_DATE . " and (START.dtl_Value || END.dtl_Value) " . "and START.dtl_RecID in (" . join(",", $bibIDs) . ")"; $res = mysql_query($squery); while ($val = mysql_fetch_row($res)) { if ($val[1] || $val[2]) { $timeObjects[$val[0]] = array($val[1], $val[2]); } } } $anyDateBibIDs = array(); //no date enabled foreach ($bibIDs as $bibID) { if (!array_key_exists($bibID, $timeObjects)) { array_push($anyDateBibIDs, $bibID); } } // now process those records that don't have specific start and end dates - // try to extract date from details if (count($anyDateBibIDs) > 0) { $dates = array(); $years = array(); $res = mysql_query("select rec_ID, min(d.dtl_Value), max(d.dtl_Value)\n from Records\n cross join defDetailTypes dt\n left join recDetails d on d.dtl_RecID = rec_ID and d.dtl_DetailTypeID = dt.dty_ID\n where rec_ID in (" . join(",", $anyDateBibIDs) . ")\n and dt.dty_Type = 'date'\n group by rec_ID"); if ($res) { while ($val = mysql_fetch_row($res)) { if ($val[1] && preg_match("/^\\d+\\s*bc/i", $val[1])) { // convert BC to a - sign $val[1] = -preg_replace("/\\s*bc/i", "", $val[1]) + 1; } if ($val[2] && preg_match("/^\\d+\\s*bc/i", $val[2])) { // convert BC to a - sign $val[2] = -preg_replace("/\\s*bc/i", "", $val[2]) + 1; } $dates[$val[0]] = array($val[1], $val[1] !== $val[2] ? $val[2] : null); } } $res = mysql_query("select rec_ID, min(d.dtl_Value), max(d.dtl_Value)\n from Records\n cross join defDetailTypes yt\n left join recDetails y on y.dtl_RecID = rec_ID and y.dtl_DetailTypeID = yt.dty_ID\n where rec_ID in (" . join(",", $anyDateBibIDs) . ")\n and yt.dty_Type = 'year'\n group by rec_ID"); if ($res) { while ($val = mysql_fetch_row($res)) { if ($val[1] && preg_match("/^\\d+\\s*bc/i", $val[1])) { // convert BC to a - sign $val[1] = -preg_replace("/\\s*bc/i", "", $val[1]) + 1; } if ($val[2] && preg_match("/^\\d+\\s*bc/i", $val[2])) { // convert BC to a - sign $val[2] = -preg_replace("/\\s*bc/i", "", $val[2]) + 1; } $years[$val[0]] = array($val[1], $val[1] !== $val[2] ? $val[2] : null); } } foreach ($anyDateBibIDs as $bibID) { $sd = @$dates[$bibID][0] ? $dates[$bibID][0] : null; $ed = @$dates[$bibID][1] ? $dates[$bibID][1] : null; $sy = @$years[$bibID][0] ? $years[$bibID][0] : null; $ey = @$years[$bibID][1] ? $years[$bibID][1] : null; if (!$sd && !$ed && $sy && $sy == $ey) { $ey = $sy + 1; } $s = $sd ? $sd : $sy; $e = $ed ? $ed : $ey; if ($s >= $e) { $e = null; } $timeObjects[$bibID] = array($s, $e); } } //if } //if not layer request //sort($geoBibIDs); $geoRecords = array(); $cnt_geo = 0; $cnt_time = 0; //foreach ($geoBibIDs as $bibID) { foreach ($bibIDs as $bibID) { //loop for all records // $bibID = ""+$bibID; $isNotGeoLoc = !@$geoBibIDs[$bibID]; if (!$isNotGeoLoc || array_key_exists($bibID, $timeObjects)) { $geoRecords[$bibID] = $records[$bibID]; if ($isNotGeoLoc) { //no geo data - only timedata array_push($geoObjects, array("bibID" => $bibID, "type" => "none")); //empty georeference $geoBibIDs[$bibID] = $bibID; } else { $cnt_geo++; } if (array_key_exists($bibID, $timeObjects)) { list($start, $end) = $timeObjects[$bibID]; $geoRecords[$bibID]["start"] = $start; if ($end) { $geoRecords[$bibID]["end"] = $end; } $cnt_time++; } } } //count($geoRecords) $mapobjects = array("records" => $geoRecords, "geoObjects" => $geoObjects, "cntWithGeo" => $cnt_geo, "cntWithTime" => $cnt_time, "layers" => $layers); return $mapobjects; }
function checkVersionOnMainServer($version_in_session) { $version_last_check = getLastCheckedVersion($version_in_session); //check data of last check and last warning email $fname = HEURIST_UPLOAD_ROOT . "lastAdviceSent.ini"; if ($version_last_check == null && file_exists($fname)) { //last check and version $version_in_session = file_get_contents($fname); $version_last_check = getLastCheckedVersion($version_in_session); } if ($version_last_check) { return $version_in_session; } //send request to main server HEURIST_INDEX_BASE_URL $url = HEURIST_INDEX_BASE_URL . "admin/setup/getCurrentVersion.php?db=H3MasterIndex&check=1"; $rawdata = loadRemoteURLContent($url); if ($rawdata) { //parse result $current_version = explode("|", $rawdata); if (count($current_version) > 0) { //debug $current_version[0] = "5.9.1 RC2"; $curver = explode(".", $current_version[0]); if (count($curver) > 2) { $major = intval($curver[0]); $subver = intval($curver[1]); //compare with local versions $locver = explode(".", HEURIST_VERSION); $major_local = intval($locver[0]); $subver_local = intval($locver[1]); $email_title = null; if ($major_local < $major) { $email_title = "Major new version of Heurist Vsn " . $current_version[0] . " available for " . HEURIST_SERVER_NAME . " (running Vsn " . HEURIST_VERSION . ")"; } else { if ($major_local == $major && $subver_local < $subver) { $email_title = "Heurist update Vsn " . $current_version[0] . " available for " . HEURIST_SERVER_NAME . " (running Vsn " . HEURIST_VERSION . ")"; } } if ($email_title) { //send email to administrator about new database registration $email_text = "Your server is running Heurist version " . HEURIST_VERSION . " The current stable version of Heurist (version " . $current_version[0] . ") is available from HeuristScholar.org We recommend updating your copy of the software if the sub-version has changed " . "(or better still with any change of version).\n\n" . "Heurist is copyright (C) The University of Sydney and available as Open Source software under the GNU-GPL licence. " . "Beta versions of the software with new features may also be available at the Google Code repository, linked from the Heurist home page."; // $rv = mail(HEURIST_MAIL_TO_ADMIN, $email_title, $email_text, "From: root"); if (!$rv) { //TODO SAW this should not fail silently error_log("mail send failed: " . HEURIST_MAIL_TO_ADMIN); //to delete check file ????? } else { } } //save current date of check $version_in_session = date("Y-m-d") . "|" . $current_version[0]; if (!saveAsFile($version_in_session, $fname)) { error_log("Can't write file " . $fname); } return $version_in_session; } } } return null; //version check fails }
function makeDatabase() { global $newDBName, $isNewDB, $done, $isDefineNewDatabase, $dbTemplateName, $errorCreatingTables; $isTemplateDB = $dbTemplateName != null && $dbTemplateName != '0'; $dataInsertionSQLFile = null; $error = false; $warning = false; if (isset($_REQUEST['dbname'])) { // Check that there is a current administrative user who can be made the owner of the new database $message = "MySQL username and password have not been set in configIni.php " . "or heuristConfigIni.php<br/> - Please do so before trying to create a new database.<br>"; if (ADMIN_DBUSERNAME == "" || ADMIN_DBUSERPSWD == "") { errorOut($message); return false; } // checking for current administrative user if (!is_logged_in()) { //this is creation+registration $captcha_code = getUsrField('ugr_Captcha'); //check capture if (@$_SESSION["captcha_code"] && $_SESSION["captcha_code"] != $captcha_code) { errorOut('Are you a bot? Please enter the correct answer to the challenge question'); print '<script type="text/javascript">isRegdataEntered=false;</script>'; $isDefineNewDatabase = true; return false; } if (@$_SESSION["captcha_code"]) { unset($_SESSION["captcha_code"]); } $firstName = getUsrField('ugr_FirstName'); $lastName = getUsrField('ugr_LastName'); $eMail = getUsrField('ugr_eMail'); $name = getUsrField('ugr_Name'); $password = getUsrField('ugr_Password'); if ($firstName == '' || $lastName == '' || $eMail == '' || $name == '' || $password == '') { errorOut('Mandatory data for your registration profile (first and last name, email, password) are not completed. Please fill out registration form'); print '<script type="text/javascript">isRegdataEntered=false;</script>'; $isDefineNewDatabase = true; return false; } } // Create a new blank database $newDBName = trim($_REQUEST['uname']) . '_'; if ($newDBName == '_') { $newDBName = ''; } // don't double up underscore if no user prefix $newDBName = $newDBName . trim($_REQUEST['dbname']); $newname = HEURIST_DB_PREFIX . $newDBName; // all databases have common prefix then user prefix $list = mysql__getdatabases(); $list = array_map("arraytolower", $list); if (false && in_array(strtolower($newDBName), $list)) { errorOut('Warning: database "' . $newname . '" already exists. Please choose a different name'); $isDefineNewDatabase = true; return false; } //get path to registered db template and download coreDefinitions.txt $reg_url = @$_REQUEST['url_template']; $exemplar_db = @$_REQUEST['exemplar']; $name = ''; //user name if (true) { // For debugging: set to false to avoid real database creation if ($exemplar_db != null) { //from example db //1a. verify that sample dump exists $templateFoldersContent = HEURIST_DIR . "admin/setup/exemplars/" . $exemplar_db . '.zip'; if (!file_exists($templateFoldersContent) || filesize($templateFoldersContent) < 1) { errorOut('Sorry, unable to find the exemplar zip file (' . $templateFoldersContent . ')containing the database folders and SQL script.'); return false; } //1b. verify that sample dump can be extracted $exemplar_dir = HEURIST_DIR . "admin/setup/exemplars/"; $exemplar_dir = str_replace('//', '/', $exemplar_dir); $dataInsertionSQLFile = HEURIST_FILESTORE_DIR . 'scratch/' . $exemplar_db . ".sql"; if (!file_exists($dataInsertionSQLFile) || filesize($templateFoldersContent) < 0) { //extract dump from archive unzip($templateFoldersContent, HEURIST_FILESTORE_DIR . 'scratch/', $exemplar_db . '.sql'); if (!file_exists($dataInsertionSQLFile) || filesize($dataInsertionSQLFile) < 0) { errorOut('Sorry, unable to extract the database script "' . $exemplar_db . '.sql" from the zipped file "' . $templateFoldersContent . '". This may be due to incorrect permissions on the program code - please consult your system administrator.'); return false; } } //2. create empty database if (!db_create($newname)) { errorOut('Sorry, unable to create new database ' . $newname); return false; } //3. restore from dump if (!db_script($newname, $dataInsertionSQLFile)) { errorOut('Error importing sample data from ' . $dataInsertionSQLFile); cleanupNewDB($newname); return false; } $dataInsertionSQLFile = null; } else { //$exemplar_db // this is global variable that is used in buildCrosswalks.php $templateFileName = "NOT DEFINED"; $templateFoldersContent = "NOT DEFINED"; if ($reg_url) { // getting definitions from an external registered database $nouse_proxy = true; $isTemplateDB = true; $data = loadRemoteURLContent($reg_url, $nouse_proxy); //without proxy $resval = isDefinitionsInvalid($data); if ($resval) { if (defined("HEURIST_HTTP_PROXY")) { $nouse_proxy = false; $data = loadRemoteURLContent($reg_url, $nouse_proxy); //with proxy $resval = isDefinitionsInvalid($data); if ($resval) { $data = null; } } else { $data = null; } } if ($resval) { errorOut("Error importing core definitions from template database {$reg_url} for database {$newname}<br>" . $resval . '<br>Please check whether this database is valid; consult Heurist support if needed'); return false; } //save data into file if (defined('HEURIST_SETTING_DIR')) { $templateFileName = HEURIST_SETTING_DIR . get_user_id() . '_dbtemplate.txt'; } else { $templateFileName = HEURIST_UPLOAD_ROOT . '0_dbtemplate.txt'; } $res = file_put_contents($templateFileName, $data); if (!$res) { errorOut('Error: cannot save definitions from template database into local file.' . ' Please verify that folder ' . (defined('HEURIST_SETTING_DIR') ? HEURIST_SETTING_DIR : HEURIST_UPLOAD_ROOT) . ' is writeable'); return false; } //download content of some folder from template database ====================== $reg_url = str_replace("getDBStructureAsSQL", "getDBFoldersForNewDB", $reg_url); //replace to other script $data = loadRemoteURLContent($reg_url, $nouse_proxy); //with proxy if ($data) { if (defined('HEURIST_SETTING_DIR')) { $templateFoldersContent = HEURIST_SETTING_DIR . get_user_id() . '_dbfolders.zip'; } else { $templateFoldersContent = HEURIST_UPLOAD_ROOT . '0_dbfolders.zip'; } $res = file_put_contents($templateFoldersContent, $data); if (!$res) { errorOut('Warning: cannot save content of settings folders from template database into local file. ' . ' Please verify that folder ' . (defined('HEURIST_SETTING_DIR') ? HEURIST_SETTING_DIR : HEURIST_UPLOAD_ROOT) . ' is writeable'); return false; } } else { errorOut('Warning: server does not return the content of settings folders from template database. ' . 'Please ask system adminstrator to verify that zip extension on remote server is installed and that upload folder is writeable'); return false; } // Example database: download data to insert into new database ================================= if ($dbTemplateName != '1') { // TODO: Artem: correct way is the donwloading data from sample database, however at the moment it is included into code. Ian: NASAT - would exposes databases to easy harvesting, but potentially OK as long as data marked public // $dbTemplateNsme is the name of the database which is used to populate the example database, the corresponding data file has the same name with _data.sql appended $dataInsertionSQLFile = HEURIST_DIR . "admin/setup/dbcreate/" . $dbTemplateName . "_data.sql"; if (!file_exists($dataInsertionSQLFile)) { errorOut('Warning: cannot find sample data file in code ' . $dataInsertionSQLFile); return false; } } } else { if ($isTemplateDB) { errorOut('Wrong parameters: Template database is not defined.'); return false; } else { $templateFileName = HEURIST_DIR . "admin/setup/dbcreate/coreDefinitions.txt"; } } if (!file_exists($templateFileName)) { errorOut('Error: template database structure file ' . $templateFileName . ' not found'); return false; } if (!createDatabaseEmpty($newDBName)) { $isDefineNewDatabase = true; return false; } // Run buildCrosswalks to import minimal definitions from coreDefinitions.txt into the new DB // yes, this is badly structured, but it works - if it ain't broke ... $isNewDB = true; // flag of context for buildCrosswalks, tells it to use coreDefinitions.txt require_once dirname(__FILE__) . '/../../structure/import/buildCrosswalks.php'; // errorCreatingTables is set to true by buildCrosswalks if an error occurred if ($errorCreatingTables) { errorOut('Error importing core definitions from ' . ($isTemplateDB ? "template database" : "coreDefinitions.txt") . ' for database ' . $newname . '<br>' . 'Please check whether this file or database is valid; consult Heurist support if needed'); cleanupNewDB($newname); return false; } } //not $exemplar_db // Get and clean information for the user creating the database if (!is_logged_in()) { // getUsrField sanitises data entered $longName = ""; $firstName = getUsrField('ugr_FirstName'); $lastName = getUsrField('ugr_LastName'); $eMail = getUsrField('ugr_eMail'); $name = getUsrField('ugr_Name'); $password = getUsrField('ugr_Password'); $department = getUsrField('ugr_Department'); $organisation = getUsrField('ugr_Organisation'); $city = getUsrField('ugr_City'); $state = getUsrField('ugr_State'); $postcode = getUsrField('ugr_Postcode'); $interests = getUsrField('ugr_Interests'); $ugr_IncomingEmailAddresses = getUsrField('ugr_IncomingEmailAddresses'); $ugr_TargetEmailAddresses = getUsrField('ugr_TargetEmailAddresses'); $ugr_URLs = getUsrField('ugr_URLs'); $s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./'; $salt = $s[rand(0, strlen($s) - 1)] . $s[rand(0, strlen($s) - 1)]; $password = crypt($password, $salt); } else { mysql_connection_insert(DATABASE); $query = mysql_query('SELECT ugr_LongName, ugr_FirstName, ugr_LastName, ugr_eMail, ugr_Name, ugr_Password, ' . 'ugr_Department, ugr_Organisation, ugr_City, ugr_State, ugr_Postcode, ugr_Interests, ' . 'ugr_IncomingEmailAddresses, ugr_TargetEmailAddresses, ugr_URLs ' . 'FROM sysUGrps WHERE ugr_ID=' . get_user_id()); $details = mysql_fetch_row($query); $longName = mysql_real_escape_string($details[0]); $firstName = mysql_real_escape_string($details[1]); $lastName = mysql_real_escape_string($details[2]); $eMail = mysql_real_escape_string($details[3]); $name = mysql_real_escape_string($details[4]); $password = mysql_real_escape_string($details[5]); $department = mysql_real_escape_string($details[6]); $organisation = mysql_real_escape_string($details[7]); $city = mysql_real_escape_string($details[8]); $state = mysql_real_escape_string($details[9]); $postcode = mysql_real_escape_string($details[10]); $interests = mysql_real_escape_string($details[11]); $ugr_IncomingEmailAddresses = mysql_real_escape_string($details[12]); $ugr_TargetEmailAddresses = mysql_real_escape_string($details[13]); $ugr_URLs = mysql_real_escape_string($details[14]); } // todo: code location of upload directory into sysIdentification, remove from edit form (should not be changed) // todo: might wish to control ownership rather than leaving it to the O/S, although this works well at present createDatabaseFolders($newDBName); if (file_exists($templateFoldersContent) && filesize($templateFoldersContent) > 0) { //override content of setting folders with template database files - rectype icons, smarty templates etc unzip($templateFoldersContent, HEURIST_UPLOAD_ROOT . $newDBName . "/"); } // Prepare to write to the newly created database mysql_connection_insert($newname); // Make the current user the owner and admin of the new database $res = mysql_query('UPDATE sysUGrps SET ugr_Enabled="Y", ugr_LongName="' . $longName . '", ugr_FirstName="' . $firstName . '", ugr_LastName="' . $lastName . '", ugr_eMail="' . $eMail . '", ugr_Name="' . $name . '", ugr_Password="******", ugr_Department="' . $department . '", ugr_Organisation="' . $organisation . '", ugr_City="' . $city . '", ugr_State="' . $state . '", ugr_Postcode="' . $postcode . '", ugr_IncomingEmailAddresses="' . $ugr_IncomingEmailAddresses . '", ugr_TargetEmailAddresses="' . $ugr_TargetEmailAddresses . '", ugr_URLs="' . $ugr_URLs . '", ugr_interests="' . $interests . '" WHERE ugr_ID=2'); if (!$res) { ?> <b>Warning: Failed to make the current user the owner and admin of the new database, error:</b> <?php print mysql_error(); } // Add the default navigation tree for the DATABASE MANAGERS group (user #1). This is copied from the Heurist_Core_Definitions database} $navTree = '{"expanded":true,"key":"root_3","title":"root","children":[{"expanded":true,"folder":true,"key":"_6","title":"Recent changes","children":[{"folder":false,"key":"19","title":"Recent changes (last week)","data":{"isfaceted":false}},{"folder":false,"key":"20","title":"Recent changes (last month)","data":{"isfaceted":false}},{"folder":false,"key":"21","title":"Recent changes (last year)","data":{"isfaceted":false}},{"folder":false,"key":"14","title":"All (most recent first)","data":{"isfaceted":false}}]},{"expanded":true,"folder":true,"key":"_1","title":"Specific types","children":[{"key":"27","title":"Bibliographic records","data":{"isfaceted":false}},{"key":"28","title":"Organisations","data":{"isfaceted":false}},{"key":"29","title":"People","data":{"isfaceted":false}},{"key":"30","title":"Media items","data":{"isfaceted":false}},{"expanded":true,"folder":true,"key":"_5","title":"Facet searches","children":[{"key":"25","title":"Persons","data":{"isfaceted":true}},{"key":"26","title":"Organisations","data":{"isfaceted":true}},{"expanded":true,"folder":true,"key":"_1","title":"Facet searches with rules","children":[{"key":"31","title":"Persons with related recs","data":{"isfaceted":true}}]}]}]},{"expanded":true,"folder":true,"key":"_5","title":"Experiments","children":[{"key":"24","title":"Mapping (layers, data sources)","data":{"isfaceted":false}}]}]}'; $res = mysql__insertupdate($newname, 'sysUGrps', 'ugr', array('ugr_ID' => 1, 'ugr_NavigationTree' => $navTree)); if (!is_int($res)) { print '<b>Warning: Failed to copy navigation tree for user (group) 1 (DB Managers) to new database, error:</b>' . $res; } // Add the default navigation tree for the DATABASE OWNER (user #2). This is copied from the Heurist_Core_Definitions database} $navTree = '"bookmark":{"expanded":true,"key":"root_1","title":"root","children":[{"folder":false,"key":"_1","title":"Recent changes","data":{"url":"?w=bookmark&q=sortby:-m after:\\"1 week ago\\"&label=Recent changes"}},{"folder":false,"key":"_2","title":"All (date order)","data":{"url":"?w=bookmark&q=sortby:-m&label=All records"}}]},"all":{"expanded":true,"key":"root_2","title":"root","children":[{"folder":false,"key":"_3","title":"Recent changes","data":{"url":"?w=all&q=sortby:-m after:\\"1 week ago\\"&label=Recent changes"}},{"folder":false,"key":"_4","title":"All (date order)","data":{"url":"?w=all&q=sortby:-m&label=All records"}},{"folder":true,"key":"_5","title":"Rules","children":[{"folder":false,"key":"12","title":"Person > anything they created","data":{"isfaceted":false}},{"folder":false,"key":"13","title":"Organisation > Assoc. places","data":{"isfaceted":false}}]}]}'; $res = mysql__insertupdate($newname, 'sysUGrps', 'ugr', array('ugr_ID' => 2, 'ugr_NavigationTree' => $navTree)); if (!is_int($res)) { print '<b>Warning: Failed to copy navigation tree for user 2 (DB Owner) to new database, error:</b>' . $res; } // email the system administrator to tell them a new database has been created user_EmailAboutNewDatabase($name, $firstName . ' ' . $lastName, $organisation, $eMail, $newDBName, $interests); } if ($dataInsertionSQLFile != null && file_exists($dataInsertionSQLFile)) { if (!db_script($newname, $dataInsertionSQLFile)) { errorOut('Error importing sample data from ' . $dataInsertionSQLFile); } } ?> <div style='padding:0px 0 10px 0; font-size:larger;'> <h2 style='padding-bottom:10px'>Congratulations, your new database [ <?php echo $newDBName; ?> ] has been created</h2> <?php if (@$_REQUEST['db'] != '' && @$_REQUEST['db'] != null) { ?> <p style="padding-left:10px"><strong>Admin username:</strong> <?php echo $name; ?> </p> <p style="padding-left:10px"><strong>Admin password:</strong> <<i>same as the account you are currently logged in as</i>></p> <?php } ?> <p style="padding-left:10px">Log into your new database with the following link:</p> <p style="padding-left:6em"><b><a href="<?php echo HEURIST_BASE_URL . "?db=" . $newDBName; ?> " title="" onclick="{closeDialog()}" target="blank"> <?php echo HEURIST_BASE_URL . "?db=" . $newDBName; ?> </a></b> <i>(we suggest bookmarking this link)</i></p> <p style="padding-left:6em"> After logging in to your new database, we suggest you import some additional entity types from one of the<br /> curated Heurist databases, or from one of the other databases listed in the central database catalogue,<br /> using Database > Structure > Acquire from Databases <!--or Database > Structure > Acquire from Templates --> </p> </div> <?php // TODO: automatically redirect to the new database in a new window // this is a point at which people tend to get lost return false; } // isset }