/**
 * put your comment there...
 *
 *
 * @param mixed $config
 */
function createMappingForm($config)
{
    global $sourcedbname, $db_prefix, $dbPrefix, $is_h2, $useOriginalID;
    $sourcedb = $db_prefix . $sourcedbname;
    print "<br>\n";
    //print "Source database: <b>$sourcedb</b> <br>\n";
    if ($is_h2) {
        $res = mysql_query("select * from `{$sourcedb}`.Users");
    } else {
        $res = mysql_query("select * from {$sourcedb}.sysIdentification");
    }
    if (!$res) {
        die("<p>Unable to open source database <b>{$sourcedb}</b>. Make sure you have included prefix");
    }
    print "<form name='mappings' action='compareStructure.php' method='post'>";
    print "<input id='mode' name='mode' value='5' type='hidden'>";
    // calls the transfer function
    print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>";
    print "<input name='h2' value='" . ($is_h2 ? 1 : 0) . "' type='hidden'>";
    //print "<input name='sourcedbname' value='$sourcedbname' type='hidden'>";
    //print "<input name='reportlevel' value='1' type='checkbox' checked='checked'>Report level: show errors only<br>";
    //print "Check the code mappings below, then click  <input type='button' value='Import data' onclick='{document.getElementById(\"mode\").value=5; document.forms[\"mappings\"].submit();}'>\n";
    // alert(document.getElementById(\"mode\").value);
    /*
    print "<input type='button' value='Save settings' onclick='{document.getElementById(\"mode\").value=3; document.forms[\"mappings\"].submit();}'>";
    
    $filename = HEURIST_FILESTORE_DIR."settings/importfrom_".$sourcedbname.".cfg";
    
    if(file_exists($filename)){
    print "<input type='submit' value='Load settings' onclick='{document.getElementById(\"mode\").value=4; document.forms[\"mappings\"].submit();}'>\n";
    }
    */
    print "<p><hr>\n";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the record type mapping, by default assume that the code is unchanged so select the equivalent record type if available
    $d_rectypes = getAllRectypeStructures();
    //in current database
    $d_dettypes = getAllDetailTypeStructures();
    $d_rtnames = $d_rectypes['names'];
    mysql_connection_overwrite($sourcedb);
    $s_rectypes = getAllRectypeStructures(false);
    $s_dettypes = getAllDetailTypeStructures(false);
    $s_rtnames = $s_rectypes['names'];
    print "<table border='1' width='900'><tr><td width='300'>" . $sourcedbname . "</td><td colspan='2'>" . HEURIST_DBNAME . "</td></tr>";
    $fi_type = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Type'];
    $fi_name = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Name'];
    $fi_rt_concept = $s_rectypes['typedefs']['commonNamesToIndex']['rty_ConceptID'];
    $fi_dt_concept = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_ConceptID'];
    foreach ($s_rtnames as $s_id => $s_name) {
        $s_conceptid = $s_rectypes['typedefs'][$s_id]['commonFields'][$fi_rt_concept];
        $dest_id = null;
        $dest_name = null;
        //find record type in destination
        foreach ($d_rtnames as $d_id => $d_name) {
            if ($useOriginalID && $d_rectypes['typedefs'][$d_id]['commonFields'][$fi_rt_concept] == $s_conceptid || !$useOriginalID && $d_name == $s_name) {
                //print "[".$d_id."]  ".$d_name."<br/>";
                //print structure in the same order as source rectype
                $dest_id = $d_id;
                $dest_name = $d_name;
                break;
            }
        }
        //Header  <tr><td colspan='2'><table border='1' width='100%'>
        print "<tr style='background-color:#AAAAAA;'><td width='250'><b>[" . $s_id . "]  " . $s_name . "</b>(" . $s_conceptid . ")</td><td width='250'>";
        if ($dest_id == null) {
            print "...not found";
        } else {
            print "<b>[" . $dest_id . "]  " . $dest_name . "</b>";
        }
        print "</td><td width='400'>&nbsp;</td></tr>";
        //list of field types
        $s_flds = $s_rectypes['typedefs'][$s_id]['dtFields'];
        foreach ($s_flds as $sft_id => $sft_desc) {
            $fld_in_dest_rectype = "&nbsp;";
            $fld_in_dest_all = "&nbsp;";
            $s_conceptid = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_dt_concept];
            $s_fitype = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_type];
            //find in destination record type
            if ($dest_id != null) {
                $d_flds = $d_rectypes['typedefs'][$dest_id]['dtFields'];
                foreach ($d_flds as $dft_id => $dft_desc) {
                    //compare by original field name and by type
                    if ($useOriginalID && $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $d_dettypes['names'][$dft_id] && $s_fitype == $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_type]) {
                        $fld_in_dest_rectype = "[" . $dft_id . "] " . $dft_desc[0];
                        break;
                    }
                }
            }
            //if not found try to find in entire list of field types
            if ($fld_in_dest_rectype == "&nbsp;") {
                $d_flds = $d_dettypes['typedefs'];
                foreach ($d_flds as $dft_id => $dft_def) {
                    //compare by original field name and by type
                    if ($useOriginalID && $dft_def['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $dft_def['commonFields'][$fi_name] && $s_fitype == $dft_def['commonFields'][$fi_type]) {
                        $fld_in_dest_all = "[" . $dft_id . "] " . $dft_def['commonFields'][$fi_name] . "  (" . $s_fitype . ")";
                        break;
                    }
                }
            }
            print "<tr><td>[" . $sft_id . "] " . $sft_desc[0] . "&nbsp;(" . $s_conceptid . ")</td><td>" . $fld_in_dest_rectype . "</td><td>" . $fld_in_dest_all . "</td></tr>";
        }
        ///print "</table></td><tr>";
    }
    print "</table>";
    return;
    $entnames = $entnames['names'];
    $seloptions = createOptions("or", $entnames);
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rec_type`,`rt_name` FROM `{$sourcedb}`.`records`,`{$sourcedb}`.`rec_types` where `rec_type`=`rt_id`";
    } else {
        $query1 = "SELECT rty_ID, rty_Name, count(rec_ID) as cnt " . "from `{$sourcedb}`.`Records` " . "left join `{$sourcedb}`.`defRecTypes` on rec_RecTypeID=rty_ID " . "group by rty_ID";
    }
    $res1 = mysql_query($query1);
    if (mysql_num_rows($res1) == 0) {
        die("<p><b>Sorry, there are no data records in this database, or database is bad format</b>");
    }
    print "<h3>Record type mappings</h3> &nbsp;[RT code] <b>{$sourcedb}</b> &nbsp;(use count) ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $rt = $row1[0];
        //0=rec_RecTypeID
        $cnt = $row1[2];
        $selopts = $seloptions;
        $selectedId = getPresetId($config, "cbr" . $rt);
        if (!$selectedId) {
            //find the closest name
            $selectedId = findClosestName($row1[1], $entnames);
            //1=rty_Name
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr><td>" . $row1[1] . " [ {$rt} ] n=({$cnt}) </td>" . "<td>==> <select id='cbr{$rt}' name='cbr{$rt}' class='rectypes'><option id='or0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through record types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the field type mapping, by default assume that the code is unchanged so select the equivalent detail type if available
    //create the string for combobox
    $entnames = getAllDetailTypeStructures();
    //in current database
    $entnames = $entnames['names'];
    $seloptions = createOptions("od", $entnames);
    print "<h3>Field type mappings</h3>[FT code] <b>{$sourcedb}</b> ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rd_type`,`rdt_name`,`rdt_type` FROM `{$sourcedb}`.`rec_details`,`{$sourcedb}`.`rec_detail_types` " . "where `rd_type`=`rdt_id`";
    } else {
        $query1 = "SELECT DISTINCT `dtl_DetailTypeID`,`dty_Name`,`dty_Type` FROM `{$sourcedb}`.`recDetails`,`{$sourcedb}`.`defDetailTypes` " . "where `dtl_DetailTypeID`=`dty_ID`";
    }
    $res1 = mysql_query($query1);
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $ft = $row1[0];
        //0=dtl_DetailTypeID
        $selopts = $seloptions;
        //find the closest name
        $selectedId = getPresetId($config, "cbd" . $ft);
        if (!$selectedId) {
            //find the closest name
            $selectedId = findClosestName($row1[1], $entnames);
            //dty_Name
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr><td>[ {$ft} ] - " . $row1[2] . " " . $row1[1] . " </td>" . "<td>==> <select id='cbd{$ft}' name='cbd{$ft}' class='detailTypes'><option id='od0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through field types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    createTermsOptions($config, 'enum');
    createTermsOptions($config, 'relation');
    print "</form>";
}
示例#2
0
    ob_start("outputAsRedirect");
    if ($_POST["heurist-sessionid"] != $_COOKIE["heurist-sessionid"]) {
        // saw TODO: check that this is ok or should this be the database session?
        // saveFile is only available through dispatcher.php, or if heurist-sessionid is known (presumably only our scripts will know this)
        jsonError("unauthorised HAPI user");
    }
}
if (!is_logged_in()) {
    jsonError("no logged-in user");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
    jsonError("File is too large. " . $_SERVER['CONTENT_LENGTH'] . " bytes exceeds the limit of " . ini_get('post_max_size') . ". Please get system administrator to increase the file size limits or load your large files on a video server or other suitable web service and use the URL to reference the file here");
} else {
    $upload = @$_FILES["file"];
    if ($upload) {
        mysql_connection_overwrite(DATABASE);
        mysql_query("start transaction");
        //POST Content-Length of 103399974 bytes exceeds the limit of 29360128 bytes in Unknown on line
        //$upload["type"]
        $fileID = upload_file($upload["name"], null, $upload["tmp_name"], $upload["error"], $upload["size"], $_REQUEST["description"], false);
        if (is_numeric($fileID)) {
            $file = get_uploaded_file_info($fileID, false);
            print json_format($file);
            mysql_query("commit");
        } else {
            if ($fileID) {
                jsonError($fileID);
            } else {
                if ($_FILES["file"]["error"]) {
                    jsonError("uploaded file was too large");
                } else {
    while (strlen($passwd) < $length) {
        $char = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
        if (!strstr($passwd, $char)) {
            $passwd .= $char;
        }
    }
    return $passwd;
}
function hash_it($passwd)
{
    $s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./';
    $salt = $s[rand(0, strlen($s) - 1)] . $s[rand(0, strlen($s) - 1)];
    return crypt($passwd, $salt);
}
if (@$_REQUEST['username']) {
    mysql_connection_overwrite(USERS_DATABASE);
    $username = mysql_real_escape_string($_REQUEST['username']);
    $res = mysql_query('select ugr_ID,ugr_eMail,ugr_FirstName,ugr_Name from sysUGrps usr where usr.ugr_Name = "' . $username . '" or ugr_eMail = "' . $username . '"');
    $row = mysql_fetch_assoc($res);
    $username = $row['ugr_Name'];
    $user_id = $row['ugr_ID'];
    $email = $row['ugr_eMail'];
    $firstname = $row['ugr_FirstName'];
    if ($user_id) {
        $new_passwd = generate_passwd();
        mysql_query('update sysUGrps usr set ugr_Password = "******" where ugr_ID = ' . $user_id);
        $email_title = 'Password reset';
        $email_text = "Dear " . $firstname . ",\n\n" . "Your Heurist password has been reset.\n\n" . "Your username is: " . $username . "\n" . "Your new password is: " . $new_passwd . "\n\n" . "To change your password go to Profile -> My User Info in the top right menu.\nYou will first be asked to log in with the new password above.";
        $email_header = 'From: ' . HEURIST_MAIL_TO_INFO;
        $rv = sendEmail($email, $email_title, $email_text, $email_header);
        if ($rv == "ok") {
示例#4
0
/**
 * put your comment there...
 *
 * @param mixed $fileID
 * @param mixed $needConnect
 * @return bool
 */
function get_uploaded_file_info_internal($fileID, $needConnect)
{
    if ($needConnect) {
        mysql_connection_overwrite(DATABASE);
    }
    $res = null;
    $fres = mysql_query('select ulf_ID as id,
			ulf_ObfuscatedFileID as nonce,
			ulf_OrigFileName as origName,
			ulf_FileSizeKB as fileSize,
			fxm_MimeType as mimeType,
			ulf_Added as date,
			ulf_Description as description,
			ulf_MimeExt as ext,
			ulf_ExternalFileReference as remoteURL,
			ulf_Parameters as parameters,
			concat(ulf_FilePath,ulf_FileName) as fullpath,
			ulf_PreferredSource as prefsource

			from recUploadedFiles left join defFileExtToMimetype on ulf_MimeExt = fxm_Extension
			where ' . (is_numeric($fileID) ? 'ulf_ID = ' . intval($fileID) : 'ulf_ObfuscatedFileID = "' . addslashes($fileID) . '"'));
    if (mysql_num_rows($fres) == 1) {
        $res = mysql_fetch_assoc($fres);
        $origName = urlencode($res["origName"]);
        $thumbnail_file = "ulf_" . $res["nonce"] . ".png";
        if (file_exists(HEURIST_THUMB_DIR . $thumbnail_file)) {
            $res["thumbURL"] = HEURIST_THUMB_BASE_URL . $thumbnail_file;
        } else {
            $res["thumbURL"] = HEURIST_BASE_URL . "common/php/resizeImage.php?" . (defined('HEURIST_DBNAME') ? "db=" . HEURIST_DBNAME . "&" : "") . "ulf_ID=" . $res["nonce"];
        }
        $downloadURL = HEURIST_BASE_URL . "records/files/downloadFile.php/" . $origName . "?" . (defined('HEURIST_DBNAME') ? "db=" . HEURIST_DBNAME . "&" : "") . "ulf_ID=" . $res["nonce"];
        if ($res["remoteURL"] != null || $res["prefsource"] == "external") {
            $res["URL"] = $res["remoteURL"];
        } else {
            $res["URL"] = $downloadURL;
        }
        $params = parseParameters($res["parameters"]);
        $res["mediaType"] = array_key_exists('mediatype', $params) ? $params['mediatype'] : null;
        $res["remoteSource"] = array_key_exists('source', $params) ? $params['source'] : null;
        $type_source = $res['remoteSource'];
        if (!($type_source == null || $type_source == 'heurist')) {
            //verify that this is actually remote resource
            if ($res['fullpath'] && file_exists($res['fullpath'])) {
                $res['remoteSource'] = 'heurist';
            }
        }
        //
        //@todo - add special parameters for specific sources and media types
        // QUESTION - store it in database? Or create on-fly??
        //
        if ($res["remoteSource"] == "youtube" || $res["mediaType"] == "image" || $res["ext"] == "pdf" || $res["mediaType"] == "video" || $res["mediaType"] == "audio") {
            $res["playerURL"] = $downloadURL . "&player=yes";
        }
        //$res = array("file" => $res);
    }
    return $res;
}
示例#5
0
/**
 *  if user is not enabled and login count=0 - this is approvement operation
 */
function isApprovement($type, $recID)
{
    $ret = false;
    if (is_admin() && $type == 'user') {
        mysql_connection_overwrite(DATABASE);
        $query = "select ugr_Enabled, ugr_LoginCount from " . DATABASE . ".sysUGrps where ugr_ID={$recID}";
        $res = mysql_query($query);
        while ($row = mysql_fetch_array($res)) {
            $ret = $row[0] == "n" && $row[1] == 0;
        }
    }
    return $ret;
}
示例#6
0
function saveWoot($args)
{
    if (!is_logged_in()) {
        return array("success" => false, "errorType" => "no logged-in user");
    }
    mysql_connection_overwrite(DATABASE);
    $wootId = intval(@$args["id"]);
    $wootTitle = mysql_real_escape_string(@$args["title"]);
    mysql_query("start transaction");
    if (!$wootId || $wootId === "new") {
        /* This is a new WOOT that hasn't been saved yet */
        if (!$wootTitle) {
            return array("success" => false, "errorType" => "missing title");
        }
        mysql__insert(WOOT_TABLE, array("woot_Title" => $wootTitle, "woot_Created" => array("now()"), "woot_Modified" => array("now()"), "woot_Version" => 0, "woot_CreatorID" => get_user_id()));
        $wootId = mysql_insert_id();
        if (!$wootId) {
            return array("success" => false, "errorType" => "a woot with the given title already exists");
        }
        $woot = mysql_fetch_assoc(mysql_query("select * from " . WOOT_TABLE . " where woot_ID={$wootId}"));
        $woot["permissions"] = $args["permissions"];
        $result = insertWootPermissions($wootId, $woot);
        if ($result["success"] != true) {
            return $result;
        }
    } else {
        /* We are saving the WOOT -- get a new version number, commit, and then do chunk-wise operations.
         * Other people can operate on a separate version at the same time.
         */
        if (!hasWootWritePermission($wootId)) {
            return array("success" => false, "errorType" => "woot doesn't exist, or insufficient permissions on woot");
        }
        mysql_query("update " . WOOT_TABLE . " set woot_Version=woot_Version+1 where woot_ID={$wootId}");
    }
    $res = mysql_query("select * from " . WOOT_TABLE . " where woot_ID={$wootId}");
    mysql_query("commit and chain");
    $woot = mysql_fetch_assoc($res);
    $version = intval($woot["woot_Version"]);
    $chunkIds = getReadableChunks($wootId, true);
    $res = mysql_query("select * from " . CHUNK_TABLE . "\n\t\t\t\t\t\t\t where chunk_WootID={$wootId} and chunk_IsLatest and !chunk_Deleted and chunk_ID in (" . join(",", $chunkIds) . ")\n\t\t\t\t\t\t  order by chunk_DisplayOrder");
    $existingVisibleChunks = array();
    while ($chunk = @mysql_fetch_assoc($res)) {
        /* The @ takes care of the possibility that there are no chunks in this woot */
        $existingVisibleChunks[$chunk["chunk_InsertOrder"]] = $chunk;
    }
    $incomingChunks = $args["chunks"];
    // Get the current chunk ordering (including the chunks the current user can't actually see)
    $existingChunkOrder = mysql__select_array(CHUNK_TABLE, "chunk_InsertOrder", "chunk_WootID={$wootId} and chunk_IsLatest and ! chunk_Deleted order by chunk_DisplayOrder");
    reset($existingChunkOrder);
    // Check that the incoming chunks are in the same order as the existing chunks, otherwise raise an error
    if (count($existingChunkOrder)) {
        foreach ($incomingChunks as $chunk) {
            if (!@$chunk["number"]) {
                continue;
            }
            // new chunk, doesn't have an ordering yet
            while (current($existingChunkOrder) != $chunk["number"]) {
                if (next($existingChunkOrder) === FALSE) {
                    // Ran out of existing chunks
                    // The incoming chunk is out of order (you're out of order, the whole court's out of order)
                    return array("success" => false, "errorType" => "invalid chunk ordering", "chunkNonce" => $chunk["nonce"]);
                }
            }
        }
    }
    $chunkNonceToNumber = array();
    $newChunks = array(NULL => array());
    $newChunkCount = 0;
    $firstExistingChunk = NULL;
    $lastExistingChunk = NULL;
    foreach ($incomingChunks as $chunk) {
        $prevChunkId = NULL;
        if (@$chunk["number"]) {
            // If the incoming chunk has a number which doesn't correspond to an existing chunk,
            // then the user has had permissions pulled out from under them (or they're playing funny buggers)
            // Either way, raise an error
            if (!@$existingVisibleChunks[$chunk["number"]]) {
                return array("success" => false, "errorType" => "chunk permissions have changed", "chunkNonce" => $chunk["nonce"]);
            }
            $chunkNumber = intval($chunk["number"]);
            // Keep track of the position of this (existing) chunk.
            // Any new chunks that occur before the next (existing) chunk will be stored in $newChunks[$lastExistingChunk]
            if (!$firstExistingChunk) {
                $firstExistingChunk = $chunkNumber;
            }
            $lastExistingChunk = $chunkNumber;
            $newChunks[$lastExistingChunk] = array();
            if (!@$chunk["unmodified"]) {
                // Chunk exists, and is reported as modified.  Make a new version of it.
                $res = mysql_query("select chunk_ID, chunk_DisplayOrder, chunk_OwnerID from " . CHUNK_TABLE . " where chunk_WootID={$wootId} and chunk_InsertOrder={$chunkNumber} and chunk_IsLatest");
                if (mysql_num_rows($res) != 1) {
                    /* should do something ... do we care? */
                }
                $prevChunk = mysql_fetch_assoc($res);
                $prevChunkId = $prevChunk["chunk_ID"];
                $chunkOrder = $prevChunk["chunk_DisplayOrder"];
                $chunkOwner = $prevChunk["chunk_OwnerID"];
                mysql__update(CHUNK_TABLE, "chunk_WootID={$wootId} and chunk_InsertOrder={$chunkNumber}", array("chunk_IsLatest" => 0));
            } else {
                // Chunk exists, but is not modified.  Nothing more to do.
                continue;
            }
        } else {
            $res = mysql_query("select max(chunk_InsertOrder) from " . CHUNK_TABLE . " where chunk_WootID={$wootId}");
            $chunkNumber = @mysql_fetch_row($res);
            $chunkNumber = intval(@$chunkNumber[0]) + 1;
            $chunkOrder = 0;
            // chunk order will be overridden anyway since there is a new chunk to take care of
            $chunkOwner = get_user_id();
            array_push($newChunks[$lastExistingChunk], $chunkNumber);
            ++$newChunkCount;
        }
        $chunkDeleted = preg_match('/^\\s*$/', $chunk["text"]);
        mysql__insert(CHUNK_TABLE, array("chunk_WootID" => $wootId, "chunk_InsertOrder" => $chunkNumber, "chunk_Version" => $version, "chunk_Text" => $chunk["text"], "chunk_IsLatest" => 1, "chunk_DisplayOrder" => $chunkOrder, "chunk_Modified" => array("now()"), "chunk_OwnerID" => $chunkOwner, "chunk_EditorID" => get_user_id(), "chunk_Deleted" => $chunkDeleted));
        $chunkId = mysql_insert_id();
        if (!$chunkDeleted) {
            if ($chunkOwner == get_user_id() || is_admin()) {
                // only the owner (or an admin) can change the permissions
                $result = insertPermissions($chunkId, $chunk, $woot["woot_CreatorID"]);
                if ($result["success"] != true) {
                    return $result;
                }
            } else {
                // copy the permissions from the previous version of the chunk
                mysql_query("insert into " . PERMISSION_TABLE . "\n\t\t\t\t\t\t\t\t (wprm_ChunkID, wprm_UGrpID, wprm_GroupID, wprm_Type, wprm_CreatorID, wprm_Created)\n\t\t\t\t\t\t   select distinct {$chunkId}, wprm_UGrpID, wprm_GroupID, wprm_Type, wprm_CreatorID, wprm_Created\n\t\t\t\t\t\t\t from " . PERMISSION_TABLE . " where wprm_ChunkID={$prevChunkId}");
            }
            if (@$chunk["nonce"]) {
                // if the client hasn't specified a nonce they're obviously not interested in the resulting chunk number
                $chunkNonceToNumber[$chunk["nonce"]] = $chunkNumber;
            }
        } else {
            if ($chunk["nonce"]) {
                $chunkNonceToNumber[$chunk["nonce"]] = NULL;
                // blast away the existing number for this chunk
            }
        }
    }
    if ($newChunkCount) {
        // New chunks have been inserted.
        // Make a merged list of existing chunks and newly inserted chunks, then update their ordering
        $allChunks = array();
        foreach ($existingChunkOrder as $existingChunkNumber) {
            // Consider chunks (A, B*, C*, D, E*) where B*, C* and E* are new chunks, and A and D are existing chunks.
            // In the merged list, B* and C* will directly follow A, and E* will directly follow D.
            // So, given existingChunkOrder (X, A, Y, D, Z) and chunkNonceToNumber (A, B*, C*, D, E*),
            // allChunks becomes (X, A, B*, C*, Y, D, E*, Z)
            if ($existingChunkNumber == $firstExistingChunk && count($newChunks[NULL])) {
                // This is the first chunk that the user can see, and there are new chunks to add before it.
                $allChunks = array_merge($allChunks, $newChunks[NULL]);
            }
            array_push($allChunks, $existingChunkNumber);
            if (count(@$newChunks[$existingChunkNumber])) {
                // There are new chunks to add directly after this chunk
                $allChunks = array_merge($allChunks, $newChunks[$existingChunkNumber]);
            }
        }
        if (!$firstExistingChunk && count($newChunks[NULL])) {
            // Okay, there were no existing chunks that the user could see ... add any new chunks at the end
            $allChunks = array_merge($allChunks, $newChunks[NULL]);
        }
        for ($i = 0; $i < count($allChunks); ++$i) {
            $order = $i + 1;
            $chunkNumber = $allChunks[$i];
            mysql_query("update " . CHUNK_TABLE . " set chunk_DisplayOrder={$order}\n\t\t\t\t\t\t\t  where chunk_WootID={$wootId} and chunk_InsertOrder={$chunkNumber} and chunk_IsLatest");
        }
    }
    mysql_query("commit");
    return array("success" => true, "id" => $wootId, "version" => $version, "chunks" => $chunkNonceToNumber);
}
function handle_notification()
{
    function getInt($strInt)
    {
        return intval(preg_replace("/[\"']/", "", $strInt));
    }
    $bib_ids = array_map("getInt", explode(',', $_REQUEST['bib_ids']));
    if (!count($bib_ids)) {
        return '<div style="color: red; font-weight: bold; padding: 5px;">(you must select at least one bookmark)</div>';
    }
    $bibIDList = join(',', $bib_ids);
    $notification_link = HEURIST_BASE_URL . '?db=' . HEURIST_DBNAME . '&w=all&q=ids:' . $bibIDList;
    $bib_titles = mysql__select_assoc('Records', 'rec_ID', 'rec_Title', 'rec_ID in (' . $bibIDList . ')');
    $title_list = "Id      Title\n" . "------  ---------\n";
    foreach ($bib_titles as $rec_id => $rec_title) {
        $title_list .= str_pad("{$rec_id}", 8) . $rec_title . "\n";
    }
    $msg = '';
    if ($_REQUEST['notify_message'] && $_REQUEST['notify_message'] != '(enter message here)') {
        $msg = '"' . $_REQUEST['notify_message'] . '"' . "\n\n";
    }
    $res = mysql_query('select ' . USERS_EMAIL_FIELD . ' from ' . USERS_DATABASE . '.' . USERS_TABLE . ' where ' . USERS_ID_FIELD . ' = ' . get_user_id());
    $row = mysql_fetch_row($res);
    if ($row) {
        $user_email = $row[0];
    }
    mysql_connection_overwrite(DATABASE);
    $email_subject = 'Email from ' . get_user_name();
    if (count($bib_ids) == 1) {
        $email_subject .= ' (one reference)';
    } else {
        $email_subject .= ' (' . count($bib_ids) . ' references)';
    }
    $email_headers = 'From: ' . get_user_name() . ' <no-reply@' . HEURIST_SERVER_NAME . '>';
    if ($user_email) {
        $email_headers .= "\r\nCc: " . get_user_name() . ' <' . $user_email . '>';
        $email_headers .= "\r\nReply-To: " . get_user_name() . ' <' . $user_email . '>';
    }
    $email_text = get_user_name() . " would like to draw some records to your attention, with the following note:\n\n" . $msg . "Access them and add them (if desired) to your Heurist records at: \n\n" . $notification_link . "\n\n" . "To add records, either click on the unfilled star left of the title\n" . "or select the ones you wish to add and then Selected > Bookmark\n\n" . $title_list;
    if ($_REQUEST['notify_group']) {
        $email_headers = preg_replace('/Cc:[^\\r\\n]*\\r\\n/', '', $email_headers);
        $res = mysql_query('select ' . GROUPS_NAME_FIELD . ' from ' . USERS_DATABASE . '.' . GROUPS_TBALE . ' where ' . GROUPS_ID_FIELD . '=' . intval($_REQUEST['notify_group']));
        $row = mysql_fetch_assoc($res);
        $grpname = $row[GROUPS_NAME_FIELD];
        $res = mysql_query('select ' . USERS_EMAIL_FIELD . '
				from ' . USERS_DATABASE . '.' . USERS_TABLE . ' left join ' . USERS_DATABASE . '.' . USER_GROUPS_TABLE . ' on ' . USER_GROUPS_USER_ID_FIELD . '=' . USERS_ID_FIELD . '
				where ' . USER_GROUPS_GROUP_ID_FIELD . '=' . intval($_REQUEST['notify_group']));
        $count = mysql_num_rows($res);
        while ($row = mysql_fetch_assoc($res)) {
            $email_headers .= "\r\nBcc: " . $row[USERS_EMAIL_FIELD];
        }
        $rv = sendEMail(get_user_name() . ' <' . $user_email . '>', $email_subject, $email_text, $email_headers, true);
        return $rv == "ok" ? 'Notification email sent to group ' . $grpname . ' (' . $count . ' members)' : $rv;
    } else {
        if ($_REQUEST['notify_person']) {
            $res = mysql_query('select ' . USERS_EMAIL_FIELD . ', concat(' . USERS_FIRSTNAME_FIELD . '," ",' . USERS_LASTNAME_FIELD . ') as fullname from ' . USERS_DATABASE . '.' . USERS_TABLE . ' where ' . USERS_ID_FIELD . '=' . $_REQUEST['notify_person']);
            $psn = mysql_fetch_assoc($res);
            $rv = sendEMail($psn[USERS_EMAIL_FIELD], $email_subject, $email_text, $email_headers, true);
            return $rv == "ok" ? 'Notification email sent to ' . addslashes($psn['fullname']) : $rv;
        } else {
            if ($_REQUEST['notify_email']) {
                $rv = sendEMail($_REQUEST['notify_email'], $email_subject, $email_text, $email_headers, true);
                return $rv == "ok" ? 'Notification email sent to ' . addslashes($_REQUEST['notify_email']) : $rv;
            } else {
                return '<div style="color: red; font-weight: bold; padding: 5px;">(you must select a group, person, or enter an email address)</div>';
            }
        }
    }
}
* @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  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/
/**
 * filename, brief description, date of creation, by whom
 * @copyright (C) 2005-2010 University of Sydney Digital Innovation Unit.
 * @link: http://HeuristNetwork.org
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
 * @package Heurist academic knowledge management system
 * @todo
 **/
require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php";
require_once dirname(__FILE__) . "/../../common/php/dbMySqlWrappers.php";
mysql_connection_overwrite("hapi");
mysql_query("start transaction");
if (!is_logged_in()) {
    /*****
     Experimental change: non-logged-in users can still store (non cross session) stuff
     2008/03/25 - tfm
    
    	jsonError("no logged-in user");
    */
    $_REQUEST["crossSession"] = false;
}
$_REQUEST = json_decode(@$_POST["data"] ? $_POST["data"] : base64_decode(@$_GET["data"]), true);
//$location = @$_REQUEST["crossDomain"]? "*" : ($baseURL? $baseURL : "Heurist.sydney.edu.au");
$location = @$_REQUEST["crossDomain"] ? "*" : ($baseURL ? $baseURL : HEURIST_SERVER_NAME);
// TESTTHIS:  replaced Heurist.sydney.edu.au with host name
$varName = $_REQUEST["name"];
示例#9
0
/**
* set_wg_and_vis: set ownership (person or workgroup) and visibility settings for currently selected records
*
* @param mixed $data
*/
function set_wg_and_vis($data)
{
    $result = array();
    if (is_admin()) {
        $rec_ids = $data['rec_ids'];
        $wg = intval(@$data['wg_id']);
        $vis = $data['vis'];
        if (($wg == -1 || $wg == 0 || $wg == get_user_id() || in_array($wg, get_group_ids())) && in_array(strtolower($vis), array('viewable', 'hidden', 'pending', 'public'))) {
            mysql_connection_overwrite(DATABASE);
            if ($wg === 0 && $vis === 'hidden') {
                $vis = 'viewable';
            }
            if ($wg >= 0) {
                $editable = ' rec_OwnerUGrpID = ' . $wg . ', ';
            } else {
                $editable = '';
            }
            $query = 'update Records set ' . $editable . 'rec_NonOwnerVisibility = "' . $vis . '"' . ' where rec_ID in (' . join(',', $rec_ids) . ')';
            mysql_query($query);
            if (mysql_error()) {
                $result['problem'] = 'MySQL error: ' . addslashes(mysql_error()) . ' : visibility not reset';
            } else {
                $result['ok'] = mysql_affected_rows() . ' records updated';
            }
        } else {
            $result['problem'] = 'Invalid arguments for workgoup or visibility';
        }
    } else {
        $result['problem'] = 'Permission denied for workgroup or visibility setting';
    }
    return $result;
}
示例#10
0
/**
* Main function
*
* @param mixed $_REQUEST
*/
function executeSmartyTemplate($params)
{
    global $smarty, $outputfile, $isJSout, $rtStructs, $dtStructs, $dtTerms, $gparams, $max_allowed_depth, $publishmode, $execution_counter, $execution_total_counter, $session_id, $mysqli;
    set_time_limit(0);
    //no script execution time limit
    mysql_connection_overwrite(DATABASE);
    //AO: mysql_connection_select - does not work since there is no access to stored procedures(getTemporalDateString)
    //    which Steve used in some queries
    //TODO SAW  grant ROuser EXECUTE on getTemporalDate and any other readonly procs
    //load definitions (USE CACHE)
    //$rtStructs = getAllRectypeStructures(true);
    //$dtStructs = getAllDetailTypeStructures(true);
    //$dtTerms = getTerms(true);
    $params["f"] = 1;
    //always search (do not use cache)
    $isJSout = array_key_exists("mode", $params) && $params["mode"] == "js";
    //use javascript wrap
    $outputfile = array_key_exists("output", $params) ? $params["output"] : null;
    $publishmode = array_key_exists("publish", $params) ? intval($params['publish']) : 0;
    $emptysetmessage = array_key_exists("emptysetmessage", $params) ? $params['emptysetmessage'] : null;
    $gparams = $params;
    //keep to use in other functions
    if (!array_key_exists("limit", $params)) {
        //not defined
        if ($publishmode == 0) {
            $limit_for_interface = intval(@$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']["display-preferences"]['smarty-output-limit']);
            if (!$limit_for_interface || $limit_for_interface < 1) {
                $limit_for_interface = 50;
                //default limit in dispPreferences
            }
            $params["limit"] = $limit_for_interface;
            //force limit
        } else {
            $params["limit"] = PHP_INT_MAX;
        }
    }
    if (@$params['recordset']) {
        //we already have the list of record ids
        if (is_array($params['recordset'])) {
            $qresult = $params['recordset'];
        } else {
            $qresult = json_decode($params['recordset'], true);
        }
        //truncate recordset  - limit does not work for publish mode
        if ($publishmode == 0 && $qresult && array_key_exists('recIDs', $qresult)) {
            $recIDs = explode(',', $qresult['recIDs']);
            if ($params["limit"] < count($recIDs)) {
                $qresult['recIDs'] = implode(',', array_slice($recIDs, 0, $params["limit"]));
            }
        }
    } else {
        if (@$params['h4'] == 1) {
            //search with h4 search engine and got list of ids
            /*    for future use
                  $params['detail']='ids';
                  $params['vo']='h3';
                  $qresult = recordSearch($system, $params);
                  */
            $url = "";
            foreach ($params as $key => $value) {
                $url = $url . $key . "=" . urlencode($value) . "&";
            }
            $url = HEURIST_BASE_URL . "hserver/controller/record_search.php?" . $url . "&detail=ids&vo=h3";
            $result = loadRemoteURLviaSocket($url);
            // loadRemoteURLContent($url);
            $qresult = json_decode($result, true);
        } else {
            $qresult = loadSearch($params);
            //from search/getSearchResults.php - loads array of records based og GET request
        }
    }
    // EMPTY RESULT SET - EXIT
    if (!$qresult || !array_key_exists('recIDs', $qresult) && !array_key_exists('records', $qresult) || $qresult['resultCount'] == 0) {
        if ($emptysetmessage) {
            $error = $emptysetmessage;
            // allows publisher of URL to customise the message if no records retrieved
        } else {
            if ($publishmode > 0) {
                $error = "<b><font color='#ff0000'>Note: There are no records in this view. The URL will only show records to which the viewer has access. Unless you are logged in to the database, you can only see records which are marked as Public visibility</font></b>";
            } else {
                $error = "<b><font color='#ff0000'>Search or Select records to see template output</font></b>";
            }
        }
        if ($isJSout) {
            $error = add_javascript_wrap4($error, null);
        }
        if ($publishmode > 0 && $outputfile != null) {
            //save empty output into file
            save_report_output2($error . "<div style=\"padding:20px;font-size:110%\">Currently there are no results</div>");
        } else {
            echo $error;
        }
        exit;
    }
    //get name of template file
    $template_file = array_key_exists('template', $params) ? $params['template'] : null;
    //get template body from request (for execution from editor)
    $template_body = array_key_exists('template_body', $params) ? $params['template_body'] : null;
    if (null != $template_file) {
        if (substr($template_file, -4) != ".tpl") {
            $template_file = $template_file . ".tpl";
        }
        if (file_exists(HEURIST_SMARTY_TEMPLATES_DIR . $template_file)) {
            $content = file_get_contents(HEURIST_SMARTY_TEMPLATES_DIR . $template_file);
        } else {
            $error = "<b><font color='#ff0000'>Template file {$template_file} does not exist</font></b>";
            echo $error;
            if ($publishmode > 0 && $outputfile != null) {
                //save empty output into file
                save_report_output2($error);
            }
            exit;
        }
    } else {
        $content = $template_body;
    }
    //verify that template has new features
    //need to detect $heurist->getRecord - if it is not found this is old version - show error message
    if (strpos($content, '$heurist->getRecord(') === false) {
        $error = '<p>To improve performance we have made some small changes to the report template specifications (July 2016).</p>' . '<p>You will need to add  {$r = $heurist->getRecord($r)}  immediately after the start of the main record loop, like this:<p/>' . '{*------------------------------------------------------------*}' . '<br/>{foreach $results as $r}' . '<br/><b>{$r = $heurist->getRecord($r)}</b>' . '<br/>{*------------------------------------------------------------*}' . '<p>and similar expressions for record pointer loops - example: {$r.f103 = $heurist->getRecord($r.f103)}</p>' . '<p>Please generate a new report to obtain an example of the syntax, or simply send your report template to ' . '<br/>support at HeuristNetwork dot org and we will adjust the template for you.</p>';
        if ($publishmode > 0 && $outputfile != null) {
            save_report_output2($error);
        } else {
            echo $error;
        }
        exit;
    }
    $k = strpos($content, "{*depth");
    $kp = 8;
    if (is_bool($k) && !$k) {
        $k = strpos($content, "{* depth");
        $kp = 9;
    }
    if (is_numeric($k) && $k >= 0) {
        $nd = substr($content, $k + $kp, 1);
        //strpos($content,"*}",$k)-$k-8);
        if (is_numeric($nd) && $nd < 3) {
            $max_allowed_depth = $nd;
        }
    }
    //end pre-parsing of template
    $mysqli = mysqli_connection_overwrite(DATABASE);
    if ($publishmode == 0 && $session_id != null) {
        updateProgress($mysqli, $session_id, true, '0,0');
    }
    //convert to array that will assigned to smarty variable
    if (array_key_exists('recIDs', $qresult)) {
        $results = explode(",", $qresult["recIDs"]);
        $execution_total_counter = count($results);
        /* OLD WAY
                $records =  explode(",", $qresult["recIDs"]);
                $results = array();
                $k = 0;
                $execution_total_counter = count($records); //'tot_count'=>$tot_count,
        
                foreach ($records as $recordID){
        
                    if(smarty_function_progress(array('done'=>$k), $smarty)){
                        echo 'Execution was terminated';
                        return;
                    }
        
                    $rec = loadRecord($recordID, false, true); //from search/getSearchResults.php
        
                    $res1 = getRecordForSmarty($rec, 0, $k);
                    $res1["recOrder"]  = $k;
                    $k++;
                    array_push($results, $res1);
                }
        */
    } else {
        $records = $qresult["records"];
        $execution_total_counter = count($records);
        //'tot_count'=>$tot_count,
        //v5.5+ $results =  array_column($records, 'recID');
        $results = array_map(function ($value) {
            return @$value['recID'] ? $value['recID'] : array();
        }, $records);
        /*  OLD WAY        
                $records =  $qresult["records"];
                $execution_total_counter = count($records); //'tot_count'=>$tot_count,
                $results = array();
                $k = 0;
                foreach ($records as $rec){
        
                    if(smarty_function_progress(array('done'=>$k), $smarty)){
                        echo 'Execution was terminated';
                        return;
                    }
        
                    $res1 = getRecordForSmarty($rec, 0, $k);
                    $res1["recOrder"]  = $k;
                    $k++;
                    array_push($results, $res1);
                }
        */
    }
    //activate default template - generic list of records
    //we have access to 2 methods getRecord and getRelatedRecords
    $heuristRec = new ReportRecord();
    //$smarty->registerObject('heurist', $heuristRec, array('getRecord'), false);
    $smarty->assignByRef('heurist', $heuristRec);
    $smarty->assign('results', $results);
    //assign
    //$smarty->getvar()
    ini_set('display_errors', 'false');
    // 'stdout' );
    $smarty->error_reporting = 0;
    if ($template_body) {
        //execute template from string - modified template in editor
        //error report level: 1 notices, 2 all, 3 debug mode
        $replevel = array_key_exists('replevel', $params) ? $params['replevel'] : 0;
        if ($replevel == "1" || $replevel == "2") {
            ini_set('display_errors', 'true');
            // 'stdout' );
            $smarty->debugging = false;
            if ($replevel == "2") {
                $smarty->error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE;
            } else {
                $smarty->error_reporting = E_NOTICE;
            }
        } else {
            $smarty->debugging = $replevel == "3";
        }
        $smarty->debug_tpl = dirname(__FILE__) . '/debug_html.tpl';
        //save temporary template
        //this is user name $template_file = "_temp.tpl";
        $template_file = "_" . get_user_username() . ".tpl";
        $file = fopen($smarty->template_dir . $template_file, "w");
        fwrite($file, $template_body);
        fclose($file);
        //$smarty->display('string:'.$template_body);
    } else {
        // usual way - from file
        if (!$template_file) {
            $template_file = 'test01.tpl';
        }
        $smarty->debugging = false;
        $smarty->error_reporting = 0;
        if ($outputfile != null) {
            $smarty->registerFilter('output', 'smarty_output_filter');
        } else {
            if ($isJSout) {
                $smarty->registerFilter('output', 'add_javascript_wrap5');
            }
        }
    }
    //DEBUG
    $smarty->registerFilter('post', 'smarty_post_filter');
    if ($publishmode == 0 && $session_id != null) {
        updateProgress($mysqli, $session_id, true, '0,' . count($results));
        /*session_start();
          $_SESSION[HEURIST_SESSION_DB_PREFIX.'heurist']['smarty_progress2'] = '0,'.count($results);
          session_write_close();*/
    }
    $execution_counter = -1;
    $execution_total_counter = count($results);
    try {
        $smarty->display($template_file);
    } catch (Exception $e) {
        echo 'Exception on execution: ', $e->getMessage(), "\n";
    }
    if ($publishmode == 0 && $session_id != null) {
        updateProgress($mysqli, $session_id, false, 'REMOVE');
    }
    $mysqli->close();
}
示例#11
0
function delete_tag()
{
    $tag_id = intval($_REQUEST['deleting']);
    mysql_connection_overwrite(DATABASE);
    mysql_query('delete from usrTags where tag_ID = ' . $tag_id);
    if (mysql_affected_rows() >= 1) {
        // overkill
        print '<div style="color: red;">1 tag deleted</div>';
    } else {
        print '<div style="color: red;">No tags deleted</div>';
    }
    mysql_query('delete from usrRecTagLinks where rtl_TagID = ' . $tag_id);
}
function do_fix_dupe()
{
    $master_rec_id = $_SESSION['master_rec_id'];
    $master_details = $_SESSION['master_details'];
    unset($_SESSION['master_details']);
    //clear master_details so we don't re-enter this code
    unset($_SESSION['master_rec_id']);
    $_SESSION['finished_merge'] = 1;
    // set state variable for next loop
    $dup_rec_ids = array();
    if (in_array($master_rec_id, explode(',', $_REQUEST['bib_ids']))) {
        $dup_rec_ids = array_diff(explode(',', $_REQUEST['bib_ids']), array($master_rec_id));
    }
    $dup_rec_list = '(' . join(',', $dup_rec_ids) . ')';
    $add_dt_ids = array();
    // array of detail ids to insert for the master record grouped by detail type is
    $update_dt_ids = array();
    // array of detail ids to get value for updating the master record
    $keep_dt_ids = array();
    // array of master record repeatable detail ids to keep grouped by detail type id- used to find master details to remove
    //parse form data
    foreach ($_REQUEST as $key => $value) {
        preg_match('/(add|update|keep)(\\d+)/', $key, $matches);
        if (!$matches) {
            continue;
        }
        switch (strtolower($matches[1])) {
            case 'add':
                $add_dt_ids[$matches[2]] = $value;
                break;
            case 'update':
                if ($value != "master") {
                    $update_dt_ids[$matches[2]] = $value;
                }
                break;
            case 'keep':
                $keep_dt_ids[$matches[2]] = $value;
                break;
        }
    }
    //   mysql_connection_overwrite("`heuristdb-nyirti`");   //for debug
    mysql_connection_overwrite(DATABASE);
    //    mysql_query('set @suppress_update_trigger:=1'); // shut off update triggers to let us munge the records with out worrying about the archive.
    // set modified on master so the changes will stick  aslo update url if there is one.
    $now = date('Y-m-d H:i:s');
    $pairs = @$_REQUEST['URL'] ? array("rec_URL" => $_REQUEST['URL'], "rec_Modified" => $now) : array("rec_Modified" => $now);
    mysql__update("Records", "rec_ID={$master_rec_id}", $pairs);
    //process keeps - which means find repeatables in master record to delete  all_details - keeps = deletes
    //get array of repeatable detail ids for master
    $master_rep_dt_ids = array();
    $res = mysql_query('select rst_DetailTypeID from defRecStructure where rst_MaxValues != 1 and rst_RecTypeID = ' . $_SESSION['rty_ID']);
    while ($row = mysql_fetch_array($res)) {
        array_push($master_rep_dt_ids, $row[0]);
    }
    $master_rep_detail_ids = array();
    foreach ($master_rep_dt_ids as $rep_dt_id) {
        if (array_key_exists($rep_dt_id, $master_details)) {
            foreach ($master_details[$rep_dt_id] as $detail) {
                array_push($master_rep_detail_ids, $detail['dtl_ID']);
            }
        }
    }
    //get flat array of keep detail ids
    if ($keep_dt_ids && count($keep_dt_ids)) {
        $master_keep_ids = array();
        foreach ($keep_dt_ids as $dt_id => $details) {
            foreach ($details as $detail) {
                array_push($master_keep_ids, $detail);
            }
        }
    }
    //diff the arrays  don't delet yet as the user might be adding an existing value
    $master_delete_dt_ids = array();
    if ($master_rep_detail_ids) {
        $master_delete_dt_ids = array_diff($master_rep_detail_ids, $master_keep_ids);
    }
    //ART HERE   $master_keep_ids
    //FIXME add code to remove any none repeatable extra details
    //for each update
    if ($update_dt_ids) {
        $update_detail = array();
        foreach ($update_dt_ids as $rdt_id => $rd_id) {
            //look up data for detail and
            $update_detail = mysql_fetch_assoc(mysql_query('select * from recDetails where dtl_ID=' . $rd_id));
            // if exist in master details  update val
            if (in_array($rdt_id, array_keys($master_details))) {
                mysql__update("recDetails", "dtl_ID=" . $master_details[$rdt_id][0]['dtl_ID'], array("dtl_Value" => $update_detail['dtl_Value']));
                // else  insert the data as detail for master record
            } else {
                unset($update_detail['dtl_ID']);
                //get rid of the detail id the insert will create a new one.
                $update_detail['dtl_RecID'] = $master_rec_id;
                // set this as a detail of the master record
                mysql__insert('recDetails', $update_detail);
            }
        }
    }
    //process adds
    if ($add_dt_ids) {
        $add_details = array();
        // for each add detail
        foreach ($add_dt_ids as $key => $detail_ids) {
            foreach ($detail_ids as $detail_id) {
                // since adds are only for repeatables check if it exist in delete array ?yes - remove from delete list if there
                if ($key_remove = array_search($detail_id, $master_delete_dt_ids) !== FALSE) {
                    //FIXME need to compare teh value not the dtl_ID (they will always be diff)
                    //remove from array
                    unset($master_delete_dt_ids[$key_remove]);
                } else {
                    //no  then lookup data for detail and insert the data as detail under the master rec id
                    $add_detail = mysql_fetch_assoc(mysql_query('select * from recDetails where dtl_ID=' . $detail_id));
                    unset($add_detail['dtl_ID']);
                    //the id is auto set during insert
                    $add_detail['dtl_RecID'] = $master_rec_id;
                    mysql__insert('recDetails', $add_detail);
                }
            }
        }
    }
    foreach ($dup_rec_ids as $dup_rec_id) {
        //saw FIXME we should be updating the chain of links
        mysql_query('insert into recForwarding (rfw_OldRecID, rfw_NewRecID) values (' . $dup_rec_id . ', ' . $master_rec_id . ')');
        //saw FIXME  we should update the relationship table on both rr_rec_idxxx  fields
    }
    // move dup bookmarks and tags to master unless they are already there
    //get bookmarkid =>userid for bookmarks of master record
    $master_bkm_UGrpIDs = mysql__select_assoc('usrBookmarks', 'bkm_ID', 'bkm_UGrpID', 'bkm_recID = ' . $master_rec_id);
    //get kwd_ids for  all bookmarks of master record
    $master_tag_ids = mysql__select_array('usrRecTagLinks', 'rtl_TagID', 'rtl_RecID = ' . $master_rec_id);
    //get bookmarkid => userid of bookmarks for dup records
    $dup_bkm_UGrpIDs = mysql__select_assoc('usrBookmarks', 'bkm_ID', 'bkm_UGrpID', 'bkm_recID in' . $dup_rec_list);
    // if dup userid already has a bookmark on master record then add dup bkm_ID to delete_bkm_IDs_list else add to  update_bkm_IDs
    $update_bkm_IDs = array();
    $delete_bkm_IDs = array();
    $dup_delete_bkm_ID_to_master_bkm_id = array();
    //for every user or group that bookmarks a dup record if it already bookmarks the master then mark it for deletion
    // otherwise mark it for update to point to the master record
    foreach ($dup_bkm_UGrpIDs as $dup_bkm_ID => $dup_bkm_UGrpID) {
        if (count(@$master_bkm_UGrpIDs) && ($matching_master_bkm_ID = array_search($dup_bkm_UGrpID, $master_bkm_UGrpIDs))) {
            array_push($delete_bkm_IDs, $dup_bkm_ID);
            $dup_delete_bkm_ID_to_master_bkm_id[$dup_bkm_ID] = $matching_master_bkm_ID;
        } else {
            array_push($update_bkm_IDs, $dup_bkm_ID);
            $master_bkm_UGrpIDs[$dup_bkm_ID] = $dup_bkm_UGrpID;
        }
    }
    //move duplicate record bookmarks for users without bookmarks on the master record
    $update_bkm_IDs_list = '(' . join(',', $update_bkm_IDs) . ")";
    $delete_bkm_IDs_list = '(' . join(',', $delete_bkm_IDs) . ")";
    if (strlen($update_bkm_IDs_list) > 2) {
        // update the bookmarks and tags that are not in the master
        mysql_query('update usrBookmarks set bkm_recID=' . $master_rec_id . ' where bkm_ID in ' . $update_bkm_IDs_list);
        //        mysql_query('update usrRecTagLinks set rtl_RecID='.$master_rec_id.' where kwl_pers_id in '.$update_bkm_IDs_list);
    }
    // process to be deleted dup bookmarks
    foreach ($delete_bkm_IDs as $delete_dup_bkm_ID) {
        //copy soon to be deleted dup bookmark data to master record bookmark  by concat notes and pwd_reminder, max of ratings and copy zotero if non existant
        $master_bkm_ID = @$dup_delete_bkm_ID_to_master_bkm_id[$delete_dup_bkm_ID];
        $res1 = mysql_query('select * from usrBookmarks where bkm_ID=' . $master_bkm_ID);
        $res2 = mysql_query('select * from usrBookmarks where bkm_ID=' . $delete_dup_bkm_ID);
        if (!($res1 && $res2)) {
            continue;
        }
        $master_pers_record = mysql_fetch_assoc($res1);
        $delete_dup_pers_record = mysql_fetch_assoc($res2);
        //        $master_pers_record['pers_notes'] .= $delete_dup_pers_record['pers_notes'];
        $master_pers_record['bkm_PwdReminder'] .= "; " . $delete_dup_pers_record['bkm_PwdReminder'];
        $master_pers_record['bkm_Rating'] = max($master_pers_record['bkm_Rating'], $delete_dup_pers_record['bkm_Rating']);
        if (!$master_pers_record['bkm_ZoteroID']) {
            $master_pers_record['bkm_ZoteroID'] = $delete_dup_pers_record['bkm_ZoteroID'];
        }
        unset($master_pers_record['bkm_ID']);
        mysql__update('usrBookmarks', 'bkm_ID=' . $master_bkm_ID, $master_pers_record);
    }
    //for every delete dup tag link whoses tag id is not already linked to the master record change the record id to master
    //get tag links for the soon to be deleted dup records
    $delete_dup_rtl_ids = mysql__select_assoc('usrRecTagLinks', 'rtl_ID', 'rtl_TagID', 'rtl_RecID in' . $dup_rec_list);
    foreach ($delete_dup_rtl_ids as $rtl_ID => $tag_id) {
        if (count($master_tag_ids) && array_search($tag_id, $master_tag_ids)) {
            //if it's already linked to the master delete it
            mysql_query('delete from usrRecTagLinks where rtl_ID = ' . $rtl_ID);
            //FIXME add error code
        } else {
            // otherwise point it to the master record
            mysql_query('update usrRecTagLinks set rtl_RecID=' . $master_rec_id . ', where rtl_ID = ' . $rtl_ID);
            array_push($master_tag_ids, $tag_id);
            // add to the array of tagids already on the master record
        }
    }
    // move reminders to master
    mysql_query('update usrReminders set rem_RecID=' . $master_rec_id . ' where rem_RecID in ' . $dup_rec_list);
    //?FIXME  do we need to check reminders like we checked usrBookmarks
    //delete master details
    if ($master_delete_dt_ids && count($master_delete_dt_ids)) {
        $master_detail_delete_list = '(' . join(',', $master_delete_dt_ids) . ')';
        mysql_query('delete from recDetails where dtl_ID in ' . $master_detail_delete_list);
        //FIXME add error code
    }
    //delete dup details
    mysql_query('delete from recDetails where dtl_RecID in ' . $dup_rec_list);
    //delete dup usrBookmarks
    if (strlen($delete_bkm_IDs_list) > 2) {
        mysql_query('delete from usrBookmarks where bkm_ID in ' . $delete_bkm_IDs_list);
    }
    // move dup record pointers to master record
    mysql_query('update recDetails left join defDetailTypes on dty_ID=dtl_DetailTypeID set dtl_Value=' . $master_rec_id . ' where dtl_Value in ' . $dup_rec_list . ' and dty_Type="resource"');
    //delete dups
    mysql_query('delete from Records where rec_ID in ' . $dup_rec_list);
    //delete unwanted details in master
    //if ($master_delete_dt_ids && $master_delete_dt_ids[0]){
    //    $master_delete_dt_ids_list = '('.join(',',$master_delete_dt_ids). ')' ;
    //    mysql_query('delete from recDetails where dtl_ID in '.$master_delete_dt_ids_list);
    // }
    //try to get the record to update title and hash
    // calculate title, do an update
    $type = $_SESSION['rty_ID'];
    $mask = mysql__select_array("defRecTypes", "rty_TitleMask", "rty_ID=" . $type);
    if ($mask && count($mask) > 0) {
        $mask = $mask[0];
        $title = fill_title_mask($mask, $master_rec_id, $type);
        if ($title) {
            mysql_query("update Records set rec_Title = '" . mysql_real_escape_string($title) . "' where rec_ID = {$master_rec_id}");
        }
    }
    mysql_query('update Records set rec_Hash = hhash(rec_ID) where rec_ID=' . $master_rec_id);
    header('Location: combineDuplicateRecords.php?db=' . HEURIST_DBNAME . '&bib_ids=' . $_REQUEST['bib_ids']);
}
示例#13
0
/**
* Main function
*
* @param mixed $_REQUEST
*/
function executeSmartyTemplate($params)
{
    global $smarty, $outputfile, $isJSout, $rtStructs, $dtStructs, $dtTerms, $gparams;
    mysql_connection_overwrite(DATABASE);
    //AO: mysql_connection_select - does not work since there is no access to stored procedures(getTemporalDateString) Steve uses in some query
    //TODO SAW  grant ROuser EXECUTE on getTemporalDate and any other readonly procs
    //load definitions (USE CACHE)
    $rtStructs = getAllRectypeStructures(true);
    $dtStructs = getAllDetailTypeStructures(true);
    $dtTerms = getTerms(true);
    $params["f"] = 1;
    //always search (do not use cache)
    $isJSout = array_key_exists("mode", $params) && $params["mode"] == "js";
    //use javascript wrap
    $outputfile = array_key_exists("output", $params) ? $params["output"] : null;
    $publishmode = array_key_exists("publish", $params) ? intval($params['publish']) : 0;
    $gparams = $params;
    //keep to use in other functions
    if (!array_key_exists("limit", $params)) {
        //not defined
        $limit = intval(@$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']["display-preferences"]['report-output-limit']);
        if (!$limit || $limit < 1) {
            $limit = 1000;
            //default limit in dispPreferences
        }
        $params["limit"] = $limit;
        //force limit
    }
    $qresult = loadSearch($params);
    //from search/getSearchResults.php - loads array of records based og GET request
    /*****DEBUG****/
    //error_log(print_r($qresult,true));
    if (!array_key_exists('records', $qresult) || $qresult['resultCount'] == 0) {
        if ($publishmode > 0) {
            $error = "<b><font color='#ff0000'>Note: There are no records in this view. The URL will only show records to which the viewer has access. Unless you are logged in to the database, you can only see records which are marked as Public visibility</font></b>";
        } else {
            $error = "<b><font color='#ff0000'>Search or Select records to see template output</font></b>";
        }
        if ($isJSout) {
            $error = add_javascript_wrap4($error, null);
        }
        echo $error;
        if ($publishmode > 0 && $outputfile != null) {
            //save empty outpurt inot file
            save_report_output2("<div style=\"padding:20px;font-size:110%\">Currently there are no results</div>");
        }
        exit;
    }
    //get name of template file
    $template_file = array_key_exists('template', $params) ? $params['template'] : null;
    //get template body from request (for execution from editor)
    $template_body = array_key_exists('template_body', $params) ? $params['template_body'] : null;
    //convert to array that will assigned to smarty variable
    $records = $qresult["records"];
    $results = array();
    $k = 0;
    foreach ($records as $rec) {
        $res1 = getRecordForSmarty($rec, 0, $k);
        $k++;
        array_push($results, $res1);
    }
    //activate default template - generic list of records
    $smarty->assign('results', $results);
    ini_set('display_errors', 'false');
    // 'stdout' );
    $smarty->error_reporting = 0;
    if ($template_body) {
        //execute template from string - modified temoplate in editor
        /*****DEBUG****/
        //error_log(">>>".$template_body."<<<");
        /*****DEBUG****/
        //error_log(">>>>>>>".$replevel."<<<<<<");
        //error report level: 1 notices, 2 all, 3 debug mode
        $replevel = array_key_exists('replevel', $params) ? $params['replevel'] : 0;
        if ($replevel == "1" || $replevel == "2") {
            ini_set('display_errors', 'true');
            // 'stdout' );
            $smarty->debugging = false;
            if ($replevel == "2") {
                $smarty->error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE;
            } else {
                $smarty->error_reporting = E_NOTICE;
            }
        } else {
            $smarty->debugging = $replevel == "3";
        }
        $smarty->debug_tpl = dirname(__FILE__) . '/debug_html.tpl';
        //save temporary template
        //this is user name $template_file = "_temp.tpl";
        $template_file = "_" . get_user_username() . ".tpl";
        $file = fopen($smarty->template_dir . $template_file, "w");
        fwrite($file, $template_body);
        fclose($file);
        //$smarty->display('string:'.$template_body);
    } else {
        // usual way - from file
        if (!$template_file) {
            $template_file = 'test01.tpl';
        }
        $smarty->debugging = false;
        $smarty->error_reporting = 0;
        if ($outputfile != null) {
            $smarty->registerFilter('output', 'save_report_output');
        } else {
            if ($isJSout) {
                $smarty->registerFilter('output', 'add_javascript_wrap5');
            }
        }
        //$smarty->unregisterFilter('post','add_javascript_wrap');
    }
    try {
        $smarty->display($template_file);
    } catch (Exception $e) {
        echo 'Exception on execution: ', $e->getMessage(), "\n";
    }
    //$tpl_vars = $smarty->get_template_vars();
    //var_dump($tpl_vars);
    //DEBUG stuff
    //@todo - return the list of record types - to obtain the applicable templates
    //echo "query result = ".print_r($qresult,true)."\n";
    //header("Content-type: text/javascript");
    //header('Content-type: text/html; charset=utf-8');
    //echo json_format( $qresult, true);
    //echo "<br/>***<br/>";
    //echo json_format( $results, true);
    //END DEBUG stuff
}