tripal_chado.pub_importers.inc 59 KB

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