tripal_pub.pub_importers.inc 66 KB

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