tripal_pub.pub_importers.inc 67 KB

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