function rollRecordBack($rec_id, $changes) { if (count($changes["updates"]) == 0 && count($changes["inserts"]) == 0 && count($changes["deletes"]) == 0) { return true; } mysql_query("start transaction"); mysql_query("update Records set rec_Modified = now() where rec_ID = {$rec_id}"); if (mysql_error()) { mysql_query("rollback"); return false; } foreach ($changes["updates"] as $update) { $rd_id = $update["ard_ID"]; $rd_val = $update["ard_Value"] ? "'" . mysql_real_escape_string($update["ard_Value"]) . "'" : "null"; $rd_file_id = $update["ard_UploadedFileID"] ? $update["ard_UploadedFileID"] : "null"; $rd_geo = $update["ard_Geo"] ? "geomfromtext('" . $update["ard_Geo"] . "')" : "null"; mysql_query("\n\t\t\tupdate recDetails\n\t\t\tset dtl_Value = {$rd_val}, dtl_UploadedFileID = {$rd_file_id}, dtl_Geo = {$rd_geo}\n\t\t\twhere dtl_RecID = {$rec_id}\n\t\t\tand dtl_ID = {$rd_id}\n\t\t"); if (mysql_error()) { mysql_query("rollback"); return false; } } foreach ($changes["inserts"] as $insert) { $rd_id = $insert["ard_ID"]; $rd_type = $insert["ard_DetailTypeID"]; $rd_val = $insert["ard_Value"] ? "'" . mysql_real_escape_string($insert["ard_Value"]) . "'" : "null"; $rd_file_id = $insert["ard_UploadedFileID"] ? $insert["ard_UploadedFileID"] : "null"; $rd_geo = $insert["ard_Geo"] ? "geomfromtext('" . $insert["ard_Geo"] . "')" : "null"; mysql_query("\n\t\t\tinsert into recDetails (dtl_RecID, dtl_DetailTypeID, dtl_Value, dtl_UploadedFileID, dtl_Geo)\n\t\t\tvalues ({$rec_id}, {$rd_type}, {$rd_val}, {$rd_file_id}, {$rd_geo})\n\t\t"); if (mysql_error()) { mysql_query("rollback"); return false; } } foreach ($changes["deletes"] as $ard_id) { mysql_query("delete from recDetails where dtl_ID = {$ard_id}"); if (mysql_error()) { mysql_query("rollback"); return false; } } // update record title if necessary $res = mysql_query("\n\t\tselect rec_RecTypeID, rty_TitleMask\n\t\tfrom Records, defRecTypes\n\t\twhere rec_ID = {$rec_id}\n\t\tand rty_ID = rec_RecTypeID\n\t"); if ($res) { $row = mysql_fetch_row($res); if ($row) { $title = fill_title_mask($row[1], $rec_id, $row[0]); if ($title) { mysql_query("set @suppress_update_trigger := 1"); mysql_query("update Records set rec_Title = '" . mysql_real_escape_string($title) . "' where rec_ID = {$rec_id}"); if (mysql_error()) { mysql_query("rollback"); mysql_query("set @suppress_update_trigger := NULL"); return false; } mysql_query("set @suppress_update_trigger := NULL"); } } } mysql_query("commit"); updateCachedRecord($rec_id); return true; }
function saveRecord($recordID, $rectype, $url, $notes, $wg, $vis, $personalised, $pnotes, $rating, $tags, $wgTags, $details, $notifyREMOVE, $notifyADD, $commentREMOVE, $commentMOD, $commentADD, &$nonces = null, &$retitleRecs = null, $modeImport = 0) { global $msgInfoSaveRec; $msgInfoSaveRec = array(); // reset the message array mysql_query("start transaction"); // $log = " saving record ($recordID) "; $recordID = intval($recordID); $wg = intval($wg); if ($wg || !is_logged_in()) { // non-member saves are not allowed $res = mysql_query("select * from " . USERS_DATABASE . ".sysUsrGrpLinks where ugl_UserID=" . get_user_id() . " and ugl_GroupID=" . $wg); if (mysql_num_rows($res) < 1) { errSaveRec("invalid workgroup, record save aborted"); return $msgInfoSaveRec; } } $rectype = intval($rectype); if ($recordID && !$rectype) { errSaveRec("cannot change existing record to private note, record save aborted"); return $msgInfoSaveRec; } if ($vis && !in_array(strtolower($vis), array('hidden', 'viewable', 'pending', 'public'))) { $vis = null; } $now = date('Y-m-d H:i:s'); // public records data if (!$recordID) { // $log .= "- inserting record "; mysql__insert("Records", array("rec_RecTypeID" => $rectype, "rec_URL" => $url, "rec_ScratchPad" => $notes, "rec_OwnerUGrpID" => $wg || $wg == 0 ? $wg : get_user_id(), "rec_NonOwnerVisibility" => $vis ? $vis : "viewable", "rec_AddedByUGrpID" => get_user_id(), "rec_Added" => $now, "rec_Modified" => $now, "rec_AddedByImport" => $modeImport > 0 ? 1 : 0)); if (mysql_error()) { errSaveRec("database record insert error - " . mysql_error()); return $msgInfoSaveRec; } $recordID = mysql_insert_id(); } else { $res = mysql_query("select * from Records left join " . USERS_DATABASE . ".sysUsrGrpLinks on ugl_GroupID=rec_OwnerUGrpID and ugl_UserID=" . get_user_id() . " where rec_ID={$recordID}"); $record = mysql_fetch_assoc($res); if ($wg != $record["rec_OwnerUGrpID"] && $record["rec_OwnerUGrpID"] != get_user_id()) { if ($record["rec_OwnerUGrpID"] > 0 && $record["ugl_Role"] != "admin") { // user is trying to change the workgroup when they are not an admin errSaveRec("user is not a workgroup admin"); return $msgInfoSaveRec; } else { if (!is_admin()) { // you must be an database admin to change a public record into a workgroup record errSaveRec("user does not have sufficient authority to change public record to workgroup record"); return $msgInfoSaveRec; } } } // $log .= "- updating record "; mysql__update("Records", "rec_ID={$recordID}", array("rec_RecTypeID" => $rectype, "rec_URL" => $url, "rec_ScratchPad" => $notes, "rec_OwnerUGrpID" => $wg || $wg == 0 ? $wg : get_user_id(), "rec_NonOwnerVisibility" => $vis ? $vis : "viewable", "rec_FlagTemporary" => 0, "rec_Modified" => $now)); if (mysql_error()) { errSaveRec("database record update error - " . mysql_error()); return $msgInfoSaveRec; } } // public recDetails data if ($details) { // $log .= "- inserting details "; $dtlIDsByAction = doDetailInsertion($recordID, $details, $rectype, $wg, $nonces, $retitleRecs, $modeImport); if (@$dtlIDsByAction['error']) { array_push($msgInfoSaveRec['error'], $dtlIDsByAction['error']); return $msgInfoSaveRec; } } // check that all the required fields are present $res = mysql_query("select rst_ID, rst_DetailTypeID, rst_DisplayName" . " from defRecStructure" . " left join recDetails on dtl_RecID={$recordID} and rst_DetailTypeID=dtl_DetailTypeID" . " where rst_RecTypeID={$rectype} and rst_RequirementType='required' and dtl_ID is null"); if (mysql_num_rows($res) > 0) { // $log .= "- testing missing detatils "; $missed = ""; while ($row = mysql_fetch_row($res)) { $missed = $missed . $row[2] . " "; } /*****DEBUG****/ //error_log("MISSED ".$missed); // at least one missing field if ($modeImport == 2) { warnSaveRec("record is missing required field(s): " . $missed); } else { errSaveRec("record is missing required field(s): " . $missed); return $msgInfoSaveRec; } } mysql_query("commit"); // if we get to here we have a valid save of the core record. // calculate title, do an update // $log .= "- filling titlemask "; $mask = mysql__select_array("defRecTypes", "rty_TitleMask", "rty_ID={$rectype}"); $mask = $mask[0]; $title = fill_title_mask($mask, $recordID, $rectype); /*****DEBUG****/ //error_log("DEBUG >>>>>>MASK=".$mask."=".$title); if ($title) { mysql_query("update Records set rec_Title = '" . addslashes($title) . "' where rec_ID = {$recordID}"); } // Update memcache: we can do this here since it's only the public data that we cache. updateCachedRecord($recordID); // private data $bkmk = @mysql_fetch_row(mysql_query("select bkm_ID from usrBookmarks where bkm_UGrpID=" . get_user_id() . " and bkm_recID=" . $recordID)); $bkm_ID = @$bkmk[0]; if ($personalised) { if (!$bkm_ID) { // Record is not yet bookmarked, but we want it to be mysql_query("insert into usrBookmarks (bkm_Added,bkm_Modified,bkm_UGrpID,bkm_recID) values (now(),now()," . get_user_id() . ",{$recordID})"); if (mysql_error()) { warnSaveRec("trying to create a bookmark - database error - " . mysql_error()); } else { $bkm_ID = mysql_insert_id(); } } // $log .= "- updating bookmark "; mysql__update("usrBookmarks", "bkm_ID={$bkm_ID}", array("bkm_Rating" => $rating, "bkm_Modified" => date('Y-m-d H:i:s'))); //WARNING tags is assumed to be a complete replacement list for personal tags on this record. doTagInsertion($recordID, $bkm_ID, $tags); } else { if ($bkm_ID) { // Record is bookmarked, but the user doesn't want it to be // $log .= "- deleting bookmark "; $query = "delete usrBookmarks, usrRecTagLinks " . "from usrBookmarks left join usrRecTagLinks on rtl_RecID = bkm_recID " . "left join usrTags on tag_ID = rtl_TagID " . "where bkm_ID={$bkm_ID} and bkm_recID={$recordID} and bkm_UGrpID = tag_UGrpID and bkm_UGrpID=" . get_user_id(); /*****DEBUG****/ //error_log("saveRecord delete bkmk - q = $query"); mysql_query($query); if (mysql_error()) { warnSaveRec("database error while removing bookmark- " . mysql_error()); } //saw TODO: add code to remove other personal data reminders, personal notes (woots), etc. } } doWgTagInsertion($recordID, $wgTags); if ($notifyREMOVE || $notifyADD) { $notifyIDs = handleNotifications($recordID, $notifyREMOVE, $notifyADD); } if ($commentREMOVE || $commentMOD || $commentADD) { $commentIDs = handleComments($recordID, $commentREMOVE, $commentMOD, $commentADD); } $rval = array("bibID" => $recordID, "bkmkID" => $bkm_ID, "modified" => $now); if ($title) { $rval["title"] = $title; } if (@$dtlIDsByAction) { $rval["detail"] = $dtlIDsByAction; } if (@$notifyIDs) { $rval["notify"] = $notifyIDs; } if (@$commentIDs) { $rval["comment"] = $commentIDs; } if (@$msgInfoSaveRec['warning']) { $rval["warning"] = $msgInfoSaveRec['warning']; } if (@$msgInfoSaveRec['error']) { //should never get here with error set $rval["error"] = $msgInfoSaveRec['error']; } else { //$rval["usageCount"] = updateRecTypeUsageCount(); } /*****DEBUG****/ //error_log($log); return $rval; }
function merge_new_biblio_data($master_biblio_id, &$entry) { global $session_data; $master_biblio_id = intval($master_biblio_id); $existingFields = array(); $bib_ids = array($master_biblio_id); while ($rec_id = array_pop($bib_ids)) { $res = mysql_query("select dtl_DetailTypeID, dtl_Value, dty_Type from recDetails left join defDetailTypes on dty_ID=dtl_DetailTypeID where dtl_RecID = " . intval($rec_id)); while ($bd = mysql_fetch_assoc($res)) { if ($bd["dty_Type"] === "resource") { if ($bd["dtl_DetailTypeID"] !== 158) { array_push($bib_ids, $bd["dtl_Value"]); } //MAGIC NUMBER// also pull in fields from non-author related fields } else { $existingFields[$bd["dtl_DetailTypeID"] . "-" . trim(strtolower($bd["dtl_Value"]))] = 1; } } } $res = mysql_query("select rec_ScratchPad from Records where rec_ID = " . $master_biblio_id); $notesString = mysql_fetch_row($res); $notesString = $notesString[0]; $notes = array(); foreach (explode("\n", $notesString) as $line) { $notes[trim(strtolower($line))] = 1; } $fields =& $entry->getFields(); $extraNotesString = ""; $newFields = array(); foreach (array_keys($fields) as $i) { if (!$fields[$i]->getValue()) { continue; } if (!$fields[$i]->getType()) { // add type-less data to the notes field foreach (explode("\n", $fields[$i]->getRawValue()) as $line) { if (!@$notes[trim(strtolower($line))]) { if ($extraNotesString) { $extraNotesString .= "\n"; } $extraNotesString .= $line; $notes[trim(strtolower($line))] = 1; } } } else { if ($fields[$i]->getGeographicValue()) { $newFields[] =& $fields[$i]; } else { if ($fields[$i]->getType() != 158) { //MAGIC NUMBER // add typed data, if it doesn't exist exactly already if (!@$existingFields[$fields[$i]->getType() . "-" . trim(strtolower($fields[$i]->getRawValue()))]) { $newFields[] =& $fields[$i]; $existingFields[$fields[$i]->getType() . "-" . trim(strtolower($fields[$i]->getRawValue()))] = 1; } } } } } if ($extraNotesString) { $newNotesString = '[' . str_replace('parser', 'import', $session_data['parser']->parserDescription()) . ', ' . $session_data['import_time'] . ', from file: ' . $session_data['in_filename'] . ', by user: '******']' . "\n" . $extraNotesString; if ($notesString) { $newNotesString = $notesString . "\n" . $newNotesString; } mysql_query("update Records set rec_Modified=now(), rec_ScratchPad='" . mysql_real_escape_string($newNotesString) . "' where rec_ID=" . $master_biblio_id); } else { if (count($newFields) > 0) { mysql_query("update Records set rec_Modified=now() where rec_ID=" . $master_biblio_id); } else { // nothing to do! return; } } // insert missing fields $insertStmt = ""; foreach (array_keys($newFields) as $i) { if ($newFields[$i]->getGeographicValue()) { // delete existing geos mysql_query("delete from recDetails where dtl_RecID = {$master_biblio_id} and dtl_DetailTypeID = " . $newFields[$i]->getType()); if ($insertStmt) { $insertStmt .= ', '; } $insertStmt .= "(" . $master_biblio_id . "," . $newFields[$i]->getType() . ",'" . mysql_real_escape_string($newFields[$i]->getValue()) . "',geomfromtext('" . mysql_real_escape_string($newFields[$i]->getGeographicValue()) . "'), 1)"; } else { if ($insertStmt) { $insertStmt .= ","; } $insertStmt .= "(" . $master_biblio_id . "," . $newFields[$i]->getType() . ",'" . mysql_real_escape_string($newFields[$i]->getRawValue()) . "', NULL, 1)"; } } $insertStmt = "insert into recDetails (dtl_RecID, dtl_DetailTypeID, dtl_Value, dtl_Geo, dtl_AddedByImport) values " . $insertStmt; mysql_query($insertStmt); // update the memcached copy of this record updateCachedRecord($master_bib_id); }
/** * Main method that parses POST and update details for given record ID * * @param int $recID */ function updateRecord($recID, $rtyID = null) { // Update the given record. // This is non-trivial: so that the versioning stuff (achive_*) works properly // we need to separate this into updates, inserts and deletes. // We get the currect record details and compare them against the post // if the details id is in the post[dtyID][dtlID] then compare the values $recID = intval($recID); // Check that the user has permissions to edit it. $res = mysql_query("select * from Records" . " left join sysUsrGrpLinks on ugl_GroupID=rec_OwnerUGrpID" . " left join defRecTypes on rty_ID=rec_RecTypeID" . " where rec_ID={$recID} and (! rec_OwnerUGrpID or rec_OwnerUGrpID=" . get_user_id() . " or ugl_UserID=" . get_user_id() . ")"); if (mysql_num_rows($res) == 0) { $res = mysql_query("select grp.ugr_Name from Records, " . USERS_DATABASE . ".sysUGrps grp where rec_ID={$recID} and grp.ugr_ID=rec_OwnerUGrpID"); $grpName = mysql_fetch_row($res); $grpName = $grpName[0]; print '({ error: "\\nSorry - you can\'t edit this record.\\nYou aren\'t in the ' . slash($grpName) . ' workgroup" })'; return; } $record = mysql_fetch_assoc($res); /*****DEBUG****/ error_log("save record dtls POST " . print_r($_POST, true)); // Upload any files submitted ... (doesn't have to take place right now, but may as well) uploadFiles(); //Artem: it does not work here - since we uploaded files at once // Get the existing records details and compare them to the incoming data $recDetails = getRecordDetails($recID); // find UPDATES - everything that is in current record and has a post value is treated as an update $recDetailUpdates = array(); /*****DEBUG****/ //error_log("save record dtls ".print_r($recDetails,true)); foreach ($recDetails as $dtyID => $dtlIDs) { $eltName = "type:" . $dtyID; if (!(@$_POST[$eltName] && is_array($_POST[$eltName]))) { // element wasn't in POST: ignore it -this could be a non-rectype detail unset($recDetails[$dtyID]); // remove from details so it's not deleted continue; } if (count($_POST[$eltName]) == 0) { // element was in POST but without content: values have been deleted client-side (need to be deleted in DB so leave POST) continue; } $bdInputHandler = getInputHandlerForType($dtyID); //returns the particular handler (processor) for given field type foreach ($dtlIDs as $dtlID => $val) { /*****DEBUG****/ //error_log(" in saveRecord details loop $dtyID, $dtlID, ".print_r($val,true)); $eltID = "bd:" . $dtlID; $val = @$_POST[$eltName][$eltID]; if (!$bdInputHandler->inputOK($val, $dtyID, $rtyID)) { /*****DEBUG****/ //error_log(" in saveRecord update details value check error $dtyID, $dtlID, ".print_r($val,true)); continue; // faulty input ... ignore } $toadd = $bdInputHandler->convertPostToMysql($val); /*****DEBUG****/ //error_log(" in saveRecord update details value converted from $val to $toadd"); if ($toadd == null) { continue; } $recDetailUpdates[$dtlID] = $toadd; $recDetailUpdates[$dtlID]["dtl_DetailTypeID"] = $dtyID; /* @TODO Since this function is utilized in (email)import we need to add verification of values according to detail type at the first for terms (enumeration field type) */ unset($_POST[$eltName][$eltID]); // remove data from post submission if (count($_POST[$eltName]) == 0) { // if nothing left in post dtyID then remove it also unset($_POST[$eltName]); } unset($recDetails[$dtyID][$dtlID]); // remove data from local reflection of the database } } /*****DEBUG****/ //error_log("save record dtls POST after updates removed ".print_r($_POST,true)); /*****DEBUG****/ //error_log("save record dtls after updates removed ".print_r($recDetails,true)); // find DELETES // Anything left in recDetails now represents recDetails rows that need to be deleted $bibDetailDeletes = array(); foreach ($recDetails as $dtyID => $dtlIDs) { foreach ($dtlIDs as $dtlID => $val) { array_push($bibDetailDeletes, $dtlID); } } // find INSERTS // Try to insert anything left in POST as new recDetails rows $bibDetailInserts = array(); /*****DEBUG****/ error_log(" in saveRecord checking for inserts _POST =" . print_r($_POST, true)); foreach ($_POST as $eltName => $bds) { // if not properly formatted or empty or an empty array then skip it if (!preg_match("/^type:\\d+\$/", $eltName) || !$_POST[$eltName] || count($_POST[$eltName]) == 0) { continue; } $dtyID = substr($eltName, 5); $bdInputHandler = getInputHandlerForType($dtyID); foreach ($bds as $eltID => $val) { if (!$bdInputHandler->inputOK($val, $dtyID, $rtyID)) { /*****DEBUG****/ //error_log(" in saveRecord insert details value check error for $eltName, $eltID, ".print_r($val,true)); continue; // faulty input ... ignore } $newBibDetail = $bdInputHandler->convertPostToMysql($val); $newBibDetail["dtl_DetailTypeID"] = $dtyID; $newBibDetail["dtl_RecID"] = $recID; /*****DEBUG****/ //error_log("new detail ".print_r($newBibDetail,true)); array_push($bibDetailInserts, $newBibDetail); unset($_POST[$eltName][$eltID]); // remove data from post submission } } // Anything left in POST now is stuff that we have no intention of inserting ... ignore it // We now have: // - $recDetailUpdates: an assoc. array of dtl_ID => column values to be updated in recDetails // - $bibDetailInserts: an array of column values to be inserted into recDetails // - $bibDetailDeletes: an array of dtl_ID values corresponding to rows to be deleted from recDetails // Commence versioning ... mysql_query("start transaction"); $recUpdates = array("rec_Modified" => array("now()"), "rec_FlagTemporary" => 0); $recUpdates["rec_ScratchPad"] = $_POST["notes"]; if (intval(@$_POST["rectype"])) { $recUpdates["rec_RecTypeID"] = intval($_POST["rectype"]); } if (array_key_exists("rec_url", $_POST)) { $recUpdates["rec_URL"] = $_POST["rec_url"]; } $owner = $record['rec_OwnerUGrpID']; if (is_admin() || is_admin('group', $owner) || $owner == get_user_id()) { // must be grpAdmin or record owner to changes ownership or visibility if (array_key_exists("rec_owner", $_POST)) { $recUpdates["rec_OwnerUGrpID"] = $_POST["rec_owner"]; } if (array_key_exists("rec_visibility", $_POST)) { $recUpdates["rec_NonOwnerVisibility"] = $_POST["rec_visibility"]; } else { if ($record['rec_NonOwnerVisibility'] == 'public' && HEURIST_PUBLIC_TO_PENDING) { $recUpdates["rec_NonOwnerVisibility"] = 'pending'; } } } /*****DEBUG****/ error_log(" in saveRecord update recUpdates = " . print_r($recUpdates, true)); mysql__update("Records", "rec_ID={$recID}", $recUpdates); $biblioUpdated = mysql_affected_rows() > 0 ? true : false; if (mysql_error()) { error_log("error rec update" . mysql_error()); } $updatedRowCount = 0; foreach ($recDetailUpdates as $bdID => $vals) { /*****DEBUG****/ error_log(" in saveRecord update details dtl_ID = {$bdID} value =" . print_r($vals, true)); mysql__update("recDetails", "dtl_ID={$bdID} and dtl_RecID={$recID}", $vals); if (mysql_affected_rows() > 0) { ++$updatedRowCount; } } if (mysql_error()) { error_log("error detail updates" . mysql_error()); } $insertedRowCount = 0; foreach ($bibDetailInserts as $vals) { /*****DEBUG****/ error_log(" in saveRecord insert details detail =" . print_r($vals, true)); mysql__insert("recDetails", $vals); if (mysql_affected_rows() > 0) { ++$insertedRowCount; } } if (mysql_error()) { error_log("error detail inserts" . mysql_error()); } $deletedRowCount = 0; if ($bibDetailDeletes) { /*****DEBUG****/ error_log(" in saveRecord delete details " . print_r($bibDetailDeletes, true)); mysql_query("delete from recDetails where dtl_ID in (" . join($bibDetailDeletes, ",") . ") and dtl_RecID={$recID}"); if (mysql_affected_rows() > 0) { $deletedRowCount = mysql_affected_rows(); } } if (mysql_error()) { error_log("error detail deletes" . mysql_error()); } // eliminate any duplicated lines $notesIn = explode("\n", str_replace("\r", "", $_POST["notes"])); $notesOut = ""; $notesMap = array(); for ($i = 0; $i < count($notesIn); ++$i) { if (!@$notesMap[$notesIn[$i]] || !$notesIn[$i]) { // preserve blank lines $notesOut .= $notesIn[$i] . "\n"; $notesMap[$notesIn[$i]] = true; } } $_POST["notes"] = preg_replace("/\n\n+/", "\n", $notesOut); if ($updatedRowCount > 0 || $insertedRowCount > 0 || $deletedRowCount > 0 || $biblioUpdated) { /* something changed: update the records title and commit all changes */ $title_check = check_title_mask2($record["rty_TitleMask"], $record["rec_RecTypeID"], true); if ($title_check != '') { $new_title = "Please go to Designer View > Essentials > Record types/fields and edit the title mask for this record type"; } else { $new_title = fill_title_mask($record["rty_TitleMask"], $record["rec_ID"], $record["rec_RecTypeID"]); } mysql_query("update Records\n set rec_Title = '" . addslashes($new_title) . "'\n where rec_ID = {$recID}"); mysql_query("commit"); // Update memcached's copy of record (if it is cached) updateCachedRecord($recID); return true; } else { /* nothing changed: rollback the transaction so we don't get false versioning */ mysql_query("rollback"); return false; } }
function saveRecord($recordID, $rectype, $url, $notes, $wg, $vis, $personalised, $pnotes, $rating, $tags, $wgTags, $details, $notifyREMOVE, $notifyADD, $commentREMOVE, $commentMOD, $commentADD, &$nonces = null, &$retitleRecs = null, $modeImport = 0) { global $msgInfoSaveRec; $msgInfoSaveRec = array(); // reset the message array mysql_query("start transaction"); // $log = " saving record ($recordID) "; $recordID = intval($recordID); $wg = intval($wg); if (!is_logged_in()) { errSaveRec("It is not possible to save record if not logged in, record save aborted"); return $msgInfoSaveRec; } else { if ($wg != null && intval($wg) > 0 && intval($wg) != get_user_id()) { // non-member saves are not allowed $uquery = "select * from " . USERS_DATABASE . ".sysUsrGrpLinks where ugl_UserID=" . get_user_id() . " and ugl_GroupID=" . $wg; $res = mysql_query($uquery); if (mysql_num_rows($res) < 1) { errSaveRec("Current user " . get_user_id() . " is not a member of required workgroup " . $wg . ", record save aborted "); return $msgInfoSaveRec; } } } $rectype = intval($rectype); if ($recordID && !$rectype) { errSaveRec("cannot change existing record to private note, record save aborted"); return $msgInfoSaveRec; } $rectypeName = null; $res = mysql_query("select rty_Name from defRecTypes where rty_ID=" . $rectype); if ($res) { $row = mysql_fetch_row($res); if ($row) { $rectypeName = $row[0]; } } if (!$rectypeName) { errSaveRec("record type #{$rectype} is not valid"); return $msgInfoSaveRec; } if ($vis) { $vis = strtolower(str_replace('"', "", $vis)); $isvalid = in_array(strtolower($vis), array('hidden', 'viewable', 'pending', 'public')); if ($isvalid == false) { $vis = null; } } $now = date('Y-m-d H:i:s'); $wg = $wg >= 0 ? $wg : get_user_id(); // public records data if (!$recordID || $recordID < 0) { //new record // $log .= "- inserting record "; $recheader = array("rec_RecTypeID" => $rectype, "rec_URL" => $url, "rec_ScratchPad" => $notes, "rec_OwnerUGrpID" => $wg, "rec_NonOwnerVisibility" => $vis ? $vis : "viewable", "rec_AddedByUGrpID" => get_user_id(), "rec_Added" => $now, "rec_Modified" => $now, "rec_AddedByImport" => $modeImport > 0 ? 1 : 0); if ($recordID < 0) { $recordID = abs($recordID); $recheader["rec_ID"] = $recordID; } mysql__insert("Records", $recheader); if (mysql_error()) { errSaveRec("Database record insert error - " . mysql_error() . " " . print_r($recheader, true)); return $msgInfoSaveRec; } $recordID = mysql_insert_id(); } else { $res = checkPermission($recordID, $wg); if ($res !== true) { errSaveRec($res); return $msgInfoSaveRec; } // $log .= "- updating record "; mysql__update("Records", "rec_ID={$recordID}", array("rec_RecTypeID" => $rectype, "rec_URL" => $url, "rec_ScratchPad" => $notes, "rec_OwnerUGrpID" => $wg, "rec_NonOwnerVisibility" => $vis ? $vis : "viewable", "rec_FlagTemporary" => 0, "rec_Modified" => $now)); updateRecordIndexEntry(DATABASE, $rectype, $recordID); // TODO: Doesn't properly update Elasticsearch if (mysql_error()) { errSaveRec("Database record update error - " . mysql_error()); return $msgInfoSaveRec; } } // public recDetails data if ($details) { // $log .= "- inserting details "; $dtlIDsByAction = doDetailInsertion($recordID, $details, $rectype, $wg, $nonces, $retitleRecs, $modeImport); if (@$dtlIDsByAction['error']) { array_push($msgInfoSaveRec['error'], $dtlIDsByAction['error']); return $msgInfoSaveRec; } } // check that all the required fields are present $res = mysql_query("select rst_ID, rst_DetailTypeID, rst_DisplayName" . " from defRecStructure" . " left join recDetails on dtl_RecID={$recordID} and rst_DetailTypeID=dtl_DetailTypeID" . " where rst_RecTypeID={$rectype} and rst_RequirementType='required' and dtl_ID is null"); if (mysql_num_rows($res) > 0) { // $log .= "- testing missing detatils "; $missed = ""; while ($row = mysql_fetch_row($res)) { //ij asked to remove$conceptCode = getDetailTypeConceptID($row[1]); $missed = $missed . $row[2]; //ij asked to remove ." (Code:".$conceptCode.") "; } // at least one missing field if ($missed) { $msg = "Missing data for Required field(s) in '{$rectypeName}'. You may need to make fields optional. Missing data: " . $missed; if ($modeImport == 2) { warnSaveRec($msg); } else { errSaveRec($msg); return $msgInfoSaveRec; } } } mysql_query("commit"); // if we get to here we have a valid save of the core record. // calculate title, do an update // $log .= "- filling titlemask "; $mask = mysql__select_array("defRecTypes", "rty_TitleMask", "rty_ID={$rectype}"); $mask = $mask[0]; $title = fill_title_mask($mask, $recordID, $rectype); if ($title) { mysql_query("update Records set rec_Title = '" . mysql_real_escape_string($title) . "' where rec_ID = {$recordID}"); } // Update memcache: we can do this here since it's only the public data that we cache. updateCachedRecord($recordID); updateRecordIndexEntry(USERS_DATABASE, $rectype, $recordID); // private data $bkmk = @mysql_fetch_row(mysql_query("select bkm_ID from usrBookmarks where bkm_UGrpID=" . get_user_id() . " and bkm_recID=" . $recordID)); $bkm_ID = @$bkmk[0]; if ($personalised) { if (!$bkm_ID) { // Record is not yet bookmarked, but we want it to be mysql_query("insert into usrBookmarks (bkm_Added,bkm_Modified,bkm_UGrpID,bkm_recID) values (now(),now()," . get_user_id() . ",{$recordID})"); if (mysql_error()) { warnSaveRec("trying to create a bookmark - database error - " . mysql_error()); } else { $bkm_ID = mysql_insert_id(); } } // $log .= "- updating bookmark "; mysql__update("usrBookmarks", "bkm_ID={$bkm_ID}", array("bkm_Rating" => $rating, "bkm_Modified" => date('Y-m-d H:i:s'))); //WARNING tags is assumed to be a complete replacement list for personal tags on this record. doTagInsertion($recordID, $bkm_ID, $tags); } else { if ($bkm_ID) { // Record is bookmarked, but the user doesn't want it to be // $log .= "- deleting bookmark "; $query = "delete usrBookmarks, usrRecTagLinks " . "from usrBookmarks left join usrRecTagLinks on rtl_RecID = bkm_recID " . "left join usrTags on tag_ID = rtl_TagID " . "where bkm_ID={$bkm_ID} and bkm_recID={$recordID} and bkm_UGrpID = tag_UGrpID and bkm_UGrpID=" . get_user_id(); mysql_query($query); if (mysql_error()) { warnSaveRec("database error while removing bookmark- " . mysql_error()); } //saw TODO: add code to remove other personal data reminders, personal notes (woots), etc. } } doWgTagInsertion($recordID, $wgTags); if ($notifyREMOVE || $notifyADD) { $notifyIDs = handleNotifications($recordID, $notifyREMOVE, $notifyADD); } if ($commentREMOVE || $commentMOD || $commentADD) { $commentIDs = handleComments($recordID, $commentREMOVE, $commentMOD, $commentADD); } $rval = array("bibID" => $recordID, "bkmkID" => $bkm_ID, "modified" => $now); if ($title) { $rval["title"] = $title; } if (@$dtlIDsByAction) { $rval["detail"] = $dtlIDsByAction; } if (@$notifyIDs) { $rval["notify"] = $notifyIDs; } if (@$commentIDs) { $rval["comment"] = $commentIDs; } if (@$msgInfoSaveRec['warning']) { $rval["warning"] = $msgInfoSaveRec['warning']; } if (@$msgInfoSaveRec['error']) { //should never get here with error set $rval["error"] = $msgInfoSaveRec['error']; } else { //$rval["usageCount"] = updateRecTypeUsageCount(); } return $rval; }