print "<p>You are logged into more than one Heurist database. Select one: <select name=instance>\n"; foreach ($user_instances as $instance) { print "<option value={$instance}>" . ($instance ? $instance : "the \"primary\" Heurist database") . "</option>\n"; } print "</select></p>\n"; } ?> <br> <input type=submit value="Generate HAPI key"></input> </form> <?php return; } require_once dirname(__FILE__) . "/../common/php/dbMySqlWrappers.php"; mysql_connection_insert("hapi"); $url = $_REQUEST["url"]; $instance = $_REQUEST["db"]; $user_id = $instance ? @$_SESSION[$instance . ".heurist"]["user_id"] : get_user_id(); if (!$user_id) { print "<p>You are not logged in to the specified database</p>\n"; return; } if (substr($url, -1) != "/") { $url .= "/"; } $res = mysql_query("select hl_key\n from hapi_locations\n where hl_location = '" . addslashes($url) . "'\n and hl_instance = '" . addslashes($instance) . "'"); if (mysql_num_rows($res) > 0) { $row = mysql_fetch_assoc($res); $key = $row["hl_key"]; } else {
if (@$result['resultCount'] != @$result['recordCount']) { print " The number of recIDs returned is not equal to the total number in the query result set."; } } } ?> <!--</div>--> </body> </html> <?php return; } // end of error output mysql_connection_insert(DATABASE); $res = mysql_query('select snd_SimRecsList from recSimilarButNotDupes'); while ($row = mysql_fetch_assoc($res)) { array_push($dupeDifferences, $row['snd_SimRecsList']); } if ($_REQUEST['dupeDiffHash']) { foreach ($_REQUEST['dupeDiffHash'] as $diffHash) { if (!in_array($diffHash, $dupeDifferences)) { array_push($dupeDifferences, $diffHash); $res = mysql_query('insert into recSimilarButNotDupes values("' . $diffHash . '")'); } } } mysql_connection_select(DATABASE); //mysql_connection_select("`heuristdb-nyirti`"); //for debug //FIXME allow user to select a single record type
function cloneDatabase($targetdbname) { set_time_limit(0); $newname = HEURIST_DB_PREFIX . $targetdbname; //create new empty database if (!db_create($newname)) { return false; } echo_flush("<p>Create Database Structure (tables)</p>"); if (db_script($newname, HEURIST_DIR . "admin/setup/dbcreate/blankDBStructure.sql")) { echo_flush('<p style="padding-left:20px">SUCCESS</p>'); } else { db_drop($newname); return false; } // Remove initial values from empty database mysql_connection_insert($newname); mysql_query('delete from sysIdentification where 1'); mysql_query('delete from sysTableLastUpdated where 1'); mysql_query('delete from sysUsrGrpLinks where 1'); mysql_query('delete from sysUGrps where ugr_ID>=0'); mysql_query('delete from defLanguages where 1'); echo_flush("<p>Copy data</p>"); // db_clone function in /common/php/db_utils.php does all the work if (db_clone(DATABASE, $newname)) { echo_flush('<p style="padding-left:20px">SUCCESS</p>'); } else { db_drop($newname); return false; } //cleanup database to avoid issues with addition of constraints //1. cleanup missed trm_InverseTermId mysql_query('update defTerms t1 left join defTerms t2 on t1.trm_InverseTermId=t2.trm_ID set t1.trm_InverseTermId=null where t1.trm_ID>0 and t2.trm_ID is NULL'); //2. remove missed recent records mysql_query('delete FROM usrRecentRecords where rre_RecID is not null and rre_RecID not in (select rec_ID from Records)'); //3. remove missed rrc_SourceRecID and rrc_TargetRecID mysql_query('delete FROM recRelationshipsCache where rrc_SourceRecID is not null and rrc_SourceRecID not in (select rec_ID from Records)'); mysql_query('delete FROM recRelationshipsCache where rrc_TargetRecID is not null and rrc_TargetRecID not in (select rec_ID from Records)'); //4. cleanup orphaned details mysql_query('delete FROM recDetails where dtl_RecID is not null and dtl_RecID not in (select rec_ID from Records)'); //5. cleanup missed references to uploaded files mysql_query('delete FROM recDetails where dtl_UploadedFileID is not null and dtl_UploadedFileID not in (select ulf_ID from recUploadedFiles)'); $sHighLoadWarning = "<p><h4>Note: </h4>Failure to clone a database may result from high server load. Please try again, and if the problem continues contact the Heurist developers at info heuristnetwork dot org</p>"; // 4. add contrainsts, procedure and triggers echo_flush("<p>Addition of Referential Constraints</p>"); if (db_script($newname, dirname(__FILE__) . "/../dbcreate/addReferentialConstraints.sql")) { echo_flush('<p style="padding-left:20px">SUCCESS</p>'); } else { db_drop($newname); print $sHighLoadWarning; return false; } echo_flush("<p>Addition of Procedures and Triggers</p>"); if (db_script($newname, dirname(__FILE__) . "/../dbcreate/addProceduresTriggers.sql")) { echo_flush('<p style="padding-left:20px">SUCCESS</p>'); } else { db_drop($newname); print $sHighLoadWarning; return false; } // 5. remove registration info and assign originID for definitions mysql_connection_insert($newname); $sourceRegID = 0; $res = mysql_query('select sys_dbRegisteredID from sysIdentification where 1'); if ($res) { $row = mysql_fetch_row($res); if ($row) { $sourceRegID = $row[0]; } } //print "<p>".$sourceRegID."</p>"; // RESET register db ID $query1 = "update sysIdentification set sys_dbRegisteredID=0, sys_hmlOutputDirectory=null, sys_htmlOutputDirectory=null, sys_SyncDefsWithDB=null, sys_MediaFolders=null where 1"; $res1 = mysql_query($query1); if (mysql_error()) { //(mysql_num_rows($res1) == 0) print "<p><h4>Warning</h4><b>Unable to reset sys_dbRegisteredID in sysIdentification table. (" . mysql_error() . ")<br> Please reset the registration ID manually</b></p>"; } //assign origin ID db_register($newname, $sourceRegID); // Index new database for Elasticsearch //TODO: Needs error report, trap error and warn or abort clone buildAllIndices($targetdbname); // Copy the images and the icons directories //TODO: Needs error report, trap error and warn or abort clone recurse_copy(HEURIST_UPLOAD_ROOT . HEURIST_DBNAME, HEURIST_UPLOAD_ROOT . $targetdbname); // Update file path in target database with absolute paths $query1 = "update recUploadedFiles set ulf_FilePath='" . HEURIST_UPLOAD_ROOT . $targetdbname . "/' where ulf_FilePath='" . HEURIST_UPLOAD_ROOT . HEURIST_DBNAME . "/' and ulf_ID>0"; $res1 = mysql_query($query1); if (mysql_error()) { //(mysql_num_rows($res1) == 0) print "<p><h4>Warning</h4><b>Unable to set database files path to new path</b>" . "<br>Query was:" . $query1 . "<br>Please get your system administrator to fix this problem BEFORE editing the database (your edits will affect the original database)</p>"; } // Success! echo "<hr><p> </p><h2>New database '{$targetdbname}' created successfully</h2>"; print "<p>Please access your new database through this link: <a href='" . HEURIST_BASE_URL . "?db=" . $targetdbname . "' title='' target=\"_new\"><strong>" . $targetdbname . "</strong></a></p>"; return true; }
$length = 8; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } $callingServer = $_SERVER['REMOTE_ADDR']; // TO DO: we need to check that the script is not being called repeatedly from the same server define("HEURIST_DB_DESCRIPTOR_RECTYPE", 22); // the record type for database (collection) descriptor records - fixed for Master database // allocate a new user for this database unless the user's email address is recognised // If a new user, log the user in and assign the record ownership to that user // By allocating users on the database based on email address we can allow them to edit their own registrations // but they can't touch anyone else's mysql_connection_insert("hdb_Heurist_Master_Index"); // hard-coded master index for the Heurist constellation // database is located at Heurist.sydney.edu.au (2015 on) and accessed via .../h4 version // Find the registering user in the index database, make them the owner of the new record $usrEmail = strtolower(trim($usrEmail)); $res = mysql_query("select ugr_ID, ugr_Name, ugr_Password, ugr_FirstName, ugr_LastName from sysUGrps where lower(ugr_eMail)='" . $usrEmail . "'"); $indexdb_user_id = null; // Check if the email address is recognised as a user name // Added 19 Jan 2012: we also use email for ugr_Name and it must be unique, so check it has not been used if ($res && mysql_num_rows($res) == 0) { // no user found on email, try querying on user name $res = mysql_query("select ugr_ID, ugr_Name, ugr_Password, ugr_FirstName, ugr_LastName from sysUGrps where lower(ugr_Name)='" . $usrEmail . "'"); } if ($res) { // query OK, now see if we have found the user if (mysql_num_rows($res) == 0) {
} $targetDBName = @$_GET["importingTargetDBName"]; $tempDBName = @$_GET["tempDBName"]; $sourceDBName = @$_GET["sourceDBName"]; $importRtyID = @$_GET["importRtyID"]; $sourceDBID = @$_GET["sourceDBID"]; $importRefdRectypes = @$_GET["noRecursion"] && $_GET["noRecursion"] == 1 ? false : true; $importVocabs = @$_GET["importVocabs"] == 1; $strictImport = @$_GET["strict"] && $_GET["strict"] == 1 ? true : false; $currentDate = date("d-m"); $error = false; $importLog = array(); $importedRecTypes = array(); //import field id -> target id - IMPORTANT for proper titlemask conversion $fields_correspondence = array(); mysql_connection_insert($targetDBName); $mysqli = mysqli_connection_overwrite($targetDBName); // mysqli for saveStructureLib switch ($_GET["action"]) { case "crosswalk": crosswalk(); break; case "import": import(); break; case "drop": dropDB(); break; default: echo "Error: Unknown action received"; }
function makeDatabase() { // Creates a new database and populates it with triggers, constraints and core definitions global $newDBName, $isNewDB, $done, $isCreateNew, $isExtended,$errorCreatingTables; $error = false; $warning=false; if (isset($_POST['dbname'])) { // Check that there is a current administrative user who can be made the owner of the new database if(ADMIN_DBUSERNAME == "") { if(ADMIN_DBUSERPSWD == "") { echo "DB Admin username and password have not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } echo "DB Admin username has not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } if(ADMIN_DBUSERPSWD == "") { echo "DB Admin password has not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } // checking for current administrative user // Create a new blank database $newDBName = trim($_POST['uname']).'_'; if ($newDBName == '_') {$newDBName='';}; // don't double up underscore if no user prefix $newDBName = $newDBName . trim($_POST['dbname']); $newname = HEURIST_DB_PREFIX . $newDBName; // all databases have common prefix then user prefix // Avoid illegal chars in db name $hasInvalid = isInValid($newname); if ($hasInvalid) { echo ("Only letters, numbers and underscores (_) are allowed in the database name"); return false; } // rejecting illegal characters in db name if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -e\"create database `$newname`\""; } else { $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -e'create database `$newname`'"; } $output1 = exec($cmdline . ' 2>&1', $output, $res1); if ($res1 != 0 ) { echo ("<p class='error'>Error code $res1 on MySQL exec: Unable to create database $newname<br> <br>"); echo("\n\n"); if(is_array($output)){ $isExists = (strpos($output[0],"1007")>0); }else{ $sqlErrorCode = split(" ", $output); $isExists = (count($sqlErrorCode) > 1 && $sqlErrorCode[1] == "1007"); } if($isExists){ echo "<strong>A database with that name already exists.</strong>"; } echo "</p>"; $isCreateNew = true; return false; } // At this point a database exists, so need cleanup if anythign goes wrong later // Create the Heurist structure for the newly created database, using the template SQL file // This file sets up teh table definitions and inserts a few critical values // it does not set referential integrity constraints or triggers $cmdline="mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < blankDBStructure.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load blankDBStructure.sql into database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); return false; } // Add referential constraints $cmdline="mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < addReferentialConstraints.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load addReferentialConstraints.sql into database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); return false; } // Add procedures and triggers $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < addProceduresTriggers.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load addProceduresTriggers.sql for database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); 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('../structure/buildCrosswalks.php'); // errorCreatingTables is set to true by buildCrosswalks if an error occurred if($errorCreatingTables) { echo ("<p class='error'>Error importing core definitions from ".($isExtended?"coreDefinitionsExtended.txt":"coreDefinitions.txt")." for database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed</p>"); cleanupNewDB($newname); return false; } // Get and clean information for the user creating the database if(!is_logged_in()) { $longName = ""; $firstName = $_REQUEST['ugr_FirstName']; $lastName = $_REQUEST['ugr_LastName']; $eMail = $_REQUEST['ugr_eMail']; $name = $_REQUEST['ugr_Name']; $password = $_REQUEST['ugr_Password']; $department = ''; $organisation = ''; $city = ''; $state = ''; $postcode = ''; $interests = ''; $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 FROM sysUGrps WHERE ugr_ID=".get_user_id()); $details = mysql_fetch_row($query); $longName = mysql_escape_string($details[0]); $firstName = mysql_escape_string($details[1]); $lastName = mysql_escape_string($details[2]); $eMail = mysql_escape_string($details[3]); $name = mysql_escape_string($details[4]); $password = mysql_escape_string($details[5]); $department = mysql_escape_string($details[6]); $organisation = mysql_escape_string($details[7]); $city = mysql_escape_string($details[8]); $state = mysql_escape_string($details[9]); $postcode = mysql_escape_string($details[10]); $interests = mysql_escape_string($details[11]); } // 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 $warnings = 0; // Create a default upload directory for uploaded files eg multimedia, images etc. $uploadPath = HEURIST_UPLOAD_ROOT.$newDBName;//TODO: This locks us into upload path. This is teh place for DB override. $cmdline = "mkdir -p -m a=rwx ".$uploadPath; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { // TODO: need to properly trap the error and distiguish different versions. // Old uplaod directories hanging around could cause problems if upload file IDs are duplicated, // so should probably NOT allow their re-use echo ("<h3>Warning:</h3> Unable to create $uploadPath directory for database $newDBName<br> <br>"); echo ("This may be because the directory already exists or the parent folder is not writable<br>"); echo ("Please check/create directory by hand. Consult Heurist helpdesk if needed<br>"); echo($output2); $warnings = 1; } // copy icon and thumbnail directories from default set in the program code (sync. with H3CoreDefinitions) $cmdline = "cp -R rectype-icons $uploadPath"; // creates directories and copies icons and thumbnails $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy record type icons folder rectype-icons to $uploadPath<br>"); echo ("If upload directory was created OK, this is probably due to incorrect file permissions on new folders<br>"); echo($output2); $warnings = 1; } // copy smarty template directory from default set in the program code $cmdline = "cp -R smarty-templates $uploadPath"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy smarty-templates folder to $uploadPath<br>"); echo($output2); $warnings = 1; } if($isExtended){ // copy xsl template directories from default set in the program code $cmdline = "cp -R xsl-templates $uploadPath"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy xsl-templates folder to $uploadPath<br>"); echo($output2); $warnings = 1; } } $warnings =+ createFolder("settings","used to store import mappings and the like"); $warnings =+ createFolder("scratch","used to store temporary files"); $warnings =+ createFolder("hml-output","used to write published records as hml files"); $warnings =+ createFolder("html-output","used to write published records as generic html files"); $warnings =+ createFolder("generated-reports","used to write generated reports"); if ($warnings > 0) { echo "<h2>Please take note of warnings above</h2>"; echo "You must create the folders indicated or uploads, icons and templates will not work<br>"; echo "If upload folder is created but icons and template forlders are not, look at file permissions on new folder creation"; } // Prepare to write to the newly created database mysql_connection_insert($newname); // Update file locations $query='update sysIdentification set sys_hmlOutputDirectory = "'.$uploadPath.'/hml-output", sys_htmlOutputDirectory = "'.$uploadPath.'/html-output"'; mysql_query($query); if (mysql_error()) { echo "<h3>Warning: </h3> Unable to update sysIdentification table - please go to DBAdmin > Databases > Properties &". " Advanced Properties, and check the path to the upload, hml and html directories. (".mysql_error().")"; } // Make the current user the owner and admin of the new database mysql_query('UPDATE sysUGrps SET 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_interests="'.$interests.'" WHERE ugr_ID=2'); // TODO: error check, although this is unlikely to fail echo "<h2>New database '$newDBName' created successfully</h2>"; echo "<p><strong>Admin username:</strong> ".$name."<br />"; echo "<strong>Admin password:</strong> <<i>same as account currently logged in to</i>></p>"; echo "<p>You may wish to bookmark the database home page (search page): <a href=\"".HEURIST_BASE_URL."?db=".$newDBName."\" title=\"\" target=\"_new\">".HEURIST_BASE_URL."?db=".$newDBName."</a>.</p>"; echo "<p><a href='".HEURIST_BASE_URL."admin/adminMenu.php?db=".$newDBName."' title='' target=\"_new\" style='font-size:1.2em;font-weight:bold'>Go to Administration page</a>, to configure your new database</p>"; // TODO: automatically redirect to the new database, maybe, in a new window return false; } // isset } //makedatabase
function unlockDatabase($isdroptemp = true) { if ($isdroptemp && $tempDBName) { mysql_query("DROP DATABASE IF EXISTS`" . $tempDBName . "`"); } mysql_connection_insert(DATABASE); // Use logged into DB $res = mysql_query("delete from sysLocks where lck_Action='buildcrosswalks'"); // Remove sysLock }
} $sError = null; /* $user_id = get_user_id(); // User must be system administrator or admin of the owners group for this database if (!is_admin()) { $sError = "You must be logged in as system administrator to register a database"; }else if (get_user_id() != 2) { $sError = "Only the owner/creator of the database (user #2) may register the database. ". "<br/><br/>This user will also own (and be able to edit) the registration record in the heuristscholar.org master index database"; return; } */ mysql_connection_insert(DATABASE); // Connect to the current database (the one being registered) // Look up current user email from sysUGrps table in the current database (the one being registered) // Registering user must be a real user so that there is an email address and password to attach to the registration record. // which rules out using the Database Managers group. Since other users will be unable to login and edit this record, it's better // to only allow the creator (user #2) to register the db, to avoid problems down the track knowing who registered it. $res = mysql_query("select ugr_eMail, ugr_Password,ugr_Name,ugr_FirstName,ugr_LastName from sysUGrps where `ugr_ID`='$user_id'"); if(mysql_num_rows($res) == 0) { $sError = "Warning<br/><br/>Unable to read your email address from user table. Note: not currently supporting deferred users database"; }else{ $row = mysql_fetch_row($res); $usrEmail = $row[0]; // Get the current user's email address from UGrps table $usrPassword = $row[1]; $usrName = $row[2]; $usrFirstName = $row[3];
require_once dirname(__FILE__) . '/../../../common/connect/applyCredentials.php'; // Requires admin user, access to definitions though get_definitions is open if (!is_admin()) { print "<html><head>"; print '<meta http-equiv="content-type" content="text/html; charset=utf-8">'; print "<link rel=stylesheet href='../../../common/css/global.css'></head>" . "<body><div class=wrap><div id=errorMsg><span>You do not have sufficient privileges to access this page</span>" . "<p><a href=" . HEURIST_BASE_URL . "common/connect/login.php?logout=1&db=" . HEURIST_DBNAME . " target='_top'>Log out</a></p></div></div></body></html>"; return; } require_once dirname(__FILE__) . '/../../../common/php/dbMySqlWrappers.php'; require_once dirname(__FILE__) . '/../../../common/php/getRecordInfoLibrary.php'; // Artem - It breaks everything! Ian - all well and good, but why? // TODO: investigate why smarty template operation file breaks something in crosswalks // TODO: I think it had one level of relative path too few - have added a ../ // require_once(dirname(__FILE__).'/../../../../viewers/smarty/templateOperations.php'); // for listing and converting smarty templates mysql_connection_insert($tempDBName); // Use temp database ?> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Heurist - Database structure import</title> <!-- YUI --> <link rel="stylesheet" type="text/css" href="../../../external/yui/2.8.2r1/build/fonts/fonts-min.css" /> <link rel="stylesheet" type="text/css" href="../../../external/yui/2.8.2r1/build/paginator/assets/skins/sam/paginator.css"> <link rel="stylesheet" type="text/css" href="../../../external/yui/2.8.2r1/samples/yui-dt-expandable.css"/> <link type="text/css" rel="stylesheet" href="../../../external/yui/2.8.2r1/build/datatable/assets/skins/sam/datatable.css"> <script type="text/javascript" src="../../../external/yui/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="../../../external/yui/2.8.2r1/build/element/element-min.js"></script>
$username = @$_REQUEST['username']; $password = @$_REQUEST['password']; if (!$username) { $LOGIN_ERROR = 'Username is mandatory'; } if (!$password) { $LOGIN_ERROR = 'Password is mandatory'; } if (strlen($username) < 5) { $LOGIN_ERROR = 'Username must be 5 characters at least'; } if (strlen($password) < 5) { $LOGIN_ERROR = 'Password must be 5 characters at least'; } $eMail = @$_REQUEST['email']; mysql_connection_insert(USERS_DATABASE); // Make the current user the owner and admin of the new database mysql_query('UPDATE ' . USERS_TABLE . ' SET ' . ($eMail ? ' ugr_eMail="' . mysql_real_escape_string($eMail) . '", ' : '') . 'ugr_Name="' . mysql_real_escape_string($username) . '", ' . 'ugr_Password="******" WHERE ugr_ID=2'); if (mysql_error()) { print "<h2>Unable to update owner email and password for database<h2> SQL error:" . mysql_error(); "<p>Please contact Heurist developers for help</p>"; } else { $needRegistration = false; $_REQUEST['username'] = $username; $_REQUEST['password'] = $password; } } else { mysql_connection_select(USERS_DATABASE); //verify that this database has proper owner userId=2 $res = mysql_query('select ugr_Password from ' . USERS_TABLE . ' where ' . USERS_ID_FIELD . ' = 2'); $needRegistration = ($user = mysql_fetch_assoc($res)) && $user[USERS_PASSWORD_FIELD] == "TO BE RESET";
* This file is called by registerDB.php * ONLY ALLOW IN HEURISTSCHOLAR.ORG index database * @copyright (C) 2005-2010 University of Sydney Digital Innovation Unit. * @link: http://HeuristScholar.org * @license http://www.gnu.org/licenses/gpl-3.0.txt * @package Heurist academic knowledge management system * @todo **/ // TO DO: WE NEED SOME MECHANISM TO AVOID DENIAL OF SERVICE ATTACK WHICH REPEATEDLY REQUESTS REGISTRATIONS // We may need to hobble/delete some of the functionality on HeuristIndex to avoid people // creating unwanted records or importing random crap into it $dbID = 0; $error = ""; require_once dirname(__FILE__) . "/../../common/config/initialise.php"; require_once dirname(__FILE__) . '/../../common/php/dbMySqlWrappers.php'; mysql_connection_insert("hdb_H3MasterIndex"); // hard-coded master index for the Heurist constellation $indexdb_user_id = 0; // Flags problem if not reset $returnData = ''; // String returned to caller, contains dbID or 0, and error message (if any) // Get parameters passed from registration request // @ preceding $_REQUEST avoids errors, sets Null if parameter missing $serverURL = $_REQUEST["serverURL"]; $dbReg = $_REQUEST["dbReg"]; $dbTitle = $_REQUEST["dbTitle"]; $dbVersion = @$_REQUEST["dbVer"]; $usrEmail = $_REQUEST["usrEmail"]; $usrPassword = $_REQUEST["usrPassword"]; $usrName = $_REQUEST["usrName"]; $usrFirstName = $_REQUEST["usrFirstName"];
function unlockDatabase($isdroptemp = true) { global $tempDBName; if ($isdroptemp && $tempDBName) { db_drop($tempDBName, false); } mysql_connection_insert(DATABASE); // Use logged into DB $res = mysql_query("delete from sysLocks where lck_Action='buildcrosswalks'"); // Remove sysLock }
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 }