tripal_pub.pub_importers.inc 49 KB

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