function getWritableChunks($wootId = NULL, $restrictToCurrent = false)
{
    /* Given a wootId to which the user has write-access,
     * return the ids of the chunks to which the user can write.
     * If restrictToCurrent is true, then the chunks should be restricted
     * to those which have not been superseded by newer versions.
     * If the wootId is omitted, then the chunks may be sourced from any woot.
     */
    $restriction = is_admin() ? "1 " : "(wprm_UGrpID=" . get_user_id() . " or wprm_GroupID in (" . join(",", get_group_ids()) . ",-1)) and wprm_Type='RW' ";
    if (!$restrictToCurrent) {
        return mysql__select_array(PERMISSION_TABLE, "wprm_ChunkID", $restriction . ($wootId ? " and chunk_WootID={$wootId}" : ""));
    } else {
        return mysql__select_array(CHUNK_TABLE . " left join " . PERMISSION_TABLE . " on chunk_ID=wprm_ChunkID", "wprm_ChunkID", "{$restriction} and chunk_IsLatest" . ($wootId ? " and chunk_WootID={$wootId}" : "") . " and wprm_ChunkID is not null");
    }
}
Beispiel #2
0
function print_biblio($bib)
{
    global $rectype;
    $output = '';
    $output .= print_bib_details($bib['rec_ID'], $bib['rec_RecTypeID'], array());
    if ($bib['rec_URL']) {
        $output .= '%U ' . $bib['rec_URL'] . "\n";
    }
    $kwds = mysql__select_array('usrBookmarks left join usrRecTagLinks on rtl_RecID = bkm_RecID
	                                       left join usrTags on tag_ID = rtl_TagID', 'tag_Text', 'bkm_recID = ' . $bib['rec_ID'] . ' and bkm_UGrpID = ' . get_user_id() . ' and tag_Text != "" and tag_Text is not null');
    if (count($kwds)) {
        $output .= '%K ' . join(', ', $kwds) . "\n";
    }
    /*
    	if ($bib['rec_ScratchPad'])
    		$output .= '%Z ' . preg_replace("/\n\n+/s", "\n", str_replace('%', '', $bib['rec_ScratchPad'])) . "\n";
    */
    if (strlen($output)) {
        print '%0 ' . $rectype[$bib['rec_RecTypeID']] . "\n" . $output . "\n";
    }
}
Beispiel #3
0
print "<form id='startform' name='startform' action='exportFAIMS.php' method='get'>";
print "<input id='rt_selected' name='rt' type='hidden'>";
print "<input name='step' value='1' type='hidden'>";
print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>";
print "<div><div class='lbl_form'>Module name</div><input name='projname' value='" . ($projname ? $projname : HEURIST_DBNAME) . "' size='25'></div>";
// List of record types for export
print "<div id='selectedRectypes' style='width:100%;color:black;'></div>";
$rtStructs = getAllRectypeStructures(false);
$int_rt_dt_type = $rtStructs['typedefs']['dtFieldNamesToIndex']["dty_Type"];
$rt_geoenabled = array();
$rt_invalid_masks = array();
if ($rt_toexport && count($rt_toexport) > 0) {
    //validate title masks
    $rtIDs = mysql__select_assoc("defRecTypes", "rty_ID", "rty_Name", " rty_ID in (" . implode(",", $rt_toexport) . ") order by rty_ID");
    foreach ($rtIDs as $rtID => $rtName) {
        $mask = mysql__select_array("defRecTypes", "rty_TitleMask", "rty_ID={$rtID}");
        $mask = $mask[0];
        $res = titlemask_make($mask, $rtID, 2, null, _ERR_REP_MSG);
        //get human readable
        if (is_array($res)) {
            //invalid mask
            array_push($rt_invalid_masks, $rtName);
        }
        $details = $rtStructs['typedefs'][$rtID]['dtFields'];
        if (!$details) {
            print "<p style='color:red'>No details defined for record type #" . $rtName . ". Edit record type structure.</p>";
            $invalid = true;
        } else {
            //check if rectype is geoenabled
            foreach ($details as $dtid => $detail) {
                $dt_type = $detail[$int_rt_dt_type];
function doTagInsertion($bkm_ID)
{
    global $usrID;
    //translate bmkID to record IT
    $res = mysql_query("select bkm_recID from usrBookmarks where bkm_ID={$bkm_ID}");
    $rec_id = mysql_fetch_row($res);
    $rec_id = $rec_id[0] ? $rec_id[0] : null;
    if (!$rec_id) {
        return "";
    }
    $tags = mysql__select_array("usrRecTagLinks, usrTags", "tag_Text", "rtl_RecID={$rec_id} and tag_ID=rtl_TagID and tag_UGrpID={$usrID} order by rtl_Order, rtl_ID");
    $tagString = join(",", $tags);
    // if the tags to insert is the same as the existing tags (in order) Nothing to do
    if (mb_strtolower(trim($_POST["tagString"]), 'UTF-8') == mb_strtolower(trim($tagString), 'UTF-8')) {
        return;
    }
    // create array of tags to be linked
    $tags = array_filter(array_map("trim", explode(",", str_replace("\\", "/", $_POST["tagString"]))));
    // replace backslashes with forwardslashes
    //create a map of this user's personal tags to tagIDs
    $kwd_map = mysql__select_assoc("usrTags", "trim(lower(tag_Text))", "tag_ID", "tag_UGrpID={$usrID} and tag_Text in (\"" . join("\",\"", array_map("mysql_real_escape_string", $tags)) . "\")");
    $tag_ids = array();
    foreach ($tags as $tag) {
        $tag = preg_replace('/\\s+/', ' ', trim($tag));
        $tag = mb_strtolower($tag, 'UTF-8');
        if (@$kwd_map[$tag]) {
            // tag exist get it's id
            $tag_id = $kwd_map[$tag];
        } else {
            // no existing tag so add it and get it's id
            $query = "insert into usrTags (tag_Text, tag_UGrpID) values (\"" . mysql_real_escape_string($tag) . "\", {$usrID})";
            mysql_query($query);
            $tag_id = mysql_insert_id();
        }
        array_push($tag_ids, $tag_id);
    }
    // Delete all personal tags for this bookmark's record
    mysql_query("delete usrRecTagLinks from usrRecTagLinks, usrTags where rtl_RecID = {$rec_id} and tag_ID=rtl_TagID and tag_UGrpID = {$usrID}");
    if (count($tag_ids) > 0) {
        $query = "";
        for ($i = 0; $i < count($tag_ids); ++$i) {
            if ($query) {
                $query .= ", ";
            }
            $query .= "({$rec_id}, " . ($i + 1) . ", " . $tag_ids[$i] . ")";
        }
        $query = "insert into usrRecTagLinks (rtl_RecID, rtl_Order, rtl_TagID) values " . $query;
        mysql_query($query);
    }
    // return new tag string
    $tags = mysql__select_array("usrRecTagLinks, usrTags", "tag_Text", "rtl_RecID = {$rec_id} and tag_ID=rtl_TagID and tag_UGrpID={$usrID} order by rtl_Order, rtl_ID");
    return join(",", $tags);
}
function get_rt_usage($rt_id)
{
    $res = mysql__select_array("Records", "count(*)", "rec_RecTypeID=" . $rt_id);
    return $res[0];
}
function loadUserDependentData(&$record)
{
    $recID = $record["rec_ID"];
    $res = mysql_query("select bkm_ID,\n\t\t\tbkm_Rating\n\t\t\tfrom usrBookmarks\n\t\t\twhere bkm_recID = {$recID}\n\t\t\tand bkm_UGrpID = " . get_user_id());
    if ($res && mysql_num_rows($res) > 0) {
        $row = mysql_fetch_assoc($res);
        $record = array_merge($record, $row);
    }
    $res = mysql_query("select rem_RecID,\n\t\t\trem_ID,\n\t\t\trem_ToWorkgroupID,\n\t\t\trem_ToUserID,\n\t\t\trem_Email,\n\t\t\trem_Message,\n\t\t\trem_StartDate,\n\t\t\trem_Freq\n\t\t\tfrom usrReminders\n\t\t\twhere rem_RecID = {$recID}\n\t\t\tand rem_OwnerUGrpID=" . get_user_id());
    $reminders = array();
    while ($res && ($rem = mysql_fetch_row($res))) {
        $rec_id = array_shift($rem);
        array_push($reminders, $rem);
    }
    $res = mysql_query("select cmt_ID,\n\t\t\tcmt_ParentCmtID,\n\t\t\tcmt_Added,\n\t\t\tcmt_Modified,\n\t\t\tcmt_Text,\n\t\t\tcmt_OwnerUgrpID,\n\t\t\tcmt_Deleted\n\t\t\tfrom recThreadedComments\n\t\t\twhere cmt_RecID = {$recID}\n\t\t\torder by cmt_ID");
    $comments = array();
    while ($cmt = mysql_fetch_row($res)) {
        $cmt[1] = intval($cmt[1]);
        $cmt[6] = intval($cmt[6]);
        if ($cmt[6]) {
            // comment has been deleted, just leave a stub
            $cmt = array($cmt[0], $cmt[1], NULL, NULL, NULL, NULL, 1);
        }
        array_push($comments, $cmt);
    }
    $record["tags"] = mysql__select_array("usrRecTagLinks, usrTags", "tag_Text", "tag_ID = rtl_TagID and\n\t\t\ttag_UGrpID= " . get_user_id() . " and\n\t\t\trtl_RecID = {$recID}\n\t\t\torder by rtl_Order");
    $record["wgTags"] = mysql__select_array("usrRecTagLinks, usrTags, " . USERS_DATABASE . ".sysUsrGrpLinks", "rtl_TagID", "tag_ID = rtl_TagID and\n\t\t\ttag_UGrpID = ugl_GroupID and\n\t\t\tugl_UserID = " . get_user_id() . " and\n\t\t\trtl_RecID = {$recID}\n\t\t\torder by rtl_Order");
    $record["notifies"] = $reminders;
    $record["comments"] = $comments;
}
Beispiel #7
0
</link>
<?php 
            if ($creator != null) {
                // this is email - not creator's rectitle
                //print "\n	<author><![CDATA[".$creator."]]></author>";
            }
        }
        if ($tagString) {
            print "\n\t<media:keywords>" . $tagString . "</media:keywords>";
        }
        if ($thubURL) {
            //width=\"120\" height=\"80\"
            print "\n\t<media:thumbnail url=\"" . htmlspecialchars($thubURL) . "\"/>";
        }
        //geo rss
        $geos = mysql__select_array("recDetails", "if(a.dtl_Geo is null, null, asText(a.dtl_Geo)) as dtl_Geo", "a.dtl_RecID=" . $row[0] . " and a.dtl_Geo is not null");
        if (count($geos) > 0) {
            $wkt = $geos[0];
            $geom = geoPHP::load($wkt, 'wkt');
            $gml = $geom->out('georss');
            if ($gml) {
                $gml = "<georss:" . substr($gml, 1);
                $gml = str_replace("</", "</georss:", $gml);
                print "\n\t" . $gml;
            }
        }
        print $isAtom ? '</entry>' : '</item>';
    }
    //while wkt records
}
if ($isAtom) {
Beispiel #8
0
function validateImport($params)
{
    global $system;
    //get rectype to import
    $rty_ID = @$params['sa_rectype'];
    $currentSeqIndex = @$params['seq_index'];
    if (intval($rty_ID) < 1) {
        $system->addError(HEURIST_INVALID_REQUEST, 'Record type not defined or wrong value');
        return false;
    }
    $imp_session = getImportSession($params['imp_ID']);
    if (is_bool($imp_session) && !$imp_session) {
        return false;
        //error - can not get import session
    }
    //add result of validation to session
    $imp_session['validation'] = array("count_update" => 0, "count_insert" => 0, "count_update_rows" => 0, "count_insert_rows" => 0, "count_error" => 0, "error" => array(), "recs_insert" => array(), "recs_update" => array());
    //get rectype to import
    $id_field = @$params['recid_field'];
    //record ID field is always defined explicitly
    $ignore_insert = @$params['ignore_insert'] == 1;
    //ignore new records
    if (@$imp_session['columns'][substr($id_field, 6)] == null) {
        $system->addError(HEURIST_INVALID_REQUEST, 'Identification field is not defined');
        return false;
    }
    $import_table = $imp_session['import_table'];
    $cnt_update_rows = 0;
    $cnt_insert_rows = 0;
    $mapping_params = @$params['mapping'];
    $mapping = array();
    // fieldtype => fieldname in import table
    $sel_query = array();
    if (is_array($mapping_params) && count($mapping_params) > 0) {
        foreach ($mapping_params as $index => $field_type) {
            $field_name = "field_" . $index;
            $mapping[$field_type] = $field_name;
            $imp_session['validation']['mapped_fields'][$field_name] = $field_type;
            //all mapped fields - they will be used in validation query
            array_push($sel_query, $field_name);
        }
    } else {
        $system->addError(HEURIST_INVALID_REQUEST, 'Mapping is not defined');
        return false;
    }
    $mysqli = $system->get_mysqli();
    $cnt_recs_insert_nonexist_id = 0;
    // validate selected record ID field
    // in case id field is not created on match step (it is from original set of columns)
    // we have to verify that its values are valid
    if (FALSE && !@$imp_session['indexes'][$id_field]) {
        //find recid with different rectype
        $query = "select imp_id, " . implode(",", $sel_query) . ", " . $id_field . " from " . $import_table . " left join Records on rec_ID=" . $id_field . " where rec_RecTypeID<>" . $rty_ID;
        // TODO: I'm not sure whether message below has been correctly interpreted
        $wrong_records = getWrongRecords($query, $imp_session, "Your input data contain record IDs in the selected ID column for existing records which are not numeric IDs. " . "The import cannot proceed until this is corrected.", "Incorrect record types", $id_field);
        if (is_array($wrong_records) && count($wrong_records) > 0) {
            $wrong_records['validation']['mapped_fields'][$id_field] = 'id';
            $imp_session = $wrong_records;
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
        if (!$ignore_insert) {
            //WARNING - it ignores possible multivalue index field
            //find record ID that do not exist in HDB - to insert
            $query = "select count(imp_id) " . " from " . $import_table . " left join Records on rec_ID=" . $id_field . " where " . $id_field . ">0 and rec_ID is null";
            $row = mysql__select_array($mysqli, $query);
            if ($row && $row[0] > 0) {
                $cnt_recs_insert_nonexist_id = $row[0];
            }
        }
    }
    // find records to update
    $select_query = "SELECT count(DISTINCT " . $id_field . ") FROM " . $import_table . " left join Records on rec_ID=" . $id_field . " WHERE rec_ID is not null and " . $id_field . ">0";
    $cnt = mysql__select_value($mysqli, $select_query);
    if ($cnt > 0) {
        $imp_session['validation']['count_update'] = $cnt;
        $imp_session['validation']['count_update_rows'] = $cnt;
        /*
        //find first 100 records to preview
        $select_query = "SELECT ".$id_field.", imp_id, ".implode(",",$sel_query)
        ." FROM ".$import_table
        ." left join Records on rec_ID=".$id_field
        ." WHERE rec_ID is not null and ".$id_field.">0"
        ." ORDER BY ".$id_field." LIMIT 5000";
        $imp_session['validation']['recs_update'] = mysql__select_all($mysqli, $select_query, false);
        */
        $imp_session['validation']['recs_update'] = array();
    }
    if (!$ignore_insert) {
        // find records to insert
        $select_query = "SELECT count(DISTINCT " . $id_field . ") FROM " . $import_table . " WHERE " . $id_field . "<0";
        //$id_field." is null OR ".
        $cnt1 = mysql__select_value($mysqli, $select_query);
        $select_query = "SELECT count(*) FROM " . $import_table . ' WHERE ' . $id_field . ' IS NULL';
        //$id_field." is null OR ".
        $cnt2 = mysql__select_value($mysqli, $select_query);
        if ($cnt1 + $cnt2 > 0) {
            $imp_session['validation']['count_insert'] = $cnt1 + $cnt2;
            $imp_session['validation']['count_insert_rows'] = $cnt1 + $cnt2;
            /*find first 100 records to display
              $select_query = 'SELECT imp_id, '.implode(',',$sel_query)
                      .' FROM '.$import_table.' WHERE '.$id_field.'<0 or '.$id_field.' IS NULL LIMIT 5000';
              $imp_session['validation']['recs_insert'] = mysql__select_all($mysqli, $select_query, false);
              */
            $imp_session['validation']['recs_insert'] = array();
        }
    }
    //additional query for non-existing IDs
    if ($cnt_recs_insert_nonexist_id > 0) {
        //NOT USED
        $imp_session['validation']['count_insert_nonexist_id'] = $cnt_recs_insert_nonexist_id;
        $imp_session['validation']['count_insert'] = $imp_session['validation']['count_insert'] + $cnt_recs_insert_nonexist_id;
        $imp_session['validation']['count_insert_rows'] = $imp_session['validation']['count_insert'];
        /*
                    $select_query = "SELECT imp_id, ".implode(",",$sel_query)
                    ." FROM ".$import_table
                    ." LEFT JOIN Records on rec_ID=".$id_field
                    ." WHERE ".$id_field.">0 and rec_ID is null LIMIT 5000";
                    $res = mysql__select_all($mysqli, $select_query, false);
                    if($res && count($res)>0){
                        if(@$imp_session['validation']['recs_insert']){
                            $imp_session['validation']['recs_insert'] = array_merge($imp_session['validation']['recs_insert'], $res);
                        }else{
                            $imp_session['validation']['recs_insert'] = $res;
                        }
                    }*/
        $imp_session['validation']['recs_insert'] = array();
    }
    // fill array with field in import table to be validated
    $recStruc = dbs_GetRectypeStructures($system, $rty_ID, 2);
    $recStruc = $recStruc['typedefs'];
    $idx_reqtype = $recStruc['dtFieldNamesToIndex']['rst_RequirementType'];
    $idx_fieldtype = $recStruc['dtFieldNamesToIndex']['dty_Type'];
    $dt_mapping = array();
    //mapping to detail type ID
    $missed = array();
    $missed_ptr = array();
    $query_reqs = array();
    //fieldnames from import table
    $query_reqs_where = array();
    //where clause for validation
    $query_enum = array();
    $query_enum_join = array();
    $query_enum_where = array();
    $query_res = array();
    $query_res_join = array();
    $query_res_where = array();
    $query_num = array();
    $query_num_nam = array();
    $query_num_where = array();
    $query_date = array();
    $query_date_nam = array();
    $query_date_where = array();
    $numeric_regex = "'^([+-]?[0-9]+\\.*)+'";
    // "'^([+-]?[0-9]+\\.?[0-9]*e?[0-9]+)|(0x[0-9A-F]+)$'";
    //loop for all fields in record type structure
    foreach ($recStruc[$rty_ID]['dtFields'] as $ft_id => $ft_vals) {
        //find fields with given field type among mappings
        $field_name = @$mapping[$ft_id];
        if (!$field_name) {
            //???????
            $field_name = array_search($rty_ID . "." . $ft_id, $imp_session["mapping"], true);
            //from previous session
        }
        if (!$field_name && $ft_vals[$idx_fieldtype] == "geo") {
            //specific mapping for geo fields
            //it may be mapped to itself or mapped to two fields - lat and long
            $field_name1 = @$mapping[$ft_id . "_lat"];
            $field_name2 = @$mapping[$ft_id . "_long"];
            if (!$field_name1 && !$field_name2) {
                $field_name1 = array_search($rty_ID . "." . $ft_id . "_lat", $imp_session["mapping"], true);
                $field_name2 = array_search($rty_ID . "." . $ft_id . "_long", $imp_session["mapping"], true);
            }
            if ($ft_vals[$idx_reqtype] == "required") {
                if (!$field_name1 || !$field_name2) {
                    array_push($missed, $ft_vals[0]);
                } else {
                    array_push($query_reqs, $field_name1);
                    array_push($query_reqs, $field_name2);
                    array_push($query_reqs_where, $field_name1 . " is null or " . $field_name1 . "=''");
                    array_push($query_reqs_where, $field_name2 . " is null or " . $field_name2 . "=''");
                }
            }
            if ($field_name1 && $field_name2) {
                array_push($query_num, $field_name1);
                array_push($query_num_where, "(NOT({$field_name1} is null or {$field_name1}='') and NOT({$field_name1} REGEXP " . $numeric_regex . "))");
                array_push($query_num, $field_name2);
                array_push($query_num_where, "(NOT({$field_name2} is null or {$field_name2}='') and NOT({$field_name2} REGEXP " . $numeric_regex . "))");
            }
        } else {
            if ($ft_vals[$idx_reqtype] == "required") {
                if (!$field_name) {
                    if ($ft_vals[$idx_fieldtype] == "resource") {
                        array_push($missed_ptr, $ft_vals[0]);
                    } else {
                        array_push($missed, $ft_vals[0]);
                    }
                } else {
                    if ($ft_vals[$idx_fieldtype] == "resource") {
                        //|| $ft_vals[$idx_fieldtype] == "enum"){
                        $squery = "not (" . $field_name . ">0)";
                    } else {
                        $squery = $field_name . " is null or " . $field_name . "=''";
                    }
                    array_push($query_reqs, $field_name);
                    array_push($query_reqs_where, $squery);
                }
            }
        }
        if ($field_name) {
            //mapping exists
            $dt_mapping[$field_name] = $ft_id;
            //$ft_vals[$idx_fieldtype];
            if ($ft_vals[$idx_fieldtype] == "enum" || $ft_vals[$idx_fieldtype] == "relationtype") {
                array_push($query_enum, $field_name);
                $trm1 = "trm" . count($query_enum);
                array_push($query_enum_join, " defTerms {$trm1} on {$trm1}.trm_Label={$field_name} ");
                array_push($query_enum_where, "(" . $trm1 . ".trm_Label is null and not ({$field_name} is null or {$field_name}=''))");
            } else {
                if ($ft_vals[$idx_fieldtype] == "resource") {
                    array_push($query_res, $field_name);
                    $trm1 = "rec" . count($query_res);
                    array_push($query_res_join, " Records {$trm1} on {$trm1}.rec_ID={$field_name} ");
                    array_push($query_res_where, "(" . $trm1 . ".rec_ID is null and not ({$field_name} is null or {$field_name}=''))");
                } else {
                    if ($ft_vals[$idx_fieldtype] == "float" || $ft_vals[$idx_fieldtype] == "integer") {
                        array_push($query_num, $field_name);
                        array_push($query_num_where, "(NOT({$field_name} is null or {$field_name}='') and NOT({$field_name} REGEXP " . $numeric_regex . "))");
                    } else {
                        if ($ft_vals[$idx_fieldtype] == "date" || $ft_vals[$idx_fieldtype] == "year") {
                            array_push($query_date, $field_name);
                            if ($ft_vals[$idx_fieldtype] == "year") {
                                array_push($query_date_where, "(concat('',{$field_name} * 1) != {$field_name} " . "and not ({$field_name} is null or {$field_name}=''))");
                            } else {
                                array_push($query_date_where, "(str_to_date({$field_name}, '%Y-%m-%d %H:%i:%s') is null " . "and str_to_date({$field_name}, '%d/%m/%Y') is null " . "and str_to_date({$field_name}, '%d-%m-%Y') is null " . "and not ({$field_name} is null or {$field_name}=''))");
                            }
                        }
                    }
                }
            }
        }
    }
    //ignore_required
    //1. Verify that all required field are mapped  =====================================================
    if ((count($missed) > 0 || count($missed_ptr) > 0) && $imp_session['validation']['count_insert'] > 0) {
        $error = '';
        if (count($missed) > 0) {
            $error = 'The following fields are required fields. You will need to map 
them to incoming data before you can import new records:<br><br>' . implode(',', $missed);
        }
        if (count($missed_ptr) > 0) {
            $error = $error . '<br>Record pointer fields( ' . implode(',', $missed_ptr) . ' ) require a record identifier value (only shown in the dropdowns in the Identifiers section). This error implies that you have not yet matched and/or imported record types that are specified in previous steps of the import workflow. Please start from the beginning. Please report the error to the Heurist developers if you think you have followed the workflow correctly.';
        }
        $system->addError(HEURIST_ERROR, $error);
        return false;
    }
    if ($id_field) {
        //validate only for defined records IDs
        if ($ignore_insert) {
            $only_for_specified_id = " (" . $id_field . " > 0) AND ";
        } else {
            $only_for_specified_id = " (NOT(" . $id_field . " is null OR " . $id_field . "='')) AND ";
        }
    } else {
        $only_for_specified_id = "";
    }
    //2. In DB: Verify that all required fields have values =============================================
    $k = 0;
    foreach ($query_reqs as $field) {
        $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} " . " where " . $only_for_specified_id . "(" . $query_reqs_where[$k] . ")";
        // implode(" or ",$query_reqs_where);
        $k++;
        $wrong_records = getWrongRecords($query, $imp_session, "This field is required - a value must be supplied for every record", "Missing Values", $field);
        if (is_array($wrong_records)) {
            $cnt = count(@$imp_session['validation']['error']);
            //was
            $imp_session = $wrong_records;
            //remove from array to be inserted - wrong records with missed required field
            if (count(@$imp_session['validation']['recs_insert']) > 0) {
                $cnt2 = count(@$imp_session['validation']['error']);
                //now
                if ($cnt2 > $cnt) {
                    $wrong_recs_ids = $imp_session['validation']['error'][$cnt]['recs_error_ids'];
                    if (count($wrong_recs_ids) > 0) {
                        $badrecs = array();
                        foreach ($imp_session['validation']['recs_insert'] as $idx => $flds) {
                            if (in_array($flds[0], $wrong_recs_ids)) {
                                array_push($badrecs, $idx);
                            }
                        }
                        $imp_session['validation']['recs_insert'] = array_diff_key($imp_session['validation']['recs_insert'], array_flip($badrecs));
                        $imp_session['validation']["count_insert"] = count($imp_session['validation']['recs_insert']);
                    }
                }
            }
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
    }
    //3. In DB: Verify that enumeration fields have correct values =====================================
    if (!@$imp_session['csv_enclosure']) {
        $imp_session['csv_enclosure'] = $params['csv_enclosure'];
    }
    if (!@$imp_session['csv_mvsep']) {
        $imp_session['csv_mvsep'] = $params['csv_mvsep'];
    }
    $hwv = " have incorrect values";
    $k = 0;
    foreach ($query_enum as $field) {
        if (true || in_array(intval(substr($field, 6)), $imp_session['multivals'])) {
            //this is multivalue field - perform special validation
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} where " . $only_for_specified_id . " 1";
            $idx = array_search($field, $sel_query) + 1;
            $wrong_records = validateEnumerations($query, $imp_session, $field, $dt_mapping[$field], $idx, $recStruc, $rty_ID, "Term list values read must match existing terms defined for the field", "Invalid Terms");
        } else {
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} left join " . $query_enum_join[$k] . " where " . $only_for_specified_id . "(" . $query_enum_where[$k] . ")";
            //implode(" or ",$query_enum_where);
            $wrong_records = getWrongRecords($query, $imp_session, "Term list values read must match existing terms defined for the field", "Invalid Terms", $field);
        }
        $k++;
        //if($wrong_records) return $wrong_records;
        if (is_array($wrong_records)) {
            $imp_session = $wrong_records;
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
    }
    //4. In DB: Verify resource fields ==================================================
    $k = 0;
    foreach ($query_res as $field) {
        if (true || in_array(intval(substr($field, 6)), $imp_session['multivals'])) {
            //this is multivalue field - perform special validation
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} where " . $only_for_specified_id . " 1";
            $idx = array_search($field, $sel_query) + 1;
            $wrong_records = validateResourcePointers($query, $imp_session, $field, $dt_mapping[$field], $idx, $recStruc, $rty_ID);
        } else {
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} left join " . $query_res_join[$k] . " where " . $only_for_specified_id . "(" . $query_res_where[$k] . ")";
            //implode(" or ",$query_res_where);
            $wrong_records = getWrongRecords($query, $imp_session, "Record pointer field values must reference an existing record in the database", "Invalid Pointers", $field);
        }
        $k++;
        //"Fields mapped as resources(pointers)".$hwv,
        if (is_array($wrong_records)) {
            $imp_session = $wrong_records;
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
    }
    //5. Verify numeric fields
    $k = 0;
    foreach ($query_num as $field) {
        if (in_array(intval(substr($field, 6)), $imp_session['multivals'])) {
            //this is multivalue field - perform special validation
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} where " . $only_for_specified_id . " 1";
            $idx = array_search($field, $sel_query) + 1;
            $wrong_records = validateNumericField($query, $imp_session, $field, $idx);
        } else {
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} " . " where " . $only_for_specified_id . "(" . $query_num_where[$k] . ")";
            $wrong_records = getWrongRecords($query, $imp_session, "Numeric fields must be pure numbers, they cannot include alphabetic characters or punctuation", "Invalid Numerics", $field);
        }
        $k++;
        // "Fields mapped as numeric".$hwv,
        if (is_array($wrong_records)) {
            $imp_session = $wrong_records;
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
    }
    //6. Verify datetime fields
    $k = 0;
    foreach ($query_date as $field) {
        if (true || in_array(intval(substr($field, 6)), $imp_session['multivals'])) {
            //this is multivalue field - perform special validation
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} where " . $only_for_specified_id . " 1";
            $idx = array_search($field, $sel_query) + 1;
            $wrong_records = validateDateField($query, $imp_session, $field, $idx);
        } else {
            $query = "select imp_id, " . implode(",", $sel_query) . " from {$import_table} " . " where " . $only_for_specified_id . "(" . $query_date_where[$k] . ")";
            //implode(" or ",$query_date_where);
            $wrong_records = getWrongRecords($query, $imp_session, "Date values must be in dd-mm-yyyy, dd/mm/yyyy or yyyy-mm-dd formats", "Invalid Dates", $field);
        }
        $k++;
        //"Fields mapped as date".$hwv,
        if (is_array($wrong_records)) {
            $imp_session = $wrong_records;
        } else {
            if ($wrong_records === false) {
                return $wrong_records;
            }
        }
    }
    //7. TODO Verify geo fields
    return $imp_session;
}
function print_relation_details($bib)
{
    global $relRT, $relSrcDT, $relTrgDT, $ACCESSABLE_OWNER_IDS, $is_map_popup, $rectypesStructure;
    $from_res = mysql_query('select recDetails.*
            from recDetails
            left join Records on rec_ID = dtl_RecID
            where dtl_DetailTypeID = ' . $relSrcDT . ' and rec_RecTypeID = ' . $relRT . ' and dtl_Value = ' . $bib['rec_ID']);
    //primary resource
    $to_res = mysql_query('select recDetails.*
            from recDetails
            left join Records on rec_ID = dtl_RecID
            where dtl_DetailTypeID = ' . $relTrgDT . ' and rec_RecTypeID = ' . $relRT . ' and dtl_Value = ' . $bib['rec_ID']);
    //linked resource
    if (mysql_num_rows($from_res) <= 0 && mysql_num_rows($to_res) <= 0) {
        return;
    }
    if ($is_map_popup) {
        print '<div>';
    } else {
        print '<div class=detailRowHeader>Related';
    }
    $accessCondition = (count($ACCESSABLE_OWNER_IDS) > 0 ? '(rec_OwnerUGrpID in (' . join(',', $ACCESSABLE_OWNER_IDS) . ') ' : '(0 ') . (is_logged_in() ? 'OR NOT rec_NonOwnerVisibility = "hidden")' : 'OR rec_NonOwnerVisibility = "public")');
    while ($reln = mysql_fetch_assoc($from_res)) {
        $bd = fetch_relation_details($reln['dtl_RecID'], true);
        // check related record
        if (!@$bd['RelatedRecID'] || !array_key_exists('rec_ID', $bd['RelatedRecID'])) {
            continue;
        }
        $relatedRecID = $bd['RelatedRecID']['rec_ID'];
        if (count(mysql__select_array("Records", "rec_ID", "rec_ID = {$relatedRecID} and {$accessCondition}")) == 0) {
            //related is not accessable
            continue;
        }
        print '<div class=detailRow>';
        //		print '<span class=label>' . htmlspecialchars($bd['RelationType']) . '</span>';	//saw Enum change
        if (array_key_exists('RelTerm', $bd)) {
            print '<div class=detailType>' . htmlspecialchars($bd['RelTerm']) . '</div>';
            // fetch now returns the enum string also
        }
        print '<div class=detail>';
        if (@$bd['RelatedRecID']) {
            if (true || $is_map_popup) {
                print '<img class="rft" style="background-image:url(' . HEURIST_ICON_URL . $bd['RelatedRecID']['rec_RecTypeID'] . '.png)" title="' . $rectypesStructure['names'][$bd['RelatedRecID']['rec_RecTypeID']] . '" src="' . HEURIST_BASE_URL . 'common/images/16x16.gif">&nbsp;';
            }
            print '<a target=_new href="' . HEURIST_BASE_URL . 'records/view/renderRecordData.php?db=' . HEURIST_DBNAME . '&recID=' . $bd['RelatedRecID']['rec_ID'] . (defined('use_alt_db') ? '&alt' : '') . '" onclick="return link_open(this);">' . htmlspecialchars($bd['RelatedRecID']['rec_Title']) . '</a>';
        } else {
            print htmlspecialchars($bd['Title']);
        }
        print '&nbsp;&nbsp;';
        if (@$bd['StartDate']) {
            print htmlspecialchars(temporalToHumanReadableString($bd['StartDate']));
        }
        if (@$bd['EndDate']) {
            print ' until ' . htmlspecialchars(temporalToHumanReadableString($bd['EndDate']));
        }
        print '</div></div>';
    }
    while ($reln = mysql_fetch_assoc($to_res)) {
        $bd = fetch_relation_details($reln['dtl_RecID'], false);
        // check related record
        if (!@$bd['RelatedRecID'] || !array_key_exists('rec_ID', $bd['RelatedRecID'])) {
            continue;
        }
        $relatedRecID = $bd['RelatedRecID']['rec_ID'];
        if (count(mysql__select_array("Records", "rec_ID", "rec_ID = {$relatedRecID} and {$accessCondition}")) == 0) {
            //related is not accessable
            continue;
        }
        print '<div class=detailRow>';
        //		print '<span class=label>' . htmlspecialchars($bd['RelationType']) . '</span>';	//saw Enum change
        if (array_key_exists('RelTerm', $bd)) {
            print '<div class=detailType>' . htmlspecialchars($bd['RelTerm']) . '</div>';
        }
        print '<div class=detail>';
        if (@$bd['RelatedRecID']) {
            if (true || $is_map_popup) {
                print '<img class="rft" style="background-image:url(' . HEURIST_ICON_URL . $bd['RelatedRecID']['rec_RecTypeID'] . '.png)" title="' . $rectypesStructure['names'][$bd['RelatedRecID']['rec_RecTypeID']] . '" src="' . HEURIST_BASE_URL . 'common/images/16x16.gif">&nbsp;';
            }
            print '<a target=_new href="' . HEURIST_BASE_URL . 'records/view/renderRecordData.php?db=' . HEURIST_DBNAME . '&recID=' . $bd['RelatedRecID']['rec_ID'] . (defined('use_alt_db') ? '&alt' : '') . '" onclick="return link_open(this);">' . htmlspecialchars($bd['RelatedRecID']['rec_Title']) . '</a>';
        } else {
            print htmlspecialchars($bd['Title']);
        }
        print '&nbsp;&nbsp;';
        if (@$bd['StartDate']) {
            print htmlspecialchars($bd['StartDate']);
        }
        if (@$bd['EndDate']) {
            print ' until ' . htmlspecialchars($bd['EndDate']);
        }
        print '</div></div>';
    }
}
function mode_crosswalking()
{
    global $session_data;
    global $import_id;
    global $heurist_rectypes;
    if (!$heurist_rectypes) {
        load_heurist_rectypes();
    }
    set_progress_bar_title('Crosswalking entries');
    $out_entries = array();
    $out_entry_count_by_rectype = array();
    $data_error_entries = array();
    $no_rectype_entries = array();
    $non_out_entries = array();
    // = data_error_entries + no_rectype_entries
    $j = 0;
    foreach (array_keys($session_data['in_entries']) as $i) {
        // FIXME: do fancy progress bar stuff
        update_progress_bar(++$j / count($session_data['in_entries']));
        $in_entry =& $session_data['in_entries'][$i];
        if ($in_entry->getPotentialReferenceType() && in_array($in_entry->getPotentialReferenceType(), $_REQUEST['use-suggested'])) {
            $in_entry->setReferenceType($in_entry->getPotentialReferenceType());
        }
        if ($in_entry->getReferenceType()) {
            unset($out_entry);
            $out_entry = $in_entry->crosswalk();
            if ($out_entry) {
                print $out_entry->getTitle() . "<br>";
                if ($out_entry->isValid()) {
                    $out_entries[] =& $out_entry;
                    @++$out_entry_count_by_rectype[$out_entry->getReferenceType()];
                } else {
                    $in_entry->addValidationErrors(format_missing_field_errors($out_entry));
                    $in_entry->addValidationErrors($out_entry->getOtherErrors());
                    $data_error_entries[] =& $in_entry;
                    $non_out_entries[] =& $in_entry;
                }
            } else {
                $data_error_entries[] =& $in_entry;
                $non_out_entries[] =& $in_entry;
            }
        } else {
            $no_rectype_entries[] =& $in_entry;
            $non_out_entries[] =& $in_entry;
        }
    }
    update_progress_bar(-1);
    $session_data['out_entries'] =& $out_entries;
    // make the error entries available to the session so that they can be downloaded
    $session_data['no_rectype_entries'] =& $no_rectype_entries;
    $session_data['data_error_entries'] =& $data_error_entries;
    $session_data['non_out_entries'] =& $non_out_entries;
    if ($out_entry_count_by_rectype) {
        ?>
        <table border=0 cellspacing=0 cellpadding=0>
            <tr>
                <td style="vertical-align: top; text-align: left; width: 5em; padding-top: 5px;">Types:</td>
                <td style="vertical-align: top; text-align: left; width: 300px;">
                    <table cellpadding="5">
                        <!-- <b>Valid entries for import:</b> -->
                        <?php 
        foreach ($out_entry_count_by_rectype as $type => $count) {
            ?>
                            <tr><td><?php 
            echo htmlspecialchars($heurist_rectypes[$type]['rty_Name']);
            ?>
</td><td><?php 
            echo intval($count);
            ?>
</td></tr>
                            <?php 
        }
        ?>
                    </table>
                </td>
                <td style="vertical-align: top; text-align: left;">
                    <table cellpadding="5">
                        <tr><td>Valid records:</td><td><b><?php 
        echo intval(count($out_entries));
        ?>
</b></td><td>&nbsp;</td></tr>
                        <?php 
        if ($non_out_entries) {
            if ($no_rectype_entries) {
                ?>
                                <tr>
                                    <td style="color: red;white-space:nowrap;">Unallocated record type:<br />(will not be imported)</td>
                                    <td><?php 
                echo count($no_rectype_entries);
                ?>
</td>
                                    <td><a target="_errors" href="interface/downloadRecsWithoutType.php/<?php 
                echo htmlspecialchars($import_id);
                ?>
-no_rectype.txt?import_id=<?php 
                echo htmlspecialchars($import_id);
                ?>
">Download errors</td>
                                    <td></td>
                                </tr>
                                <?php 
            }
            if ($data_error_entries) {
                ?>
                                <tr>
                                    <td style="color: red;white-space:nowrap;">Data errors:<br />(will not be imported)</td>
                                    <td><?php 
                echo count($data_error_entries);
                ?>
</td>
                                    <td><a target="_errors" href="interface/downloadRecsWithErrors.php/<?php 
                echo htmlspecialchars($import_id);
                ?>
-data_error.txt?import_id=<?php 
                echo htmlspecialchars($import_id);
                ?>
">Download errors</a></td>
                                </tr>
                                <?php 
            }
            ?>
                            <tr><td>Total records:</td><td><b><?php 
            echo intval(count($out_entries) + count($no_rectype_entries) + count($data_error_entries));
            ?>
</b></td><td>&nbsp;</td></tr>
                            <?php 
        }
        ?>
                    </table>
                </td>
            </tr>
        </table>

        <hr>

        <?php 
    }
    if ($out_entries) {
        print_tag_stuff($out_entries);
        ?>
        <p style="margin-left: 15px;">
        <p>Specify tags to add to all imported records:</p>

        <div class="smallgr" style="padding-left: 10ex; margin-left: 10px;white-space:nowrap;">
            Add: <a href="#" target="_ignore" onClick="add_tag('Favourites'); return false;">Favourites</a>&nbsp;
            <a href="#" target="_ignore" onClick="add_tag('To Read'); return false;">To Read</a>&nbsp;
        </div>
        <?php 
        $top_tags = mysql__select_array('usrRecTagLinks left join usrTags on rtl_TagID=tag_ID', 'tag_Text, count(tag_ID) as count', 'tag_UGrpID=' . get_user_id() . ' group by tag_ID order by count desc limit 5');
        if ($top_tags) {
            ?>
            <div class="smallgr" style="padding-left: 10ex; margin-left: 10px;white-space:nowrap;">
                Top:&nbsp;
                <?php 
            foreach ($top_tags as $tag) {
                $tag = htmlspecialchars($tag);
                ?>
      	<a href="#" target="_ignore" onClick="add_tag('<?php 
                echo $tag;
                ?>
'); return false;"><?php 
                echo $tag;
                ?>
</a>&nbsp; <?php 
            }
            ?>
            </div>
            <?php 
        }
        ?>

        <?php 
        $recent_tags = mysql__select_array('usrRecTagLinks left join usrTags on rtl_TagID=tag_ID', 'distinct(tag_Text)', 'tag_UGrpID=' . get_user_id() . ' order by rtl_ID desc limit 5');
        if ($recent_tags) {
            ?>
            <div class="smallgr" style="padding-left: 10ex; margin-left: 10px; padding-bottom: 5px;white-space:nowrap;">
                Recent:
                <?php 
            foreach ($recent_tags as $tag) {
                $tag = htmlspecialchars($tag);
                ?>
      	<a href="#" target="_ignore" onClick="add_tag('<?php 
                echo $tag;
                ?>
'); return false;"><?php 
                echo $tag;
                ?>
</a>&nbsp; <?php 
            }
            ?>
            </div>
            <?php 
        }
        ?>


        </div>



        <div style="padding-left: 10ex;"><input type="text" name="tags_for_all" id="tags_for_all" style="width: 180px; border: 1px solid black;" autocomplete=off>
            <script>
                var tagsElt = document.getElementById("tags_for_all");
                new top.HEURIST.autocomplete.AutoComplete(tagsElt, top.HEURIST.util.tagAutofill, { nonVocabularyCallback: top.HEURIST.util.showConfirmNewTag });

                function add_tag(tag) {
                    // check if the tag is already in the list somewhere
                    var tags = tagsElt.value.split(/,/);
                    for (var i=0; i < tags.length; ++i) {
                        if (tags[i].replace(/^\s+|\s+$/g, '').replace(/\s+/, ' ').toLowerCase() == tag.toLowerCase()) return;
                    }

                    // otherwise, add it to the end
                    if (tagsElt.value.match(/^\s*$/)) tagsElt.value = tag;
                    else tagsElt.value += "," + tag;
                }

            </script>
            <span class="smallgr">Separate tags with commas</span>
        </div>

        <?php 
        /* are there any workgroup-tags for any workgroups this user is in? If so, show the workgroup-tag section */
        $res = mysql_query('select tag_ID, grp.ugr_Name, tag_Text from usrTags, ' . USERS_DATABASE . '.sysUsrGrpLinks, ' . USERS_DATABASE . '.sysUGrps grp where tag_UGrpID=ugl_GroupID and ugl_GroupID=grp.ugr_ID and ugl_UserID=' . get_user_id() . ' order by grp.ugr_Name, tag_Text');
        if (mysql_num_rows($res) > 0) {
            ?>
            <div style="margin-top: 1ex; margin-left: 10ex;white-space:nowrap;">
                Workgroup tag:
                <select name="workgroup_tag">
                    <option selected></option>
                    <?php 
            while ($row = mysql_fetch_assoc($res)) {
                //saw TODO: add option grouping by workgroup and remove groupname\
                ?>
                        <option value="<?php 
                echo addslashes($row['tag_ID']);
                ?>
">
                            <?php 
                echo htmlspecialchars($row['ugr_Name']);
                ?>
 \ <?php 
                echo htmlspecialchars($row['tag_Text']);
                ?>
                        </option>
                        <?php 
            }
            ?>
                </select>
            </div>
            <?php 
        }
        ?>
        </p>

        <br clear=all>
        <hr>
        <br clear=all>

        <?php 
        if (!@$session_data['zoteroImport']) {
            ?>
            <input type="button" value="Cancel" onClick="window.location.replace('importerFramework.php?db=<?php 
            echo HEURIST_DBNAME;
            ?>
');" style="margin-right: 4ex;">
            <?php 
        } else {
            ?>
            <input type="button" value="Cancel" onClick="window.close();" style="margin-right: 4ex;">
            <?php 
        }
        ?>

        <input type="submit" name="continue" value="Continue" style="font-weight: bold;">
        <p>
            <b>Import is non-reversible!</b> Data will be written to the Heurist database.
        </p>

        <?php 
    } else {
        ?>
        <div>Heurist was unable to import any of your entries.<!-- Maybe you should try it with somebody else's data that doesn't suck --></div>
        <br clear=all>
        <hr>
        <br clear=all>

        <?php 
        if (@$session_data['data_error_entries']) {
            ?>
            <a target="_errors" href="interface/downloadRecsWithErrors.php/<?php 
            echo htmlspecialchars($import_id);
            ?>
-data_error.txt?import_id=<?php 
            echo htmlspecialchars($import_id);
            ?>
">Download errors</a>
            <?php 
        }
        ?>
        <?php 
        if (!@$session_data['zoteroImport']) {
            ?>
            <input type="button" value="Cancel" onClick="window.location.replace('importerFramework.php?db=<?php 
            echo HEURIST_DBNAME;
            ?>
');">
            <?php 
        } else {
            ?>
            <input type="button" value="Cancel" onClick="window.close();">
            <?php 
        }
        ?>
        <?php 
        $session_data['mode'] = 'error';
    }
}
        } else {
            $password = "";
        }
        $needcrypt = false;
    } else {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $needcrypt = true;
        //(array_key_exists('mode', $_REQUEST) && $_REQUEST['mode']=='2');
    }
    mysql_connection_select($db_prefix . $sourcedbname);
    $res = mysql_query('select * from ' . USERS_TABLE . ' where ' . USERS_USERNAME_FIELD . ' = "' . addslashes($username) . '"');
    $user = mysql_fetch_assoc($res);
    if ($user && $user[USERS_ACTIVE_FIELD] == 'y' && ($needcrypt && crypt($password, $user[USERS_PASSWORD_FIELD]) == $user[USERS_PASSWORD_FIELD] || !$needcrypt && $password == $user[USERS_PASSWORD_FIELD])) {
        $user_id_insource = $user[USERS_ID_FIELD];
        $user_workgroups = mysql__select_array('sysUsrGrpLinks left join sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . $user_id_insource . ' and grp.ugr_Type != "User" order by ugl_GroupID');
    } else {
        header('Location: ' . HEURIST_BASE_URL . 'import/direct/getRecordsFromDB.php?loginerror=1&db=' . HEURIST_DBNAME);
        exit;
    }
    mysql_connection_overwrite(DATABASE);
}
if (@$_REQUEST['mode'] == '2') {
    createMappingForm(null);
} else {
    // ---- visit #3 - SAVE SETTINGS -----------------------------------------------------------------
    if (@$_REQUEST['mode'] == '3') {
        saveSettings();
    } else {
        // ---- visit #4 - LOAD SETTINGS -----------------------------------------------------------------
        if (@$_REQUEST['mode'] == '4') {
Beispiel #12
0
    }
    function is_admin()
    {
        return false;
    }
    function is_logged_in()
    {
        return false;
    }
    $ss_id = 0;
} else {
    // loggin required entry
    $ss_id = 0;
    require_once dirname(__FILE__) . '/../../common/connect/applyCredentials.php';
}
$ACCESSABLE_OWNER_IDS = mysql__select_array('sysUsrGrpLinks left join sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . get_user_id() . ' and grp.ugr_Type != "user" order by ugl_GroupID');
if (is_logged_in()) {
    array_push($ACCESSABLE_OWNER_IDS, get_user_id());
    if (!in_array(0, $ACCESSABLE_OWNER_IDS)) {
        array_push($ACCESSABLE_OWNER_IDS, 0);
    }
}
//----------------------------------------------------------------------------//
// Traversal functions
// The aim here is to bundle all the queries for each level of relationships
// into one query, rather than doing them all recursively.
//----------------------------------------------------------------------------//
/**
* findPointers - Helper function that finds recIDs of record pointer details for all records in a given set of recIDs
* which can be filtered to a set of rectypes
* @author Stephen White derived from original work by Kim Jackson
            break;
        case "urlinclude":
            $row[3] = "urlinclude";
            break;
        case "integer":
        case "float":
            $row[3] = "numeric";
            break;
        default:
            $row[3] = "literal";
    }
    array_push($detailTypes, $row);
}
// detailRequirements is an array of [recordTypeID, detailTypeID, requiremence, repeatable, name, prompt, match, size, order, default] values
$detailRequirements = array();
$rec_types = mysql__select_array("defRecTypes", "distinct rty_ID", "1 order by rty_ID");
//$rec_types = mysql__select_array("defRecStructure left join defDetailType on dty_ID = rst_DetailTypeID",
//									"distinct rst_RecTypeID", "1 order by rst_RecTypeID");
// rdr = [ rst_DetailTypeID => [
// 0-rst_DisplayName
// 1-rst_DisplayHelpText
// 2-rst_DisplayExtendedDescription
// 3-rst_DefaultValue
// 4-rst_RequirementType
// 5-rst_MaxValues
// 6-rst_MinValues
// 7-rst_DisplayWidth
// 8-rst_RecordMatchOrder
// 9-rst_DisplayOrder
//10-rst_DisplayDetailTypeGroupID
//11-rst_FilteredJsonTermIDTree
Beispiel #14
0
/**
 * return the first column of first row
 *
 * @param mixed $mysqli
 * @param mixed $query
 */
function mysql__select_value($mysqli, $query)
{
    $row = mysql__select_array($mysqli, $query);
    if ($row && @$row[0]) {
        $result = $row[0];
    } else {
        $result = null;
    }
    return $result;
}
Beispiel #15
0
    $first = true;
    while ($row = mysql_fetch_row($res)) {
        if (!$first) {
            print ",";
        }
        print " ";
        $first = false;
        print "\"" . addslashes($row[0]) . "\"";
    }
    ?>
 ];

	    top.HEURIST.user.workgroups = [<?php 
    if (is_array(@$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']['user_access'])) {
        $query = "grp.ugr_ID in (" . join(",", array_keys($_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']['user_access'])) . ") and grp.ugr_Type !='user' order by grp.ugr_Name";
        $workgroups = mysql__select_array(USERS_DATABASE . ".sysUGrps grp", "grp.ugr_ID", $query);
        if (is_array($workgroups)) {
            print join(", ", $workgroups);
        }
    }
    ?>
 ];

	    top.HEURIST.user.workgroupSavedSearches = <?php 
    $ws = array();
    if (@$workgroups) {
        $res = mysql_query("select svs_UGrpID, svs_ID, svs_Name, svs_Query from usrSavedSearches left join " . USERS_DATABASE . ".sysUGrps grp on grp.ugr_ID = svs_UGrpID where svs_UGrpID in (" . join(",", $workgroups) . ") order by grp.ugr_Name, svs_Name");
        while ($row = mysql_fetch_assoc($res)) {
            json_decode($row['svs_Query']);
            if (json_last_error() == JSON_ERROR_NONE) {
                continue;
function checkRectypeMask($rtID, $rtName, $mask, $coMask, $recID, $check)
{
    if (!@$mask && @$rtID) {
        $mask = mysql__select_array("defRecTypes", "rty_TitleMask", "rty_ID={$rtID}");
        $mask = $mask[0];
    }
    if (!@$coMask && @$rtID) {
        $coMask = mysql__select_array("defRecTypes", "rty_CanonicalTitleMask", "rty_ID={$rtID}");
        $coMask = $coMask[0];
    }
    //echo print_r($_REQUEST,true);
    if ($check > 0 || !$recID) {
        ?>
			<div>
				<h3>Checking rectype "<b><i><?php 
        echo $rtName;
        ?>
</i></b>"[<?php 
        echo $rtID;
        ?>
]</h3>
			</div>
<?php 
        $retMaskCheck = check_title_mask2($mask, $rtID, true);
        echo "<div class='resultsRow'><div class='statusCell " . ($retMaskCheck == "" ? "valid'>" : "invalid'>in") . "valid</div>";
        echo "<div class='maskCell'>mask = <i>{$mask}</i></div>";
        if ($retMaskCheck != "") {
            echo "<div class='errorCell'>" . $retMaskCheck . "</div>";
        }
        echo "</div>";
        $retCoMaskCheck = check_title_mask2($coMask, $rtID, true);
        echo "<div class='resultsRow'><div class='statusCell " . ($retCoMaskCheck == "" ? "valid'>" : "invalid'>in") . "valid</div>";
        echo "<div class='maskCell'>canonical mask = <i>{$coMask}</i></div>";
        if ($retCoMaskCheck != "") {
            echo "<div class='errorCell'>" . $retCoMaskCheck . "</div>";
        }
        echo "</div>";
        if ($retCoMaskCheck !== "" && $retMaskCheck == "") {
            $coMask = make_canonical_title_mask($mask, $rtID);
            if ($check != 2) {
                echo "<div class='resultsRow'><div class='statusCell'></div><div class='maskCell'>Correct canonical mask = <span class='valid'>{$coMask}</span></div></div>";
            } else {
                // repair canonical
                mysql_query("update defRecTypes set rty_CanonicalTitleMask='{$coMask}' where rty_ID={$rtID}");
                $error = mysql_error();
                echo "<div class='resultsRow'><div class='statusCell " . ($error == "" ? "valid'>Update successful" : "invalid'>Failed to update") . "</div>";
                echo "<div class='maskCell'>Correct canonical mask = <span class='valid'>{$coMask}</span></div>";
                echo ($error ? "<div class='errorCell invalid'> Error : " . $error . "</div>" : "") . "</div>";
            }
        }
        echo "<hr>\n";
    } else {
        echo "checking type mask {$mask} for recType {$rtID} and rec {$recID} <br/>";
        echo fill_title_mask($mask, $recID, $rtID);
    }
}
function getDetailRollbacks($rec_id, $version)
{
    $potential_updates = array();
    $potential_deletes = array();
    $updates = array();
    $inserts = array();
    $deletes = array();
    $ard_ids = getAffectedDetails($rec_id, $version);
    foreach ($ard_ids as $ard_id) {
        $deltas = getDetailHistory($ard_id, $version);
        if (count($deltas) === 0) {
            // this detail didn't exist before or at the target version
            // delete it if it exists
            array_push($potential_deletes, $ard_id);
        } else {
            $latest = $deltas[0];
            if ($latest["ard_Value"] || $latest["ard_UploadedFileID"] || $latest["ard_Geo"]) {
                // an insert or update
                array_push($potential_updates, $latest);
            } else {
                // a delete
                // this shouldn't be possible - if a detail was deleted before the target version,
                // it would not be in the list returned by getAffectedDetails()
                array_push($potential_deletes, $ard_id);
            }
        }
    }
    $current_details = mysql__select_array("recDetails", "dtl_ID", "dtl_RecID = {$rec_id}");
    foreach ($potential_deletes as $potential_delete) {
        if (in_array($potential_delete, $current_details)) {
            array_push($deletes, $potential_delete);
        }
    }
    foreach ($potential_updates as $potential_update) {
        if (in_array($potential_update["ard_ID"], $current_details)) {
            // check if the current value is actually the same
            // (this would happen if the detail has been changed, and changed back)
            $ard_id = $potential_update["ard_ID"];
            $ard_val = $potential_update["ard_Value"];
            $ard_file_id = $potential_update["ard_UploadedFileID"];
            $ard_geo = $potential_update["ard_Geo"];
            $res = mysql_query("\n\t\t\t\tselect dtl_ID\n\t\t\t\tfrom recDetails\n\t\t\t\twhere dtl_ID = {$ard_id}\n\t\t\t\tand dtl_Value " . ($ard_val ? "= '" . mysql_real_escape_string($ard_val) . "'" : "is null") . "\n\t\t\t\tand dtl_UploadedFileID " . ($ard_file_id ? "= {$ard_file_id}" : "is null") . "\n\t\t\t\tand AsWKT(dtl_Geo) " . ($ard_geo ? "= '{$ard_geo}'" : "is null"));
            if (mysql_num_rows($res) == 0) {
                array_push($updates, $potential_update);
            }
        } else {
            array_push($inserts, $potential_update);
        }
    }
    return array("updates" => $updates, "inserts" => $inserts, "deletes" => $deletes);
}
* @author      Ian Johnson   <*****@*****.**>
* @author      Stephen White
* @author      Artem Osmakov   <*****@*****.**>
* @copyright   (C) 2005-2016 University of Sydney
* @link        http://HeuristNetwork.org
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/
require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php";
mysql_connection_select(DATABASE);
$tags = null;
if (@$_REQUEST['recid']) {
    $rec_ID = $_REQUEST['recid'];
    $tags = mysql__select_array('usrRecTagLinks, usrTags', 'tag_Text', "rtl_TagID=tag_ID and rtl_RecID={$rec_ID} and tag_UGrpID = " . get_user_id() . " order by rtl_Order");
}
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel=stylesheet href="../../common/css/autocomplete.css">
        <link rel=stylesheet href="../../common/css/global.css">
        <link rel=stylesheet href="../../common/css/edit.css">
        <script src="../../external/jquery/jquery.js"></script>
        <title>Tags</title>
        <style>
            .input-row div.input-header-cell, .input-row label {width:45px;max-width:45px}
            .input-row .input-cell #tags {background-color:#ECF1FB;min-width:100%;border:1px solid #DCDCDC;width:100%; white-space:nowrap}
            .actionButtons {position:absolute; left:5px; right:5px; bottom:10px}
            .actionButtons > * {margin:0 5px;}
if (array_key_exists("rec_OwnerUGrpID", $bib) && $bib["rec_OwnerUGrpID"] != $usrID && $bib["rec_OwnerUGrpID"] != 0 && $bib["rec_NonOwnerVisibility"] == "hidden") {
    /*****DEBUG****/
    //	error_log("select ugl_GroupID from ".USERS_DATABASE.".sysUsrGrpLinks where ugl_UserID=$usrID and ugl_GroupID=" . intval($bib["rec_OwnerUGrpID"]));
    $res = mysql_query("select ugl_GroupID from " . USERS_DATABASE . ".sysUsrGrpLinks " . "where ugl_UserID={$usrID} and ugl_GroupID=" . intval($bib["rec_OwnerUGrpID"]));
    if (!mysql_num_rows($res)) {
        $res = mysql_query("select grp.ugr_Name from " . USERS_DATABASE . ".sysUGrps grp where grp.ugr_ID=" . $bib["rec_OwnerUGrpID"]);
        $grp_name = mysql_fetch_row($res);
        $grp_name = $grp_name[0];
        print "{ error: \"record is restricted to workgroup " . slash($grp_name) . "\" }";
        return;
    }
}
/* check -- maybe the user has this bookmarked already ..? */
$res = mysql_query("select * from usrBookmarks where bkm_recID={$rec_id} and bkm_UGrpID={$usrID}");
if (mysql_num_rows($res) == 0) {
    /* full steam ahead */
    mysql_query("insert into usrBookmarks (bkm_recID, bkm_UGrpID, bkm_Added, bkm_Modified) values (" . $rec_id . ", {$usrID}, now(), now())");
    $res = mysql_query("select * from usrBookmarks where bkm_ID=last_insert_id()");
    if (mysql_num_rows($res) == 0) {
        print "{ error: \"internal database error while adding bookmark\" }";
        return;
    }
    $bkmk = mysql_fetch_assoc($res);
    $tagString = "";
} else {
    $bkmk = mysql_fetch_assoc($res);
    $kwds = mysql__select_array("usrRecTagLinks left join usrTags on tag_ID=rtl_TagID", "tag_Text", "rtl_RecID={$rec_id} and tag_UGrpID={$usrID} order by rtl_Order, rtl_ID");
    $tagString = join(",", $kwds);
}
$record = array("bkmkID" => $bkmk["bkm_ID"], "tagString" => $tagString, "rating" => $bkmk["bkm_Rating"], "reminders" => array(), "passwordReminder" => $bkmk["bkm_PwdReminder"]);
print json_format($record);
$hinclude = @$_REQUEST['hinclude'] ? $_REQUEST['hinclude'] : ($recID ? 0 : -1);
//default to 0 will output xincludes all non record id related records, -1 puts out all xinclude
mysql_connection_select(DATABASE);
if ($recID) {
    // check access first
    $res = mysql_query("select * from Records where rec_ID = {$recID}");
    $row = mysql_fetch_assoc($res);
    $ACCESSABLE_OWNER_IDS = mysql__select_array('sysUsrGrpLinks left join sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . get_user_id() . ' and grp.ugr_Type != "user" order by ugl_GroupID');
    if (is_logged_in()) {
        array_push($ACCESSABLE_OWNER_IDS, get_user_id());
        if (!in_array(0, $ACCESSABLE_OWNER_IDS)) {
            array_push($ACCESSABLE_OWNER_IDS, 0);
            // 0 = belong to everyone
        }
    }
    $rec_owner_id = mysql__select_array("Records", "rec_OwnerUGrpID", "rec_ID={$recID}");
    if ($row['rec_NonOwnerVisibility'] != 'public' && (count($rec_owner_id) < 1 || !in_array($rec_owner_id[0], $ACCESSABLE_OWNER_IDS) || is_logged_in() && $row['rec_NonOwnerVisibility'] == 'hidden')) {
        returnXMLErrorMsgPage(" no access to record id {$recID} ");
    }
}
saveRecordHML(HEURIST_BASE_URL . "export/xml/flathml.php?ver=1&a=1&f=1&pubonly=1&" . "depth={$depth}&hinclude={$hinclude}&w=all&q={$q}&db=" . HEURIST_DBNAME . (@$_REQUEST['outputFilename'] ? "&filename=" . $_REQUEST['outputFilename'] : "") . ($outFullName && @$_REQUEST['debug'] ? "&pathfilename=" . $outFullName : ""));
//  ---------Helper Functions
function saveRecordHML($filename)
{
    global $recID, $outFullName;
    $hml = loadRemoteURLContent($filename);
    if ($hml) {
        $xml = new DOMDocument();
        $xml->loadXML($hml);
        // convert to xml
        if (!$xml) {
/**
* main request to find crosstab data
* 
* @param mixed $mysqli
* @param mixed $params
*               dt_page - detail type for page/groups
*               dt_col - detail type for columns
*               dt_row - detail type for rows
*               agg_mode - aggreagation mode: sum, avg, count   
*               agg_field - field for avg or sum mode
*               q - current Heurist query
*/
function getCrossTab($mysqli, $params)
{
    $dt_page = @$params['dt_page'];
    if ($dt_page) {
        $pagefld = ", d4.dtl_Value as page";
    } else {
        $pagefld = "";
    }
    $dt_col = @$params['dt_col'];
    if ($dt_col) {
        $columnfld = "d1.dtl_Value as cls, ";
    } else {
        $columnfld = "0, ";
    }
    $mode = @$params['agg_mode'];
    $issum = ($mode == "avg" || $mode == "sum") && @$params['agg_field'];
    if ($issum) {
        $mode = $mode . "(cast(d3.dtl_Value as decimal(20,2)))";
        //.$params['agg_field'].")";
    } else {
        $mode = "count(*)";
    }
    if (function_exists('get_user_id')) {
        $wg_ids = mysql__select_array(USERS_DATABASE . '.sysUsrGrpLinks left join ' . USERS_DATABASE . '.sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . get_user_id() . ' and grp.ugr_Type != "User" order by ugl_GroupID');
    } else {
        $wg_ids = null;
    }
    $search_type = @$params['w'] == "bookmark" || @$params['w'] == "b" ? $params['w'] : "all";
    $where = getWhereRecordIds($params);
    if ($where == null) {
        $where = parse_query($search_type, @$params['q'], null, $wg_ids, false);
    } else {
        $where = parse_query($search_type, 'ids:' . $where, null, $wg_ids, false);
    }
    //remove order by
    $pos = strrpos($where, " order by ");
    if ($pos) {
        $where = substr($where, 0, $pos);
    }
    //insert our where clauses
    $pos = strpos($where, " where ");
    $where_1 = substr($where, 0, $pos);
    $where_2 = substr($where, $pos + 7);
    $query = "select d2.dtl_Value as rws, " . $columnfld . $mode . " as cnt " . $pagefld . " " . $where_1;
    $query = $query . " left join recDetails d2 on d2.dtl_RecID=rec_ID and d2.dtl_DetailTypeID=" . $params['dt_row'];
    if ($dt_col) {
        $query = $query . " left join recDetails d1 on d1.dtl_RecID=rec_ID and d1.dtl_DetailTypeID=" . $dt_col;
    }
    if ($dt_page) {
        $query = $query . " left join recDetails d4 on d4.dtl_RecID=rec_ID and d4.dtl_DetailTypeID=" . $dt_page;
    }
    if ($issum) {
        $query = $query . " ,recDetails d3 " . " where d3.dtl_RecID=rec_ID and d3.dtl_Value is not null && d3.dtl_DetailTypeID=" . $params['agg_field'] . " and " . $where_2;
    } else {
        $query = $query . " where " . $where_2;
        //20130517 rec_RectypeID=".$params['rt'];
    }
    //20130517 $query = $query." and ".$where_2;
    $query = $query . " group by d2.dtl_Value ";
    if ($dt_col) {
        $query = $query . ", d1.dtl_Value";
    }
    if ($dt_page) {
        $query = $query . ", d4.dtl_Value ";
    }
    $query = $query . " order by ";
    if ($dt_page) {
        if ($params['dt_pagetype'] == "integer" || $params['dt_pagetype'] == "float") {
            $query = $query . " cast(d4.dtl_Value as decimal(20,2)), ";
        } else {
            $query = $query . " d4.dtl_Value, ";
        }
    }
    if ($params['dt_rowtype'] == "integer" || $params['dt_rowtype'] == "float") {
        $query = $query . " cast(d2.dtl_Value as decimal(20,2)) ";
    } else {
        $query = $query . " d2.dtl_Value ";
    }
    if ($dt_col) {
        if ($params['dt_coltype'] == "integer" || $params['dt_coltype'] == "float") {
            $query = $query . ", cast(d1.dtl_Value as decimal(20,2))";
        } else {
            $query = $query . ", d1.dtl_Value";
        }
    }
    //error_log($query);
    $res = $mysqli->query($query);
    if (!$res) {
        $response = array("status" => "INVALID REQUEST", "message" => $mysqli->error);
        //$response = $system->addError(HEURIST_DB_ERROR, "Search query error", $mysqli->error);
    } else {
        $outp = array();
        while ($row = $res->fetch_row()) {
            array_push($outp, $row);
        }
        $response = array("status" => "OK", "data" => $outp);
        $res->close();
    }
    return $response;
}
* @author      Ian Johnson   <*****@*****.**>
* @author      Stephen White   
* @author      Artem Osmakov   <*****@*****.**>
* @copyright   (C) 2005-2016 University of Sydney
* @link        http://HeuristNetwork.org
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/
define('dirname(__FILE__)', dirname(__FILE__));
// this line can be removed on new versions of PHP as dirname(__FILE__) is a magic constant
require_once dirname(__FILE__) . '/../../common/connect/applyCredentials.php';
require_once dirname(__FILE__) . '/../../common/php/dbMySqlWrappers.php';
mysql_connection_select(DATABASE);
$ref_detail_types = mysql__select_array('defDetailTypes', 'dty_ID', 'dty_Type="resource"');
function ref_detail_types()
{
    global $ref_detail_types;
    return $ref_detail_types;
}
function parent_detail_types()
{
    return array('217', '225', '226', '227', '228', '229', '236', '237', '238', '241', '242');
}
function fetch_bib_details($rec_id, $recurse = false, $visited = array())
{
    array_push($visited, $rec_id);
    $details = array();
    $res = mysql_query('select dtl_DetailTypeID, dtl_Value
	                      from recDetails
/**
* put your comment there...
*
* @param mixed $query
* @param mixed $search_type
* @param mixed $parms
* @param mixed $wg_ids
* @param mixed $publicOnly
*/
function REQUEST_to_query($query, $search_type, $parms = NULL, $wg_ids = NULL, $publicOnly = false)
{
    // wg_ids is a list of the workgroups we can access; Records records marked with a rec_OwnerUGrpID not in this list are omitted
    /* use the supplied _REQUEST variables (or $parms if supplied) to construct a query starting with $query */
    if (!$parms) {
        $parms = $_REQUEST;
    }
    if (!defined('stype') && @$parms['stype']) {
        define('stype', @$parms['stype']);
    }
    if (!$wg_ids && function_exists('get_user_id')) {
        $wg_ids = mysql__select_array(USERS_DATABASE . '.sysUsrGrpLinks left join ' . USERS_DATABASE . '.sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . get_user_id() . ' and grp.ugr_Type != "User" order by ugl_GroupID');
    }
    if (!@$parms['qq'] && !preg_match('/&&|\\bAND\\b/i', @$parms['q'])) {
        $query .= parse_query($search_type, @$parms['q'], @$parms['s'], $wg_ids, $publicOnly);
    } else {
        // search-within-search gives us top-level ANDing (full expressiveness of conjunctions and disjunctions! hot damn)
        // basically for free!
        /*
        		$q_bits = explode('&&', $parms['qq']);
        		if ($parms['q']) array_push($q_bits, $parms['q']);
        */
        $qq = @$parms['qq'];
        if ($parms['q']) {
            if ($qq) {
                $qq .= ' && ' . $parms['q'];
            } else {
                $qq = $parms['q'];
            }
        }
        $q_bits = preg_split('/&&|\\bAND\\b/i', $qq);
        $where_clause = '';
        $q_clauses = array();
        foreach ($q_bits as $q_bit) {
            $q = parse_query($search_type, $q_bit, @$parms['s'], $wg_ids, $publicOnly);
            // for each qbit if there is owner/vis followed by clause followed by order by, capture it for and'ing
            preg_match('/.*?where [(]rec_OwnerUGrpID=[-0-9]* or (?:rec_NonOwnerVisibility="public"|not rec_NonOwnerVisibility="hidden")(?: or rec_OwnerUGrpID in \\([0-9,]*\\))?[)] and (.*?) order by/s', $q, $matches);
            if ($matches[1]) {
                array_push($q_clauses, '(' . $matches[1] . ')');
            }
        }
        sort($q_clauses);
        $where_clause = join(' and ', $q_clauses);
        // check last qbits for form of owner/vis prefix and order by suffix, then capture and add them
        if (preg_match('/(.*?where [(]rec_OwnerUGrpID=[0-9]* or (?:rec_NonOwnerVisibility="public"|not rec_NonOwnerVisibility="hidden")(?: or rec_OwnerUGrpID in [(][0-9,]*[)])?[)] and ).*?( order by.*)$/s', $q, $matches)) {
            $query .= $matches[1] . $where_clause . $matches[2];
        }
    }
    if (array_key_exists("l", $parms) || array_key_exists("limit", $parms)) {
        if (array_key_exists("l", $parms)) {
            $limit = intval(@$parms["l"]);
            unset($parms["l"]);
        } else {
            if (array_key_exists("limit", $parms)) {
                $limit = intval(@$parms["limit"]);
                // this is back in since hml.php passes through stuff from sitemap.xmap
            } else {
                $limit = 100;
            }
        }
        if ($limit < 1) {
            unset($limit);
        }
        if (@$limit) {
            //ARTEM. It should not overwrite the limit specified in dispPreferences $limit = min($limit, 1000);
        } else {
            $limit = 100;
            // Artem says 12/3/12 that this will not happen b/c it only happens if the parameter is bad.
        }
        if (array_key_exists("o", $parms)) {
            $offset = intval(@$parms["o"]);
            unset($parms["o"]);
        } else {
            if (array_key_exists("offset", $parms)) {
                $offset = intval(@$parms["offset"]);
                // this is back in since hml.php passes through stuff from sitemap.xmap
            }
        }
        $query .= (@$limit ? " limit {$limit}" : "") . (@$offset ? " offset {$offset} " : "");
    }
    return $query;
}
        $template = str_replace('<body ', '<body class=bookmark_import ', $template);
    }
}
$template = str_replace('{tag_edit}', @$_REQUEST['tag_edit'], $template);
$template = str_replace('{bookmark_import}', @$_REQUEST['bookmark_import'], $template);
$template = str_replace('{body_only}', array_key_exists('body_only', $_REQUEST) ? '<input type=hidden name=body_only>' : '', $template);
$template = str_replace('{section}', @$_REQUEST['section'], $template);
mysql_connection_select(USERS_DATABASE);
$res = mysql_query('select ugr_MinHyperlinkWords from sysUGrps usr where usr.ugr_ID = ' . get_user_id());
$row = mysql_fetch_row($res);
$word_limit = $row[0];
// minimum number of spaces that must appear in the link text
mysql_connection_select(DATABASE);
$word_limit_options = '<option value="0" ' . ($word_limit == 0 ? 'selected' : '') . '>any number of words</option>' . '<option value="1" ' . ($word_limit == 1 ? 'selected' : '') . '>at least one word</option>' . '<option value="2" ' . ($word_limit == 2 ? 'selected' : '') . '>at least two words</option>' . '<option value="3" ' . ($word_limit == 3 ? 'selected' : '') . '>at least three words</option>' . '<option value="4" ' . ($word_limit == 4 ? 'selected' : '') . '>at least four words</option>' . '<option value="5" ' . ($word_limit == 5 ? 'selected' : '') . '>at least five words</option>';
$template = str_replace('{word_limit_options}', $word_limit_options, $template);
$atags = mysql__select_array('usrHyperlinkFilter', 'hyf_String', 'hyf_UGrpID is null or hyf_UGrpID=' . get_user_id());
if (is_array($atags) && count($atags) > 0) {
    $hyperlinks_ignored = '<div>' . implode("</div>\n<div>", $atags) . '</div>';
} else {
    $hyperlinks_ignored = '<div/>';
}
$bookmarklet_script = dirname(__FILE__) . '/../../import/bookmarklet/bookmarklet.js';
$template = str_replace('{hyperlinks_ignored}', $hyperlinks_ignored, $template);
if (file_exists($bookmarklet_script)) {
    $template = str_replace('{Bookmarklet}', file_get_contents($file), $template);
}
$res = mysql_query('select count(rtl_ID) as cnt from usrTags left join usrRecTagLinks on rtl_TagID=tag_ID where tag_UGrpID= ' . get_user_id() . ' group by tag_ID order by cnt desc, tag_Text limit 1');
$row = mysql_fetch_row($res);
$max_cnt = intval($row[0]);
if (@$_REQUEST['order_by_popularity']) {
    $res = mysql_query('select tag_ID, tag_Text, count(rtl_ID) as cnt from usrTags left join usrRecTagLinks on rtl_TagID=tag_ID where tag_UGrpID= ' . get_user_id() . ' group by tag_ID order by cnt desc, tag_Text');
Beispiel #25
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);
}
Beispiel #26
0
function handleComments($recordID, $removals, $modifications, $additions)
{
    // removals are encoded as just the comments ID# ... easy.
    if ($removals) {
        $removals = array_map("intval", $removals);
        mysql_query("update recThreadedComments set cmt_Deleted=1\n                where cmt_OwnerUGrpID=" . get_user_id() . " and cmt_RecID={$recordID} and cmt_ID in (" . join(",", $removals) . ")");
    }
    // modifications have the values
    // .id, .parentComment, .text
    foreach ($modifications as $modification) {
        // note that parentComment (of course) cannot be modified
        mysql__update("recThreadedComments", "cmt_ID=" . intval($modification["id"]) . " and cmt_OwnerUGrpID=" . get_user_id(), array("cmt_Text" => $modification["text"], "cmt_Modified" => date('Y-m-d H:i:s')));
    }
    // additions are the same as modifications, except that the COMMENT-ID is blank (of course!)
    $newIDs = array();
    foreach ($additions as $addition) {
        $parentID = intval($addition["parentComment"]);
        // do a sanity check first: does this reply make sense?
        $parentTest = $parentID ? "cmt_ID={$parentID}" : "cmt_ID is null";
        if (!mysql__select_array("Records left join recThreadedComments on rec_ID=cmt_RecID and {$parentTest}", "rec_ID", "rec_ID={$recordID} and {$parentTest}")) {
            array_push($newIDs, array("error" => "invalid parent comments"));
            continue;
        }
        if (!$parentID || intval($parentID) === 0) {
            $parentID = null;
        }
        mysql__insert("recThreadedComments", array("cmt_Text" => $addition["text"], "cmt_Added" => date('Y-m-d H:i:s'), "cmt_OwnerUGrpID" => get_user_id(), "cmt_ParentCmtID" => $parentID, "cmt_RecID" => $recordID));
        array_push($newIDs, array("id" => mysql_insert_id()));
    }
    return $newIDs;
}
Beispiel #27
0
/**
 *  if user is not enabled and login count=0 - this is approvement operation
 */
function user_isApprovement($system, $recID)
{
    $ret = false;
    if ($system->is_admin() && $recID > 0) {
        $res = mysql__select_array($system->get_mysqli(), "select ugr_Type, ugr_Enabled, ugr_LoginCount from sysUGrps  where ugr_ID=" . $recID);
        $ret = $row[0] == "user" && $row[1] == "n" && $row[2] == 0;
    }
    return $ret;
}
 * @link: http://HeuristScholar.org
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
 * @package Heurist academic knowledge management system
 * @todo
 **/
/* Find any records which are *exactly the same* as another record */
define('dirname(__FILE__)', dirname(__FILE__));
// this line can be removed on new versions of PHP as dirname(__FILE__) is a magic constant
require_once dirname(__FILE__) . '/../../common/connect/applyCredentials.php';
require_once dirname(__FILE__) . '/../../common/php/dbMySqlWrappers.php';
if (!is_admin()) {
    return;
}
mysql_connection_overwrite(DATABASE);
/* Necessary but insufficient condition is for the rec_Hash to be the same */
$bibIDs = mysql__select_array("Records", "group_concat(rec_ID), count(rec_ID) C", "1 group by rec_Hash having C > 1");
print mysql_error();
$res = mysql_query("select A.rec_Hash, A.rec_ID, B.rec_ID, count(BB.dtl_ID) as C\n                      from Records A left join recDetails AA on AA.dtl_RecID = A.rec_ID,\n                           Records B left join recDetails BB on BB.dtl_RecID = B.rec_ID\n                     where AA.dtl_DetailTypeID = BB.dtl_DetailTypeID and AA.dtl_Value = BB.dtl_Value and A.rec_Hash = B.rec_Hash\n\t\t       and A.rec_ID in (" . join(',', $bibIDs) . ")\n                       and A.rec_replaced_by_rec_id is null and B.rec_replaced_by_rec_id is null\n                       and (A.rec_URL = B.rec_URL or (A.rec_URL is null and B.rec_URL is null))\n                       and (A.rec_Title = B.rec_Title)\n                  group by A.rec_ID, B.rec_ID order by B.rec_Hash, C desc");
$prev_hhash = NULL;
$prev_count = 0;
$bibs = array();
print mysql_error() . "\n";
?>
<style>
td { text-align: center; }
td:first-child { text-align: right; }
</style>
<?php 
mysql_query("start transaction");
print "<table><tr><th>master bib ID</th><th>#records</th><th>#references</th><th>#bkmk</th><th>#kwd</th><th>#reminders</th><th>errors</th></tr>";
while ($bib = mysql_fetch_row($res)) {
/**
 * get object of tools with lookup by toolRecID and by transformRecID
 * tools = {"byTransform" => {transRecID => [toolRecID,...], ...},
 *          "byID" => {toolRecID => {property => val,...},...}}
 * @return    object tool information lookup by toolRecID and transRecID
 * @uses      HEURIST_BASE_URL
 * @uses      HEURIST_DBNAME
 * @uses      get_user_id()
 */
function getToolsByTransform()
{
    $toolRT = defined('RT_TOOL') ? RT_TOOL : 0;
    $toolNameDT = defined('DT_NAME') ? DT_NAME : 0;
    $toolIconDT = defined('DT_THUMBNAIL') ? DT_THUMBNAIL : 0;
    $colourDT = defined('DT_COLOUR') ? DT_COLOUR : 0;
    $toolTransDT = defined('DT_TRANSFORM_RESOURCE') ? DT_TRANSFORM_RESOURCE : 0;
    $rectypeDT = defined('DT_RECORD_TYPE') ? DT_RECORD_TYPE : 0;
    $detailTypeDT = defined('DT_DETAIL_TYPE') ? DT_DETAIL_TYPE : 0;
    $toolDtValueDT = defined('DT_TOOL_TYPE') ? DT_TOOL_TYPE : 0;
    $commandDT = defined('DT_COMMAND') ? DT_COMMAND : 0;
    $ACCESSABLE_OWNER_IDS = mysql__select_array('sysUsrGrpLinks left join sysUGrps grp on grp.ugr_ID=ugl_GroupID', 'ugl_GroupID', 'ugl_UserID=' . get_user_id() . ' and grp.ugr_Type != "user" order by ugl_GroupID');
    if (is_logged_in()) {
        array_push($ACCESSABLE_OWNER_IDS, get_user_id());
        if (!in_array(0, $ACCESSABLE_OWNER_IDS)) {
            array_push($ACCESSABLE_OWNER_IDS, 0);
        }
    }
    $tools = array("byTransform" => array(), "byId" => array());
    $query = 'select rec_ID, dtname.dtl_Value as name, ulf_ExternalFileReference as uri, ulf_ObfuscatedFileID as fileID,' . ' clrTrm.trm_Label as colour, dttype.dtl_Value as dt, rttype.dtl_Value as rt, dtv.trm_Label as value,' . ' cmd.dtl_Value as command' . ' from Records' . ' left join recDetails dtname on rec_ID=dtname.dtl_RecID and dtname.dtl_DetailTypeID=' . $toolNameDT . ' left join recDetails dtIcon on rec_ID=dtIcon.dtl_RecID and dtIcon.dtl_DetailTypeID=' . $toolIconDT . ' left join recUploadedFiles on dtIcon.dtl_UploadedFileID = ulf_ID' . ' left join recDetails clr on rec_ID=clr.dtl_RecID and clr.dtl_DetailTypeID=' . $colourDT . ' left join defTerms clrTrm on clr.dtl_Value = clrTrm.trm_ID' . ' left join recDetails rttype on rec_ID=rttype.dtl_RecID and rttype.dtl_DetailTypeID=' . $rectypeDT . ' left join recDetails dttype on rec_ID=dttype.dtl_RecID and dttype.dtl_DetailTypeID=' . $detailTypeDT . ' left join recDetails dtValue on rec_ID=dtValue.dtl_RecID and dtValue.dtl_DetailTypeID=' . $toolDtValueDT . ' left join defTerms dtv on dtValue.dtl_Value = dtv.trm_ID' . ' left join recDetails cmd on rec_ID=cmd.dtl_RecID and cmd.dtl_DetailTypeID=' . $commandDT . ' where rec_RecTypeID=' . $toolRT . ' and (rec_OwnerUGrpID in (' . join(',', $ACCESSABLE_OWNER_IDS) . ') OR ' . 'NOT rec_NonOwnerVisibility = "hidden")' . ' order by name';
    $res = mysql_query($query);
    /*****DEBUG****/
    //error_log("query ".print_r($query,true));
    /*****DEBUG****/
    //error_log("error ".print_r(mysql_error(),true));
    while ($row = mysql_fetch_assoc($res)) {
        $toolRecID = $row['rec_ID'];
        $tools["byId"][$toolRecID] = array("name" => $row['name'], "recID" => $row['rec_ID'], "img" => @$row['uri'] ? $row['uri'] : (@$row['fileID'] ? HEURIST_BASE_URL . "records/files/downloadFile.php?db=" . HEURIST_DBNAME . "&ulf_ID=" . $row['fileID'] : null), "colour" => $row['colour'], "dt" => $row['dt'], "rt" => $row['rt'], "value" => $row['value'], "command" => $row['command'], "trans" => mysql__select_array("recDetails", "dtl_Value", "dtl_RecID=" . $row['rec_ID'] . " and dtl_DetailTypeID=" . $toolTransDT));
        foreach ($tools["byId"][$toolRecID]["trans"] as $transRecID) {
            if (!array_key_exists($transRecID, $tools["byTransform"])) {
                $tools["byTransform"][$transRecID] = array($toolRecID);
            } else {
                if (!in_array($toolRecID, $tools["byTransform"][$transRecID])) {
                    array_push($tools["byTransform"][$transRecID], $toolRecID);
                }
            }
        }
    }
    return $tools;
}
        $template = str_replace('<body ', '<body class=bookmark_import ', $template);
    }
}
$template = str_replace('{tag_edit}', @$_REQUEST['tag_edit'], $template);
$template = str_replace('{bookmark_import}', @$_REQUEST['bookmark_import'], $template);
$template = str_replace('{body_only}', array_key_exists('body_only', $_REQUEST) ? '<input type=hidden name=body_only>' : '', $template);
$template = str_replace('{section}', @$_REQUEST['section'], $template);
mysql_connection_select(USERS_DATABASE);
$res = mysql_query('select ugr_MinHyperlinkWords from sysUGrps usr where usr.ugr_ID = ' . get_user_id());
$row = mysql_fetch_row($res);
$word_limit = $row[0];
// minimum number of spaces that must appear in the link text
mysql_connection_select(DATABASE);
$word_limit_options = '<option value="0" ' . ($word_limit == 0 ? 'selected' : '') . '>any number of words</option>' . '<option value="1" ' . ($word_limit == 1 ? 'selected' : '') . '>at least one word</option>' . '<option value="2" ' . ($word_limit == 2 ? 'selected' : '') . '>at least two words</option>' . '<option value="3" ' . ($word_limit == 3 ? 'selected' : '') . '>at least three words</option>' . '<option value="4" ' . ($word_limit == 4 ? 'selected' : '') . '>at least four words</option>' . '<option value="5" ' . ($word_limit == 5 ? 'selected' : '') . '>at least five words</option>';
$template = str_replace('{word_limit_options}', $word_limit_options, $template);
$hyperlinks_ignored = '<div>' . join("</div>\n<div>", mysql__select_array('usrHyperlinkFilter', 'hyf_String', 'hyf_UGrpID is null or hyf_UGrpID=' . get_user_id())) . '</div>';
$template = str_replace('{hyperlinks_ignored}', $hyperlinks_ignored, $template);
$template = str_replace('{Bookmarklet}', file_get_contents(dirname(__FILE__) . '/../../import/bookmarklet/bookmarklet.js'), $template);
$res = mysql_query('select count(rtl_ID) as cnt from usrTags left join usrRecTagLinks on rtl_TagID=tag_ID where tag_UGrpID= ' . get_user_id() . ' group by tag_ID order by cnt desc, tag_Text limit 1');
$row = mysql_fetch_row($res);
$max_cnt = intval($row[0]);
if (@$_REQUEST['order_by_popularity']) {
    $res = mysql_query('select tag_ID, tag_Text, count(rtl_ID) as cnt from usrTags left join usrRecTagLinks on rtl_TagID=tag_ID where tag_UGrpID= ' . get_user_id() . ' group by tag_ID order by cnt desc, tag_Text');
} else {
    $res = mysql_query('select tag_ID, tag_Text, count(rtl_ID) as cnt from usrTags left join usrRecTagLinks on rtl_TagID=tag_ID where tag_UGrpID= ' . get_user_id() . ' group by tag_ID order by tag_Text');
}
$foreach_kwd = $foreach_kwd_js = '';
while ($row = mysql_fetch_row($res)) {
    $foreach_kwd .= '<tr>
 <td nowrap>
  <input type="checkbox" style="vertical-align: middle;" name="delete_kwds[' . $row[0] . ']">