function __construct() { $this->rtStructs = getAllRectypeStructures(true); $this->dtStructs = getAllDetailTypeStructures(true); $this->dtTerms = getTerms(true); $this->loaded_recs = array(); }
/** * put your comment there... * * * @param mixed $config */ function createMappingForm($config) { global $sourcedbname, $db_prefix, $dbPrefix, $is_h2, $useOriginalID; $sourcedb = $db_prefix . $sourcedbname; print "<br>\n"; //print "Source database: <b>$sourcedb</b> <br>\n"; if ($is_h2) { $res = mysql_query("select * from `{$sourcedb}`.Users"); } else { $res = mysql_query("select * from {$sourcedb}.sysIdentification"); } if (!$res) { die("<p>Unable to open source database <b>{$sourcedb}</b>. Make sure you have included prefix"); } print "<form name='mappings' action='compareStructure.php' method='post'>"; print "<input id='mode' name='mode' value='5' type='hidden'>"; // calls the transfer function print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>"; print "<input name='h2' value='" . ($is_h2 ? 1 : 0) . "' type='hidden'>"; //print "<input name='sourcedbname' value='$sourcedbname' type='hidden'>"; //print "<input name='reportlevel' value='1' type='checkbox' checked='checked'>Report level: show errors only<br>"; //print "Check the code mappings below, then click <input type='button' value='Import data' onclick='{document.getElementById(\"mode\").value=5; document.forms[\"mappings\"].submit();}'>\n"; // alert(document.getElementById(\"mode\").value); /* print "<input type='button' value='Save settings' onclick='{document.getElementById(\"mode\").value=3; document.forms[\"mappings\"].submit();}'>"; $filename = HEURIST_FILESTORE_DIR."settings/importfrom_".$sourcedbname.".cfg"; if(file_exists($filename)){ print "<input type='submit' value='Load settings' onclick='{document.getElementById(\"mode\").value=4; document.forms[\"mappings\"].submit();}'>\n"; } */ print "<p><hr>\n"; // -------------------------------------------------------------------------------------------------------------------- // Get the record type mapping, by default assume that the code is unchanged so select the equivalent record type if available $d_rectypes = getAllRectypeStructures(); //in current database $d_dettypes = getAllDetailTypeStructures(); $d_rtnames = $d_rectypes['names']; mysql_connection_overwrite($sourcedb); $s_rectypes = getAllRectypeStructures(false); $s_dettypes = getAllDetailTypeStructures(false); $s_rtnames = $s_rectypes['names']; print "<table border='1' width='900'><tr><td width='300'>" . $sourcedbname . "</td><td colspan='2'>" . HEURIST_DBNAME . "</td></tr>"; $fi_type = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Type']; $fi_name = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Name']; $fi_rt_concept = $s_rectypes['typedefs']['commonNamesToIndex']['rty_ConceptID']; $fi_dt_concept = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_ConceptID']; foreach ($s_rtnames as $s_id => $s_name) { $s_conceptid = $s_rectypes['typedefs'][$s_id]['commonFields'][$fi_rt_concept]; $dest_id = null; $dest_name = null; //find record type in destination foreach ($d_rtnames as $d_id => $d_name) { if ($useOriginalID && $d_rectypes['typedefs'][$d_id]['commonFields'][$fi_rt_concept] == $s_conceptid || !$useOriginalID && $d_name == $s_name) { //print "[".$d_id."] ".$d_name."<br/>"; //print structure in the same order as source rectype $dest_id = $d_id; $dest_name = $d_name; break; } } //Header <tr><td colspan='2'><table border='1' width='100%'> print "<tr style='background-color:#AAAAAA;'><td width='250'><b>[" . $s_id . "] " . $s_name . "</b>(" . $s_conceptid . ")</td><td width='250'>"; if ($dest_id == null) { print "...not found"; } else { print "<b>[" . $dest_id . "] " . $dest_name . "</b>"; } print "</td><td width='400'> </td></tr>"; //list of field types $s_flds = $s_rectypes['typedefs'][$s_id]['dtFields']; foreach ($s_flds as $sft_id => $sft_desc) { $fld_in_dest_rectype = " "; $fld_in_dest_all = " "; $s_conceptid = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_dt_concept]; $s_fitype = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_type]; //find in destination record type if ($dest_id != null) { $d_flds = $d_rectypes['typedefs'][$dest_id]['dtFields']; foreach ($d_flds as $dft_id => $dft_desc) { //compare by original field name and by type if ($useOriginalID && $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $d_dettypes['names'][$dft_id] && $s_fitype == $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_type]) { $fld_in_dest_rectype = "[" . $dft_id . "] " . $dft_desc[0]; break; } } } //if not found try to find in entire list of field types if ($fld_in_dest_rectype == " ") { $d_flds = $d_dettypes['typedefs']; foreach ($d_flds as $dft_id => $dft_def) { //compare by original field name and by type if ($useOriginalID && $dft_def['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $dft_def['commonFields'][$fi_name] && $s_fitype == $dft_def['commonFields'][$fi_type]) { $fld_in_dest_all = "[" . $dft_id . "] " . $dft_def['commonFields'][$fi_name] . " (" . $s_fitype . ")"; break; } } } print "<tr><td>[" . $sft_id . "] " . $sft_desc[0] . " (" . $s_conceptid . ")</td><td>" . $fld_in_dest_rectype . "</td><td>" . $fld_in_dest_all . "</td></tr>"; } ///print "</table></td><tr>"; } print "</table>"; return; $entnames = $entnames['names']; $seloptions = createOptions("or", $entnames); if ($is_h2) { $query1 = "SELECT DISTINCT `rec_type`,`rt_name` FROM `{$sourcedb}`.`records`,`{$sourcedb}`.`rec_types` where `rec_type`=`rt_id`"; } else { $query1 = "SELECT rty_ID, rty_Name, count(rec_ID) as cnt " . "from `{$sourcedb}`.`Records` " . "left join `{$sourcedb}`.`defRecTypes` on rec_RecTypeID=rty_ID " . "group by rty_ID"; } $res1 = mysql_query($query1); if (mysql_num_rows($res1) == 0) { die("<p><b>Sorry, there are no data records in this database, or database is bad format</b>"); } print "<h3>Record type mappings</h3> [RT code] <b>{$sourcedb}</b> (use count) ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>"; // . "<p>"; print "<table>"; while ($row1 = mysql_fetch_array($res1)) { $rt = $row1[0]; //0=rec_RecTypeID $cnt = $row1[2]; $selopts = $seloptions; $selectedId = getPresetId($config, "cbr" . $rt); if (!$selectedId) { //find the closest name $selectedId = findClosestName($row1[1], $entnames); //1=rty_Name } if ($selectedId) { $repl = "value='" . $selectedId . "'"; $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts); } print "<tr><td>" . $row1[1] . " [ {$rt} ] n=({$cnt}) </td>" . "<td>==> <select id='cbr{$rt}' name='cbr{$rt}' class='rectypes'><option id='or0' value='0'></option>" . $selopts . "</select></td></tr>\n"; } // loop through record types print "</table>"; // -------------------------------------------------------------------------------------------------------------------- // Get the field type mapping, by default assume that the code is unchanged so select the equivalent detail type if available //create the string for combobox $entnames = getAllDetailTypeStructures(); //in current database $entnames = $entnames['names']; $seloptions = createOptions("od", $entnames); print "<h3>Field type mappings</h3>[FT code] <b>{$sourcedb}</b> ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>"; // . "<p>"; if ($is_h2) { $query1 = "SELECT DISTINCT `rd_type`,`rdt_name`,`rdt_type` FROM `{$sourcedb}`.`rec_details`,`{$sourcedb}`.`rec_detail_types` " . "where `rd_type`=`rdt_id`"; } else { $query1 = "SELECT DISTINCT `dtl_DetailTypeID`,`dty_Name`,`dty_Type` FROM `{$sourcedb}`.`recDetails`,`{$sourcedb}`.`defDetailTypes` " . "where `dtl_DetailTypeID`=`dty_ID`"; } $res1 = mysql_query($query1); print "<table>"; while ($row1 = mysql_fetch_array($res1)) { $ft = $row1[0]; //0=dtl_DetailTypeID $selopts = $seloptions; //find the closest name $selectedId = getPresetId($config, "cbd" . $ft); if (!$selectedId) { //find the closest name $selectedId = findClosestName($row1[1], $entnames); //dty_Name } if ($selectedId) { $repl = "value='" . $selectedId . "'"; $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts); } print "<tr><td>[ {$ft} ] - " . $row1[2] . " " . $row1[1] . " </td>" . "<td>==> <select id='cbd{$ft}' name='cbd{$ft}' class='detailTypes'><option id='od0' value='0'></option>" . $selopts . "</select></td></tr>\n"; } // loop through field types print "</table>"; // -------------------------------------------------------------------------------------------------------------------- createTermsOptions($config, 'enum'); createTermsOptions($config, 'relation'); print "</form>"; }
/** * main form generation code build the model to approximate HML, the form UI and the binding between UI and model * @staticvar array [$dettypes] array detail type definitions for this database * @staticvar object [$di] field name to index mapping for detail type definition * @staticvar array [$rectypes] array record type structure definitions for this database * @staticvar object [$ri] field name to index mapping for record field structure definition * @staticvar object [$ti] field name to index mapping for term definition * @staticvar array [$termLookup] array term structure definitions for the enumerations in this database * @staticvar array [$relnLookup] array term structure definitions for the relationships in this database * @param integer [$rt_id] the rectype locally unique identifier * @return object an array of strings representing form, rtName, rtConceptID, rtDescription, and report on success * @uses getXFormTypeFromBaseType() * @uses createRecordLookup() * @uses createTermSelect() * @uses getTerms() * @uses getAllDetailTypeStructures() * @uses getAllRectypeStructures() * @uses HEURIST_UPLOAD_DIR * @uses HEURIST_BASE_URL * @uses HEURIST_DBNAME */ function buildform($rt_id) { // mappings and lookups - static so we only retrieve once per service call static $dettypes, $di, $rectypes, $ri, $rid, $terms, $ti, $termLookup, $relnLookup; if (!$dettypes || !$di) { $dettypes = getAllDetailTypeStructures(); $dettypes = $dettypes['typedefs']; $di = $dettypes['fieldNamesToIndex']; } if (!$rectypes || !$ri || !$rid) { $rectypes = getAllRectypeStructures(); $ri = $rectypes['typedefs']['commonNamesToIndex']; $rid = $rectypes['typedefs']['dtFieldNamesToIndex']; } if (!$terms || !$ti || !$termLookup || !$relnLookup) { $terms = getTerms(); $ti = $terms['fieldNamesToIndex']; $termLookup = $terms['termsByDomainLookup']['enum']; $relnLookup = $terms['termsByDomainLookup']['relation']; } if (!array_key_exists($rt_id, $rectypes['typedefs'])) { error_log("rectypes " . print_r($rectypes['typedefs'][$rt_id], true)); return array(null, null, null, null, "Rectype# {$rt_id} not found"); } $report = ""; $rectype = $rectypes['typedefs'][$rt_id]; // error_log("rectype is ".print_r($rectype,true)); //record type info $rtName = $rectypes['names'][$rt_id]; //detail or field type info $fieldTypeConceptIDIndex = $di['dty_ConceptID']; $fieldTypeNameIndex = $di['dty_Name']; $fieldBaseTypeIndex = $di['dty_Type']; //record field info $fieldNameIndex = $rid['rst_DisplayName']; $fieldDefaultValIndex = $rid['rst_DefaultValue']; $fieldHelpTextIndex = $rid['rst_DisplayHelpText']; $fieldTermsListIndex = $rid['rst_FilteredJsonTermIDTree']; $fieldTermHeaderListIndex = $rid['rst_TermIDTreeNonSelectableIDs']; $fieldPtrRectypeIDsListIndex = $rid['rst_PtrFilteredIDs']; $fieldMaxRepeatIndex = $rid['rst_MaxValues']; $rtConceptID = $rectype['commonFields'][$ri['rty_ConceptID']]; if (!$rtConceptID) { $rtConceptID = "0-" . $rt_id; } $rtDescription = $rectype['commonFields'][$ri['rty_Description']]; // output structure variables $model = "<instance>\n" . "<fhml id=\"heuristscholar.org:{$rtConceptID}\" version=\"" . date("Ymd") . "\">\n" . "<database id=\"" . HEURIST_DBID . "\" urlBase=\"" . HEURIST_BASE_URL . "\">" . HEURIST_DBNAME . "</database>\n" . "<query depth=\"0\" db=\"" . HEURIST_DBNAME . "\" q=\"t:{$rt_id}\" />\n" . "<generatedBy userID=\"" . get_user_id() . "\">" . get_user_name() . "</generatedBy>\n" . "<createdBy/>\n" . "<deviceID/>\n" . "<createTime/>\n" . "<uuid/>\n" . "<records count=\"1\">\n" . "<record depth=\"0\">\n" . "<type>\n" . "<conceptID>{$rtConceptID}</conceptID>\n" . "<label>{$rtName}</label>\n" . "</type>\n" . "<nonce/>\n" . "<details>\n"; $bind = "<bind nodeset=\"createdBy\" type=\"string\" jr:preload=\"property\" jr:preloadParams=\"username\"/>\n" . "<bind nodeset=\"createTime\" type=\"dateTime\" jr:preload=\"timestamp\" jr:preloadParams=\"start\"/>\n" . "<bind nodeset=\"deviceID\" type=\"string\" jr:preload=\"property\" jr:preloadParams=\"deviceid\"/>\n" . "<bind nodeset=\"uuid\" type=\"string\" readonly=\"true()\" calculate=\"uuid()\"/>\n" . "<bind nodeset=\"records/record/nonce\" type=\"string\" readonly=\"true()\" calculate=\"concat(/fhml/deviceID,'|',/fhml/createTime,'|',/fhml/uuid)\"/>\n"; $body = "<h:body>\n" . "<group appearance=\"field-list\">\n"; $groupSeparator = "</group>\n" . "<group appearance=\"field-list\">\n"; //@todo - sort by rst_DisplayOrder $fieldsLeft = count($rectype['dtFields']); $atGroupStart = true; //init separator detection for repatables foreach ($rectype['dtFields'] as $dt_id => $rt_dt) { if ($rt_dt[$rid['rst_NonOwnerVisibility']] == 'hidden') { continue; } --$fieldsLeft; // count down fields so we know when we hit the last one $dettype = $dettypes[$dt_id]['commonFields']; //get detail type description $baseType = $dettype[$fieldBaseTypeIndex]; $fieldTypeName = $dettype[$fieldTypeNameIndex]; $fieldName = $rt_dt[$fieldNameIndex]; $fieldtype = getXFormTypeFromBaseType($baseType); $fieldMaxCount = $rt_dt[$fieldMaxRepeatIndex]; $isRepeatable = $fieldMaxCount > 1 || $fieldMaxCount == NULL; //skip any unsupport field types if (!$fieldtype) { $report = $report . " {$rtName}." . $dettype[$fieldTypeNameIndex] . " ignored since type " . $baseType . " not supported<br/>"; continue; // not supported } if ($fieldtype == "groupbreak" && $atGroupStart) { //skip double separator, note that this includes separators before non supported types continue; } if ($baseType == "resource") { $rtIDs = $dettype[$di['dty_PtrTargetRectypeIDs']]; if (!$rtIDs || $rtIDs == "") { //unconstrained pointers not supported $report = $report . " {$rtName}." . $dettype[$fieldTypeNameIndex] . " ignored since unconstrained resource pointers are not supported<br/>"; continue; } } $dt_conceptid = $dettype[$fieldTypeConceptIDIndex]; if (!$dt_conceptid) { $dt_conceptid = "0-" . $dt_id; } $defaultValue = $rt_dt[$fieldDefaultValIndex]; // load default value //for controlled vocabs convert any local term ID to it's concept ID if ($baseType == "enum" && array_key_exists("{$defaultValue}", $termLookup)) { $termID = $termLookup[$defaultValue][$ti['trm_ConceptID']]; if ($termID) { $defaultValue = $termID; } else { $defaultValue = HEURIST_DBID . "-" . $defaultValue; } } else { if ($baseType == "relation" && array_key_exists("{$defaultValue}", $relnLookup)) { $termID = $relnLookup[$defaultValue][$ti['trm_ConceptID']]; if ($termID) { $defaultValue = $termID; } else { $defaultValue = HEURIST_DBID . "-" . $defaultValue; } } } if ($fieldtype != "groupbreak") { $model = $model . "<dt{$dt_id} conceptID=\"{$dt_conceptid}\" type=\"{$fieldTypeName}\" name=\"{$fieldName}\">" . ($defaultValue ? htmlentities($defaultValue) : "") . "</dt" . $dt_id . ">\n"; } if ($rt_dt[$rid['rst_RequirementType']] == 'required') { $isrequired = 'required="true()"'; } else { if ($rt_dt[$rid['rst_RequirementType']] == 'forbidden') { $isrequired = 'readonly="true()"'; } else { $isrequired = ''; } } $constraint = ''; /* @todo if($rt_dt[$rid['rst_MinValues']]=='required'){ //constraint=". > 10.51 and . < 18.39" jr:constraintMsg="number must be between 10.51 and 18.39" } */ // if repeatable vocab make it multi select. TODO: we should extend Heurist to include multi-select which is different than repeatable if ($fieldtype == "select1" && $isRepeatable) { $fieldtype = "select"; $isRepeatable = false; } $label = htmlentities($rt_dt[$fieldNameIndex]); $hint = htmlentities($rt_dt[$fieldHelpTextIndex]); $inputDefBody = "<label>{$label}</label>\n" . "<hint>{$hint}</hint>\n"; $xpathPrefix = "/fhml/records/record/details/"; $groupRepeatHdr = ($atGroupStart ? "" : $groupSeparator) . "<label>{$label}</label>\n" . "<repeat nodeset=\"/fhml/records/record/details/dt{$dt_id}\">\n"; $groupRepeatFtr = "</repeat>\n" . ($fieldsLeft ? $groupSeparator : ""); $atGroupStart = false; // past detection code so if ($fieldtype != "groupbreak") { $bind = $bind . "<bind nodeset=\"records/record/details/dt{$dt_id}\" type=\"{$fieldtype}\" {$isrequired} {$constraint}/>\n"; } if ($isRepeatable) { $body .= $groupRepeatHdr; } if ($fieldtype == "select1" || $fieldtype == "select") { if ($baseType == "resource") { $body = $body . "<{$fieldtype} appearance=\"minimal\" ref=\"" . $xpathPrefix . "dt" . $dt_id . "\">\n" . $inputDefBody . createRecordLookup($rtIDs) . "</{$fieldtype}>\n"; } else { $termIDTree = $dettype[$di['dty_JsonTermIDTree']]; $disabledTermIDsList = $dettype[$di['dty_TermIDTreeNonSelectableIDs']]; $fieldLookup = $baseType == "relation" ? $relnLookup : $termLookup; $body = $body . "<{$fieldtype} appearance=\"minimal\" ref=\"" . $xpathPrefix . "dt" . $dt_id . "\">\n" . $inputDefBody . createTermSelect($termIDTree, $disabledTermIDsList, $fieldLookup, false, $ti) . "</{$fieldtype}>\n"; } } else { if ($fieldtype == "binary") { //todo check for sketch type $isDrawing = false; $appearance = $dt_id == DT_DRAWING ? "draw" : "annotate"; $body = $body . "<upload ref=\"" . $xpathPrefix . "dt{$dt_id}\" appearance=\"{$appearance}\" mediatype=\"image/*\">\n" . $inputDefBody . "</upload>\n"; } else { if ($fieldtype == "groupbreak") { // if we get to here we have a legitament sepearator so break $body .= $groupSeparator; $atGroupStart = true; } else { if ($dt_id == DT_COUNTER) { //we have a counter field so let's launch the Inventory Counter $body = $body . "<input appearance=\"ex:faims.android.INVENTORYCOUNT\" ref=\"" . $xpathPrefix . "dt{$dt_id}\">\n" . $inputDefBody . "</input>\n"; } else { //all others and $fieldtype=="geopoint" as well $body = $body . "<input ref=\"" . $xpathPrefix . "dt{$dt_id}\">\n" . $inputDefBody . "</input>\n"; } } } } if ($isRepeatable) { $body .= $groupRepeatFtr; if ($fieldsLeft > 0) { $atGroupStart = true; } } } $model = $model . "</details>\n" . "</record>\n" . "</records>\n" . "</fhml>\n" . "</instance>\n"; $body = $body . "</group>\n" . "</h:body>\n"; $form = "<?xml version=\"1.0\"?>\n" . "<h:html xmlns=\"http://www.w3.org/2002/forms\" xmlns:h=\"http://www.w3.org/1999/xhtml\" " . "xmlns:ev=\"http://www.w3.org/2001/xml-events\" " . "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " . "xmlns:jr=\"http://openrosa.org/javarosa\">\n" . "<h:head>\n" . "<h:title>{$rtName}</h:title>\n" . "<model>\n" . $model . $bind . "</model>\n" . "</h:head>\n" . $body . "</h:html>"; return array($form, $rtName, $rtConceptID, $rtDescription, $report); }
break; case 'checkDTusage': //used in editRecStructure to prevent detail type delete $rtyID = @$_REQUEST['rtyID']; $dtyID = @$_REQUEST['dtyID']; $rv = findTitleMaskEntries($rtyID, $dtyID); break; case 'deleteDetailType': case 'deleteDT': $dtyID = @$_REQUEST['dtyID']; if (!$dtyID) { $rv['error'] = "Error: No IDs or invalid IDs sent with deleteDetailType method call to saveStructure.php"; } else { $rv = deleteDetailType($dtyID); if (!array_key_exists('error', $rv)) { $rv['detailTypes'] = getAllDetailTypeStructures(); } } break; //------------------------------------------------------------ //------------------------------------------------------------ case 'saveTerms': // Terms if (!array_key_exists('terms', $data) || !array_key_exists('colNames', $data['terms']) || !array_key_exists('defs', $data['terms'])) { error_exit("Invalid data structure sent with saveTerms method call to saveStructure.php"); } $colNames = $data['terms']['colNames']; $rv['result'] = array(); //result foreach ($data['terms']['defs'] as $trmID => $dt) { $res = updateTerms($colNames, $trmID, $dt, null);
// note we use special global array $fields_correspondence - for proper conversion of remote id to concept code $res = updateTitleMask($rectypes_correspondence[$rtyID], $mask); if (!is_numeric($res)) { error_exit($res); } } } $mysqli->commit(); $mysqli->close(); // ------------------------------------------------------------------------------------------------ // Confirmation of import results if ($outputFormat == "json") { header("Content-type: text/javascript"); } else { $trg_rectypes = getAllRectypeStructures(); $trg_fieldtypes = getAllDetailTypeStructures(); $trg_terms = getTerms(); ?> <html> <head> <link rel="stylesheet" type="text/css" href="../../../common/css/global.css"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body class="popup" title="Annotated template import"> <h4>Record type and associated structures imported</h4> <hr />
function addDefaultFieldForNewRecordType($rtyID) { $dt = getAllDetailTypeStructures(); $dt = $dt['typedefs']; $rv = getAllRectypeStructures(); $dtFieldNames = $rv['typedefs']['dtFieldNames']; $di = $dt['fieldNamesToIndex']; $ri = $rv['typedefs']['dtFieldNamesToIndex']; $data = array(); $data['dtFields'] = array(DT_NAME => getInitRty($ri, $di, $dt, DT_NAME, array('required', 1, 40)), DT_SHORT_SUMMARY => getInitRty($ri, $di, $dt, DT_SHORT_SUMMARY, array('recommended', 1, 60))); updateRecStructure($dtFieldNames, $rtyID, $data); }
function renderRecordsError($imp_session) { $is_missed = false; $tabs = $imp_session['validation']['error']; if (count($tabs) > 1) { $k = 0; print '<div id="tabs_records"><ul>'; foreach ($tabs as $rec_tab) { $colname = @$imp_session['columns'][substr($rec_tab['field_checked'], 6)]; print '<li><a href="#rec__' . $k . '" style="color:red">' . $colname . '<br><span style="font-size:0.7em">' . @$rec_tab['short_message'] . '</span></a></li>'; $k++; } print '</ul>'; $k++; } $mapped_fields = $imp_session['validation']['mapped_fields']; $k = 0; foreach ($tabs as $rec_tab) { print '<div id="rec__' . $k . '">'; $k++; $cnt = $rec_tab['count_error']; $records = $rec_tab['recs_error']; if ($cnt > count($records)) { print "<div class='error'><b>Only the first " . count($records) . " of " . $cnt . " rows are shown</b></div>"; } $checked_field = $rec_tab['field_checked']; if (in_array(intval(substr($checked_field, 6)), $imp_session['multivals'])) { $ismultivalue = true; //highlight errors individually } else { $ismultivalue = false; } print "<div><span class='error'>Values in red are invalid: "; print "</span> " . $rec_tab['err_message'] . "<br/><br/></div>"; $is_missed = strpos($rec_tab['err_message'], 'a value must be supplied') > 0; if (count($records) > 25) { print '<br/><input type="button" value="Close popup" onClick="showRecords(\'mapping\');"><br/><br/>'; } //all this code only for small asterics //$recStruct = getAllRectypeStructures(true); //$recStruct = $recStruct['typedefs'][] $recordType = @$_REQUEST['sa_rectype']; if ($recordType) { $recStruc = getRectypeStructures(array($recordType)); $idx_reqtype = $recStruc['dtFieldNamesToIndex']['rst_RequirementType']; $recStruc = $recStruc[$recordType]['dtFields']; } else { $recStruc = null; } $detDefs = getAllDetailTypeStructures(true); $detLookup = $detDefs['lookups']; $detDefs = $detDefs['typedefs']; $idx_dt_type = $detDefs['fieldNamesToIndex']['dty_Type']; //find distinct terms values $is_enum = false; if (!$is_missed) { $err_col = 0; $m = 1; foreach ($mapped_fields as $field_name => $dt_id) { if ($field_name == $checked_field && @$detDefs[$dt_id]) { $err_col = $m; $dttype = $detDefs[$dt_id]['commonFields'][$idx_dt_type]; $is_enum = $dttype == 'enum' || $dttype == 'relationtype'; break; } $m++; } if ($is_enum) { $distinct_value = array(); if ($records && is_array($records)) { foreach ($records as $row) { $value = $row[$err_col]; if (!in_array($value, $distinct_value)) { array_push($distinct_value, $value); } } } if (count($distinct_value) > 0) { //print distinct term values print '<div style="display:none;padding-bottom:10px;" id="distinct_terms_' . $k . '"><br>'; foreach ($distinct_value as $value) { print '<div style="margin-left:30px;">' . $value . ' </div>'; } print '</div>'; print '<div><a href="#" onclick="{top.HEURIST.util.popupTinyElement(window, document.getElementById(\'distinct_terms_' . $k . '\'),{\'no-close\':false, \'no-titlebar\':false });}">Get list of unrecognised terms</a>' . ' (can be imported into terms tree)<br/> </div>'; } } } //end find distict terms values print '<table class="tbmain" cellspacing="0" cellpadding="2" width="100%"><thead><tr>'; // class="tbmain" print '<th width="20px">Line #</th>'; //HEADER - only error field $m = 1; $err_col = 0; foreach ($mapped_fields as $field_name => $dt_id) { if ($field_name == $checked_field) { $colname = @$imp_session['columns'][substr($field_name, 6)]; if (@$recStruc[$dt_id][$idx_reqtype] == "required") { $colname = $colname . "*"; } if ($is_enum) { $showlink = ' <a href="#" onclick="{showTermListPreview(' . $dt_id . ')}">show list of terms</a>'; } else { $showlink = ''; } $colname = "<font color='red'>" . $colname . "</font>" . '<br><font style="font-size:10px;font-weight:normal">' . (is_numeric($dt_id) ? $detLookup[$detDefs[$dt_id]['commonFields'][$idx_dt_type]] : $dt_id) . $showlink . "</font>"; if ($is_enum) { $colname = $colname . "<div id='termspreview" . $dt_id . "'></div>"; //container for } print "<th style='min-width:90px'>" . $colname . "</th>"; $err_col = $m; break; } $m++; } //raw row print '<th>Record content</th>'; print "</tr></thead>"; $import_table = $imp_session['import_table']; //BODY if ($records && is_array($records)) { foreach ($records as $row) { print "<tr>"; if (is_array($row)) { print "<td class='truncate'>" . $row[0] . "</td>"; if ($is_missed) { print "<td style='color:red'><missing></td>"; } else { if ($ismultivalue) { print "<td class='truncate'>" . @$row[$err_col] . "</td>"; } else { print "<td class='truncate' style='color:red'>" . @$row[$err_col] . "</td>"; } } // print raw content of import data $res = get_import_value($row[0], $import_table); if (is_array($res)) { $s = htmlspecialchars(implode(", ", $res)); print "<td title='" . $s . "'>" . $s . "</td>"; } else { print "<td> </td>"; } } print "</tr>"; } } print "</table>"; print "</div>"; } //tabs if (count($tabs) > 1) { print '</div>'; } print '<br /><br /><input type="button" value="Back to previous screen" onClick="showRecords(\'mapping\');">'; }
/** * simple description * detailed desription * @global type description of global variable usage in a function * @param type [$varname] description * @return type description * @link URL * @see name of another element (function or object) used in this function * @throws list of exceptions thrown in this code */ function parseImportForm($fhmlFilename, $resources) { global $xmlForms, $formImportDir, $resourceUriRoot; static $dettypes, $di, $rectypes, $ri, $rid, $terms, $ti, $termLookup, $relnLookup; if (!$dettypes || !$di) { $dettypes = getAllDetailTypeStructures(); $dettypes = $dettypes['typedefs']; $di = $dettypes['fieldNamesToIndex']; } if (!$rectypes || !$ri || !$rid) { $rectypes = getAllRectypeStructures(); $ri = $rectypes['typedefs']['commonNamesToIndex']; $rid = $rectypes['typedefs']['dtFieldNamesToIndex']; } if (!$terms || !$ti || !$termLookup || !$relnLookup) { $terms = getTerms(); $ti = $terms['fieldNamesToIndex']; $termLookup = $terms['termsByDomainLookup']['enum']; $relnLookup = $terms['termsByDomainLookup']['relation']; } $dtyIDTrans = array("15" => "327", "28" => "119", "332" => "520", "336" => "510", "337" => "511", "322" => "508", 15 => 327, 28 => 119, 332 => 520, 336 => 510, 337 => 511, 322 => 508); //Survey Unit $fhmlDoc = simplexml_load_file($xmlForms["form"][$fhmlFilename]); $header = array(); $dataRow = array(); $recType = $fhmlDoc->xpath("/fhml/records/record/type/label"); echo "processing rectype: \"" . $recType[0] . "\" from: " . $fhmlFilename . "<br>"; // echo "rectyp: ".$recType[0]."<br>"; array_push($header, "rectype"); array_push($dataRow, $recType[0]); $formID = $fhmlDoc->xpath("/fhml/@id"); // echo "nonce: ".$nonce[0]."<br>"; array_push($header, "formID"); array_push($dataRow, $formID[0]); $formVer = $fhmlDoc->xpath("/fhml/@version"); // echo "nonce: ".$nonce[0]."<br>"; array_push($header, "formVer"); array_push($dataRow, $formVer[0]); $nonce = $fhmlDoc->xpath("/fhml/records/record/nonce"); // echo "nonce: ".$nonce[0]."<br>"; array_push($header, "nonce"); array_push($dataRow, $nonce[0]); // error_log("nonce = ".print_r($nonce,true)); $database = $fhmlDoc->xpath("/fhml/database"); $database = $database[0]; $dbID = $database->attributes(); $dbID = $dbID["id"]; $dateStamp = @$fhmlDoc->xpath("/fhml/dateStamp"); $createTime = @$fhmlDoc->xpath("/fhml/createTime"); if (!@$dateStamp[0] && @$createTime[0]) { $dateStamp = $createTime; } // echo "dataStamp: ".$dateStamp[0]."<br>"; array_push($header, "dateStamp"); array_push($dataRow, $dateStamp[0]); $deviceID = $fhmlDoc->xpath("/fhml/deviceID"); array_push($header, "deviceID"); array_push($dataRow, $deviceID[0]); $details = $fhmlDoc->xpath("/fhml/records/record/details"); foreach ($details[0]->children() as $detail) { // if ("".$detail == "") continue; $attr = $detail->attributes(); $dtyID = $detail->getName(); // error_log("dtyID ".print_r($dtyID,true)); $dtyID = preg_replace("/dt/", "", $dtyID); if ($dtyID == "15" || $dtyID == "345") { $detail = findRecorder($detail); } if ($dtyID == "322" || $dtyID == "344") { $detail = findSurveyUnit($detail); } //error_log("form dtyID ".print_r($dtyID,true)); $dtyID = @$dtyIDTrans[$dtyID] ? $dtyIDTrans[$dtyID] : $dtyID; // SPECIAL FOR ZAGORA IMPORT REMOVE!!!!!!!!!!!!!!!! //error_log("detailtype $dtyID ".print_r($dettypes[intval($dtyID)]['commonFields'],true)); $dtBaseType = $dettypes[intval($dtyID)]['commonFields'][$di['dty_Type']]; $detailName = $attr["name"] ? $attr["name"] : $detail->getName(); if ($dtBaseType == "freetext" || $dtBaseType == "blocktext") { //text so enclose in quotes if (preg_match("/\"/", $detail)) { $detail = preg_replace("/\"/", "'", $detail); //strip any quotes for non string values } $detail = "\"" . $detail . "\""; } else { $detail = preg_replace("/\"/", "", $detail); //strip any quotes for non string values } $dbConceptPrefix = $dbID . "-"; error_log("basetype = " . print_r($dtBaseType, true)); if ($dtBaseType == "enum" || $dtBaseType == 'relation') { $detail = preg_replace("/{$dbConceptPrefix}/", "", $detail); } else { if ($dtBaseType == 'geo') { preg_match_all("/\\d+\\.\\d+/", $detail, $match); //error_log("match".print_r($match,true)); $detail = "POINT(" . $match[0][1] . " " . $match[0][0] . ")"; } } // error_log("attr = ".$attr["name"]); // echo "".($attr["name"] ? $attr["name"] : $detail->getName()).": ". $detail."<br>"; array_push($header, $detailName); if ("" . $detail != "" && $resourceUriRoot && ($dtyID == DT_IMAGES || $dtyID == DT_DRAWING)) { // echo "has resource $inputFormResourceDir/$detail<br>"; //error_log("Photo magic= ".DT_IMAGES." dtyID= $dtyID"); //error_log("Sketch magic= ".DT_DRAWING." dtyID= $dtyID"); if (array_key_exists($detail, $resources)) { array_push($dataRow, $resourceUriRoot . $resources[$detail]); } else { array_push($dataRow, "resource file {$detail} not found"); } } else { array_push($dataRow, $detail); } } // echo "scratchPad: ".$fhmlDoc->asXML()."<br><br>"; array_push($header, "scratchPad"); $fhmlDoc->addChild('filename', $fhmlFilename); $fhml = $fhmlDoc->asXML(); $fhml = preg_replace("/^\\<\\?xml[^\\?]+\\?\\>/", "", $fhml); $fhml = "\"" . preg_replace("/\"/", "'", $fhml) . "\""; $fhml = "\"" . preg_replace("/\\</", "<", $fhml) . "\""; $fhml = "\"" . preg_replace("/\\>/", ">", $fhml) . "\""; array_push($dataRow, $fhml); array_push($header, "importFilename"); array_push($dataRow, $fhmlFilename); // echo join(",", $header); // echo "<br>"; // echo join(",", $dataRow); // echo "<br>"; // echo "<br>"; return array($recType[0], join(",", $header), join(",", $dataRow)); }
print "<p style='color:red'><br />No proper field mapping found for record types:"; print "<br />" . implode("<br />", $mapping_rt_errors2) . '</p>'; } if (count($mapping_dt_errors) > 0) { print "<p style='color:red'><br />Issues with base field (detail) types:<br />" . implode("<br />", $mapping_dt_errors) . '</p>'; } print "<p style='color:red'>Please import them from the Heurist_Reference_Set database (# 3) using Database > Structure > From Databases</p>"; print "</div>"; } } } } } else { if ($step == '2') { //second step - sync $alldettypes = getAllDetailTypeStructures(); $allterms = getTerms(); $fi_dettype = $alldettypes['typedefs']['fieldNamesToIndex']['dty_Type']; $fi_constraint = $alldettypes['typedefs']['fieldNamesToIndex']['dty_PtrTargetRectypeIDs']; $fi_trmlabel = $allterms['fieldNamesToIndex']['trm_Label']; $report_log = ""; $unresolved_pointers = array(); // 1) start loop: fetch items by 100 $cnt_updated = 0; $cnt_added = 0; $cnt_ignored = 0; $arr_ignored = array(); $start = 0; $fetch = min($_REQUEST['cnt'], 100); $totalitems = $_REQUEST['cnt']; $new_recid = 0;
print "top.HEURIST.database.name = " . json_format(HEURIST_DBNAME) . ";\n"; print "top.HEURIST.database.sessionPrefix = " . json_format(HEURIST_SESSION_DB_PREFIX) . ";\n"; print "top.HEURIST.database.version = " . json_format(HEURIST_DBVERSION) . ";\n"; print "if (!top.HEURIST.baseURL_V3) top.HEURIST.baseURL_V3 = " . json_format(HEURIST_BASE_URL) . ";\n"; print "if (!top.HEURIST.baseURL_V4) top.HEURIST.baseURL_V4 = " . json_format(HEURIST_BASE_URL) . ";\n"; print "if (!top.HEURIST.iconDir) top.HEURIST.iconDir = " . json_format(HEURIST_ICON_DIR) . ";\n"; print "if (!top.HEURIST.iconBaseURL) top.HEURIST.iconBaseURL = top.HEURIST.baseURL_V4+ 'hserver/dbaccess/rt_icon.php?db='+top.HEURIST.database.name+'&id=';\n"; //.json_format(HEURIST_ICON_URL) . ";\n"; //print "alert(top.HEURIST.iconBaseURL);"; // $cache=true - use cache //$cache = (!array_keys(@$_REQUEST, 'cache') || @$_REQUEST['cache']=="1"); /* rectypes are an array of names sorted alphabetically, and lists of primary (bibliographic) and other rectypes, also sorted alphbetically */ print "top.HEURIST.rectypes = " . json_format(getAllRectypeStructures(true)) . ";\n"; /* detailTypes */ print "top.HEURIST.detailTypes = " . json_format(getAllDetailTypeStructures(true)) . ";\n\n"; print "\ntop.HEURIST.terms = \n" . json_format(getTerms(true), true) . ";\n"; print "\ntop.HEURIST.transforms = \n" . json_format(getTransformsByOwnerGroup(), true) . ";\n"; print "\ntop.HEURIST.tools = \n" . json_format(getToolsByTransform(), true) . ";\n"; /*print "\ntop.HEURIST.terms.termsByDomainLookup = \n" . json_format(getTerms(),true) . ";\n"; print "\ntop.HEURIST.terms.treesByDomain = { 'relation' : " . json_format(getTermTree("reltype","prefix"),true).",\n 'enum' : " . json_format(getTermTree("enum","prefix"),true)." };\n"; */ ?> top.HEURIST.ratings = {"0": "not rated", "1": "*", "2": "**", "3": "***", "4": "****",
function createMappingForm($config) { global $sourcedbname, $db_prefix, $dbPrefix, $is_h2, $password, $username; $sourcedb = $db_prefix . $sourcedbname; print "<br>\n"; print "Source database: <b>{$sourcedb}</b> <br>\n"; if ($is_h2) { $res = mysql_query("select * from `{$sourcedb}`.Users"); } else { $res = mysql_query("select * from {$sourcedb}.sysIdentification"); } if (!$res) { die("<p>Unable to open source database <b>{$sourcedb}</b>. Make sure you have included prefix"); } print "<form id='mapping' name='mappings' action='getRecordsFromDB.php' method='post'>"; print "<input id='mode' name='mode' value='5' type='hidden'>"; // calls the transfer function print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>"; print "<input name='h2' value='" . ($is_h2 ? 1 : 0) . "' type='hidden'>"; print "<input name='sourcedbname' value='{$sourcedbname}' type='hidden'>"; if (!$is_h2) { print "<input name='username' value='{$username}' type='hidden'>"; print "<input name='password' value='{$password}' type='hidden'>"; } print "<input name='reportlevel' value='1' type='checkbox' checked='checked'> Report level: show errors only<br>"; print "Check the code mappings below, then click <input type='button' value='Import data' onclick='{document.getElementById(\"mode\").value=5; document.forms[\"mappings\"].submit();}'>\n"; // alert(document.getElementById(\"mode\").value); print "<input type='button' value='Print mapping' onclick='{printMapping();}'> "; print "<input type='button' value='Save settings' onclick='{document.getElementById(\"mode\").value=3; document.forms[\"mappings\"].submit();}'>"; $filename = HEURIST_UPLOAD_DIR . "settings/importfrom_" . $sourcedbname . ".cfg"; if (file_exists($filename)) { print " <input type='submit' value='Load settings' onclick='{document.getElementById(\"mode\").value=4; document.forms[\"mappings\"].submit();}'>\n"; } print "<p><hr>\n"; // -------------------------------------------------------------------------------------------------------------------- // Get the record type mapping, by default assume that the code is unchanged so select the equivalent record type if available $allrectypes = getAllRectypeStructures(); //in current database $entnames = $allrectypes['names']; $seloptions = createOptions("or", $entnames); if ($is_h2) { $query1 = "SELECT DISTINCT `rec_type`,`rt_name`, '0' as cnt FROM `{$sourcedb}`.`records`,`{$sourcedb}`.`rec_types` where `rec_type`=`rt_id`"; } else { $query1 = "SELECT rty_ID, rty_Name, count(rec_ID) as cnt, rty_OriginatingDBID, rty_IDInOriginatingDB " . "from `{$sourcedb}`.`Records` " . "left join `{$sourcedb}`.`defRecTypes` on rec_RecTypeID=rty_ID " . "group by rty_ID"; } $res1 = mysql_query($query1); if (mysql_num_rows($res1) == 0) { die("<p><b>Sorry, there are no data records in this database, or database is bad format</b>"); } print "<h3>Record type mappings</h3>[RT code] <b>{$sourcedb}</b> (use count) ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>"; // . "<p>"; print "<table>"; while ($row1 = mysql_fetch_array($res1)) { $rt = $row1[0]; //0=rec_RecTypeID $cnt = $row1[2]; $selopts = $seloptions; $selectedId = null; $bgcolor = ""; if ($config) { $selectedId = getPresetId($config, "cbr" . $rt); } else { if (!$is_h2) { //find by concept code $selectedId = findByRtConceptCode($row1[3], $row1[4], $allrectypes); if ($selectedId) { $bgcolor = "style='background-color:#ccffcc;'"; } } if (!$selectedId) { //find the closest name $selectedId = findClosestName($row1[1], $entnames); //1=rty_Name if ($selectedId < 0) { //exact match $bgcolor = "style='background-color:#ccc;'"; $selectedId = -$selectedId; } } } if ($selectedId) { $repl = "value='" . $selectedId . "'"; $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts); } print "<tr {$bgcolor}><td><label id='lblr{$rt}'>[ {$rt} ] " . $row1[1] . ($is_h2 ? "" : "({$cnt}) ") . "</label></td>" . "<td>==> <select id='cbr{$rt}' name='cbr{$rt}' class='rectypes'><option id='or0' value='0'></option>" . $selopts . "</select></td></tr>\n"; } // loop through record types print "</table>"; // -------------------------------------------------------------------------------------------------------------------- // Get the field type mapping, by default assume that the code is unchanged so select the equivalent detail type if available //create the string for combobox $alldettypes = getAllDetailTypeStructures(); //in current database $entnames = $alldettypes['names']; $seloptions = createOptionsDt($alldettypes); print "<h3>Field type mappings</h3>[FT code] <b>{$sourcedb}</b> ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>"; // . "<p>"; if ($is_h2) { $query1 = "SELECT DISTINCT `rd_type`,`rdt_name`,`rdt_type` FROM `{$sourcedb}`.`rec_details`,`{$sourcedb}`.`rec_detail_types` " . "where `rd_type`=`rdt_id`"; } else { $query1 = "SELECT DISTINCT `dtl_DetailTypeID`,`dty_Name`,`dty_Type`,`dty_OriginatingDBID`,`dty_IDInOriginatingDB` FROM `{$sourcedb}`.`recDetails`,`{$sourcedb}`.`defDetailTypes` " . "where `dtl_DetailTypeID`=`dty_ID`"; } $res1 = mysql_query($query1); print "<table>"; while ($row1 = mysql_fetch_array($res1)) { $ft = $row1[0]; //0=dtl_DetailTypeID $selopts = $seloptions; $bgcolor = ""; $selectedId = null; //find the closest name if ($config) { $selectedId = getPresetId($config, "cbd" . $ft); } else { if (!$is_h2) { //find by concept code $selectedId = findByDtConceptCode($row1[3], $row1[4], $alldettypes); if ($selectedId) { $bgcolor = "style='background-color:#ccffcc;'"; } } if (!$selectedId) { //find the closest name $selectedId = findClosestName($row1[1], $entnames); //dty_Name if ($selectedId < 0) { //exact match $bgcolor = "style='background-color:#ccc;'"; $selectedId = -$selectedId; } } } if ($selectedId) { $repl = "value='" . $selectedId . "'"; $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts); } print "<tr {$bgcolor}><td><label id='lbld{$ft}'>[ {$ft} - " . $row1[2] . " ] " . $row1[1] . "</label></td>" . "<td>==> <select id='cbd{$ft}' name='cbd{$ft}' class='detailTypes'><option id='od0' value='0'></option>" . $selopts . "</select></td></tr>\n"; } // loop through field types print "</table>"; // -------------------------------------------------------------------------------------------------------------------- createTermsOptions($config, 'enum'); createTermsOptions($config, 'relation'); print "</form>"; }
/*art 2014-02-24 if($rt_toexport){ print "<script>showSelectedRecTypes('".$rt_toexport."')</script>"; }*/ if ($rt_toexport && count($rt_toexport) > 0 && !$invalid) { $folder = HEURIST_FILESTORE_DIR . "faims/new/" . $projname; //create export folder if (!file_exists($folder)) { if (!mkdir($folder, 0777, true)) { die('Failed to create folder for ' . $folder . ' - check that file permissions are correctly set'); } } else { //clear folder delFolderTree($folder, false); } //load definitions (USE CACHE) $dtStructs = getAllDetailTypeStructures(false); $dtTerms = getTerms(false); $ind_parentid = $dtTerms['fieldNamesToIndex']['trm_ParentTermID']; $ind_label = $dtTerms['fieldNamesToIndex']['trm_Label']; $ind_descr = $dtTerms['fieldNamesToIndex']['trm_Description']; // $unsupported was original specification, but this will stuff up if new types are added $supported = array('freetext', 'blocktext', 'integer', 'date', 'year', 'boolean', 'enum', 'float', 'file', 'resource'); //$unsupported = array('relmarker','relationtype','separator','calculated','fieldsetmarker','urlinclude','geo'); // Note: Geos are supported, but FAIMS uses a different methodology for recording them, that is they are an implicit part of every record $content_a16n = null; //file_put_contents($folder."/project.settings", $projname." and basic information 3"); file_put_contents($folder . "/data_schema.xml", generateSchema($projname, $rt_toexport, $rt_geoenabled)); file_put_contents($folder . "/ui_schema.xml", generate_UI_Schema($projname, $rt_toexport, $rt_geoenabled)); file_put_contents($folder . "/arch16N.properties", arrToProps()); file_put_contents($folder . "/ui_logic.bsh", generate_Logic($projname, $rt_toexport, $rt_toexport_toplevel, $rt_geoenabled)); file_put_contents($folder . "/style.css", getStyling());
* @author Artem Osmakov * @version 2011.0819 * @package Heurist academic knowledge management system * @todo **/ define('SEARCH_VERSION', 1); require_once dirname(__FILE__) . '/../../common/config/initialise.php'; require_once dirname(__FILE__) . '/../../common/php/dbMySqlWrappers.php'; require_once dirname(__FILE__) . '/../../search/getSearchResults.php'; require_once dirname(__FILE__) . '/../../common/php/getRecordInfoLibrary.php'; require_once 'libs.inc.php'; mysql_connection_overwrite(DATABASE); //was mysql_connection_select(DATABASE); //load definitions (USE CACHE) $rtStructs = getAllRectypeStructures(true); $dtStructs = getAllDetailTypeStructures(true); $dtTerms = getTerms(true); $recursion_depth = 0; $first_record = null; //to obtain names of record header fields $resVars = array(); $resVarsByType = array(); $mode = @$_REQUEST['mode']; if ($mode == 'varsonly') { $rectypeID = @$_REQUEST['rty_id']; $res0 = getRecordHeaderSectionForSmarty(null, 'r', 0); //from $resVars = array_merge($resVars, $res0['vars']); /* array_push($resVarsByType, array("id"=>"0", "name"=>"common",
/** * Main function * * @param mixed $_REQUEST */ function executeSmartyTemplate($params) { global $smarty, $outputfile, $isJSout, $rtStructs, $dtStructs, $dtTerms, $gparams; mysql_connection_overwrite(DATABASE); //AO: mysql_connection_select - does not work since there is no access to stored procedures(getTemporalDateString) Steve uses in some query //TODO SAW grant ROuser EXECUTE on getTemporalDate and any other readonly procs //load definitions (USE CACHE) $rtStructs = getAllRectypeStructures(true); $dtStructs = getAllDetailTypeStructures(true); $dtTerms = getTerms(true); $params["f"] = 1; //always search (do not use cache) $isJSout = array_key_exists("mode", $params) && $params["mode"] == "js"; //use javascript wrap $outputfile = array_key_exists("output", $params) ? $params["output"] : null; $publishmode = array_key_exists("publish", $params) ? intval($params['publish']) : 0; $gparams = $params; //keep to use in other functions if (!array_key_exists("limit", $params)) { //not defined $limit = intval(@$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']["display-preferences"]['report-output-limit']); if (!$limit || $limit < 1) { $limit = 1000; //default limit in dispPreferences } $params["limit"] = $limit; //force limit } $qresult = loadSearch($params); //from search/getSearchResults.php - loads array of records based og GET request /*****DEBUG****/ //error_log(print_r($qresult,true)); if (!array_key_exists('records', $qresult) || $qresult['resultCount'] == 0) { if ($publishmode > 0) { $error = "<b><font color='#ff0000'>Note: There are no records in this view. The URL will only show records to which the viewer has access. Unless you are logged in to the database, you can only see records which are marked as Public visibility</font></b>"; } else { $error = "<b><font color='#ff0000'>Search or Select records to see template output</font></b>"; } if ($isJSout) { $error = add_javascript_wrap4($error, null); } echo $error; if ($publishmode > 0 && $outputfile != null) { //save empty outpurt inot file save_report_output2("<div style=\"padding:20px;font-size:110%\">Currently there are no results</div>"); } exit; } //get name of template file $template_file = array_key_exists('template', $params) ? $params['template'] : null; //get template body from request (for execution from editor) $template_body = array_key_exists('template_body', $params) ? $params['template_body'] : null; //convert to array that will assigned to smarty variable $records = $qresult["records"]; $results = array(); $k = 0; foreach ($records as $rec) { $res1 = getRecordForSmarty($rec, 0, $k); $k++; array_push($results, $res1); } //activate default template - generic list of records $smarty->assign('results', $results); ini_set('display_errors', 'false'); // 'stdout' ); $smarty->error_reporting = 0; if ($template_body) { //execute template from string - modified temoplate in editor /*****DEBUG****/ //error_log(">>>".$template_body."<<<"); /*****DEBUG****/ //error_log(">>>>>>>".$replevel."<<<<<<"); //error report level: 1 notices, 2 all, 3 debug mode $replevel = array_key_exists('replevel', $params) ? $params['replevel'] : 0; if ($replevel == "1" || $replevel == "2") { ini_set('display_errors', 'true'); // 'stdout' ); $smarty->debugging = false; if ($replevel == "2") { $smarty->error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE; } else { $smarty->error_reporting = E_NOTICE; } } else { $smarty->debugging = $replevel == "3"; } $smarty->debug_tpl = dirname(__FILE__) . '/debug_html.tpl'; //save temporary template //this is user name $template_file = "_temp.tpl"; $template_file = "_" . get_user_username() . ".tpl"; $file = fopen($smarty->template_dir . $template_file, "w"); fwrite($file, $template_body); fclose($file); //$smarty->display('string:'.$template_body); } else { // usual way - from file if (!$template_file) { $template_file = 'test01.tpl'; } $smarty->debugging = false; $smarty->error_reporting = 0; if ($outputfile != null) { $smarty->registerFilter('output', 'save_report_output'); } else { if ($isJSout) { $smarty->registerFilter('output', 'add_javascript_wrap5'); } } //$smarty->unregisterFilter('post','add_javascript_wrap'); } try { $smarty->display($template_file); } catch (Exception $e) { echo 'Exception on execution: ', $e->getMessage(), "\n"; } //$tpl_vars = $smarty->get_template_vars(); //var_dump($tpl_vars); //DEBUG stuff //@todo - return the list of record types - to obtain the applicable templates //echo "query result = ".print_r($qresult,true)."\n"; //header("Content-type: text/javascript"); //header('Content-type: text/html; charset=utf-8'); //echo json_format( $qresult, true); //echo "<br/>***<br/>"; //echo json_format( $results, true); //END DEBUG stuff }