tripal_pub.api.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. <?php
  2. /**
  3. * @file
  4. * The Tripal Pub API
  5. *
  6. * @defgroup tripal_pub_api Publication Module API
  7. * @ingroup tripal_api
  8. */
  9. /*
  10. * Retrieves a list of publications as an associated array where
  11. * keys correspond directly with Tripal Pub CV terms.
  12. *
  13. * @param remote_db
  14. * The name of the remote publication database to query. These names should
  15. * match the name of the databases in the Chado 'db' table. Currently
  16. * supported databass include
  17. * 'PMID': PubMed
  18. *
  19. * @param search_array
  20. * An associate array containing the search criteria. The following key
  21. * are expected
  22. * 'remote_db': Specifies the name of the remote publication database
  23. * 'num_criteria': Specifies the number of criteria present in the search array
  24. * 'days': The number of days to include in the search starting from today
  25. * 'criteria': An associate array containing the search critiera. There should
  26. * be no less than 'num_criteria' elements in this array.
  27. *
  28. * The following keys are expected in the 'criteria' array
  29. * 'search_terms': A list of terms to search on, separated by spaces.
  30. * 'scope': The fields to search in the remote database. Valid values
  31. * include: 'title', 'abstract', 'author' and 'any'
  32. * 'operation': The logical operation to use for this criteria. Valid
  33. * values include: 'AND', 'OR' and 'NOT'.
  34. * @param $num_to_retrieve
  35. * The number of records to retrieve. In cases with large numbers of
  36. * records to retrieve, the remote database may limit the size of each
  37. * retrieval.
  38. * @param $pager_id
  39. * Optional. This function uses the 'tripal_pager_callback' function
  40. * to page a set of results. This is helpful when generating results to
  41. * be view online. The pager works identical to the pager_query function
  42. * of drupal. Simply provide a unique integer value for this argument. Each
  43. * form on a single page should have a unique $pager_id.
  44. * @param $page
  45. * Optional. If this function is called where the
  46. * page for the pager cannot be set using the $_GET variable, use this
  47. * argument to specify the page to retrieve.
  48. *
  49. * @return
  50. * Returns an array of pubs where each element is
  51. * an associative array where the keys are Tripal Pub CV terms.
  52. *
  53. * @ingroup tripal_pub_api
  54. */
  55. function tripal_pub_get_remote_search_results($remote_db, $search_array,
  56. $num_to_retrieve, $pager_id = 0, $page = 0) {
  57. // manually set the $_GET['page'] parameter to trick the pager
  58. // into giving us the requested page
  59. if (is_int($page) and $page > 0) {
  60. $_GET['page'] = $page;
  61. }
  62. // now call the callback function to get the results
  63. $callback = "tripal_pub_remote_search_$remote_db";
  64. $pubs = array();
  65. if (function_exists($callback)) {
  66. $pubs = call_user_func($callback, $search_array, $num_to_retrieve, $pager_id);
  67. }
  68. return $pubs;
  69. }
  70. /*
  71. * @ingroup tripal_pub_api
  72. */
  73. function tripal_pub_get_raw_data($dbxref) {
  74. if(preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  75. $remote_db = $matches[1];
  76. $accession = $matches[2];
  77. // check that the database is supported
  78. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  79. if(!in_array($remote_db, $supported_dbs)) {
  80. return "Unsupported database: $dbxref";
  81. }
  82. // build the search criteria
  83. $search = array(
  84. 'remote_db' => $remote_db,
  85. 'criteria' => array(
  86. array(
  87. 'search_terms' => $accession,
  88. 'scope' => 'id',
  89. ),
  90. ),
  91. );
  92. $search['num_criteria'] = 0;
  93. $pubs = tripal_pub_get_remote_search_results($remote_db, $search, 1, 0);
  94. return '<textarea cols=80 rows=20>' . $pubs[0]['raw'] . '</textarea>';
  95. }
  96. return 'Invalid DB xref';
  97. }
  98. /*
  99. * @ingroup tripal_pub_api
  100. */
  101. function tripal_pub_update_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
  102. // get a persistent connection
  103. $connection = tripal_db_persistent_chado();
  104. if (!$connection) {
  105. print "A persistant connection was not obtained. Loading will be slow\n";
  106. }
  107. // if we cannot get a connection then let the user know the loading will be slow
  108. tripal_db_start_transaction();
  109. if ($connection) {
  110. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  111. "If the load fails or is terminated prematurely then the entire set of \n" .
  112. "insertions/updates is rolled back and will not be found in the database\n\n";
  113. }
  114. // get a list of all publications by their Dbxrefs that have supported databases
  115. $sql = "
  116. SELECT DB.name as db_name, DBX.accession
  117. FROM pub P
  118. INNER JOIN pub_dbxref PDBX ON P.pub_id = PDBX.pub_id
  119. INNER JOIN dbxref DBX ON DBX.dbxref_id = PDBX.dbxref_id
  120. INNER JOIN db DB ON DB.db_id = DBX.db_id
  121. ";
  122. $args = array();
  123. if ($dbxref and preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  124. $dbname = $matches[1];
  125. $accession = $matches[2];
  126. $sql .= "WHERE DBX.accession = '%s' and DB.name = '%s' ";
  127. $args[] = $accession;
  128. $args[] = $dbname;
  129. }
  130. elseif ($db) {
  131. $sql .= " WHERE DB.name = '%s' ";
  132. $args[] = $db;
  133. }
  134. $sql .= "ORDER BY DB.name, P.pub_id";
  135. $results = chado_query($sql, $args);
  136. $num_to_retrieve = 100;
  137. $i = 0; // count the number of IDs. When we hit $num_to_retrieve we'll do the query
  138. $curr_db = ''; // keeps track of the current current database
  139. $ids = array(); // the list of IDs for the database
  140. $search = array(); // the search array passed to the search function
  141. // iterate through the pub IDs
  142. while ($pub = db_fetch_object($results)) {
  143. $accession = $pub->accession;
  144. $remote_db = $pub->db_name;
  145. // here we need to only update publications for databases we support
  146. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  147. if(!in_array($remote_db, $supported_dbs)) {
  148. continue;
  149. }
  150. $search = array(
  151. 'num_criteria' => 1,
  152. 'remote_db' => $remote_db,
  153. 'criteria' => array(
  154. '1' => array(
  155. 'search_terms' => "$remote_db:$accession",
  156. 'scope' => 'id',
  157. 'operation' => '',
  158. 'is_phrase' => 0,
  159. ),
  160. ),
  161. );
  162. $pubs = tripal_pub_get_remote_search_results($remote_db, $search, 1, 0);
  163. tripal_pub_add_publications($pubs, $do_contact, TRUE);
  164. $i++;
  165. }
  166. // transaction is complete
  167. tripal_db_commit_transaction();
  168. print "Transaction Complete\n";
  169. // sync the newly added publications with Drupal
  170. print "Syncing publications with Drupal...\n";
  171. tripal_pub_sync_pubs();
  172. // if the caller wants to create contacts then we should sync them
  173. if ($do_contact) {
  174. print "Syncing contacts with Drupal...\n";
  175. tripal_contact_sync_contacts();
  176. }
  177. print "Done.\n";
  178. }
  179. /*
  180. * @ingroup tripal_pub_api
  181. */
  182. function tripal_pub_import_publications($report_email = FALSE) {
  183. $num_to_retrieve = 100;
  184. $pager_id = 0;
  185. $page = 0;
  186. $num_pubs = 0;
  187. // get a persistent connection
  188. $connection = tripal_db_persistent_chado();
  189. if (!$connection) {
  190. print "A persistant connection was not obtained. Loading will be slow\n";
  191. }
  192. // if we cannot get a connection then let the user know the loading will be slow
  193. tripal_db_start_transaction();
  194. if ($connection) {
  195. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  196. "If the load fails or is terminated prematurely then the entire set of \n" .
  197. "insertions/updates is rolled back and will not be found in the database\n\n";
  198. }
  199. // get all of the loaders
  200. $args = array();
  201. $sql = "SELECT * FROM {tripal_pub_import} WHERE disabled = 0 ";
  202. $results = db_query($sql, $args);
  203. $do_contact = FALSE;
  204. $reports = array();
  205. while ($import = db_fetch_object($results)) {
  206. print "Importing: " . $import->name . "\n";
  207. // keep track if any of the importers want to create contacts from authors
  208. if ($import->do_contact == 1) {
  209. $do_contact = TRUE;
  210. }
  211. $criteria = unserialize($import->criteria);
  212. $remote_db = $criteria['remote_db'];
  213. do {
  214. // retrieve the pubs for this page. We'll retreive 10 at a time
  215. $pubs = tripal_pub_get_remote_search_results($remote_db, $criteria, $num_to_retrieve, $pager_id, $page);
  216. $reports[$import->name] = tripal_pub_add_publications($pubs, $import->do_contact);
  217. $page++;
  218. }
  219. // continue looping until we have a $pubs array that does not have
  220. // our requested numer of records. This means we've hit the end
  221. while (count($pubs) == $num_to_retrieve);
  222. }
  223. // transaction is complete
  224. tripal_db_commit_transaction();
  225. print "Transaction Complete\n";
  226. // sync the newly added publications with Drupal. If the user
  227. // requested a report then we don't want to print any syncing information
  228. // so pass 'FALSE' to the sync call
  229. print "Syncing publications with Drupal...\n";
  230. tripal_pub_sync_pubs();
  231. // iterate through each of the reports and generate a final report with HTML links
  232. $HTML_report = '';
  233. if ($report_email) {
  234. $HTML_report .= "<html>";
  235. global $base_url;
  236. foreach ($reports as $importer => $report) {
  237. $total = count($report['inserted']);
  238. $HTML_report .= "<b>$total new publications from importer: $importer</b><br><ol>\n";
  239. foreach ($report['inserted'] as $pub) {
  240. $item = $pub['Title'];
  241. if ($pub['pub_id']) {
  242. $nid = chado_get_node_id('pub', $pub['pub_id']);
  243. $item = l($pub['Title'], "$base_url/node/$nid");
  244. }
  245. $HTML_report .= "<li>$item</li>\n";
  246. }
  247. $HTML_report .= "</ol>\n";
  248. }
  249. $HTML_report .= "</html>";
  250. $site_email = variable_get('site_mail', '');
  251. $params = array(
  252. 'message' => $HTML_report
  253. );
  254. drupal_mail('tripal_pub', 'import_report', $report_email, language_default(), $params, $site_email, TRUE);
  255. }
  256. // if any of the importers wanted to create contacts from the authors then sync them
  257. if($do_contact) {
  258. print "Syncing contacts with Drupal...\n";
  259. tripal_contact_sync_contacts();
  260. }
  261. print "Done.\n";
  262. }
  263. /*
  264. * @ingroup tripal_pub_api
  265. */
  266. function tripal_pub_import_by_dbxref($pub_dbxref, $do_contact = FALSE) {
  267. $num_to_retrieve = 1;
  268. $pager_id = 0;
  269. $page = 0;
  270. $num_pubs = 0;
  271. // get a persistent connection
  272. $connection = tripal_db_persistent_chado();
  273. if (!$connection) {
  274. print "A persistant connection was not obtained. Loading will be slow\n";
  275. }
  276. // if we cannot get a connection then let the user know the loading will be slow
  277. tripal_db_start_transaction();
  278. if ($connection) {
  279. print "\nNOTE: Loading of the publication is performed using a database transaction. \n" .
  280. "If the load fails or is terminated prematurely then the entire set of \n" .
  281. "insertions/updates is rolled back and will not be found in the database\n\n";
  282. }
  283. if(preg_match('/^(.*?):(.*?)$/', $pub_dbxref, $matches)) {
  284. $dbname = $matches[1];
  285. $accession = $matches[2];
  286. $criteria['remote_db'] = $dbname;
  287. $criteria['num_criteria'] = 1;
  288. $criteria['criteria'][1]['search_terms'] = $accession;
  289. $criteria['criteria'][1]['scope'] = 'id';
  290. $criteria['criteria'][1]['is_phrase'] = 0;
  291. $criteria['criteria'][1]['operation'] = '';
  292. $remote_db = $criteria['remote_db'];
  293. $pubs = tripal_pub_get_remote_search_results($remote_db, $criteria, $num_to_retrieve, $pager_id, $page);
  294. $pub_id = tripal_pub_add_publications($pubs, $do_contact);
  295. }
  296. // transaction is complete
  297. tripal_db_commit_transaction();
  298. print "Transaction Complete\n";
  299. // sync the newly added publications with Drupal
  300. print "Syncing publications with Drupal...\n";
  301. tripal_pub_sync_pubs();
  302. // if any of the importers wanted to create contacts from the authors then sync them
  303. if($do_contact) {
  304. print "Syncing contacts with Drupal...\n";
  305. tripal_contact_sync_contacts();
  306. }
  307. print "Done.\n";
  308. }
  309. /*
  310. *
  311. */
  312. function tripal_pub_add_publications($pubs, $do_contact, $update = FALSE) {
  313. $report = array();
  314. $report['error'] = 0;
  315. $report['inserted'] = array();
  316. $report['skipped'] = array();
  317. $total_pubs = count($pubs);
  318. // iterate through the publications and add each one
  319. $i = 1;
  320. foreach ($pubs as $pub) {
  321. $memory = number_format(memory_get_usage()) . " bytes";
  322. print "Processing $i of $total_pubs. Memory usage: $memory.\r";
  323. // add the publication to Chado
  324. $action = '';
  325. $pub_id = tripal_pub_add_publication($pub, $action, $do_contact, $update);
  326. if ($pub_id){
  327. // add the publication cross reference (e.g. to PubMed)
  328. if ($pub_id and $pub['Publication Dbxref']) {
  329. $pub_dbxref = tripal_pub_add_pub_dbxref($pub_id, $pub['Publication Dbxref']);
  330. }
  331. $pub['pub_id'] = $pub_id;
  332. }
  333. switch ($action) {
  334. case 'error':
  335. $report['error']++;
  336. break;
  337. case 'inserted':
  338. $report['inserted'][] = $pub;
  339. break;
  340. case 'skipped':
  341. $report['skipped'][] = $pub;
  342. break;
  343. }
  344. $i++;
  345. }
  346. print "\n";
  347. return $report;
  348. }
  349. /*
  350. *
  351. */
  352. function tripal_pub_add_pub_dbxref($pub_id, $pub_dbxref) {
  353. // break apart the dbxref
  354. $dbname = '';
  355. $accession = '';
  356. if(preg_match('/^(.*?):(.*?)$/', $pub_dbxref, $matches)) {
  357. $dbname = $matches[1];
  358. $accession = $matches[2];
  359. }
  360. else {
  361. return FALSE;
  362. }
  363. // check to see if the pub_dbxref record already exist
  364. $values = array(
  365. 'dbxref_id' => array(
  366. 'accession' => $accession,
  367. 'db_id' => array(
  368. 'name' => $dbname,
  369. ),
  370. ),
  371. 'pub_id' => $pub_id,
  372. );
  373. $options = array('statement_name' => 'sel_pubdbxref_dbpu');
  374. $results = tripal_core_chado_select('pub_dbxref', array('*'), $values, $options);
  375. // if the pub_dbxref record exist then we don't need to re-add it.
  376. if(count($results) > 0) {
  377. return $results[0];
  378. }
  379. // make sure our database already exists
  380. $db = tripal_db_add_db($dbname);
  381. // get the database cross-reference
  382. $dbxvalues = array(
  383. 'accession' => $accession,
  384. 'db_id' => $db->db_id,
  385. );
  386. $dbxoptions = array('statement_name' => 'sel_dbxref_acdb');
  387. $results = tripal_core_chado_select('dbxref', array('dbxref_id'), $dbxvalues, $dbxoptions);
  388. // if the accession doesn't exist then add it
  389. if(count($results) == 0){
  390. $dbxref = tripal_db_add_dbxref($db->db_id, $accession);
  391. }
  392. else {
  393. $dbxref = $results[0];
  394. }
  395. // now add the record
  396. $options = array('statement_name' => 'ins_pubdbxref_dbpu');
  397. $results = tripal_core_chado_insert('pub_dbxref', $values, $options);
  398. if (!$results) {
  399. watchdog('tripal_pub', "Cannot add publication dbxref: %db:%accession.",
  400. array('%db' => $dbname, '%accession' => $accession). WATCHDOG_ERROR);
  401. return FALSE;
  402. }
  403. return $results;
  404. }
  405. /**
  406. * Returns the list of publications that are assigned the database
  407. * cross-reference provided
  408. *
  409. * @param $pub_dbxref
  410. * The database cross reference accession. It should be in the form
  411. * DB:ACCESSION, where DB is the database name and ACCESSION is the
  412. * unique publication identifier (e.g. PMID:4382934)
  413. *
  414. * @return
  415. * Returns an array of all the publications that have the provided
  416. * cross reference. If no publications match, then an empty array
  417. * is returned.
  418. *
  419. * @ingroup tripal_pub_api
  420. *
  421. */
  422. function tripal_pub_get_pubs_by_dbxref($pub_dbxref) {
  423. $return = array();
  424. if(preg_match('/^(.*?):(.*?)$/', $pub_dbxref, $matches)) {
  425. $dbname = $matches[1];
  426. $accession = $matches[2];
  427. $values = array(
  428. 'dbxref_id' => array (
  429. 'accession' => $accession,
  430. 'db_id' => array(
  431. 'name' => $dbname
  432. ),
  433. ),
  434. );
  435. $options = array('statement_name' => 'sel_pubdbxref_db');
  436. $results = tripal_core_chado_select('pub_dbxref', array('pub_id'), $values, $options);
  437. foreach ($results as $index => $pub) {
  438. $return[] = $pub->pub_id;
  439. }
  440. }
  441. return $return;
  442. }
  443. /**
  444. * Returns the list of publications that match a given title and year
  445. *
  446. * @param title
  447. * The title of the publication to look for
  448. * @param type
  449. * The publication type. The value of this field should come from
  450. * the Tripal Pub vocabulary
  451. * @param year
  452. * Optional. The year the publication was published.
  453. *
  454. * @return
  455. * Returns an array of all the publications that have the provided
  456. * cross reference. If no publications match, then an empty array
  457. * is returned.
  458. *
  459. * @ingroup tripal_pub_api
  460. *
  461. */
  462. function tripal_pub_get_pubs_by_title_type_pyear($title, $type, $pyear = '') {
  463. $return = array();
  464. // build the values array for the query. The $pyear is not required.
  465. $values = array(
  466. 'title' => $title,
  467. 'type_id' => array(
  468. 'name' => $type,
  469. 'cv_id' => array(
  470. 'name' => 'tripal_pub'
  471. )
  472. )
  473. );
  474. $stmnt_suffix = 'tity';
  475. if ($pub_details['Year']) {
  476. $values['pyear'] = $pyear;
  477. $stmnt_suffix .= 'py';
  478. }
  479. $options = array('statement_name' => 'sel_pub_' . $stmnt_suffix);
  480. $results = tripal_core_chado_select('pub', array('pub_id'), $values, $options);
  481. // iterate through any matches and pull out the pub_id
  482. foreach ($results as $index => $pub) {
  483. $return[] = $pub->pub_id;
  484. }
  485. return $return;
  486. }
  487. /**
  488. * Adds a new publication to the Chado, along with all properties and
  489. * database cross-references. If the publication does not already exist
  490. * in Chado then it is added. If it does exist nothing is done. If
  491. * the $update parameter is TRUE then the publication is updated if it exists.
  492. *
  493. * @param $pub_details
  494. * An associative array containing all of the details about the publication.
  495. * @param $action
  496. * This variable will get set to a text value indicating the action that was
  497. * performed. The values include 'skipped', 'inserted', 'updated' or 'error'.
  498. * @param $do_contact
  499. * Optional. Set to TRUE if a contact entry should be added to the Chado contact table
  500. * for authors of the publication.
  501. * @param $update_if_exists
  502. * Optional. If the publication already exists then this function will return
  503. * without adding a new publication. However, set this value to TRUE to force
  504. * the function to pudate the publication using the $pub_details that are provided.
  505. *
  506. * @return
  507. * If the publication already exists, is inserted or updated then the publication
  508. * ID is returned, otherwise FALSE is returned. If the publication already exists
  509. * and $update_if_exists is not TRUE then the $action variable is set to 'skipped'.
  510. * If the publication already exists and $update_if_exists is TRUE and if the update
  511. * was successful then $action is set to 'updated'. Otherwise on successful insert
  512. * the $action variable is set to 'inserted'. If the function failes then the
  513. * $action variable is set to 'error'
  514. *
  515. */
  516. function tripal_pub_add_publication($pub_details, &$action, $do_contact = FALSE, $update_if_exists = FALSE) {
  517. $pub_id = 0;
  518. // first try to find the publication using the accession number. It will have
  519. // one if the pub has already been loaded for the publication database
  520. if ($pub_details['Publication Dbxref']) {
  521. $results = tripal_pub_get_pubs_by_dbxref($pub_details['Publication Dbxref']);
  522. if(count($results) == 1) {
  523. $pub_id = $results[0];
  524. }
  525. elseif (count($results) > 1) {
  526. watchdog('tripal_pub', "There are two publications with this accession: %db:%accession. Cannot determine which to update.",
  527. array('%db' => $dbname, '%accession' => $accession), WATCHDOG_ERROR);
  528. $action = 'error';
  529. return FALSE;
  530. }
  531. }
  532. // if we couldn't find a publication by the accession (which means it doesn't
  533. // yet exist or it has been added using a different publication database) then
  534. // try to find it using the title and publication year.
  535. if (!$pub_id and $pub_details['Title']) {
  536. $results = tripal_pub_get_pubs_by_title_type_pyear($pub_details['Title'], $pub_details['Publication Type'], $pub_details['Year']);
  537. if (count($results) == 1) {
  538. $pub_id = $results[0];
  539. }
  540. elseif (count($results) > 1) {
  541. watchdog('tripal_pub', "The publication with the same title, type and year is present multiple times. Cannot ".
  542. "determine which to use. Title: '%title'. Type: '%type'. Year: '%year'",
  543. array('%title' => $pub_details['Title'], '%type' => $pub_details['Publication Type'], '%year' => $pub_details['Year']), WATCHDOG_ERROR);
  544. $action = 'error';
  545. return FALSE;
  546. }
  547. }
  548. // if there is a pub id and we've been told not to update then return
  549. if ($pub_id and !$update_if_exists) {
  550. $action = 'skipped';
  551. return $pub_id;
  552. }
  553. // get the publication type (use the first publication type, any others will get stored as properties)
  554. if (is_array($pub_details['Publication Type'])) {
  555. $pub_type = tripal_cv_get_cvterm_by_name($pub_details['Publication Type'][0], NULL, 'tripal_pub');
  556. }
  557. elseif ($pub_details['Publication Type']) {
  558. $pub_type = tripal_cv_get_cvterm_by_name($pub_details['Publication Type'], NULL, 'tripal_pub');
  559. }
  560. else {
  561. watchdog('tripal_pub', "The Publication Type is a required property but is missing", array(), WATCHDOG_ERROR);
  562. $action = 'error';
  563. return FALSE;
  564. }
  565. if (!$pub_type) {
  566. watchdog('tripal_pub', "Cannot find publication type: '%type'",
  567. array('%type' => $pub_details['Publication Type'][0]), WATCHDOG_ERROR);
  568. $action = 'error';
  569. return FALSE;
  570. }
  571. // build the values array for inserting or updating
  572. $values = array(
  573. 'title' => $pub_details['Title'],
  574. 'volume' => $pub_details['Volume'],
  575. 'series_name' => $pub_details['Journal Name'],
  576. 'issue' => $pub_details['Issue'],
  577. 'pyear' => $pub_details['Year'],
  578. 'pages' => $pub_details['Pages'],
  579. 'uniquename' => $pub_details['Citation'],
  580. 'type_id' => $pub_type->cvterm_id,
  581. );
  582. // if there is no pub_id then we need to do an insert.
  583. if (!$pub_id) {
  584. $options = array('statement_name' => 'ins_pub_tivoseispypaunty');
  585. $pub = tripal_core_chado_insert('pub', $values, $options);
  586. if (!$pub) {
  587. watchdog('tripal_pub', "Cannot insert the publication with title: %title",
  588. array('%title' => $pub_details['Title']), WATCHDOG_ERROR);
  589. $action = 'error';
  590. return FALSE;
  591. }
  592. $pub_id = $pub['pub_id'];
  593. $action = 'inserted';
  594. }
  595. // if there is a pub_id and we've been told to update, then do the update
  596. if ($pub_id and $update_if_exists) {
  597. $match = array('pub_id' => $pub_id);
  598. $options = array('statement_name' => 'up_pub_tivoseispypaunty');
  599. $success = tripal_core_chado_update('pub', $match, $values, $options);
  600. if (!$success) {
  601. watchdog('tripal_pub', "Cannot update the publication with title: %title",
  602. array('%title' => $pub_details['Title']), WATCHDOG_ERROR);
  603. $action = 'error';
  604. return FALSE;
  605. }
  606. $action = 'updated';
  607. }
  608. // before we add any new properties we need to remove those that are there if this
  609. // is an update. The only thing we don't want to remove are the 'Publication Dbxref'
  610. if ($update_if_exists) {
  611. $sql = "
  612. DELETE FROM {pubprop}
  613. WHERE
  614. pub_id = %d AND
  615. NOT type_id in (
  616. SELECT cvterm_id
  617. FROM {cvterm}
  618. WHERE name = 'Publication Dbxref'
  619. )
  620. ";
  621. chado_query($sql, $pub_id);
  622. }
  623. // iterate through the properties and add them
  624. foreach ($pub_details as $key => $value) {
  625. // the pub_details may have the raw search data (e.g. in XML from PubMed. We'll irgnore this for now
  626. if($key == 'raw') {
  627. continue;
  628. }
  629. // get the cvterm by name or synonym
  630. $cvterm = tripal_cv_get_cvterm_by_name($key, NULL, 'tripal_pub');
  631. if (!$cvterm) {
  632. $cvterm = tripal_cv_get_cvterm_by_synonym($key, NULL, 'tripal_pub');
  633. }
  634. if (!$cvterm) {
  635. watchdog('tripal_pub', "Cannot find term: '%prop'. Skipping.", array('%prop' => $key), WATCHDOG_ERROR);
  636. continue;
  637. }
  638. // skip details that won't be stored as properties
  639. if ($key == 'Author List') {
  640. tripal_pub_add_authors($pub_id, $value, $do_contact);
  641. continue;
  642. }
  643. if ($key == 'Title' or $key == 'Volume' or $key == 'Journal Name' or $key == 'Issue' or
  644. $key == 'Year' or $key == 'Pages') {
  645. continue;
  646. }
  647. $success = 0;
  648. if (is_array($value)) {
  649. foreach ($value as $subkey => $subvalue) {
  650. // if the key is an integer then this array is a simple list and
  651. // we will insert using the primary key. Otheriwse, use the new key
  652. if(is_int($subkey)) {
  653. $success = tripal_core_insert_property('pub', $pub_id, $key, 'tripal_pub', $subvalue, FALSE);
  654. }
  655. else {
  656. $success = tripal_core_insert_property('pub', $pub_id, $subkey, 'tripal_pub', $subvalue, FALSE);
  657. }
  658. }
  659. }
  660. else {
  661. $success = tripal_core_insert_property('pub', $pub_id, $key, 'tripal_pub', $value, TRUE);
  662. }
  663. if (!$success) {
  664. watchdog('tripal_pub', "Cannot add property '%prop' to publication. Skipping.",
  665. array('%prop' => $key), WATCHDOG_ERROR);
  666. continue;
  667. }
  668. }
  669. return $pub_id;
  670. }
  671. /*
  672. *
  673. */
  674. function tripal_pub_add_authors($pub_id, $authors, $do_contact) {
  675. $rank = 0;
  676. // first remove any of the existing pubauthor entires
  677. $sql = "DELETE FROM {pubauthor} WHERE pub_id = %d";
  678. chado_query($sql, $pub_id);
  679. // iterate through the authors and add them to the pubauthors and contact
  680. // tables of chado, then link them through the custom pubauthors_contact table
  681. foreach ($authors as $author) {
  682. // skip invalid author entires
  683. if ($author['valid'] == 'N') {
  684. continue;
  685. }
  686. // remove the 'valid' property as we don't have a CV term for it
  687. unset($author['valid']);
  688. // construct the contact.name field using the author information
  689. $name = '';
  690. $type = 'Person';
  691. if ($author['Given Name']) {
  692. $name .= $author['Given Name'];
  693. }
  694. if ($author['Surname']) {
  695. $name .= ' ' . $author['Surname'];
  696. }
  697. if ($author['Suffix']) {
  698. $name .= ' ' . $author['Suffix'];
  699. }
  700. if ($author['Collective']) {
  701. $name = $author['Collective'];
  702. $type = 'Collective';
  703. }
  704. $name = trim($name);
  705. // add an entry to the pubauthors table
  706. $values = array(
  707. 'pub_id' => $pub_id,
  708. 'rank' => $rank,
  709. 'surname' => $author['Surname'] ? $author['Surname'] : $author['Collective'],
  710. 'givennames' => $author['Given Name'],
  711. 'suffix' => $author['Suffix'],
  712. );
  713. $options = array('statement_name' => 'ins_pubauthor_idrasugisu');
  714. $pubauthor = tripal_core_chado_insert('pubauthor', $values, $options);
  715. // if the user wants us to create a contact for each author then do it.
  716. if ($do_contact) {
  717. // Add the contact
  718. $contact = tripal_contact_add_contact($name, '', $type, $author);
  719. // if we have succesfully added the contact and the pubauthor entries then we want to
  720. // link them together
  721. if ($contact and $pubauthor) {
  722. // link the pubauthor entry to the contact
  723. $values = array(
  724. 'pubauthor_id' => $pubauthor['pubauthor_id'],
  725. 'contact_id' => $contact['contact_id'],
  726. );
  727. $options = array('statement_name' => 'ins_pubauthorcontact_puco');
  728. $pubauthor_contact = tripal_core_chado_insert('pubauthor_contact', $values, $options);
  729. if (!$pubauthor_contact) {
  730. watchdog('tripal_pub', "Cannot link pub authro and contact.", array(), WATCHDOG_ERROR);
  731. }
  732. }
  733. }
  734. $rank++;
  735. }
  736. }
  737. /**
  738. * Retrieve properties of a given type for a given pub
  739. *
  740. * @param $pub_id
  741. * The pub_id of the properties you would like to retrieve
  742. * @param $property
  743. * The cvterm name of the properties to retrieve
  744. *
  745. * @return
  746. * An pub chado variable with the specified properties expanded
  747. *
  748. * @ingroup tripal_pub_api
  749. */
  750. function tripal_pub_get_property($pub_id, $property) {
  751. return tripal_core_get_property('pub', $pub_id, $property, 'tripal');
  752. }
  753. /**
  754. * Insert a given property
  755. *
  756. * @param $pub_id
  757. * The pub_id of the property to insert
  758. * @param $property
  759. * The cvterm name of the property to insert
  760. * @param $value
  761. * The value of the property to insert
  762. * @param $update_if_present
  763. * A boolean indicated whether to update the record if it's already present
  764. *
  765. * @return
  766. * True of success, False otherwise
  767. *
  768. * @ingroup tripal_pub_api
  769. */
  770. function tripal_pub_insert_property($pub_id, $property, $value, $update_if_present = 0) {
  771. return tripal_core_insert_property('pub', $pub_id, $property, 'tripal_pub', $value, $update_if_present);
  772. }
  773. /**
  774. * Update a given property
  775. *
  776. * @param $pub_id
  777. * The pub_id of the property to update
  778. * @param $property
  779. * The cvterm name of the property to update
  780. * @param $value
  781. * The value of the property to update
  782. * @param $insert_if_missing
  783. * A boolean indicated whether to insert the record if it's absent
  784. *
  785. * Note: The property will be identified using the unique combination of the $pub_id and $property
  786. * and then it will be updated with the supplied value
  787. *
  788. * @return
  789. * True of success, False otherwise
  790. *
  791. * @ingroup tripal_pub_api
  792. */
  793. function tripal_pub_update_property($pub_id, $property, $value, $insert_if_missing = 0) {
  794. return tripal_core_update_property('pub', $pub_id, $property, 'tripal_pub', $value, $insert_if_missing);
  795. }
  796. /**
  797. * Delete a given property
  798. *
  799. * @param $pub_id
  800. * The pub_id of the property to delete
  801. * @param $property
  802. * The cvterm name of the property to delete
  803. *
  804. * Note: The property will be identified using the unique combination of the $pub_id and $property
  805. * and then it will be deleted
  806. *
  807. * @return
  808. * True of success, False otherwise
  809. *
  810. * @ingroup tripal_pub_api
  811. */
  812. function tripal_pub_delete_property($pub_id, $property) {
  813. return tripal_core_delete_property('pub', $pub_id, $property, 'tripal');
  814. }
  815. /*
  816. *
  817. */
  818. function tripal_pub_create_citation($pub) {
  819. $citation = $pub['Authors'] . '. ' . $pub['Title'] . '. ';
  820. if ($pub['Journal Name']) {
  821. $citation .= $pub['Journal Name'] . '. ';
  822. }
  823. elseif ($pub['Journal Abbreviation']) {
  824. $citation .= $pub['Journal Abbreviation'] . '. ';
  825. }
  826. $citation .= $pub['Publication Date'];
  827. if ($pub['Volume'] or $pub['Issue'] or $pub['Pages']) {
  828. $citation .= '; ';
  829. }
  830. if ($pub['Volume']) {
  831. $citation .= $pub['Volume'];
  832. }
  833. if ($pub['Issue']) {
  834. $citation .= '(' . $pub['Issue'] . ')';
  835. }
  836. if ($pub['Pages']) {
  837. if($pub['Volume']) {
  838. $citation .= ':';
  839. }
  840. $citation .= $pub['Pages'];
  841. }
  842. $citation .= '.';
  843. return $citation;
  844. }