tripal_chado.pub_importers.inc 58 KB

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