tripal_chado.pub_importers.inc 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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;
  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('Remote Database'),
  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. tripal_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);
  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. 'tripal_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. *
  805. * @return
  806. * Returns an array containing the number of publications that were
  807. * inserted, updated, skipped and which had an error during import.
  808. *
  809. * @ingroup tripal_pub
  810. */
  811. function tripal_pub_add_publications($pubs, $do_contact, $update = FALSE) {
  812. $report = array();
  813. $report['error'] = 0;
  814. $report['inserted'] = array();
  815. $report['skipped'] = array();
  816. $total_pubs = count($pubs);
  817. // iterate through the publications and add each one
  818. $i = 1;
  819. foreach ($pubs as $pub) {
  820. $memory = number_format(memory_get_usage()) . " bytes";
  821. print "Processing $i of $total_pubs. Memory usage: $memory.\r";
  822. // add the publication to Chado
  823. $action = '';
  824. $pub_id = tripal_pub_add_publication($pub, $action, $do_contact, $update);
  825. if ($pub_id){
  826. // add the publication cross reference (e.g. to PubMed)
  827. if ($pub_id and $pub['Publication Dbxref']) {
  828. $dbxref = array();
  829. if (preg_match('/^(.*?):(.*?)$/', trim($pub['Publication Dbxref']), $matches)) {
  830. $dbxref['db_name'] = $matches[1];
  831. $dbxref['accession'] = $matches[2];
  832. }
  833. else {
  834. tripal_report_error(
  835. 'tripal_pub',
  836. TRIPAL_ERROR,
  837. 'Unable to extract the dbxref to be associated with the publication (pub ID=@pub_id) from @dbxref. This reference should be [database-name]:[accession]',
  838. array('@pub_id' => $pub_id, '@dbxref' => $pub['Publication Dbxref'])
  839. );
  840. }
  841. $pub_dbxref = tripal_associate_dbxref('pub', $pub_id, $dbxref);
  842. }
  843. $pub['pub_id'] = $pub_id;
  844. }
  845. switch ($action) {
  846. case 'error':
  847. $report['error']++;
  848. break;
  849. case 'inserted':
  850. $report['inserted'][] = $pub;
  851. break;
  852. case 'updated':
  853. $report['updated'][] = $pub;
  854. break;
  855. case 'skipped':
  856. $report['skipped'][] = $pub;
  857. break;
  858. }
  859. $i++;
  860. }
  861. print "\n";
  862. return $report;
  863. }
  864. /**
  865. * Adds a new publication to the Chado, along with all properties and
  866. * database cross-references. If the publication does not already exist
  867. * in Chado then it is added. If it does exist nothing is done. If
  868. * the $update parameter is TRUE then the publication is updated if it exists.
  869. *
  870. * @param $pub_details
  871. * An associative array containing all of the details about the publication.
  872. * @param $action
  873. * This variable will get set to a text value indicating the action that was
  874. * performed. The values include 'skipped', 'inserted', 'updated' or 'error'.
  875. * @param $do_contact
  876. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  877. * for authors of the publication.
  878. * @param $update_if_exists
  879. * Optional. If the publication already exists then this function will return
  880. * without adding a new publication. However, set this value to TRUE to force
  881. * the function to pudate the publication using the $pub_details that are provided.
  882. *
  883. * @return
  884. * If the publication already exists, is inserted or updated then the publication
  885. * ID is returned, otherwise FALSE is returned. If the publication already exists
  886. * and $update_if_exists is not TRUE then the $action variable is set to 'skipped'.
  887. * If the publication already exists and $update_if_exists is TRUE and if the update
  888. * was successful then $action is set to 'updated'. Otherwise on successful insert
  889. * the $action variable is set to 'inserted'. If the function failes then the
  890. * $action variable is set to 'error'
  891. *
  892. * @ingroup tripal_pub
  893. */
  894. function tripal_pub_add_publication($pub_details, &$action, $do_contact = FALSE, $update_if_exists = FALSE) {
  895. $pub_id = 0;
  896. if (!is_array($pub_details)) {
  897. return FALSE;
  898. }
  899. // before proceeding check to see if the publication already exists. If there is only one match
  900. // and the $update_if_exists is NOT set then return FALSE
  901. $pub_ids = chado_publication_exists($pub_details);
  902. if(count($pub_ids) == 1 and !$update_if_exists) {
  903. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  904. "There is a publication that is a duplicate of this publication. Cannot continue. It either ".
  905. "has a matching Dbxref (e.g. PubMed ID), a non-unique citation or matches on the unique " .
  906. "constraint set by the Tripal publication module configuration page. \nCitation: %title %dbxref.\nMatching Pub id: %ids",
  907. array(
  908. '%title' => $pub_details['Citation'],
  909. '%dbxref' => $pub_details['Publication Dbxref'],
  910. '%ids' => implode(",", $pub_ids),
  911. )
  912. );
  913. $action = 'skipped';
  914. return FALSE;
  915. }
  916. // if we have more than one matching pub then return an error as we don't know which to update even if
  917. // update_if_exists is set to TRUE
  918. if(count($pub_ids) > 1) {
  919. tripal_report_error('tripal_pub', TRIPAL_NOTICE,
  920. "There are %num publications that are duplicates of this publication. They either " .
  921. "have a matching Dbxref (e.g. PubMed ID) or match on the unique constraint set by the Tripal publication module ".
  922. "configuration page. \nCitation: %title %dbxref.\nMatching Pub ids: %ids",
  923. array(
  924. '%num' => count($pub_ids),
  925. '%title' => $pub_details['Citation'],
  926. '%dbxref' => $pub_details['Publication Dbxref'],
  927. '%ids' => implode(",", $pub_ids),
  928. )
  929. );
  930. $action = 'skipped';
  931. return FALSE;
  932. }
  933. if(count($pub_ids) == 1 and $update_if_exists) {
  934. $pub_id = $pub_ids[0];
  935. }
  936. // get the publication type (use the first publication type)
  937. if (array_key_exists('Publication Type', $pub_details)) {
  938. $pub_type = '';
  939. if(is_array($pub_details['Publication Type'])) {
  940. $pub_type = $pub_details['Publication Type'][0];
  941. }
  942. else {
  943. $pub_type = $pub_details['Publication Type'];
  944. }
  945. $identifiers = array(
  946. 'name' => $pub_type,
  947. 'cv_id' => array(
  948. 'name' => 'tripal_pub'
  949. ),
  950. );
  951. $pub_type = chado_get_cvterm($identifiers);
  952. }
  953. else {
  954. tripal_report_error('tripal_pub', TRIPAL_ERROR,
  955. "The Publication Type is a required property but is missing", array());
  956. $action = 'error';
  957. return FALSE;
  958. }
  959. if (!$pub_type) {
  960. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find publication type: '%type'",
  961. array('%type' => $pub_details['Publication Type'][0]));
  962. $action = 'error';
  963. return FALSE;
  964. }
  965. // the series name field in the pub table is only 255 characters, so we should trim just in case
  966. $series_name = '';
  967. if (array_key_exists('Series_Name', $pub_details)) {
  968. $series_name = substr($pub_details['Series Name'], 0, 255);
  969. }
  970. if (array_key_exists('Journal Name', $pub_details)) {
  971. $series_name = substr($pub_details['Journal Name'], 0, 255);
  972. }
  973. // build the values array for inserting or updating
  974. $values = array(
  975. 'title' => $pub_details['Title'],
  976. 'volume' => (isset($pub_details['Volume'])) ? $pub_details['Volume'] : '',
  977. 'series_name' => $series_name,
  978. 'issue' => (isset($pub_details['Issue'])) ? $pub_details['Issue'] : '',
  979. 'pyear' => (isset($pub_details['Year'])) ? $pub_details['Year'] : '',
  980. 'pages' => (isset($pub_details['Pages'])) ? $pub_details['Pages'] : '',
  981. 'uniquename' => $pub_details['Citation'],
  982. 'type_id' => $pub_type->cvterm_id,
  983. );
  984. // if there is no pub_id then we need to do an insert.
  985. if (!$pub_id) {
  986. $options = array('statement_name' => 'ins_pub_tivoseispypaunty');
  987. $pub = chado_insert_record('pub', $values, $options);
  988. if (!$pub) {
  989. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot insert the publication with title: %title",
  990. array('%title' => $pub_details['Title']));
  991. $action = 'error';
  992. return FALSE;
  993. }
  994. $pub_id = $pub['pub_id'];
  995. $action = 'inserted';
  996. }
  997. // if there is a pub_id and we've been told to update, then do the update
  998. if ($pub_id and $update_if_exists) {
  999. $match = array('pub_id' => $pub_id);
  1000. $options = array('statement_name' => 'up_pub_tivoseispypaunty');
  1001. $success = chado_update_record('pub', $match, $values, $options);
  1002. if (!$success) {
  1003. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot update the publication with title: %title",
  1004. array('%title' => $pub_details['Title']));
  1005. $action = 'error';
  1006. return FALSE;
  1007. }
  1008. $action = 'updated';
  1009. }
  1010. // before we add any new properties we need to remove those that are there if this
  1011. // is an update. The only thing we don't want to remove are the 'Publication Dbxref'
  1012. if ($update_if_exists) {
  1013. $sql = "
  1014. DELETE FROM {pubprop}
  1015. WHERE
  1016. pub_id = :pub_id AND
  1017. NOT type_id in (
  1018. SELECT cvterm_id
  1019. FROM {cvterm}
  1020. WHERE name = 'Publication Dbxref'
  1021. )
  1022. ";
  1023. chado_query($sql, array(':pub_id' => $pub_id));
  1024. }
  1025. // iterate through the properties and add them
  1026. foreach ($pub_details as $key => $value) {
  1027. // the pub_details may have the raw search data (e.g. in XML from PubMed. We'll irgnore this for now
  1028. if($key == 'raw') {
  1029. continue;
  1030. }
  1031. // get the cvterm by name
  1032. $identifiers = array(
  1033. 'name' => $key,
  1034. 'cv_id' => array(
  1035. 'name' => 'tripal_pub'
  1036. ),
  1037. );
  1038. $cvterm = chado_get_cvterm($identifiers);
  1039. // if we could not find the cvterm by name then try by synonym
  1040. //$cvterm = chado_get_cvterm(array('name' => $key, 'cv_id' => array('name' => 'tripal_pub')));
  1041. if (!$cvterm) {
  1042. $identifiers = array(
  1043. 'synonym' => array(
  1044. 'name' => $key,
  1045. 'cv_name' => 'tripal_pub'
  1046. )
  1047. );
  1048. $cvterm = chado_get_cvterm($identifiers);
  1049. }
  1050. if (!$cvterm) {
  1051. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot find term: '%prop'. Skipping.", array('%prop' => $key));
  1052. continue;
  1053. }
  1054. // skip details that won't be stored as properties
  1055. if ($key == 'Author List') {
  1056. tripal_pub_add_authors($pub_id, $value, $do_contact);
  1057. continue;
  1058. }
  1059. if ($key == 'Title' or $key == 'Volume' or $key == 'Journal Name' or $key == 'Issue' or
  1060. $key == 'Year' or $key == 'Pages') {
  1061. continue;
  1062. }
  1063. $success = 0;
  1064. if (is_array($value)) {
  1065. foreach ($value as $subkey => $subvalue) {
  1066. // if the key is an integer then this array is a simple list and
  1067. // we will insert using the primary key. Otheriwse, use the new key
  1068. if(is_int($subkey)) {
  1069. $success = chado_insert_property(
  1070. array('table' => 'pub', 'id' => $pub_id),
  1071. array('type_name' => $key, 'cv_name' => 'tripal_pub', 'value' => $subvalue)
  1072. );
  1073. }
  1074. else {
  1075. $success = chado_insert_property(
  1076. array('table' => 'pub', 'id' => $pub_id),
  1077. array('type_name' => $subkey, 'cv_name' => 'tripal_pub', 'value' => $subvalue)
  1078. );
  1079. }
  1080. }
  1081. }
  1082. else {
  1083. $success = chado_insert_property(
  1084. array('table' => 'pub', 'id' => $pub_id),
  1085. array('type_name' => $key, 'cv_name' => 'tripal_pub', 'value' => $value),
  1086. array('update_if_present' => TRUE)
  1087. );
  1088. }
  1089. if (!$success) {
  1090. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot add property '%prop' to publication. Skipping.",
  1091. array('%prop' => $key));
  1092. continue;
  1093. }
  1094. }
  1095. return $pub_id;
  1096. }
  1097. /**
  1098. * Add one or more authors to a publication
  1099. *
  1100. * @param $pub_id
  1101. * The publication ID of the pub in Chado.
  1102. * @param $authors
  1103. * An array of authors. Each author should have a set of keys/value pairs
  1104. * describing the author.
  1105. * @param $do_contact
  1106. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  1107. * for authors of the publication.
  1108. * @ingroup tripal_pub
  1109. */
  1110. function tripal_pub_add_authors($pub_id, $authors, $do_contact) {
  1111. $rank = 0;
  1112. // First remove any of the existing pubauthor entires.
  1113. $sql = "DELETE FROM {pubauthor} WHERE pub_id = :pub_id";
  1114. chado_query($sql, array(':pub_id' => $pub_id));
  1115. // Iterate through the authors and add them to the pubauthors and contact
  1116. // tables of chado, then link them through the custom pubauthors_contact
  1117. // table.
  1118. foreach ($authors as $author) {
  1119. // Skip invalid author entires.
  1120. if (isset($author['valid']) AND $author['valid'] == 'N') {
  1121. continue;
  1122. }
  1123. // remove the 'valid' property as we don't have a CV term for it
  1124. unset($author['valid']);
  1125. $values = array(
  1126. 'pub_id' => $pub_id,
  1127. 'rank' => $rank,
  1128. );
  1129. // construct the contact.name field using the author information
  1130. $name = '';
  1131. $type = 'Person';
  1132. if (isset($author['Given Name'])) {
  1133. $name .= $author['Given Name'];
  1134. $values['givennames'] = $author['Given Name'];
  1135. }
  1136. if (isset($author['Surname'])) {
  1137. $name .= ' ' . $author['Surname'];
  1138. $values['surname'] = substr($author['Surname'], 0, 100);
  1139. }
  1140. if (isset($author['Suffix'])) {
  1141. $name .= ' ' . $author['Suffix'];
  1142. $values['suffix'] = $author['Suffix'];
  1143. }
  1144. if (isset($author['Collective'])) {
  1145. $name = $author['Collective'];
  1146. $type = 'Collective';
  1147. if (!isset($author['Surname']))
  1148. $values['surname'] = substr($author['Collective'], 0, 100);
  1149. }
  1150. $name = trim($name);
  1151. // add an entry to the pubauthors table
  1152. $options = array('statement_name' => 'ins_pubauthor_idrasugisu');
  1153. $pubauthor = chado_insert_record('pubauthor', $values, $options);
  1154. // if the user wants us to create a contact for each author then do it.
  1155. if ($do_contact) {
  1156. // Add the contact
  1157. $contact = chado_insert_contact(array(
  1158. 'name' => $name,
  1159. 'description' => '',
  1160. 'type_name' => $type,
  1161. 'properties' => $author
  1162. ));
  1163. // if we have succesfully added the contact and the pubauthor entries then we want to
  1164. // link them together
  1165. if ($contact and $pubauthor) {
  1166. // link the pubauthor entry to the contact
  1167. $values = array(
  1168. 'pubauthor_id' => $pubauthor['pubauthor_id'],
  1169. 'contact_id' => $contact['contact_id'],
  1170. );
  1171. $options = array('statement_name' => 'ins_pubauthorcontact_puco');
  1172. $pubauthor_contact = chado_insert_record('pubauthor_contact', $values, $options);
  1173. if (!$pubauthor_contact) {
  1174. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Cannot link pub authro and contact.", array());
  1175. }
  1176. }
  1177. }
  1178. $rank++;
  1179. }
  1180. }
  1181. /**
  1182. * This function generates an array suitable for use with the
  1183. * tripal_pub_create_citation function for any publication
  1184. * already stored in the Chado tables.
  1185. *
  1186. * @param $pub_id
  1187. * The publication ID
  1188. * @param $skip_existing
  1189. * Set to TRUE to skip publications that already have a citation
  1190. * in the pubprop table. Set to FALSE to generate a citation
  1191. * regardless if the citation already exists.
  1192. *
  1193. * @return
  1194. * An array suitable for the trpial_pub_create_citation function. On
  1195. * failure returns FALSE.
  1196. *
  1197. * @ingroup tripal_pub
  1198. */
  1199. function tripal_pub_get_publication_array($pub_id, $skip_existing = TRUE) {
  1200. $options = array('return_array' => 1);
  1201. // ---------------------------------
  1202. // get the publication
  1203. // ---------------------------------
  1204. $values = array('pub_id' => $pub_id);
  1205. $pub = chado_generate_var('pub', $values);
  1206. // expand the title
  1207. $pub = chado_expand_var($pub, 'field', 'pub.title');
  1208. $pub = chado_expand_var($pub, 'field', 'pub.volumetitle');
  1209. $pub = chado_expand_var($pub, 'field', 'pub.uniquename');
  1210. $pub_array = array();
  1211. if (trim($pub->title)) {
  1212. $pub_array['Title'] = $pub->title;
  1213. }
  1214. if (trim($pub->volumetitle)) {
  1215. $pub_array['Volume Title'] = $pub->volumetitle;
  1216. }
  1217. if (trim($pub->volume)) {
  1218. $pub_array['Volume'] = $pub->volume;
  1219. }
  1220. if (trim($pub->series_name)) {
  1221. $pub_array['Series Name'] = $pub->series_name;
  1222. }
  1223. if (trim($pub->issue)) {
  1224. $pub_array['Issue'] = $pub->issue;
  1225. }
  1226. if (trim($pub->pyear)) {
  1227. $pub_array['Year'] = $pub->pyear;
  1228. }
  1229. if (trim($pub->pages)) {
  1230. $pub_array['Pages'] = $pub->pages;
  1231. }
  1232. if (trim($pub->miniref)) {
  1233. $pub_array['Mini Ref'] = $pub->miniref;
  1234. }
  1235. if (trim($pub->uniquename)) {
  1236. $pub_array['Uniquename'] = $pub->uniquename;
  1237. }
  1238. $pub_array['Publication Type'][] = $pub->type_id->name;
  1239. // ---------------------------------
  1240. // get the citation
  1241. // ---------------------------------
  1242. $values = array(
  1243. 'pub_id' => $pub->pub_id,
  1244. 'type_id' => array(
  1245. 'name' => 'Citation',
  1246. ),
  1247. );
  1248. $citation = chado_generate_var('pubprop', $values);
  1249. if ($citation) {
  1250. $citation = chado_expand_var($citation, 'field', 'pubprop.value', $options);
  1251. if (count($citation) > 1) {
  1252. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple citations already: %pub_id",
  1253. array('%pub_id' => $pubid));
  1254. return FALSE;
  1255. }
  1256. elseif (count($citation) == 1 and $skip_existing == TRUE) {
  1257. // skip this publication, it already has a citation
  1258. return FALSE;
  1259. }
  1260. }
  1261. // ---------------------------------
  1262. // get the publication types
  1263. // ---------------------------------
  1264. $values = array(
  1265. 'pub_id' => $pub->pub_id,
  1266. 'type_id' => array(
  1267. 'name' => 'Publication Type',
  1268. ),
  1269. );
  1270. $ptypes = chado_generate_var('pubprop', $values, $options);
  1271. if ($ptypes) {
  1272. $ptypes = chado_expand_var($ptypes, 'field', 'pubprop.value', $options);
  1273. foreach ($ptypes as $ptype) {
  1274. $pub_array['Publication Type'][] = $ptype->value;
  1275. }
  1276. }
  1277. // ---------------------------------
  1278. // get the authors list
  1279. // ---------------------------------
  1280. $values = array(
  1281. 'pub_id' => $pub->pub_id,
  1282. 'type_id' => array(
  1283. 'name' => 'Authors',
  1284. ),
  1285. );
  1286. $authors = chado_generate_var('pubprop', $values);
  1287. $authors = chado_expand_var($authors, 'field', 'pubprop.value', $options);
  1288. if (count($authors) > 1) {
  1289. tripal_report_error('tripal_pub', TRIPAL_ERROR, "Publication has multiple author lists. It should have only one list: %pub_id",
  1290. array('%pub_id' => $pubid));
  1291. return FALSE;
  1292. }
  1293. else if (trim($authors->value)) {
  1294. $pub_array['Authors'] = $authors->value;
  1295. }
  1296. // if there is no 'Author's property then try to retreive authors from the pubauthor table
  1297. else {
  1298. $sql = "
  1299. SELECT string_agg(surname || ' ' || givennames, ', ')
  1300. FROM {pubauthor}
  1301. WHERE pub_id = :pub_id
  1302. GROUP BY pub_id
  1303. ";
  1304. $au = chado_query($sql, array(':pub_id' => $pub_id))->fetchField();
  1305. if ($au) {
  1306. $pub_array['Authors'] = $au;
  1307. }
  1308. }
  1309. //Get other props
  1310. $props = array(
  1311. 'Journal Abbreviation',
  1312. 'Elocation',
  1313. 'Media Code',
  1314. 'Conference Name',
  1315. 'Keywords',
  1316. 'Series Name',
  1317. 'pISSN',
  1318. 'Publication Date',
  1319. 'Journal Code',
  1320. 'Journal Alias',
  1321. 'Journal Country',
  1322. 'Published Location',
  1323. 'Publication Model',
  1324. 'Language Abbr',
  1325. 'Alias',
  1326. 'Publication Dbxref',
  1327. 'Copyright',
  1328. 'Abstract',
  1329. 'Notes',
  1330. 'Citation',
  1331. 'Language',
  1332. 'URL',
  1333. 'eISSN',
  1334. 'DOI',
  1335. 'ISSN',
  1336. 'Publication Code',
  1337. 'Comments',
  1338. 'Publisher',
  1339. 'Media Alias',
  1340. 'Original Title'
  1341. );
  1342. foreach ($props AS $prop) {
  1343. $sql =
  1344. "SELECT value FROM {pubprop}
  1345. WHERE type_id =
  1346. (SELECT cvterm_id
  1347. FROM {cvterm}
  1348. WHERE name = :cvtname AND cv_id =
  1349. (SELECT cv_id
  1350. FROM {cv}
  1351. WHERE name = 'tripal_pub'
  1352. )
  1353. )
  1354. AND pub_id = :pub_id
  1355. ";
  1356. $val = trim(chado_query($sql, array(':cvtname' => $prop, ':pub_id' => $pub->pub_id))->fetchField());
  1357. if ($val) {
  1358. $pub_array[$prop] =$val;
  1359. }
  1360. }
  1361. return $pub_array;
  1362. }
  1363. /**
  1364. * Imports all publications for a given publication import setup.
  1365. *
  1366. * @param $import_id
  1367. * The ID of the import setup to use
  1368. * @param $job_id
  1369. * The jobs management job_id for the job if this function is run as a job.
  1370. *
  1371. * @ingroup tripal_pub
  1372. */
  1373. function tripal_execute_pub_importer($import_id, $job_id = NULL) {
  1374. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  1375. "If the load fails or is terminated prematurely then the entire set of \n" .
  1376. "insertions/updates is rolled back and will not be found in the database\n\n";
  1377. // start the transaction
  1378. $transaction = db_transaction();
  1379. try {
  1380. $page = 0;
  1381. $do_contact = FALSE;
  1382. $num_to_retrieve = 100;
  1383. // get all of the loaders
  1384. $args = array(':import_id' => $import_id);
  1385. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :import_id ";
  1386. $import = db_query($sql, $args)->fetchObject();
  1387. print "Executing Importer: '" . $import->name . "'\n";
  1388. $criteria = unserialize($import->criteria);
  1389. $remote_db = $criteria['remote_db'];
  1390. $total_pubs = 0;
  1391. do {
  1392. // retrieve the pubs for this page. We'll retreive 100 at a time
  1393. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  1394. $pubs = $results['pubs'];
  1395. $num_pubs = $rseults['total_records'];
  1396. $total_pubs += $num_pubs;
  1397. tripal_pub_add_publications($pubs, $import->do_contact);
  1398. $page++;
  1399. }
  1400. // continue looping until we have a $pubs array that does not have
  1401. // our requested numer of records. This means we've hit the end
  1402. while (count($pubs) == $num_to_retrieve);
  1403. // For backwards compatibility check to see if the legacy pub module
  1404. // is enabled. If so, then sync the nodes.
  1405. if (module_exists('tripal_pub')) {
  1406. // sync the newly added publications with Drupal. If the user
  1407. // requested a report then we don't want to print any syncing information
  1408. // so pass 'FALSE' to the sync call
  1409. print "Syncing publications with Drupal...\n";
  1410. chado_node_sync_records('pub');
  1411. // if any of the importers wanted to create contacts from the authors then sync them
  1412. if($import->do_contact) {
  1413. print "Syncing contacts with Drupal...\n";
  1414. chado_node_sync_records('contact');
  1415. }
  1416. }
  1417. // For Tripal v3 we want to publish the new publications
  1418. else {
  1419. $bundle = tripal_load_bundle_entity(['label' => 'Publication']);
  1420. if ($bundle) {
  1421. chado_publish_records(['bundle_name' => $bundle->name], $job_id);
  1422. }
  1423. }
  1424. tripal_set_job_progress($job_id, '100');
  1425. }
  1426. catch (Exception $e) {
  1427. $transaction->rollback();
  1428. print "\n"; // make sure we start errors on new line
  1429. watchdog_exception('T_pub_import', $e);
  1430. print "FAILED: Rolling back database changes...\n";
  1431. return;
  1432. }
  1433. print "Done.\n";
  1434. }
  1435. /**
  1436. * This function is used to perfom a query using one of the supported databases
  1437. * and return the raw query results. This may be XML or some other format
  1438. * as provided by the database.
  1439. *
  1440. * @param $dbxref
  1441. * The unique database ID for the record to retrieve. This value must
  1442. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  1443. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  1444. * for the record in the database.
  1445. *
  1446. * @return
  1447. * Returns the publication array or FALSE if a problem occurs
  1448. *
  1449. * @ingroup tripal_pub
  1450. */
  1451. function tripal_get_remote_pub($dbxref) {
  1452. if(preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  1453. $remote_db = $matches[1];
  1454. $accession = $matches[2];
  1455. // check that the database is supported
  1456. $supported_dbs = variable_get('tripal_pub_supported_dbs', array('PMID'));
  1457. if(!in_array($remote_db, $supported_dbs)) {
  1458. return FALSE;
  1459. }
  1460. $search = array(
  1461. 'num_criteria' => 1,
  1462. 'remote_db' => $remote_db,
  1463. 'criteria' => array(
  1464. '1' => array(
  1465. 'search_terms' => "$remote_db:$accession",
  1466. 'scope' => 'id',
  1467. 'operation' => '',
  1468. 'is_phrase' => 0,
  1469. ),
  1470. ),
  1471. );
  1472. $pubs = tripal_get_remote_pubs($remote_db, $search, 1, 0);
  1473. return $pubs['pubs'][0];
  1474. }
  1475. return FALSE;
  1476. }
  1477. /**
  1478. * Retrieves a list of publications as an associated array where
  1479. * keys correspond directly with Tripal Pub CV terms.
  1480. *
  1481. * @param remote_db
  1482. * The name of the remote publication database to query. These names should
  1483. * match the name of the databases in the Chado 'db' table. Currently
  1484. * supported databass include
  1485. * 'PMID': PubMed
  1486. *
  1487. * @param search_array
  1488. * An associate array containing the search criteria. The following key
  1489. * are expected
  1490. * 'remote_db': Specifies the name of the remote publication database
  1491. * 'num_criteria': Specifies the number of criteria present in the search array
  1492. * 'days': The number of days to include in the search starting from today
  1493. * 'criteria': An associate array containing the search critiera. There should
  1494. * be no less than 'num_criteria' elements in this array.
  1495. *
  1496. * The following keys are expected in the 'criteria' array
  1497. * 'search_terms': A list of terms to search on, separated by spaces.
  1498. * 'scope': The fields to search in the remote database. Valid values
  1499. * include: 'title', 'abstract', 'author' and 'any'
  1500. * 'operation': The logical operation to use for this criteria. Valid
  1501. * values include: 'AND', 'OR' and 'NOT'.
  1502. * @param $num_to_retrieve
  1503. * The number of records to retrieve. In cases with large numbers of
  1504. * records to retrieve, the remote database may limit the size of each
  1505. * retrieval.
  1506. * @param $page
  1507. * Optional. If this function is called where the
  1508. * page for the pager cannot be set using the $_GET variable, use this
  1509. * argument to specify the page to retrieve.
  1510. *
  1511. * @return
  1512. * Returns an array of pubs where each element is
  1513. * an associative array where the keys are Tripal Pub CV terms.
  1514. *
  1515. * @ingroup tripal_pub
  1516. */
  1517. function tripal_get_remote_pubs($remote_db, $search_array, $num_to_retrieve, $page = 0) {
  1518. // now call the callback function to get the results
  1519. $callback = "tripal_pub_remote_search_$remote_db";
  1520. $pubs = array(
  1521. 'total_records' => 0,
  1522. 'search_str' => '',
  1523. 'pubs' => array(),
  1524. );
  1525. if (function_exists($callback)) {
  1526. $pubs = call_user_func($callback, $search_array, $num_to_retrieve, $page);
  1527. }
  1528. return $pubs;
  1529. }
  1530. /**
  1531. * The admin form for submitting job to create citations
  1532. *
  1533. * @param $form_state
  1534. *
  1535. * @ingroup tripal_pub
  1536. */
  1537. function tripal_pub_citation_form($form, &$form_state) {
  1538. $form['instructions'] = array(
  1539. '#markup' => '<p>Use this form to unify publication citations. Citations are created automtically when
  1540. importing publications but citations are set by the user when publications are added manually.
  1541. Or publications added to the Chado database by tools other than the Tripal Publication Importer may
  1542. not have citations set. If you are certain that all necessary information for all publications is present (e.g.
  1543. authors, volume, issue, page numbers, etc.) but citations are not consistent, then you can
  1544. choose to update all citations for all publications using the form below. Alternatively, you
  1545. can update citations only for publication that do not already have one.</p>'
  1546. );
  1547. $form['options'] = array(
  1548. '#type' => 'radios',
  1549. '#options' => array(
  1550. 'all' => 'Create citation for all publications. Replace the existing citation if it exists.',
  1551. 'new' => 'Create citation for publication only if it does not already have one.'),
  1552. '#default_value' => 'all'
  1553. );
  1554. $form['submit'] = array(
  1555. '#type' => 'submit',
  1556. '#value' => t('Submit')
  1557. );
  1558. return $form;
  1559. }
  1560. /**
  1561. * Submit form. Create Tripal job for citations
  1562. *
  1563. * @param $form_state
  1564. *
  1565. * @ingroup tripal_pub
  1566. */
  1567. function tripal_pub_citation_form_submit(&$form_state) {
  1568. $options [0] = $form_state['options']['#value'];
  1569. tripal_add_job("Create citations ($options[0])", 'tripal_pub', 'chado_pub_create_citations', $options, $user->uid);
  1570. }