tripal_chado.pub_importers.inc 60 KB

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