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>&nbsp;</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;
}
 * @copyright   (C) 2005-2016 University of Sydney
 * @author      Artem Osmakov   <*****@*****.**>
 * @author      Ian Johnson     <*****@*****.**>
 * @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
 * @version     4.0   
 */
/*
 * Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.txt
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and limitations under the License.
 */
require_once dirname(__FILE__) . '/../../common/connect/applyCredentials.php';
require_once dirname(__FILE__) . '/../../records/index/elasticSearchFunctions.php';
if (isForAdminOnly("to rebuild the Lucene indices")) {
    return;
}
mysql_connection_overwrite(DATABASE);
if (mysql_error()) {
    die("MySQL error - unable to connect to database, MySQL error: " + mysql_error());
}
print "<html><head><link rel=stylesheet href='../../common/css/global.css'></head><body class='popup'>\n    Rebuilding Lucene indices for all tables ... ";
$code = buildAllIndices(HEURIST_DBNAME);
if ($code == 0) {
    print "<html><head><link rel=stylesheet href='../../common/css/global.css'></head><body class='popup'>\n        <h2> Database indices have been rebuilt, please check for errors above</h2>";
} else {
    die('<p>Failed to rebuild indices, please consult Heurist support team (error code: ' + $code + ')</p>');
}
print "</body>";
print "</html>";