tripal_pub.pub_importers.inc 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. <?php
  2. /**
  3. * @file
  4. * Management of importers
  5. */
  6. /**
  7. * A function to generate a table containing the list of publication importers
  8. *
  9. * @ingroup tripal_pub
  10. */
  11. function tripal_pub_importers_list() {
  12. // clear out the session variable when we view the list.
  13. unset($_SESSION['tripal_pub_import']);
  14. $header = array('', 'Importer Name', 'Database', 'Search String', 'Disabled', 'Create Contact', '');
  15. $rows = array();
  16. $importers = db_query("SELECT * FROM {tripal_pub_import} ORDER BY name");
  17. while ($importer = $importers->fetchObject()) {
  18. $criteria = unserialize($importer->criteria);
  19. $num_criteria = $criteria['num_criteria'];
  20. $criteria_str = '';
  21. for ($i = 1; $i <= $num_criteria; $i++) {
  22. $search_terms = $criteria['criteria'][$i]['search_terms'];
  23. $scope = $criteria['criteria'][$i]['scope'];
  24. $is_phrase = $criteria['criteria'][$i]['is_phrase'];
  25. $operation = $criteria['criteria'][$i]['operation'];
  26. $criteria_str .= "$operation ($scope: $search_terms) ";
  27. }
  28. $rows[] = array(
  29. array(
  30. 'data' => l(t('Edit/Test'), "admin/tripal/chado/tripal_pub/import/edit/$importer->pub_import_id") . '<br>' .
  31. l(t('Import Pubs'), "admin/tripal/chado/tripal_pub/import/submit/$importer->pub_import_id"),
  32. 'nowrap' => 'nowrap'
  33. ),
  34. $importer->name,
  35. $criteria['remote_db'],
  36. $criteria_str,
  37. $importer->disabled ? 'Yes' : 'No',
  38. $importer->do_contact ? 'Yes' : 'No',
  39. l(t('Delete'), "admin/tripal/chado/tripal_pub/import/delete/$importer->pub_import_id"),
  40. );
  41. }
  42. $page = "<ul class='action-links'>";
  43. $page .= ' <li>' . l('New Importer', 'admin/tripal/chado/tripal_pub/import/new') . '</li>';
  44. $page .= '</ul>';
  45. $page .= '<p>' . t(
  46. "A publication importer is used to create a set of search criteria that can be used
  47. to query a remote database, find publications that match the specified criteria
  48. and then import those publications into the Chado database. An example use case would
  49. be to peridocially add new publications to this Tripal site that have appeared in PubMed
  50. in the last 30 days. You can import publications in one of two ways:
  51. <ol>
  52. <li>Create a new importer by clicking the 'New Importer' link above, and after saving it should appear in the list below. Click the
  53. link labeled 'Import Pubs' to schedule a job to import the publications</li>
  54. <li>The first method only performs the import once. However, you can schedule the
  55. importer to run peridically by adding a cron job. See the " .
  56. l("Pub Module help instructions", "admin/tripal/chado/tripal_pub/help") . " to learn how to
  57. set the importers to run automatically.") . '</li>
  58. </ol><br>';
  59. $page .= theme('table', array('header' => $header, 'rows' => $rows));
  60. return $page;
  61. }
  62. /**
  63. * Creates the page that contains the publication importer setup form and
  64. * test results.
  65. *
  66. * @param $action
  67. * The action to perform
  68. * @param $pub_import_id
  69. * The importer ID
  70. *
  71. * @return
  72. * The HTML for the importer setup page
  73. *
  74. * @ingroup tripal_pub
  75. */
  76. function tripal_pub_importer_setup_page($action = 'new', $pub_import_id = NULL) {
  77. global $base_path;
  78. // make sure the tripal_pub and tripal_contact ontologies are loaded
  79. $values = array('name' => 'tripal_pub');
  80. $tpub_cv = chado_select_record('cv', array('cv_id'), $values);
  81. if (count($tpub_cv) == 0) {
  82. drupal_set_message(t('Before importing publications you must first ') . l(t('load the Tripal Pub Ontology'), 'admin/tripal/tripal_cv/obo_loader'), 'error');
  83. }
  84. $values = array('name' => 'tripal_contact');
  85. $tpub_cv = chado_select_record('cv', array('cv_id'), $values);
  86. if (count($tpub_cv) == 0) {
  87. drupal_set_message(t('If you want to create contact pages for authors, you must first ') . l(t('load the Tripal Contact Ontology'), 'admin/tripal/tripal_cv/obo_loader'), 'error');
  88. }
  89. if(!extension_loaded ('yaz')){
  90. drupal_set_message(t('<b>Note:</b> In order to create an importer using the USDA National Agricultural Library (AGL) you must install the yaz libraries. See the ') . l(t('Pub Module help page'), 'admin/tripal/chado/tripal_pub/help') . ' for assistance. If you do not want to use AGL you can ignore this warning.', 'warning');
  91. }
  92. // generate the search form
  93. $form = drupal_get_form('tripal_pub_importer_setup_form', $pub_import_id, $action);
  94. $output = l("Return to publication importers list", "admin/tripal/chado/tripal_pub/import_list");
  95. $output .= drupal_render($form);
  96. // retrieve any results
  97. if (array_key_exists('tripal_pub_import', $_SESSION)) {
  98. $remote_db = $_SESSION['tripal_pub_import']['remote_db'];
  99. $num_criteria = $_SESSION['tripal_pub_import']['num_criteria'];
  100. $days = $_SESSION['tripal_pub_import']['days'];
  101. $search_array = array();
  102. $search_array['remote_db'] = $remote_db;
  103. $search_array['num_criteria'] = $num_criteria;
  104. $search_array['days'] = $days;
  105. for ($i = 1; $i <= $num_criteria; $i++) {
  106. $search_array['criteria'][$i]['search_terms'] = $_SESSION['tripal_pub_import']['criteria'][$i]['search_terms'];
  107. $search_array['criteria'][$i]['scope'] = $_SESSION['tripal_pub_import']['criteria'][$i]['scope'];
  108. $search_array['criteria'][$i]['is_phrase'] = $_SESSION['tripal_pub_import']['criteria'][$i]['is_phrase'];
  109. $search_array['criteria'][$i]['operation'] = $_SESSION['tripal_pub_import']['criteria'][$i]['operation'];
  110. }
  111. // if the form has been submitted with the 'test' button then get the results
  112. if ($_SESSION['tripal_pub_import']['perform_search']) {
  113. $limit = 25;
  114. // get the list of publications from the remote database using the search criteria.
  115. $page = isset($_GET['page']) ? $_GET['page'] : '0';
  116. $results = tripal_get_remote_pubs($remote_db, $search_array, $limit, $page);
  117. $total_records = $results['total_records'];
  118. $search_str = $results['search_str'];
  119. $pubs = $results['pubs'];
  120. // iterate through the results and construct the table displaying the publications
  121. $rows = array();
  122. $i = $page * $limit + 1;
  123. if (count($pubs) > 0) {
  124. foreach ($pubs as $pub) {
  125. $citation = htmlspecialchars($pub['Citation']);
  126. $raw_link = '';
  127. if($pub['Publication Dbxref']) {
  128. $raw_link = l('raw', 'admin/tripal/chado/tripal_pub/import/raw/' . $pub['Publication Dbxref'], array('attributes' => array('target' => '_blank')));
  129. }
  130. $rows[] = array(
  131. number_format($i),
  132. $citation,
  133. $raw_link,
  134. );
  135. $i++;
  136. }
  137. }
  138. if (count($rows) == 0) {
  139. $rows[] = array(
  140. array(
  141. 'data' => 'No results found',
  142. 'colspan' => 3,
  143. ),
  144. );
  145. }
  146. $headers = array('', 'Publication', 'Raw Results');
  147. $table = array(
  148. 'header' => $headers,
  149. 'rows' => $rows,
  150. 'attributes' => array(
  151. 'id' => 'tripal_pub-importer-test',
  152. 'class' => 'tripal-data-table'
  153. ),
  154. 'sticky' => FALSE,
  155. 'caption' => '',
  156. 'colgroups' => array(),
  157. 'empty' => '',
  158. );
  159. // once we have our table array structure defined, we call Drupal's theme_table()
  160. // function to generate the table.
  161. $table = theme_table($table);
  162. // generate the pager
  163. pager_default_initialize($total_records, $limit);
  164. $pager = array(
  165. 'tags' => array(),
  166. 'element' => 0,
  167. 'parameters' => array(),
  168. 'quantity' => $limit,
  169. );
  170. $pager = theme_pager($pager);
  171. // because this is an ajax callback, the theme_pager will set the URL to be
  172. // "system/ajax", so we need to reset that
  173. $pager = str_replace($base_path . "system/ajax", "", $pager) ;
  174. // join all to form the results
  175. $total_pages = (int) ($total_records / $limit) + 1;
  176. $page = isset($_GET['page']) ? $_GET['page'] : '0';
  177. $output .= "$pager<br><b>Found " . number_format($total_records) . " publications. Page " . ($page + 1) . " of $total_pages.</b> " .
  178. "<br>$remote_db Search String: $search_str $table<br>$pager";
  179. }
  180. }
  181. return $output;
  182. }
  183. /**
  184. * The form used for creating publication importers.
  185. *
  186. * @param $form
  187. * The Drupal form
  188. * @param $form_state
  189. * The form state
  190. * @param $pub_import_id
  191. * The publication importer ID
  192. * @param $action
  193. * The action to perform
  194. *
  195. * @return
  196. * A form array
  197. *
  198. * @ingroup tripal_pub
  199. */
  200. function tripal_pub_importer_setup_form($form, &$form_state = NULL, $pub_import_id = NULL, $action = 'new') {
  201. // Default values can come in the following ways:
  202. //
  203. // 1) as elements of the $pub_importer object. This occurs when editing an existing importer
  204. // 2) in the $form_state['values'] array which occurs on a failed validation or
  205. // ajax callbacks from non submit form elements
  206. // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
  207. // form elements and the form is being rebuilt
  208. //
  209. // set form field defaults
  210. // Set the default values. If the pub_import_id isn't already defined by the form values
  211. // and one is provided then look it up in the database
  212. $criteria = NULL;
  213. $remote_db = '';
  214. $days = '';
  215. $disabled = '';
  216. $do_contact = '';
  217. $num_criteria = 1;
  218. $loader_name = '';
  219. // if this is an edit the we are pulling an import object from the database
  220. if ($action == "edit") {
  221. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :pub_import_id";
  222. $importer = db_query($sql, array(':pub_import_id' => $pub_import_id))->fetchObject();
  223. $criteria = unserialize($importer->criteria);
  224. $remote_db = $criteria['remote_db'];
  225. $days = $criteria['days'];
  226. $disabled = $criteria['disabled'];
  227. $do_contact = $criteria['do_contact'];
  228. $num_criteria = $criteria['num_criteria'];
  229. $loader_name = $criteria['loader_name'];
  230. }
  231. // if there are any session variables then use those
  232. if (array_key_exists('tripal_pub_import', $_SESSION)) {
  233. $remote_db = $_SESSION['tripal_pub_import']['remote_db'];
  234. $days = $_SESSION['tripal_pub_import']['days'];
  235. $disabled = $_SESSION['tripal_pub_import']['disabled'];
  236. $do_contact = $_SESSION['tripal_pub_import']['do_contact'];
  237. $num_criteria = $_SESSION['tripal_pub_import']['num_criteria'];
  238. $loader_name = $_SESSION['tripal_pub_import']['loader_name'];
  239. // check if the pub_import_id in the session variable is not the same as the one we've been provided
  240. // if so, then clear the session variable
  241. if ($pub_import_id and $pub_import_id != $_SESSION['tripal_pub_import']['pub_import_id']) {
  242. unset($_SESSION['tripal_pub_import']);
  243. }
  244. }
  245. // if we are re constructing the form from a failed validation or ajax callback
  246. // then use the $form_state['values'] values
  247. if (array_key_exists('values', $form_state)) {
  248. $remote_db = $form_state['values']['remote_db'];
  249. $days = $form_state['values']['days'];
  250. $disabled = $form_state['values']['disabled'];
  251. $do_contact = $form_state['values']['do_contact'];
  252. $num_criteria = $form_state['values']['num_criteria'];
  253. $loader_name = $form_state['values']['loader_name'];
  254. }
  255. // if we are re building the form from after submission (from ajax call) then
  256. // the values are in the $form_state['input'] array
  257. if (array_key_exists('input', $form_state) and !empty($form_state['input'])) {
  258. $remote_db = $form_state['input']['remote_db'];
  259. $days = $form_state['input']['days'];
  260. $disabled = $form_state['input']['disabled'];
  261. $do_contact = $form_state['input']['do_contact'];
  262. $loader_name = $form_state['input']['loader_name'];
  263. // because the num_criteria is a value and not a visible or hidden form
  264. // element it is not part of the ['input'] array, so we need to get it from the form
  265. $num_criteria = $form_state['complete form']['num_criteria']['#value'];
  266. }
  267. if (array_key_exists('triggering_element', $form_state) and
  268. $form_state['triggering_element']['#name'] == 'add') {
  269. $num_criteria++;
  270. }
  271. if (array_key_exists('triggering_element', $form_state) and
  272. $form_state['triggering_element']['#name'] == 'remove') {
  273. $num_criteria--;
  274. }
  275. // set the values we need for later but that should not be shown on the form
  276. $form['num_criteria']= array(
  277. '#type' => 'value',
  278. '#value' => $num_criteria,
  279. );
  280. $form['pub_import_id'] = array(
  281. '#type' => 'value',
  282. '#value' => $pub_import_id,
  283. );
  284. $form['action'] = array(
  285. '#type' => 'value',
  286. '#value' => $action,
  287. );
  288. // add in the elements that will be organized via a theme function
  289. $form['themed_element']['loader_name'] = array(
  290. '#type' => 'textfield',
  291. '#title' => t('Loader Name'),
  292. '#description' => t('Please provide a name for this loader setup.'),
  293. '#default_value' => $loader_name,
  294. '#required' => TRUE,
  295. );
  296. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  297. $remote_dbs = array();
  298. $values = array(
  299. 'name' => $supported_dbs,
  300. );
  301. $dbs = chado_select_record('db', array('*'), $values);
  302. foreach ($dbs as $index => $db) {
  303. $remote_dbs[$db->name] = $db->description;
  304. };
  305. // use PubMed as the default
  306. if (!$remote_db) {
  307. $remote_db = 'PMID';
  308. }
  309. $form['themed_element']['remote_db'] = array(
  310. '#title' => t('Remote Database'),
  311. '#type' => 'select',
  312. '#options' => $remote_dbs,
  313. '#default_value' => $remote_db,
  314. '#ajax' => array(
  315. 'callback' => "tripal_pubs_setup_form_ajax_update",
  316. 'wrapper' => 'tripal-pubs-importer-setup',
  317. 'effect' => 'fade',
  318. 'method' => 'replace',
  319. ),
  320. );
  321. $form['themed_element']['days'] = array(
  322. '#type' => 'textfield',
  323. '#title' => t('Days since record modified'),
  324. '#description' => t('Limit the search to include pubs that have been added no more than this many days before today.'),
  325. '#default_value' => $days,
  326. '#size' => 5,
  327. );
  328. $form['themed_element']['disabled'] = array(
  329. '#type' => 'checkbox',
  330. '#title' => t('Disabled'),
  331. '#description' => t('Check to disable this importer.'),
  332. '#default_value' => $disabled,
  333. );
  334. $form['themed_element']['do_contact'] = array(
  335. '#type' => 'checkbox',
  336. '#title' => t('Create Contact'),
  337. '#description' => t('Check to create an entry in the contact table for each author of a matching publication during import. This allows storage of
  338. additional information such as affilation, etc. Otherwise, only authors names are retrieved.'),
  339. '#default_value' => $do_contact,
  340. );
  341. // add in the form for the criteria
  342. tripal_pub_importer_setup_add_criteria_fields($form, $form_state, $num_criteria, $criteria);
  343. // add in the buttons
  344. $form['save'] = array(
  345. '#type' => 'submit',
  346. '#value' => t('Save Importer'),
  347. );
  348. $form['test'] = array(
  349. '#type' => 'submit',
  350. '#value' => t('Test Importer'),
  351. );
  352. $form['delete'] = array(
  353. '#type' => 'submit',
  354. '#value' => t('Delete Importer'),
  355. '#attributes' => array('style' => 'float: right;')
  356. );
  357. // add in the section where the test results will appear
  358. $form['results'] = array(
  359. '#markup' => '<div id="tripal-pub-importer-test-section"></div>',
  360. );
  361. // allow the selected remote database to make changes to the form if needed
  362. $callback = "tripal_pub_remote_alter_form_$remote_db";
  363. $form = call_user_func($callback, $form, $form_state, $num_criteria);
  364. $form['themed_element']['#theme'] = 'tripal_pub_importer_setup_form_elements';
  365. return $form;
  366. }
  367. /**
  368. * A helper function for the importer setup form that adds the criteria to
  369. * the form that belong to the importer.
  370. *
  371. * @param $form
  372. * The form
  373. * @param $form_state
  374. * The form state
  375. * @param $num_criteria
  376. * The number of criteria that exist for the importer
  377. * @param $criteria
  378. * An array containing the criteria
  379. *
  380. *@return
  381. * A form array
  382. *
  383. * @ingroup tripal_pub
  384. */
  385. function tripal_pub_importer_setup_add_criteria_fields(&$form, &$form_state, $num_criteria, $criteria){
  386. // choices array
  387. $scope_choices = array(
  388. 'any' => 'Any Field',
  389. 'abstract' => 'Abstract',
  390. 'author' => 'Author',
  391. 'id' => 'Accession',
  392. 'title' => 'Title',
  393. 'journal' => 'Journal Name'
  394. );
  395. $first_op_choices = array(
  396. '' => '',
  397. 'NOT' => 'NOT'
  398. );
  399. $op_choices = array(
  400. 'AND' => 'AND',
  401. 'OR' => 'OR',
  402. 'NOT' => 'NOT'
  403. );
  404. for($i = 1; $i <= $num_criteria; $i++) {
  405. $is_phrase = 1;
  406. $search_terms = '';
  407. $scope = '';
  408. $is_phrase = '';
  409. $operation = '';
  410. // if we have criteria supplied from the database then use that as the initial defaults
  411. if ($criteria) {
  412. $search_terms = $criteria['criteria'][$i]['search_terms'];
  413. $scope = $criteria['criteria'][$i]['scope'];
  414. $is_phrase = $criteria['criteria'][$i]['is_phrase'];
  415. $operation = $criteria['criteria'][$i]['operation'];
  416. }
  417. // if the criteria comes the session
  418. if (array_key_exists('tripal_pub_import', $_SESSION)) {
  419. $search_terms = isset($_SESSION['tripal_pub_import']['criteria'][$i]['search_terms']) ? $_SESSION['tripal_pub_import']['criteria'][$i]['search_terms'] : $search_terms;
  420. $scope = isset($_SESSION['tripal_pub_import']['criteria'][$i]['scope']) ? $_SESSION['tripal_pub_import']['criteria'][$i]['scope'] : $scope;
  421. $is_phrase = isset($_SESSION['tripal_pub_import']['criteria'][$i]['is_phrase']) ? $_SESSION['tripal_pub_import']['criteria'][$i]['is_phrase'] : $is_phrase;
  422. $operation = isset($_SESSION['tripal_pub_import']['criteria'][$i]['operation']) ? $_SESSION['tripal_pub_import']['criteria'][$i]['operation'] : $operation;
  423. }
  424. // If the form_state has variables then use those. This happens when an error occurs on the form or the
  425. // form is resbumitted using AJAX
  426. if (array_key_exists('values', $form_state)) {
  427. $search_terms = $form_state['values']["search_terms-$i"];
  428. $scope = $form_state['values']["scope-$i"];
  429. $is_phrase = $form_state['values']["is_phrase-$i"];
  430. $operation = $form_state['values']["operation-$i"];
  431. }
  432. $form['themed_element']['criteria'][$i]["scope-$i"] = array(
  433. '#type' => 'select',
  434. '#description' => t('Please select the fields to search for this term.'),
  435. '#options' => $scope_choices,
  436. '#default_value' => $scope,
  437. );
  438. $form['themed_element']['criteria'][$i]["search_terms-$i"] = array(
  439. '#type' => 'textfield',
  440. '#description' => t('<span style="white-space: normal">Please provide a list of words for searching. You may use
  441. conjunctions such as "AND" or "OR" to separate words if they are expected in
  442. the same scope, but do not mix ANDs and ORs. Check the "Is Phrase" checkbox to use conjunctions as part of the text to search</span>'),
  443. '#default_value' => $search_terms,
  444. '#required' => TRUE,
  445. '#maxlength' => 2048,
  446. );
  447. $form['themed_element']['criteria'][$i]["is_phrase-$i"] = array(
  448. '#type' => 'checkbox',
  449. '#title' => t('Is Phrase?'),
  450. '#default_value' => $is_phrase,
  451. );
  452. if ($i == 1) {
  453. /*
  454. $form['criteria'][$i]["operation-$i"] = array(
  455. '#type' => 'select',
  456. '#options' => $first_op_choices,
  457. '#default_value' => $operation,
  458. );*/
  459. }
  460. if ($i > 1) {
  461. $form['themed_element']['criteria'][$i]["operation-$i"] = array(
  462. '#type' => 'select',
  463. '#options' => $op_choices,
  464. '#default_value' => $operation,
  465. );
  466. }
  467. if ($i == $num_criteria) {
  468. if($i > 1) {
  469. $form['themed_element']['criteria'][$i]["remove-$i"] = array(
  470. '#type' => 'button',
  471. '#name' => 'remove',
  472. '#value' => t('Remove'),
  473. '#ajax' => array(
  474. 'callback' => "tripal_pubs_setup_form_ajax_update",
  475. 'wrapper' => 'tripal-pubs-importer-setup',
  476. 'effect' => 'fade',
  477. 'method' => 'replace',
  478. 'prevent' => 'click'
  479. ),
  480. // When this button is clicked, the form will be validated and submitted.
  481. // Therefore, we set custom submit and validate functions to override the
  482. // default form submit. In the validate function we set the form_state
  483. // to rebuild the form so the submit function never actually gets called,
  484. // but we need it or Drupal will run the default validate anyway.
  485. // we also set #limit_validation_errors to empty so fields that
  486. // are required that don't have values won't generate warnings.
  487. '#submit' => array('tripal_pub_setup_form_ajax_button_submit'),
  488. '#validate' => array('tripal_pub_setup_form_ajax_button_validate'),
  489. '#limit_validation_errors' => array(),
  490. );
  491. }
  492. $form['themed_element']['criteria'][$i]["add-$i"] = array(
  493. '#type' => 'button',
  494. '#name' => 'add',
  495. '#value' => t('Add'),
  496. '#ajax' => array(
  497. 'callback' => "tripal_pubs_setup_form_ajax_update",
  498. 'wrapper' => 'tripal-pubs-importer-setup',
  499. 'effect' => 'fade',
  500. 'method' => 'replace',
  501. 'prevent' => 'click'
  502. ),
  503. // When this button is clicked, the form will be validated and submitted.
  504. // Therefore, we set custom submit and validate functions to override the
  505. // default form submit. In the validate function we set the form_state
  506. // to rebuild the form so the submit function never actually gets called,
  507. // but we need it or Drupal will run the default validate anyway.
  508. // we also set #limit_validation_errors to empty so fields that
  509. // are required that don't have values won't generate warnings.
  510. '#submit' => array('tripal_pub_setup_form_ajax_button_submit'),
  511. '#validate' => array('tripal_pub_setup_form_ajax_button_validate'),
  512. '#limit_validation_errors' => array(),
  513. );
  514. }
  515. }
  516. }
  517. /**
  518. * This function is used to rebuild the form if an ajax call is made vai a button.
  519. * The button causes the form to be submitted. We don't want this so we override
  520. * the validate and submit routines on the form button. Therefore, this function
  521. * only needs to tell Drupal to rebuild the form
  522. *
  523. * @ingroup tripal_pub
  524. */
  525. function tripal_pub_setup_form_ajax_button_validate($form, &$form_state){
  526. $form_state['rebuild'] = TRUE;
  527. }
  528. /**
  529. * This function is just a dummy to override the default form submit on ajax calls for buttons
  530. *
  531. * @ingroup tripal_pub
  532. */
  533. function tripal_pub_setup_form_ajax_button_submit($form, &$form_state){
  534. // do nothing
  535. }
  536. /**
  537. * Validate the tripal_pub_importer_setup_form form
  538. *
  539. * @ingroup tripal_pub
  540. */
  541. function tripal_pub_importer_setup_form_validate($form, &$form_state) {
  542. $num_criteria = $form_state['values']['num_criteria'];
  543. $remote_db = $form_state['values']["remote_db"];
  544. $days = trim($form_state['values']["days"]);
  545. $disabled = $form_state['values']["disabled"];
  546. $do_contact = $form_state['values']["do_contact"];
  547. $loader_name = trim($form_state['values']["loader_name"]);
  548. for ($i = 1; $i <= $num_criteria; $i++) {
  549. $search_terms = trim($form_state['values']["search_terms-$i"]);
  550. $scope = $form_state['values']["scope-$i"];
  551. $is_phrase = $form_state['values']["is_phrase-$i"];
  552. $operation = '';
  553. if($i > 1) {
  554. $operation = $form_state['values']["operation-$i"];
  555. }
  556. if (!$is_phrase) {
  557. if (preg_match('/and/i', $search_terms) and preg_match('/or/i', $search_terms)) {
  558. form_set_error("search_terms-$i", "You may use 'AND' or 'OR' but cannot use both. Add a new entry below with the same scope for the other conunction.");
  559. $_SESSION['tripal_pub_import']['perform_search'] = 0;
  560. }
  561. }
  562. }
  563. if ($days and !is_numeric($days) or preg_match('/\./', $days)) {
  564. form_set_error("days", "Please enter a numeric, non decimal value, for the number of days.");
  565. $_SESSION['tripal_pub_import']['perform_search'] = 0;
  566. }
  567. // allow the selected remote database to validate any changes to the form if needed
  568. $callback = "tripal_pub_remote_validate_form_$remote_db";
  569. $form = call_user_func($callback, $form, $form_state);
  570. }
  571. /**
  572. * Submit the tripal_pub_importer_setup_form form
  573. *
  574. * @ingroup tripal_pub
  575. */
  576. function tripal_pub_importer_setup_form_submit($form, &$form_state) {
  577. $pub_import_id = $form_state['values']['pub_import_id'];
  578. $num_criteria = $form_state['values']['num_criteria'];
  579. $remote_db = $form_state['values']["remote_db"];
  580. $days = trim($form_state['values']["days"]);
  581. $loader_name = trim($form_state['values']["loader_name"]);
  582. $disabled = $form_state['values']["disabled"];
  583. $do_contact = $form_state['values']["do_contact"];
  584. // set the session variables
  585. $_SESSION['tripal_pub_import']['remote_db'] = $remote_db;
  586. $_SESSION['tripal_pub_import']['days'] = $days;
  587. $_SESSION['tripal_pub_import']['num_criteria'] = $num_criteria;
  588. $_SESSION['tripal_pub_import']['loader_name'] = $loader_name;
  589. $_SESSION['tripal_pub_import']['disabled'] = $disabled;
  590. $_SESSION['tripal_pub_import']['do_contact'] = $do_contact;
  591. $_SESSION['tripal_pub_import']['pub_import_id'] = $pub_import_id;
  592. unset($_SESSION['tripal_pub_import']['criteria']);
  593. for ($i = 1; $i <= $num_criteria; $i++) {
  594. $search_terms = trim($form_state['values']["search_terms-$i"]);
  595. $scope = $form_state['values']["scope-$i"];
  596. $is_phrase = $form_state['values']["is_phrase-$i"];
  597. $operation = '';
  598. if ($i > 1) {
  599. $operation = $form_state['values']["operation-$i"];
  600. }
  601. $_SESSION['tripal_pub_import']['criteria'][$i] = array(
  602. 'search_terms' => $search_terms,
  603. 'scope' => $scope,
  604. 'is_phrase' => $is_phrase,
  605. 'operation' => $operation
  606. );
  607. }
  608. // now perform the appropriate action for the button clicked
  609. if ($form_state['values']['op'] == 'Test Importer') {
  610. $_SESSION['tripal_pub_import']['perform_search'] = 1;
  611. }
  612. if ($form_state['values']['op'] == 'Save Importer' or
  613. $form_state['values']['op'] == 'Save & Import Now') {
  614. $record = array(
  615. 'name' => $loader_name,
  616. 'criteria' => serialize($_SESSION['tripal_pub_import']),
  617. 'disabled' => $disabled,
  618. 'do_contact' => $do_contact
  619. );
  620. // first check to see if this pub_import_id is already present. If so,
  621. // do an update rather than an insert
  622. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :pub_import_id";
  623. $importer = db_query($sql, array(':pub_import_id' => $pub_import_id))->fetchObject();
  624. if($importer) {
  625. // do the update
  626. $record['pub_import_id'] = $pub_import_id;
  627. if(drupal_write_record('tripal_pub_import', $record, 'pub_import_id')){
  628. unset($_SESSION['tripal_pub_import']);
  629. drupal_set_message('Publication import settings updated.');
  630. drupal_goto('admin/tripal/chado/tripal_pub/import_list');
  631. }
  632. else {
  633. drupal_set_message('Could not update publication import settings.', 'error');
  634. }
  635. }
  636. else {
  637. // do the insert
  638. if(drupal_write_record('tripal_pub_import', $record)){
  639. unset($_SESSION['tripal_pub_import']);
  640. drupal_set_message('Publication import settings saved.');
  641. // if the user wants to do the import now then do it (may time out
  642. // for long jobs)
  643. if ($form_state['values']['op'] == 'Save & Import Now') {
  644. tripal_execute_pub_importer($record['pub_import_id']);
  645. }
  646. drupal_goto('admin/tripal/chado/tripal_pub/import_list');
  647. }
  648. else {
  649. drupal_set_message('Could not save publication import settings.', 'error');
  650. }
  651. }
  652. }
  653. if ($form_state['values']['op'] == 'Delete Importer') {
  654. $sql = "DELETE FROM {tripal_pub_import} WHERE pub_import_id = :pub_import_id";
  655. $success = db_query($sql, array(':pub_import_id' => $pub_import_id));
  656. if ($success) {
  657. drupal_set_message('Publication importer deleted.');
  658. drupal_goto('admin/tripal/chado/tripal_pub/import_list');
  659. }
  660. else {
  661. drupal_set_message('Could not delete publication importer.', 'error');
  662. }
  663. }
  664. }
  665. /**
  666. * AJAX callback for updating the form.
  667. *
  668. * @ingroup tripal_pub
  669. */
  670. function tripal_pubs_setup_form_ajax_update($form, $form_state) {
  671. return $form['themed_element'];
  672. }
  673. /**
  674. * Theme the tripal_pub_importer_setup_form form.
  675. *
  676. * @ingroup tripal_pub
  677. */
  678. function theme_tripal_pub_importer_setup_form_elements($variables) {
  679. $form = $variables['form'];
  680. // first render the fields at the top of the form
  681. $markup = '';
  682. $markup .= '<div id="pub-search-form-row0">';
  683. $markup .= ' <div id="pub-search-form-row0-col1" style="float: left">' . drupal_render($form['remote_db']) . '</div>';
  684. $markup .= ' <div id="pub-search-form-row0-col2" style="float: left; margin-left: 10px">' . drupal_render($form['loader_name']) . '</div>';
  685. $markup .= '</div>';
  686. $markup .= '<div id="pub-search-form-row1" style="clear:both">';
  687. $markup .= ' <div id="pub-search-form-row1-col1">' . drupal_render($form['days']) . '</div>';
  688. $markup .= '</div>';
  689. $markup .= '<div id="pub-search-form-row2">' . drupal_render($form['disabled']) . '</div>';
  690. $markup .= '<div id="pub-search-form-row3">' . drupal_render($form['do_contact']) . '</div>';
  691. // next render the criteria fields into a table format
  692. $rows = array();
  693. foreach ($form['criteria'] as $i => $element) {
  694. if(is_numeric($i)) {
  695. $rows[] = array(
  696. drupal_render($element["operation-$i"]),
  697. drupal_render($element["scope-$i"]),
  698. drupal_render($element["search_terms-$i"]),
  699. drupal_render($element["is_phrase-$i"]),
  700. drupal_render($element["add-$i"]) . drupal_render($element["remove-$i"]),
  701. );
  702. }
  703. }
  704. $headers = array('Operation','Scope', 'Search Terms', '','');
  705. $table = array(
  706. 'header' => $headers,
  707. 'rows' => $rows,
  708. 'attributes' => array(
  709. 'class' => array('tripal-data-table')
  710. ),
  711. 'sticky' => TRUE,
  712. 'caption' => '',
  713. 'colgroups' => array(),
  714. 'empty' => '',
  715. );
  716. $criteria_table = theme_table($table);
  717. $markup .= $criteria_table;
  718. // add the rendered form
  719. $form = array(
  720. '#markup' => $markup,
  721. '#prefix' => '<div id="tripal-pubs-importer-setup">',
  722. '#suffix' => '</div>',
  723. );
  724. return drupal_render($form);
  725. }
  726. /**
  727. * Add a job to import publications
  728. *
  729. * @param $pub_importer_id
  730. * The id of the importer to submit a job to update
  731. *
  732. * @ingroup tripal_pub
  733. */
  734. function tripal_pub_importer_submit_job($import_id) {
  735. global $user;
  736. // get all of the loaders
  737. $args = array(':import_id' => $import_id);
  738. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :import_id ";
  739. $import = db_query($sql, $args)->fetchObject();
  740. $args = array($import_id);
  741. tripal_add_job("Import publications $import->name", 'tripal_pub',
  742. 'tripal_execute_pub_importer', $args, $user->uid);
  743. drupal_goto('admin/tripal/chado/tripal_pub/import_list');
  744. }
  745. /**
  746. * Adds publications that have been retrieved from a remote database and
  747. * consolidated into an array of details.
  748. *
  749. * @param $pubs
  750. * An array containing a list of publications to add to Chado. The
  751. * array contains a set of details for the publication.
  752. * @param $do_contact
  753. * Set to TRUE if authors should automatically have a contact record added
  754. * to Chado.
  755. * @param $update
  756. * If set to TRUE then publications that already exist in the Chado database
  757. * will be updated, whereas if FALSE only new publications will be added
  758. *
  759. * @return
  760. * Returns an array containing the number of publications that were
  761. * inserted, updated, skipped and which had an error during import.
  762. *
  763. * @ingroup tripal_pub
  764. */
  765. function tripal_pub_add_publications($pubs, $do_contact, $update = FALSE) {
  766. $report = array();
  767. $report['error'] = 0;
  768. $report['inserted'] = array();
  769. $report['skipped'] = array();
  770. $total_pubs = count($pubs);
  771. // iterate through the publications and add each one
  772. $i = 1;
  773. foreach ($pubs as $pub) {
  774. $memory = number_format(memory_get_usage()) . " bytes";
  775. print "Processing $i of $total_pubs. Memory usage: $memory.\r";
  776. // add the publication to Chado
  777. $action = '';
  778. $pub_id = tripal_pub_add_publication($pub, $action, $do_contact, $update);
  779. if ($pub_id){
  780. // add the publication cross reference (e.g. to PubMed)
  781. if ($pub_id and $pub['Publication Dbxref']) {
  782. $dbxref = array();
  783. if (preg_match('/^(.*?):(.*?)$/', trim($pub['Publication Dbxref']), $matches)) {
  784. $dbxref['db_name'] = $matches[1];
  785. $dbxref['accession'] = $matches[2];
  786. }
  787. else {
  788. tripal_report_error(
  789. 'tripal_pub',
  790. TRIPAL_ERROR,
  791. 'Unable to extract the dbxref to be associated with the publication (pub ID=@pub_id) from @dbxref. This reference should be [database-name]:[accession]',
  792. array('@pub_id' => $pub_id, '@dbxref' => $pub['Publication Dbxref'])
  793. );
  794. }
  795. $pub_dbxref = tripal_associate_dbxref('pub', $pub_id, $dbxref);
  796. }
  797. $pub['pub_id'] = $pub_id;
  798. }
  799. switch ($action) {
  800. case 'error':
  801. $report['error']++;
  802. break;
  803. case 'inserted':
  804. $report['inserted'][] = $pub;
  805. break;
  806. case 'updated':
  807. $report['updated'][] = $pub;
  808. break;
  809. case 'skipped':
  810. $report['skipped'][] = $pub;
  811. break;
  812. }
  813. $i++;
  814. }
  815. print "\n";
  816. return $report;
  817. }
  818. /**
  819. * Adds a new publication to the Chado, along with all properties and
  820. * database cross-references. If the publication does not already exist
  821. * in Chado then it is added. If it does exist nothing is done. If
  822. * the $update parameter is TRUE then the publication is updated if it exists.
  823. *
  824. * @param $pub_details
  825. * An associative array containing all of the details about the publication.
  826. * @param $action
  827. * This variable will get set to a text value indicating the action that was
  828. * performed. The values include 'skipped', 'inserted', 'updated' or 'error'.
  829. * @param $do_contact
  830. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  831. * for authors of the publication.
  832. * @param $update_if_exists
  833. * Optional. If the publication already exists then this function will return
  834. * without adding a new publication. However, set this value to TRUE to force
  835. * the function to pudate the publication using the $pub_details that are provided.
  836. *
  837. * @return
  838. * If the publication already exists, is inserted or updated then the publication
  839. * ID is returned, otherwise FALSE is returned. If the publication already exists
  840. * and $update_if_exists is not TRUE then the $action variable is set to 'skipped'.
  841. * If the publication already exists and $update_if_exists is TRUE and if the update
  842. * was successful then $action is set to 'updated'. Otherwise on successful insert
  843. * the $action variable is set to 'inserted'. If the function failes then the
  844. * $action variable is set to 'error'
  845. *
  846. * @ingroup tripal_pub
  847. */
  848. function tripal_pub_add_publication($pub_details, &$action, $do_contact = FALSE, $update_if_exists = FALSE) {
  849. $pub_id = 0;
  850. if (!is_array($pub_details)) {
  851. return FALSE;
  852. }
  853. // before proceeding check to see if the publication already exists. If there is only one match
  854. // and the $update_if_exists is NOT set then return FALSE
  855. $pub_ids = tripal_publication_exists($pub_details);
  856. if(count($pub_ids) == 1 and !$update_if_exists) {
  857. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  858. "There is a publication that is a duplicate of this publication. Cannot continue. It either ".
  859. "has a matching Dbxref (e.g. PubMed ID), a non-unique citation or matches on the unique " .
  860. "constraint set by the Tripal publication module configuration page. \nCitation: %title %dbxref.\nMatching Pub id: %ids",
  861. array(
  862. '%title' => $pub_details['Citation'],
  863. '%dbxref' => $pub_details['Publication Dbxref'],
  864. '%ids' => implode(",", $pub_ids),
  865. )
  866. );
  867. $action = 'skipped';
  868. return FALSE;
  869. }
  870. // if we have more than one matching pub then return an error as we don't know which to update even if
  871. // update_if_exists is set to TRUE
  872. if(count($pub_ids) > 1) {
  873. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  874. "There are %num publications that are duplicates of this publication. They either " .
  875. "have a matching Dbxref (e.g. PubMed ID) or match on the unique constraint set by the Tripal publication module ".
  876. "configuration page. \nCitation: %title %dbxref.\nMatching Pub ids: %ids",
  877. array(
  878. '%num' => count($pub_ids),
  879. '%title' => $pub_details['Citation'],
  880. '%dbxref' => $pub_details['Publication Dbxref'],
  881. '%ids' => implode(",", $pub_ids),
  882. )
  883. );
  884. $action = 'skipped';
  885. return FALSE;
  886. }
  887. // get the publication type (use the first publication type)
  888. if (array_key_exists('Publication Type', $pub_details)) {
  889. $pub_type = '';
  890. if(is_array($pub_details['Publication Type'])) {
  891. $pub_type = $pub_details['Publication Type'][0];
  892. }
  893. else {
  894. $pub_type = $pub_details['Publication Type'];
  895. }
  896. $identifiers = array(
  897. 'name' => $pub_type,
  898. 'cv_id' => array(
  899. 'name' => 'tripal_pub'
  900. ),
  901. );
  902. $pub_type = tripal_get_cvterm($identifiers);
  903. }
  904. else {
  905. tripal_report_error('tripal_pub', TRIPAL_ERROR,
  906. "The Publication Type is a required property but is missing", array());
  907. $action = 'error';
  908. return FALSE;
  909. }
  910. if (!$pub_type) {
  911. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find publication type: '%type'",
  912. array('%type' => $pub_details['Publication Type'][0]));
  913. $action = 'error';
  914. return FALSE;
  915. }
  916. // the series name field in the pub table is only 255 characters, so we should trim just in case
  917. $series_name = '';
  918. if (array_key_exists('Series_Name', $pub_details)) {
  919. $series_name = substr($pub_details['Series Name'], 0, 255);
  920. }
  921. if (array_key_exists('Journal Name', $pub_details)) {
  922. $series_name = substr($pub_details['Journal Name'], 0, 255);
  923. }
  924. // build the values array for inserting or updating
  925. $values = array(
  926. 'title' => $pub_details['Title'],
  927. 'volume' => $pub_details['Volume'],
  928. 'series_name' => $series_name,
  929. 'issue' => $pub_details['Issue'],
  930. 'pyear' => $pub_details['Year'],
  931. 'pages' => $pub_details['Pages'],
  932. 'uniquename' => $pub_details['Citation'],
  933. 'type_id' => $pub_type->cvterm_id,
  934. );
  935. // if there is no pub_id then we need to do an insert.
  936. if (!$pub_id) {
  937. $options = array('statement_name' => 'ins_pub_tivoseispypaunty');
  938. $pub = chado_insert_record('pub', $values, $options);
  939. if (!$pub) {
  940. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot insert the publication with title: %title",
  941. array('%title' => $pub_details['Title']));
  942. $action = 'error';
  943. return FALSE;
  944. }
  945. $pub_id = $pub['pub_id'];
  946. $action = 'inserted';
  947. }
  948. // if there is a pub_id and we've been told to update, then do the update
  949. if ($pub_id and $update_if_exists) {
  950. $match = array('pub_id' => $pub_id);
  951. $options = array('statement_name' => 'up_pub_tivoseispypaunty');
  952. $success = chado_update_record('pub', $match, $values, $options);
  953. if (!$success) {
  954. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot update the publication with title: %title",
  955. array('%title' => $pub_details['Title']));
  956. $action = 'error';
  957. return FALSE;
  958. }
  959. $action = 'updated';
  960. }
  961. // before we add any new properties we need to remove those that are there if this
  962. // is an update. The only thing we don't want to remove are the 'Publication Dbxref'
  963. if ($update_if_exists) {
  964. $sql = "
  965. DELETE FROM {pubprop}
  966. WHERE
  967. pub_id = :pub_id AND
  968. NOT type_id in (
  969. SELECT cvterm_id
  970. FROM {cvterm}
  971. WHERE name = 'Publication Dbxref'
  972. )
  973. ";
  974. chado_query($sql, array(':pub_id' => $pub_id));
  975. }
  976. // iterate through the properties and add them
  977. foreach ($pub_details as $key => $value) {
  978. // the pub_details may have the raw search data (e.g. in XML from PubMed. We'll irgnore this for now
  979. if($key == 'raw') {
  980. continue;
  981. }
  982. // get the cvterm by name
  983. $identifiers = array(
  984. 'name' => $key,
  985. 'cv_id' => array(
  986. 'name' => 'tripal_pub'
  987. ),
  988. );
  989. $cvterm = tripal_get_cvterm($identifiers);
  990. // if we could not find the cvterm by name then try by synonym
  991. //$cvterm = tripal_get_cvterm(array('name' => $key, 'cv_id' => array('name' => 'tripal_pub')));
  992. if (!$cvterm) {
  993. $identifiers = array(
  994. 'synonym' => array(
  995. 'name' => $key,
  996. 'cv_name' => 'tripal_pub'
  997. )
  998. );
  999. $cvterm = tripal_get_cvterm($identifiers);
  1000. }
  1001. if (!$cvterm) {
  1002. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find term: '%prop'. Skipping.", array('%prop' => $key));
  1003. continue;
  1004. }
  1005. // skip details that won't be stored as properties
  1006. if ($key == 'Author List') {
  1007. tripal_pub_add_authors($pub_id, $value, $do_contact);
  1008. continue;
  1009. }
  1010. if ($key == 'Title' or $key == 'Volume' or $key == 'Journal Name' or $key == 'Issue' or
  1011. $key == 'Year' or $key == 'Pages') {
  1012. continue;
  1013. }
  1014. $success = 0;
  1015. if (is_array($value)) {
  1016. foreach ($value as $subkey => $subvalue) {
  1017. // if the key is an integer then this array is a simple list and
  1018. // we will insert using the primary key. Otheriwse, use the new key
  1019. if(is_int($subkey)) {
  1020. $success = chado_insert_property(
  1021. array('table' => 'pub', 'id' => $pub_id),
  1022. array('type_name' => $key, 'cv_name' => 'tripal_pub', 'value' => $subvalue)
  1023. );
  1024. }
  1025. else {
  1026. $success = chado_insert_property(
  1027. array('table' => 'pub', 'id' => $pub_id),
  1028. array('type_name' => $subkey, 'cv_name' => 'tripal_pub', 'value' => $subvalue)
  1029. );
  1030. }
  1031. }
  1032. }
  1033. else {
  1034. $success = chado_insert_property(
  1035. array('table' => 'pub', 'id' => $pub_id),
  1036. array('type_name' => $key, 'cv_name' => 'tripal_pub', 'value' => $value),
  1037. array('update_if_present' => TRUE)
  1038. );
  1039. }
  1040. if (!$success) {
  1041. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot add property '%prop' to publication. Skipping.",
  1042. array('%prop' => $key));
  1043. continue;
  1044. }
  1045. }
  1046. return $pub_id;
  1047. }
  1048. /**
  1049. * Add one or more authors to a publication
  1050. *
  1051. * @param $pub_id
  1052. * The publication ID of the pub in Chado.
  1053. * @param $authors
  1054. * An array of authors. Each author should have a set of keys/value pairs
  1055. * describing the author.
  1056. * @param $do_contact
  1057. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  1058. * for authors of the publication.
  1059. * @ingroup tripal_pub
  1060. */
  1061. function tripal_pub_add_authors($pub_id, $authors, $do_contact) {
  1062. $rank = 0;
  1063. // first remove any of the existing pubauthor entires
  1064. $sql = "DELETE FROM {pubauthor} WHERE pub_id = :pub_id";
  1065. chado_query($sql, array(':pub_id' => $pub_id));
  1066. // iterate through the authors and add them to the pubauthors and contact
  1067. // tables of chado, then link them through the custom pubauthors_contact table
  1068. foreach ($authors as $author) {
  1069. // skip invalid author entires
  1070. if ($author['valid'] == 'N') {
  1071. continue;
  1072. }
  1073. // remove the 'valid' property as we don't have a CV term for it
  1074. unset($author['valid']);
  1075. // construct the contact.name field using the author information
  1076. $name = '';
  1077. $type = 'Person';
  1078. if ($author['Given Name']) {
  1079. $name .= $author['Given Name'];
  1080. }
  1081. if ($author['Surname']) {
  1082. $name .= ' ' . $author['Surname'];
  1083. }
  1084. if ($author['Suffix']) {
  1085. $name .= ' ' . $author['Suffix'];
  1086. }
  1087. if ($author['Collective']) {
  1088. $name = $author['Collective'];
  1089. $type = 'Collective';
  1090. }
  1091. $name = trim($name);
  1092. // add an entry to the pubauthors table
  1093. $values = array(
  1094. 'pub_id' => $pub_id,
  1095. 'rank' => $rank,
  1096. 'surname' => $author['Surname'] ? substr($author['Surname'], 0, 100) : substr($author['Collective'], 0, 100),
  1097. 'givennames' => $author['Given Name'],
  1098. 'suffix' => $author['Suffix'],
  1099. );
  1100. $options = array('statement_name' => 'ins_pubauthor_idrasugisu');
  1101. $pubauthor = chado_insert_record('pubauthor', $values, $options);
  1102. // if the user wants us to create a contact for each author then do it.
  1103. if ($do_contact) {
  1104. // Add the contact
  1105. $contact = tripal_insert_contact(array(
  1106. 'name' => $name,
  1107. 'description' => '',
  1108. 'type_name' => $type,
  1109. 'properties' => $author
  1110. ));
  1111. // if we have succesfully added the contact and the pubauthor entries then we want to
  1112. // link them together
  1113. if ($contact and $pubauthor) {
  1114. // link the pubauthor entry to the contact
  1115. $values = array(
  1116. 'pubauthor_id' => $pubauthor['pubauthor_id'],
  1117. 'contact_id' => $contact['contact_id'],
  1118. );
  1119. $options = array('statement_name' => 'ins_pubauthorcontact_puco');
  1120. $pubauthor_contact = chado_insert_record('pubauthor_contact', $values, $options);
  1121. if (!$pubauthor_contact) {
  1122. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot link pub authro and contact.", array());
  1123. }
  1124. }
  1125. }
  1126. $rank++;
  1127. }
  1128. }
  1129. /**
  1130. * This function generates an array suitable for use with the
  1131. * tripal_pub_create_citation function for any publication
  1132. * already stored in the Chado tables.
  1133. *
  1134. * @param $pub_id
  1135. * The publication ID
  1136. * @param $skip_existing
  1137. * Set to TRUE to skip publications that already have a citation
  1138. * in the pubprop table. Set to FALSE to generate a citation
  1139. * regardless if the citation already exists.
  1140. *
  1141. * @return
  1142. * An array suitable for the trpial_pub_create_citation function. On
  1143. * failure returns FALSE.
  1144. *
  1145. * @ingroup tripal_pub
  1146. */
  1147. function tripal_pub_get_publication_array($pub_id, $skip_existing = TRUE) {
  1148. $options = array('return_array' => 1);
  1149. // ---------------------------------
  1150. // get the publication
  1151. // ---------------------------------
  1152. $values = array('pub_id' => $pub_id);
  1153. $pub = chado_generate_var('pub', $values);
  1154. // expand the title
  1155. $pub = chado_expand_var($pub, 'field', 'pub.title');
  1156. $pub = chado_expand_var($pub, 'field', 'pub.volumetitle');
  1157. $pub = chado_expand_var($pub, 'field', 'pub.uniquename');
  1158. $pub_array = array();
  1159. if (trim($pub->title)) {
  1160. $pub_array['Title'] = $pub->title;
  1161. }
  1162. if (trim($pub->volumetitle)) {
  1163. $pub_array['Volume Title'] = $pub->volumetitle;
  1164. }
  1165. if (trim($pub->volume)) {
  1166. $pub_array['Volume'] = $pub->volume;
  1167. }
  1168. if (trim($pub->series_name)) {
  1169. $pub_array['Series Name'] = $pub->series_name;
  1170. }
  1171. if (trim($pub->issue)) {
  1172. $pub_array['Issue'] = $pub->issue;
  1173. }
  1174. if (trim($pub->pyear)) {
  1175. $pub_array['Year'] = $pub->pyear;
  1176. }
  1177. if (trim($pub->pages)) {
  1178. $pub_array['Pages'] = $pub->pages;
  1179. }
  1180. if (trim($pub->miniref)) {
  1181. $pub_array['Mini Ref'] = $pub->miniref;
  1182. }
  1183. if (trim($pub->uniquename)) {
  1184. $pub_array['Uniquename'] = $pub->uniquename;
  1185. }
  1186. $pub_array['Publication Type'][] = $pub->type_id->name;
  1187. // ---------------------------------
  1188. // get the citation
  1189. // ---------------------------------
  1190. $values = array(
  1191. 'pub_id' => $pub->pub_id,
  1192. 'type_id' => array(
  1193. 'name' => 'Citation',
  1194. ),
  1195. );
  1196. $citation = chado_generate_var('pubprop', $values);
  1197. if ($citation) {
  1198. $citation = chado_expand_var($citation, 'field', 'pubprop.value', $options);
  1199. if (count($citation) > 1) {
  1200. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple citations already: %pub_id",
  1201. array('%pub_id' => $pubid));
  1202. return FALSE;
  1203. }
  1204. elseif (count($citation) == 1 and $skip_existing == TRUE) {
  1205. // skip this publication, it already has a citation
  1206. return FALSE;
  1207. }
  1208. }
  1209. // ---------------------------------
  1210. // get the publication types
  1211. // ---------------------------------
  1212. $values = array(
  1213. 'pub_id' => $pub->pub_id,
  1214. 'type_id' => array(
  1215. 'name' => 'Publication Type',
  1216. ),
  1217. );
  1218. $ptypes = chado_generate_var('pubprop', $values, $options);
  1219. if ($ptypes) {
  1220. $ptypes = chado_expand_var($ptypes, 'field', 'pubprop.value', $options);
  1221. foreach ($ptypes as $ptype) {
  1222. $pub_array['Publication Type'][] = $ptype->value;
  1223. }
  1224. }
  1225. // ---------------------------------
  1226. // get the authors list
  1227. // ---------------------------------
  1228. $values = array(
  1229. 'pub_id' => $pub->pub_id,
  1230. 'type_id' => array(
  1231. 'name' => 'Authors',
  1232. ),
  1233. );
  1234. $authors = chado_generate_var('pubprop', $values);
  1235. $authors = chado_expand_var($authors, 'field', 'pubprop.value', $options);
  1236. if (count($authors) > 1) {
  1237. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple author lists. It should have only one list: %pub_id",
  1238. array('%pub_id' => $pubid));
  1239. return FALSE;
  1240. }
  1241. else if (trim($authors->value)) {
  1242. $pub_array['Authors'] = $authors->value;
  1243. }
  1244. // if there is no 'Author's property then try to retreive authors from the pubauthor table
  1245. else {
  1246. $sql = "
  1247. SELECT string_agg(surname || ' ' || givennames, ', ')
  1248. FROM {pubauthor}
  1249. WHERE pub_id = :pub_id
  1250. GROUP BY pub_id
  1251. ";
  1252. $au = chado_query($sql, array(':pub_id' => $pub_id))->fetchField();
  1253. if ($au) {
  1254. $pub_array['Authors'] = $au;
  1255. }
  1256. }
  1257. //Get other props
  1258. $props = array(
  1259. 'Journal Abbreviation',
  1260. 'Elocation',
  1261. 'Media Code',
  1262. 'Conference Name',
  1263. 'Keywords',
  1264. 'Series Name',
  1265. 'pISSN',
  1266. 'Publication Date',
  1267. 'Journal Code',
  1268. 'Journal Alias',
  1269. 'Journal Country',
  1270. 'Published Location',
  1271. 'Publication Model',
  1272. 'Language Abbr',
  1273. 'Alias',
  1274. 'Publication Dbxref',
  1275. 'Copyright',
  1276. 'Abstract',
  1277. 'Notes',
  1278. 'Citation',
  1279. 'Language',
  1280. 'URL',
  1281. 'eISSN',
  1282. 'DOI',
  1283. 'ISSN',
  1284. 'Publication Code',
  1285. 'Comments',
  1286. 'Publisher',
  1287. 'Media Alias',
  1288. 'Original Title'
  1289. );
  1290. foreach ($props AS $prop) {
  1291. $sql =
  1292. "SELECT value FROM {pubprop}
  1293. WHERE type_id =
  1294. (SELECT cvterm_id
  1295. FROM {cvterm}
  1296. WHERE name = :cvtname AND cv_id =
  1297. (SELECT cv_id
  1298. FROM {cv}
  1299. WHERE name = 'tripal_pub'
  1300. )
  1301. )
  1302. AND pub_id = :pub_id
  1303. ";
  1304. $val = trim(chado_query($sql, array(':cvtname' => $prop, ':pub_id' => $pub->pub_id))->fetchField());
  1305. if ($val) {
  1306. $pub_array[$prop] =$val;
  1307. }
  1308. }
  1309. return $pub_array;
  1310. }
  1311. /**
  1312. * Imports all publications for all active import setups.
  1313. *
  1314. * @param $report_email
  1315. * A list of email address, separated by commas, that should be notified
  1316. * once importing has completed
  1317. * @param $do_update
  1318. * If set to TRUE then publications that already exist in the Chado database
  1319. * will be updated, whereas if FALSE only new publications will be added
  1320. *
  1321. * @ingroup tripal_pub
  1322. */
  1323. function tripal_execute_active_pub_importers($report_email = FALSE, $do_update = FALSE) {
  1324. $num_to_retrieve = 100;
  1325. $page = 0;
  1326. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  1327. "If the load fails or is terminated prematurely then the entire set of \n" .
  1328. "insertions/updates is rolled back and will not be found in the database\n\n";
  1329. // start the transaction
  1330. $transaction = db_transaction();
  1331. try {
  1332. // get all of the loaders
  1333. $args = array();
  1334. $sql = "SELECT * FROM {tripal_pub_import} WHERE disabled = 0 ";
  1335. $results = db_query($sql, $args);
  1336. $do_contact = FALSE;
  1337. $reports = array();
  1338. foreach ($results as $import) {
  1339. $page = 0;
  1340. print "Executing importer: '" . $import->name . "'\n";
  1341. // keep track if any of the importers want to create contacts from authors
  1342. if ($import->do_contact == 1) {
  1343. $do_contact = TRUE;
  1344. }
  1345. $criteria = unserialize($import->criteria);
  1346. $remote_db = $criteria['remote_db'];
  1347. do {
  1348. // retrieve the pubs for this page. We'll retreive 100 at a time
  1349. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  1350. $pubs = $results['pubs'];
  1351. $reports[$import->name] = tripal_pub_add_publications($pubs, $import->do_contact, $do_update);
  1352. $page++;
  1353. }
  1354. // continue looping until we have a $pubs array that does not have
  1355. // our requested numer of records. This means we've hit the end
  1356. while (count($pubs) == $num_to_retrieve);
  1357. }
  1358. // sync the newly added publications with Drupal. If the user
  1359. // requested a report then we don't want to print any syncing information
  1360. // so pass 'FALSE' to the sync call
  1361. print "Syncing publications with Drupal...\n";
  1362. chado_node_sync_records('pub');
  1363. // iterate through each of the reports and generate a final report with HTML links
  1364. $HTML_report = '';
  1365. if ($report_email) {
  1366. $HTML_report .= "<html>";
  1367. global $base_url;
  1368. foreach ($reports as $importer => $report) {
  1369. $total = count($report['inserted']);
  1370. $HTML_report .= "<b>$total new publications from importer: $importer</b><br><ol>\n";
  1371. foreach ($report['inserted'] as $pub) {
  1372. $item = $pub['Title'];
  1373. if (array_key_exists('pub_id', $pub)) {
  1374. $item = l($pub['Title'], "$base_url/pub/" . $pub['pub_id']);
  1375. }
  1376. $HTML_report .= "<li>$item</li>\n";
  1377. }
  1378. $HTML_report .= "</ol>\n";
  1379. }
  1380. $HTML_report .= "</html>";
  1381. $site_email = variable_get('site_mail', '');
  1382. $params = array(
  1383. 'message' => $HTML_report
  1384. );
  1385. drupal_mail('tripal_pub', 'import_report', $report_email, language_default(), $params, $site_email, TRUE);
  1386. }
  1387. // if any of the importers wanted to create contacts from the authors then sync them
  1388. if($do_contact) {
  1389. print "Syncing contacts with Drupal...\n";
  1390. chado_node_sync_records('contact');
  1391. }
  1392. }
  1393. catch (Exception $e) {
  1394. $transaction->rollback();
  1395. print "\n"; // make sure we start errors on new line
  1396. watchdog_exception('T_pub_import', $e);
  1397. print "FAILED: Rolling back database changes...\n";
  1398. return;
  1399. }
  1400. print "Done.\n";
  1401. }
  1402. /**
  1403. * Imports all publications for a given publication import setup.
  1404. *
  1405. * @param $import_id
  1406. * The ID of the import setup to use
  1407. * @param $job_id
  1408. * The jobs management job_id for the job if this function is run as a job.
  1409. *
  1410. * @ingroup tripal_pub
  1411. */
  1412. function tripal_execute_pub_importer($import_id, $job_id = NULL) {
  1413. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  1414. "If the load fails or is terminated prematurely then the entire set of \n" .
  1415. "insertions/updates is rolled back and will not be found in the database\n\n";
  1416. // start the transaction
  1417. $transaction = db_transaction();
  1418. try {
  1419. $page = 0;
  1420. $do_contact = FALSE;
  1421. $num_to_retrieve = 100;
  1422. // get all of the loaders
  1423. $args = array(':import_id' => $import_id);
  1424. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :import_id ";
  1425. $import = db_query($sql, $args)->fetchObject();
  1426. print "Executing Importer: '" . $import->name . "'\n";
  1427. $criteria = unserialize($import->criteria);
  1428. $remote_db = $criteria['remote_db'];
  1429. $total_pubs = 0;
  1430. do {
  1431. // retrieve the pubs for this page. We'll retreive 100 at a time
  1432. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  1433. $pubs = $results['pubs'];
  1434. $num_pubs = $rseults['total_records'];
  1435. $total_pubs += $num_pubs;
  1436. tripal_pub_add_publications($pubs, $import->do_contact);
  1437. $page++;
  1438. }
  1439. // continue looping until we have a $pubs array that does not have
  1440. // our requested numer of records. This means we've hit the end
  1441. while (count($pubs) == $num_to_retrieve);
  1442. // sync the newly added publications with Drupal. If the user
  1443. // requested a report then we don't want to print any syncing information
  1444. // so pass 'FALSE' to the sync call
  1445. print "Syncing publications with Drupal...\n";
  1446. chado_node_sync_records('pub');
  1447. // if any of the importers wanted to create contacts from the authors then sync them
  1448. if($import->do_contact) {
  1449. print "Syncing contacts with Drupal...\n";
  1450. chado_node_sync_records('contact');
  1451. }
  1452. tripal_set_job_progress($job_id, '100');
  1453. }
  1454. catch (Exception $e) {
  1455. $transaction->rollback();
  1456. print "\n"; // make sure we start errors on new line
  1457. watchdog_exception('T_pub_import', $e);
  1458. print "FAILED: Rolling back database changes...\n";
  1459. return;
  1460. }
  1461. print "Done.\n";
  1462. }
  1463. /**
  1464. * This function is used to perfom a query using one of the supported databases
  1465. * and return the raw query results. This may be XML or some other format
  1466. * as provided by the database.
  1467. *
  1468. * @param $dbxref
  1469. * The unique database ID for the record to retrieve. This value must
  1470. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  1471. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  1472. * for the record in the database.
  1473. *
  1474. * @return
  1475. * Returns the publication array or FALSE if a problem occurs
  1476. *
  1477. * @ingroup tripal_pub
  1478. */
  1479. function tripal_get_remote_pub($dbxref) {
  1480. if(preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  1481. $remote_db = $matches[1];
  1482. $accession = $matches[2];
  1483. // check that the database is supported
  1484. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  1485. if(!in_array($remote_db, $supported_dbs)) {
  1486. return FALSE;
  1487. }
  1488. $search = array(
  1489. 'num_criteria' => 1,
  1490. 'remote_db' => $remote_db,
  1491. 'criteria' => array(
  1492. '1' => array(
  1493. 'search_terms' => "$remote_db:$accession",
  1494. 'scope' => 'id',
  1495. 'operation' => '',
  1496. 'is_phrase' => 0,
  1497. ),
  1498. ),
  1499. );
  1500. $pubs = tripal_get_remote_pubs($remote_db, $search, 1, 0);
  1501. return $pubs['pubs'][0];
  1502. }
  1503. return FALSE;
  1504. }
  1505. /**
  1506. * Retrieves a list of publications as an associated array where
  1507. * keys correspond directly with Tripal Pub CV terms.
  1508. *
  1509. * @param remote_db
  1510. * The name of the remote publication database to query. These names should
  1511. * match the name of the databases in the Chado 'db' table. Currently
  1512. * supported databass include
  1513. * 'PMID': PubMed
  1514. *
  1515. * @param search_array
  1516. * An associate array containing the search criteria. The following key
  1517. * are expected
  1518. * 'remote_db': Specifies the name of the remote publication database
  1519. * 'num_criteria': Specifies the number of criteria present in the search array
  1520. * 'days': The number of days to include in the search starting from today
  1521. * 'criteria': An associate array containing the search critiera. There should
  1522. * be no less than 'num_criteria' elements in this array.
  1523. *
  1524. * The following keys are expected in the 'criteria' array
  1525. * 'search_terms': A list of terms to search on, separated by spaces.
  1526. * 'scope': The fields to search in the remote database. Valid values
  1527. * include: 'title', 'abstract', 'author' and 'any'
  1528. * 'operation': The logical operation to use for this criteria. Valid
  1529. * values include: 'AND', 'OR' and 'NOT'.
  1530. * @param $num_to_retrieve
  1531. * The number of records to retrieve. In cases with large numbers of
  1532. * records to retrieve, the remote database may limit the size of each
  1533. * retrieval.
  1534. * @param $page
  1535. * Optional. If this function is called where the
  1536. * page for the pager cannot be set using the $_GET variable, use this
  1537. * argument to specify the page to retrieve.
  1538. *
  1539. * @return
  1540. * Returns an array of pubs where each element is
  1541. * an associative array where the keys are Tripal Pub CV terms.
  1542. *
  1543. * @ingroup tripal_pub
  1544. */
  1545. function tripal_get_remote_pubs($remote_db, $search_array, $num_to_retrieve, $page = 0) {
  1546. // now call the callback function to get the results
  1547. $callback = "tripal_pub_remote_search_$remote_db";
  1548. $pubs = array(
  1549. 'total_records' => 0,
  1550. 'search_str' => '',
  1551. 'pubs' => array(),
  1552. );
  1553. if (function_exists($callback)) {
  1554. $pubs = call_user_func($callback, $search_array, $num_to_retrieve, $page);
  1555. }
  1556. return $pubs;
  1557. }
  1558. /**
  1559. * Imports a singe publication specified by a remote database cross reference.
  1560. *
  1561. * @param $pub_dbxref
  1562. * The unique database ID for the record to update. This value must
  1563. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  1564. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  1565. * for the record in the database.
  1566. * @param $do_contact
  1567. * Set to TRUE if authors should automatically have a contact record added
  1568. * to Chado.
  1569. * @param $do_update
  1570. * If set to TRUE then the publication will be updated if it already exists
  1571. * in the database.
  1572. *
  1573. * @ingroup tripal_pub
  1574. */
  1575. function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_update) {
  1576. $num_to_retrieve = 1;
  1577. $pager_id = 0;
  1578. $page = 0;
  1579. $num_pubs = 0;
  1580. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  1581. "If the load fails or is terminated prematurely then the entire set of \n" .
  1582. "insertions/updates is rolled back and will not be found in the database\n\n";
  1583. $transaction = db_transaction();
  1584. try {
  1585. if(preg_match('/^(.*?):(.*?)$/', $pub_dbxref, $matches)) {
  1586. $dbname = $matches[1];
  1587. $accession = $matches[2];
  1588. $criteria = array(
  1589. 'num_criteria' => 1,
  1590. 'remote_db' => $dbname,
  1591. 'criteria' => array(
  1592. '1' => array(
  1593. 'search_terms' => "$dbname:$accession",
  1594. 'scope' => 'id',
  1595. 'operation' => '',
  1596. 'is_phrase' => 0,
  1597. ),
  1598. ),
  1599. );
  1600. $remote_db = $criteria['remote_db'];
  1601. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  1602. $pubs = $results['pubs'];
  1603. $search_str = $results['search_str'];
  1604. $total_records = $results['total_records'];
  1605. $pub_id = tripal_pub_add_publications($pubs, $do_contact, $do_update);
  1606. }
  1607. // sync the newly added publications with Drupal
  1608. print "Syncing publications with Drupal...\n";
  1609. chado_node_sync_records('pub');
  1610. // if any of the importers wanted to create contacts from the authors then sync them
  1611. if($do_contact) {
  1612. print "Syncing contacts with Drupal...\n";
  1613. chado_node_sync_records('contact');
  1614. }
  1615. }
  1616. catch (Exception $e) {
  1617. $transaction->rollback();
  1618. print "\n"; // make sure we start errors on new line
  1619. watchdog_exception('T_pub_import', $e);
  1620. print "FAILED: Rolling back database changes...\n";
  1621. return;
  1622. }
  1623. print "Done.\n";
  1624. }
  1625. /**
  1626. * Updates publication records that currently exist in the Chado pub table
  1627. * with the most recent data in the remote database.
  1628. *
  1629. * @param $do_contact
  1630. * Set to TRUE if authors should automatically have a contact record added
  1631. * to Chado. Contacts are added using the name provided by the remote
  1632. * database.
  1633. * @param $dbxref
  1634. * The unique database ID for the record to update. This value must
  1635. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  1636. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  1637. * for the record in the database.
  1638. * @param $db
  1639. * The name of the remote database to update. If this value is provided and
  1640. * no dbxref then all of the publications currently in the Chado database
  1641. * for this remote database will be updated.
  1642. *
  1643. * @ingroup tripal_pub
  1644. */
  1645. function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
  1646. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  1647. "If the load fails or is terminated prematurely then the entire set of \n" .
  1648. "insertions/updates is rolled back and will not be found in the database\n\n";
  1649. $transaction = db_transaction();
  1650. try {
  1651. // get a list of all publications by their Dbxrefs that have supported databases
  1652. $sql = "
  1653. SELECT DB.name as db_name, DBX.accession
  1654. FROM pub P
  1655. INNER JOIN pub_dbxref PDBX ON P.pub_id = PDBX.pub_id
  1656. INNER JOIN dbxref DBX ON DBX.dbxref_id = PDBX.dbxref_id
  1657. INNER JOIN db DB ON DB.db_id = DBX.db_id
  1658. ";
  1659. $args = array();
  1660. if ($dbxref and preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  1661. $dbname = $matches[1];
  1662. $accession = $matches[2];
  1663. $sql .= "WHERE DBX.accession = :accession and DB.name = :dbname ";
  1664. $args[':accession'] = $accession;
  1665. $args[':dbname'] = $dbname;
  1666. }
  1667. elseif ($db) {
  1668. $sql .= " WHERE DB.name = :dbname ";
  1669. $args[':dbname'] = $db;
  1670. }
  1671. $sql .= "ORDER BY DB.name, P.pub_id";
  1672. $results = chado_query($sql, $args);
  1673. $num_to_retrieve = 100;
  1674. $i = 0; // count the number of IDs. When we hit $num_to_retrieve we'll do the query
  1675. $curr_db = ''; // keeps track of the current current database
  1676. $ids = array(); // the list of IDs for the database
  1677. $search = array(); // the search array passed to the search function
  1678. // iterate through the pub IDs
  1679. while ($pub = $results->fetchObject()) {
  1680. $accession = $pub->accession;
  1681. $remote_db = $pub->db_name;
  1682. // here we need to only update publications for databases we support
  1683. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  1684. if(!in_array($remote_db, $supported_dbs)) {
  1685. continue;
  1686. }
  1687. $search = array(
  1688. 'num_criteria' => 1,
  1689. 'remote_db' => $remote_db,
  1690. 'criteria' => array(
  1691. '1' => array(
  1692. 'search_terms' => "$remote_db:$accession",
  1693. 'scope' => 'id',
  1694. 'operation' => '',
  1695. 'is_phrase' => 0,
  1696. ),
  1697. ),
  1698. );
  1699. $pubs = tripal_get_remote_pubs($remote_db, $search, 1, 0);
  1700. tripal_pub_add_publications($pubs, $do_contact, TRUE);
  1701. $i++;
  1702. }
  1703. // sync the newly added publications with Drupal
  1704. print "Syncing publications with Drupal...\n";
  1705. chado_node_sync_records('pub');
  1706. // if the caller wants to create contacts then we should sync them
  1707. if ($do_contact) {
  1708. print "Syncing contacts with Drupal...\n";
  1709. chado_node_sync_records('contact');
  1710. }
  1711. }
  1712. catch (Exception $e) {
  1713. $transaction->rollback();
  1714. print "\n"; // make sure we start errors on new line
  1715. watchdog_exception('T_pub_import', $e);
  1716. print "FAILED: Rolling back database changes...\n";
  1717. return;
  1718. }
  1719. print "Done.\n";
  1720. }