コード例 #1
0
    <?php 
    exit;
}
// ---- PROCESS THE COPY FUNCTION (second pass) --------------------------------------------------------------------
function isInValid($str)
{
    return preg_match('[\\W]', $str);
}
function arraytolower($item)
{
    return strtolower($item);
}
if (array_key_exists('mode', $_REQUEST) && $_REQUEST['mode'] == '2') {
    $targetdbname = $_REQUEST['targetdbname'];
    // Avoid illegal chars in db name
    $hasInvalid = isInValid($targetdbname);
    if ($hasInvalid) {
        echo "<p><hr><p>&nbsp;<p>Requested database copy name: <b>{$targetdbname}</b>" . "<p>Sorry, only letters, numbers and underscores (_) are allowed in the database name";
        return false;
    }
    // rejecting illegal characters in db name
    $list = mysql__getdatabases();
    $list = array_map("arraytolower", $list);
    if (in_array(strtolower($targetdbname), $list)) {
        echo "<p class='error'>Warning: database '" . $targetdbname . "' already exists. Please choose a different name<br/></p>";
        return false;
    }
    $res = cloneDatabase($targetdbname);
    if (!$res) {
        echo_flush('<p style="padding-left:20px;"><h2 style="color:red">WARNING: Your database has not been cloned.</h2>' . 'Please contact your system administrator or the Heurist developers (support at HeuristNetwork dot org) for assistance with cloning of your database.');
    }
コード例 #2
0
	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>&nbsp;<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>&nbsp;<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>&nbsp;<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>&nbsp;<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>&nbsp;<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> &#60;<i>same as account currently logged in to</i>&#62;</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