tripal_pub.api.inc 31 KB

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