tripal_chado.pub_importers.inc 58 KB

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