tripal_pub.pub_importers.inc 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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('class' => 'tripal-data-table'),
  709. 'sticky' => TRUE,
  710. 'caption' => '',
  711. 'colgroups' => array(),
  712. 'empty' => '',
  713. );
  714. $criteria_table = theme_table($table);
  715. $markup .= $criteria_table;
  716. // add the rendered form
  717. $form = array(
  718. '#markup' => $markup,
  719. '#prefix' => '<div id="tripal-pubs-importer-setup">',
  720. '#suffix' => '</div>',
  721. );
  722. return drupal_render($form);
  723. }
  724. /**
  725. * Add a job to import publications
  726. *
  727. * @param $pub_importer_id
  728. * The id of the importer to submit a job to update
  729. *
  730. * @ingroup tripal_pub
  731. */
  732. function tripal_pub_importer_submit_job($import_id) {
  733. global $user;
  734. // get all of the loaders
  735. $args = array(':import_id' => $import_id);
  736. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :import_id ";
  737. $import = db_query($sql, $args)->fetchObject();
  738. $args = array($import_id);
  739. tripal_add_job("Import publications $import->name", 'tripal_pub',
  740. 'tripal_execute_pub_importer', $args, $user->uid);
  741. drupal_goto('admin/tripal/chado/tripal_pub/import_list');
  742. }
  743. /**
  744. * Adds publications that have been retrieved from a remote database and
  745. * consolidated into an array of details.
  746. *
  747. * @param $pubs
  748. * An array containing a list of publications to add to Chado. The
  749. * array contains a set of details for the publication.
  750. * @param $do_contact
  751. * Set to TRUE if authors should automatically have a contact record added
  752. * to Chado.
  753. * @param $update
  754. * If set to TRUE then publications that already exist in the Chado database
  755. * will be updated, whereas if FALSE only new publications will be added
  756. *
  757. * @return
  758. * Returns an array containing the number of publications that were
  759. * inserted, updated, skipped and which had an error during import.
  760. *
  761. * @ingroup tripal_pub
  762. */
  763. function tripal_pub_add_publications($pubs, $do_contact, $update = FALSE) {
  764. $report = array();
  765. $report['error'] = 0;
  766. $report['inserted'] = array();
  767. $report['skipped'] = array();
  768. $total_pubs = count($pubs);
  769. // iterate through the publications and add each one
  770. $i = 1;
  771. foreach ($pubs as $pub) {
  772. $memory = number_format(memory_get_usage()) . " bytes";
  773. print "Processing $i of $total_pubs. Memory usage: $memory.\r";
  774. // add the publication to Chado
  775. $action = '';
  776. $pub_id = tripal_pub_add_publication($pub, $action, $do_contact, $update);
  777. if ($pub_id){
  778. // add the publication cross reference (e.g. to PubMed)
  779. if ($pub_id and $pub['Publication Dbxref']) {
  780. $pub_dbxref = tripal_pub_add_pub_dbxref($pub_id, $pub['Publication Dbxref']);
  781. }
  782. $pub['pub_id'] = $pub_id;
  783. }
  784. switch ($action) {
  785. case 'error':
  786. $report['error']++;
  787. break;
  788. case 'inserted':
  789. $report['inserted'][] = $pub;
  790. break;
  791. case 'updated':
  792. $report['updated'][] = $pub;
  793. break;
  794. case 'skipped':
  795. $report['skipped'][] = $pub;
  796. break;
  797. }
  798. $i++;
  799. }
  800. print "\n";
  801. return $report;
  802. }
  803. /**
  804. * Adds a new publication to the Chado, along with all properties and
  805. * database cross-references. If the publication does not already exist
  806. * in Chado then it is added. If it does exist nothing is done. If
  807. * the $update parameter is TRUE then the publication is updated if it exists.
  808. *
  809. * @param $pub_details
  810. * An associative array containing all of the details about the publication.
  811. * @param $action
  812. * This variable will get set to a text value indicating the action that was
  813. * performed. The values include 'skipped', 'inserted', 'updated' or 'error'.
  814. * @param $do_contact
  815. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  816. * for authors of the publication.
  817. * @param $update_if_exists
  818. * Optional. If the publication already exists then this function will return
  819. * without adding a new publication. However, set this value to TRUE to force
  820. * the function to pudate the publication using the $pub_details that are provided.
  821. *
  822. * @return
  823. * If the publication already exists, is inserted or updated then the publication
  824. * ID is returned, otherwise FALSE is returned. If the publication already exists
  825. * and $update_if_exists is not TRUE then the $action variable is set to 'skipped'.
  826. * If the publication already exists and $update_if_exists is TRUE and if the update
  827. * was successful then $action is set to 'updated'. Otherwise on successful insert
  828. * the $action variable is set to 'inserted'. If the function failes then the
  829. * $action variable is set to 'error'
  830. *
  831. * @ingroup tripal_pub
  832. */
  833. function tripal_pub_add_publication($pub_details, &$action, $do_contact = FALSE, $update_if_exists = FALSE) {
  834. $pub_id = 0;
  835. if (!is_array($pub_details)) {
  836. return FALSE;
  837. }
  838. // before proceeding check to see if the publication already exists. If there is only one match
  839. // and the $update_if_exists is NOT set then return FALSE
  840. $pub_ids = chado_does_pub_exist($pub_details);
  841. if(count($pub_ids) == 1 and !$update_if_exists) {
  842. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  843. "There is a publication that is a duplicate of this publication. Cannot continue. It either ".
  844. "has a matching Dbxref (e.g. PubMed ID), a non-unique citation or matches on the unique " .
  845. "constraint set by the Tripal publication module configuration page. \nCitation: %title %dbxref.\nMatching Pub id: %ids",
  846. array(
  847. '%title' => $pub_details['Citation'],
  848. '%dbxref' => $pub_details['Publication Dbxref'],
  849. '%ids' => implode(",", $pub_ids),
  850. )
  851. );
  852. $action = 'skipped';
  853. return FALSE;
  854. }
  855. // if we have more than one matching pub then return an error as we don't know which to update even if
  856. // update_if_exists is set to TRUE
  857. if(count($pub_ids) > 1) {
  858. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  859. "There are %num publications that are duplicates of this publication. They either " .
  860. "have a matching Dbxref (e.g. PubMed ID) or match on the unique constraint set by the Tripal publication module ".
  861. "configuration page. \nCitation: %title %dbxref.\nMatching Pub ids: %ids",
  862. array(
  863. '%num' => count($pub_ids),
  864. '%title' => $pub_details['Citation'],
  865. '%dbxref' => $pub_details['Publication Dbxref'],
  866. '%ids' => implode(",", $pub_ids),
  867. )
  868. );
  869. $action = 'skipped';
  870. return FALSE;
  871. }
  872. // get the publication type (use the first publication type)
  873. if (array_key_exists('Publication Type', $pub_details)) {
  874. $pub_type = '';
  875. if(is_array($pub_details['Publication Type'])) {
  876. $pub_type = $pub_details['Publication Type'][0];
  877. }
  878. else {
  879. $pub_type = $pub_details['Publication Type'];
  880. }
  881. $identifiers = array(
  882. 'name' => $pub_type,
  883. 'cv_id' => array(
  884. 'name' => 'tripal_pub'
  885. ),
  886. );
  887. $pub_type = tripal_get_cvterm($identifiers);
  888. }
  889. else {
  890. tripal_report_error('tripal_pub', TRIPAL_ERROR,
  891. "The Publication Type is a required property but is missing", array());
  892. $action = 'error';
  893. return FALSE;
  894. }
  895. if (!$pub_type) {
  896. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find publication type: '%type'",
  897. array('%type' => $pub_details['Publication Type'][0]));
  898. $action = 'error';
  899. return FALSE;
  900. }
  901. // the series name field in the pub table is only 255 characters, so we should trim just in case
  902. $series_name = '';
  903. if (array_key_exists('Series_Name', $pub_details)) {
  904. $series_name = substr($pub_details['Series Name'], 0, 255);
  905. }
  906. if (array_key_exists('Journal Name', $pub_details)) {
  907. $series_name = substr($pub_details['Journal Name'], 0, 255);
  908. }
  909. // build the values array for inserting or updating
  910. $values = array(
  911. 'title' => $pub_details['Title'],
  912. 'volume' => $pub_details['Volume'],
  913. 'series_name' => $series_name,
  914. 'issue' => $pub_details['Issue'],
  915. 'pyear' => $pub_details['Year'],
  916. 'pages' => $pub_details['Pages'],
  917. 'uniquename' => $pub_details['Citation'],
  918. 'type_id' => $pub_type->cvterm_id,
  919. );
  920. // if there is no pub_id then we need to do an insert.
  921. if (!$pub_id) {
  922. $options = array('statement_name' => 'ins_pub_tivoseispypaunty');
  923. $pub = chado_insert_record('pub', $values, $options);
  924. if (!$pub) {
  925. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot insert the publication with title: %title",
  926. array('%title' => $pub_details['Title']));
  927. $action = 'error';
  928. return FALSE;
  929. }
  930. $pub_id = $pub['pub_id'];
  931. $action = 'inserted';
  932. }
  933. // if there is a pub_id and we've been told to update, then do the update
  934. if ($pub_id and $update_if_exists) {
  935. $match = array('pub_id' => $pub_id);
  936. $options = array('statement_name' => 'up_pub_tivoseispypaunty');
  937. $success = chado_update_record('pub', $match, $values, $options);
  938. if (!$success) {
  939. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot update the publication with title: %title",
  940. array('%title' => $pub_details['Title']));
  941. $action = 'error';
  942. return FALSE;
  943. }
  944. $action = 'updated';
  945. }
  946. // before we add any new properties we need to remove those that are there if this
  947. // is an update. The only thing we don't want to remove are the 'Publication Dbxref'
  948. if ($update_if_exists) {
  949. $sql = "
  950. DELETE FROM {pubprop}
  951. WHERE
  952. pub_id = :pub_id AND
  953. NOT type_id in (
  954. SELECT cvterm_id
  955. FROM {cvterm}
  956. WHERE name = 'Publication Dbxref'
  957. )
  958. ";
  959. chado_query($sql, array(':pub_id' => $pub_id));
  960. }
  961. // iterate through the properties and add them
  962. foreach ($pub_details as $key => $value) {
  963. // the pub_details may have the raw search data (e.g. in XML from PubMed. We'll irgnore this for now
  964. if($key == 'raw') {
  965. continue;
  966. }
  967. // get the cvterm by name
  968. $identifiers = array(
  969. 'name' => $key,
  970. 'cv_id' => array(
  971. 'name' => 'tripal_pub'
  972. ),
  973. );
  974. $cvterm = tripal_get_cvterm($identifiers);
  975. // if we could not find the cvterm by name then try by synonym
  976. //$cvterm = tripal_cv_get_cvterm_by_name($key, NULL, 'tripal_pub');
  977. if (!$cvterm) {
  978. $identifiers = array(
  979. 'synonym' => array(
  980. 'name' => $key,
  981. 'cv_name' => 'tripal_pub'
  982. )
  983. );
  984. $cvterm = tripal_get_cvterm($identifiers);
  985. }
  986. if (!$cvterm) {
  987. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find term: '%prop'. Skipping.", array('%prop' => $key));
  988. continue;
  989. }
  990. // skip details that won't be stored as properties
  991. if ($key == 'Author List') {
  992. tripal_pub_add_authors($pub_id, $value, $do_contact);
  993. continue;
  994. }
  995. if ($key == 'Title' or $key == 'Volume' or $key == 'Journal Name' or $key == 'Issue' or
  996. $key == 'Year' or $key == 'Pages') {
  997. continue;
  998. }
  999. $success = 0;
  1000. if (is_array($value)) {
  1001. foreach ($value as $subkey => $subvalue) {
  1002. // if the key is an integer then this array is a simple list and
  1003. // we will insert using the primary key. Otheriwse, use the new key
  1004. if(is_int($subkey)) {
  1005. $success = chado_insert_property('pub', $pub_id, $key, 'tripal_pub', $subvalue, FALSE);
  1006. }
  1007. else {
  1008. $success = chado_insert_property('pub', $pub_id, $subkey, 'tripal_pub', $subvalue, FALSE);
  1009. }
  1010. }
  1011. }
  1012. else {
  1013. $success = chado_insert_property('pub', $pub_id, $key, 'tripal_pub', $value, TRUE);
  1014. }
  1015. if (!$success) {
  1016. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot add property '%prop' to publication. Skipping.",
  1017. array('%prop' => $key));
  1018. continue;
  1019. }
  1020. }
  1021. return $pub_id;
  1022. }
  1023. /**
  1024. * Add one or more authors to a publication
  1025. *
  1026. * @param $pub_id
  1027. * The publication ID of the pub in Chado.
  1028. * @param $authors
  1029. * An array of authors. Each author should have a set of keys/value pairs
  1030. * describing the author.
  1031. * @param $do_contact
  1032. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  1033. * for authors of the publication.
  1034. * @ingroup tripal_pub
  1035. */
  1036. function tripal_pub_add_authors($pub_id, $authors, $do_contact) {
  1037. $rank = 0;
  1038. // first remove any of the existing pubauthor entires
  1039. $sql = "DELETE FROM {pubauthor} WHERE pub_id = :pub_id";
  1040. chado_query($sql, array(':pub_id' => $pub_id));
  1041. // iterate through the authors and add them to the pubauthors and contact
  1042. // tables of chado, then link them through the custom pubauthors_contact table
  1043. foreach ($authors as $author) {
  1044. // skip invalid author entires
  1045. if ($author['valid'] == 'N') {
  1046. continue;
  1047. }
  1048. // remove the 'valid' property as we don't have a CV term for it
  1049. unset($author['valid']);
  1050. // construct the contact.name field using the author information
  1051. $name = '';
  1052. $type = 'Person';
  1053. if ($author['Given Name']) {
  1054. $name .= $author['Given Name'];
  1055. }
  1056. if ($author['Surname']) {
  1057. $name .= ' ' . $author['Surname'];
  1058. }
  1059. if ($author['Suffix']) {
  1060. $name .= ' ' . $author['Suffix'];
  1061. }
  1062. if ($author['Collective']) {
  1063. $name = $author['Collective'];
  1064. $type = 'Collective';
  1065. }
  1066. $name = trim($name);
  1067. // add an entry to the pubauthors table
  1068. $values = array(
  1069. 'pub_id' => $pub_id,
  1070. 'rank' => $rank,
  1071. 'surname' => $author['Surname'] ? substr($author['Surname'], 0, 100) : substr($author['Collective'], 0, 100),
  1072. 'givennames' => $author['Given Name'],
  1073. 'suffix' => $author['Suffix'],
  1074. );
  1075. $options = array('statement_name' => 'ins_pubauthor_idrasugisu');
  1076. $pubauthor = chado_insert_record('pubauthor', $values, $options);
  1077. // if the user wants us to create a contact for each author then do it.
  1078. if ($do_contact) {
  1079. // Add the contact
  1080. $contact = tripal_contact_add_contact($name, '', $type, $author);
  1081. // if we have succesfully added the contact and the pubauthor entries then we want to
  1082. // link them together
  1083. if ($contact and $pubauthor) {
  1084. // link the pubauthor entry to the contact
  1085. $values = array(
  1086. 'pubauthor_id' => $pubauthor['pubauthor_id'],
  1087. 'contact_id' => $contact['contact_id'],
  1088. );
  1089. $options = array('statement_name' => 'ins_pubauthorcontact_puco');
  1090. $pubauthor_contact = chado_insert_record('pubauthor_contact', $values, $options);
  1091. if (!$pubauthor_contact) {
  1092. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot link pub authro and contact.", array());
  1093. }
  1094. }
  1095. }
  1096. $rank++;
  1097. }
  1098. }
  1099. /**
  1100. * This function generates an array suitable for use with the
  1101. * tripal_pub_create_citation function for any publication
  1102. * already stored in the Chado tables.
  1103. *
  1104. * @param $pub_id
  1105. * The publication ID
  1106. * @param $skip_existing
  1107. * Set to TRUE to skip publications that already have a citation
  1108. * in the pubprop table. Set to FALSE to generate a citation
  1109. * regardless if the citation already exists.
  1110. *
  1111. * @return
  1112. * An array suitable for the trpial_pub_create_citation function. On
  1113. * failure returns FALSE.
  1114. *
  1115. * @ingroup tripal_pub
  1116. */
  1117. function tripal_pub_get_publication_array($pub_id, $skip_existing = TRUE) {
  1118. $options = array('return_array' => 1);
  1119. // ---------------------------------
  1120. // get the publication
  1121. // ---------------------------------
  1122. $values = array('pub_id' => $pub_id);
  1123. $pub = chado_generate_var('pub', $values);
  1124. // expand the title
  1125. $pub = chado_expand_var($pub, 'field', 'pub.title');
  1126. $pub = chado_expand_var($pub, 'field', 'pub.volumetitle');
  1127. $pub = chado_expand_var($pub, 'field', 'pub.uniquename');
  1128. $pub_array = array();
  1129. if (trim($pub->title)) {
  1130. $pub_array['Title'] = $pub->title;
  1131. }
  1132. if (trim($pub->volumetitle)) {
  1133. $pub_array['Volume Title'] = $pub->volumetitle;
  1134. }
  1135. if (trim($pub->volume)) {
  1136. $pub_array['Volume'] = $pub->volume;
  1137. }
  1138. if (trim($pub->series_name)) {
  1139. $pub_array['Series Name'] = $pub->series_name;
  1140. }
  1141. if (trim($pub->issue)) {
  1142. $pub_array['Issue'] = $pub->issue;
  1143. }
  1144. if (trim($pub->pyear)) {
  1145. $pub_array['Year'] = $pub->pyear;
  1146. }
  1147. if (trim($pub->pages)) {
  1148. $pub_array['Pages'] = $pub->pages;
  1149. }
  1150. if (trim($pub->miniref)) {
  1151. $pub_array['Mini Ref'] = $pub->miniref;
  1152. }
  1153. if (trim($pub->uniquename)) {
  1154. $pub_array['Uniquename'] = $pub->uniquename;
  1155. }
  1156. $pub_array['Publication Type'][] = $pub->type_id->name;
  1157. // ---------------------------------
  1158. // get the citation
  1159. // ---------------------------------
  1160. $values = array(
  1161. 'pub_id' => $pub->pub_id,
  1162. 'type_id' => array(
  1163. 'name' => 'Citation',
  1164. ),
  1165. );
  1166. $citation = chado_generate_var('pubprop', $values);
  1167. if ($citation) {
  1168. $citation = chado_expand_var($citation, 'field', 'pubprop.value', $options);
  1169. if (count($citation) > 1) {
  1170. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple citations already: %pub_id",
  1171. array('%pub_id' => $pubid));
  1172. return FALSE;
  1173. }
  1174. elseif (count($citation) == 1 and $skip_existing == TRUE) {
  1175. // skip this publication, it already has a citation
  1176. return FALSE;
  1177. }
  1178. }
  1179. // ---------------------------------
  1180. // get the publication types
  1181. // ---------------------------------
  1182. $values = array(
  1183. 'pub_id' => $pub->pub_id,
  1184. 'type_id' => array(
  1185. 'name' => 'Publication Type',
  1186. ),
  1187. );
  1188. $ptypes = chado_generate_var('pubprop', $values, $options);
  1189. if ($ptypes) {
  1190. $ptypes = chado_expand_var($ptypes, 'field', 'pubprop.value', $options);
  1191. foreach ($ptypes as $ptype) {
  1192. $pub_array['Publication Type'][] = $ptype->value;
  1193. }
  1194. }
  1195. // ---------------------------------
  1196. // get the authors list
  1197. // ---------------------------------
  1198. $values = array(
  1199. 'pub_id' => $pub->pub_id,
  1200. 'type_id' => array(
  1201. 'name' => 'Authors',
  1202. ),
  1203. );
  1204. $authors = chado_generate_var('pubprop', $values);
  1205. $authors = chado_expand_var($authors, 'field', 'pubprop.value', $options);
  1206. if (count($authors) > 1) {
  1207. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple author lists. It should have only one list: %pub_id",
  1208. array('%pub_id' => $pubid));
  1209. return FALSE;
  1210. }
  1211. else if (trim($authors->value)) {
  1212. $pub_array['Authors'] = $authors->value;
  1213. }
  1214. // if there is no 'Author's property then try to retreive authors from the pubauthor table
  1215. else {
  1216. $sql = "
  1217. SELECT string_agg(surname || ' ' || givennames, ', ')
  1218. FROM {pubauthor}
  1219. WHERE pub_id = :pub_id
  1220. GROUP BY pub_id
  1221. ";
  1222. $au = chado_query($sql, array(':pub_id' => $pub_id))->fetchField();
  1223. if ($au) {
  1224. $pub_array['Authors'] = $au;
  1225. }
  1226. }
  1227. //Get other props
  1228. $props = array(
  1229. 'Journal Abbreviation',
  1230. 'Elocation',
  1231. 'Media Code',
  1232. 'Conference Name',
  1233. 'Keywords',
  1234. 'Series Name',
  1235. 'pISSN',
  1236. 'Publication Date',
  1237. 'Journal Code',
  1238. 'Journal Alias',
  1239. 'Journal Country',
  1240. 'Published Location',
  1241. 'Publication Model',
  1242. 'Language Abbr',
  1243. 'Alias',
  1244. 'Publication Dbxref',
  1245. 'Copyright',
  1246. 'Abstract',
  1247. 'Notes',
  1248. 'Citation',
  1249. 'Language',
  1250. 'URL',
  1251. 'eISSN',
  1252. 'DOI',
  1253. 'ISSN',
  1254. 'Publication Code',
  1255. 'Comments',
  1256. 'Publisher',
  1257. 'Media Alias',
  1258. 'Original Title'
  1259. );
  1260. foreach ($props AS $prop) {
  1261. $sql =
  1262. "SELECT value FROM {pubprop}
  1263. WHERE type_id =
  1264. (SELECT cvterm_id
  1265. FROM {cvterm}
  1266. WHERE name = :cvtname AND cv_id =
  1267. (SELECT cv_id
  1268. FROM {cv}
  1269. WHERE name = 'tripal_pub'
  1270. )
  1271. )
  1272. AND pub_id = :pub_id
  1273. ";
  1274. $val = trim(chado_query($sql, array(':cvtname' => $prop, ':pub_id' => $pub->pub_id))->fetchField());
  1275. if ($val) {
  1276. $pub_array[$prop] =$val;
  1277. }
  1278. }
  1279. return $pub_array;
  1280. }