tripal_pub.api.inc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. <?php
  2. /**
  3. * @file
  4. * Provides an application programming interface (API) to manage chado publications
  5. */
  6. /**
  7. * @defgroup tripal_pub_api Publication Module API
  8. * @ingroup tripal_api
  9. * @{
  10. * Provides an application programming interface (API) to manage chado publications
  11. *
  12. * @stephen add documentation here for how to add a new importer.
  13. *
  14. * @}
  15. */
  16. /**
  17. * Retrieves a list of publications as an associated array where
  18. * keys correspond directly with Tripal Pub CV terms.
  19. *
  20. * @param remote_db
  21. * The name of the remote publication database to query. These names should
  22. * match the name of the databases in the Chado 'db' table. Currently
  23. * supported databass include
  24. * 'PMID': PubMed
  25. *
  26. * @param search_array
  27. * An associate array containing the search criteria. The following key
  28. * are expected
  29. * 'remote_db': Specifies the name of the remote publication database
  30. * 'num_criteria': Specifies the number of criteria present in the search array
  31. * 'days': The number of days to include in the search starting from today
  32. * 'criteria': An associate array containing the search critiera. There should
  33. * be no less than 'num_criteria' elements in this array.
  34. *
  35. * The following keys are expected in the 'criteria' array
  36. * 'search_terms': A list of terms to search on, separated by spaces.
  37. * 'scope': The fields to search in the remote database. Valid values
  38. * include: 'title', 'abstract', 'author' and 'any'
  39. * 'operation': The logical operation to use for this criteria. Valid
  40. * values include: 'AND', 'OR' and 'NOT'.
  41. * @param $num_to_retrieve
  42. * The number of records to retrieve. In cases with large numbers of
  43. * records to retrieve, the remote database may limit the size of each
  44. * retrieval.
  45. * @param $page
  46. * Optional. If this function is called where the
  47. * page for the pager cannot be set using the $_GET variable, use this
  48. * argument to specify the page to retrieve.
  49. *
  50. * @return
  51. * Returns an array of pubs where each element is
  52. * an associative array where the keys are Tripal Pub CV terms.
  53. *
  54. * @ingroup tripal_pub_api
  55. */
  56. function tripal_get_remote_pubs($remote_db, $search_array, $num_to_retrieve, $page = 0) {
  57. // now call the callback function to get the results
  58. $callback = "tripal_pub_remote_search_$remote_db";
  59. $pubs = array(
  60. 'total_records' => 0,
  61. 'search_str' => '',
  62. 'pubs' => array(),
  63. );
  64. if (function_exists($callback)) {
  65. $pubs = call_user_func($callback, $search_array, $num_to_retrieve, $page);
  66. }
  67. return $pubs;
  68. }
  69. /**
  70. * This function is used to perfom a query using one of the supported databases
  71. * and return the raw query results. This may be XML or some other format
  72. * as provided by the database.
  73. *
  74. * @param $dbxref
  75. * The unique database ID for the record to retrieve. This value must
  76. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  77. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  78. * for the record in the database.
  79. *
  80. * @return
  81. * Returns the raw output wrapped in an HTML textarea element or an
  82. * error message indicating if the database type is unsupported or the
  83. * dbxref is invalid
  84. *
  85. * @ingroup tripal_pub_api
  86. */
  87. function tripal_get_remote_pub($dbxref) {
  88. if(preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  89. $remote_db = $matches[1];
  90. $accession = $matches[2];
  91. // check that the database is supported
  92. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  93. if(!in_array($remote_db, $supported_dbs)) {
  94. return "Unsupported database: $dbxref";
  95. }
  96. $search = array(
  97. 'num_criteria' => 1,
  98. 'remote_db' => $remote_db,
  99. 'criteria' => array(
  100. '1' => array(
  101. 'search_terms' => "$remote_db:$accession",
  102. 'scope' => 'id',
  103. 'operation' => '',
  104. 'is_phrase' => 0,
  105. ),
  106. ),
  107. );
  108. $pubs = tripal_get_remote_pubs($remote_db, $search, 1, 0);
  109. return $pubs[0]['raw'];
  110. }
  111. return 'Invalid DB xref';
  112. }
  113. /**
  114. * Builds the SQL statement need to search Chado for the publications
  115. * that match the user supplied criteria. Tpyically, this function is
  116. * called by the search form generated by the tripal_pub_search_form() function
  117. * but this function is included in the API for calling by anyone.
  118. *
  119. * @param $search_array
  120. * An array of search criteria provided by the user. The search array is
  121. * an associative array with the following keys:
  122. * 'num_criteria': an integer indicating the number of search criteria supplied
  123. * 'from_year': filters records by a start year
  124. * 'to_year': filters records by an end year
  125. * 'criteria': an array of criteria. Each criteria is an associative
  126. * array with the following keys:
  127. * 'search_terms': The text used for searching
  128. * 'scope': The cvterm_id of the property used for filtering
  129. * 'mode': The operation (e.g. AND, OR or NOT)
  130. * @param $offset
  131. * The offset for paging records. The first record returned will be
  132. * at the offset indicated here, and the next $limit number of records
  133. * will be returned.
  134. *
  135. * @param $limit
  136. * The number of records to retrieve
  137. *
  138. * @param total_records
  139. * A value passed by reference. This value will get set to the total
  140. * number of matching records
  141. *
  142. * @return
  143. * a PDO database object of the query results.
  144. *
  145. * @ingroup tripal_pub
  146. */
  147. function pub_search($search_array, $offset, $limit, &$total_records) {
  148. // build the SQL based on the criteria provided by the user
  149. $select = "SELECT DISTINCT P.*, CP.nid ";
  150. $from = "FROM {pub} P
  151. LEFT JOIN public.chado_pub CP on P.pub_id = CP.pub_id
  152. INNER JOIN {cvterm} CVT on CVT.cvterm_id = P.type_id
  153. ";
  154. $where = "WHERE (NOT P.title = 'null') "; // always exclude the dummy pub
  155. $order = "ORDER BY P.pyear DESC, P.title ASC";
  156. $args = array(); // arguments for where clause
  157. $join = 0;
  158. $num_criteria = $search_array['num_criteria'];
  159. $from_year = $search_array['from_year'];
  160. $to_year = $search_array['to_year'];
  161. for ($i = 1; $i <= $num_criteria; $i++) {
  162. $value = $search_array['criteria'][$i]['search_terms'];
  163. $type_id = $search_array['criteria'][$i]['scope'];
  164. $mode = $search_array['criteria'][$i]['mode'];
  165. $op = $search_array['criteria'][$i]['operation'];
  166. // skip criteria with no values
  167. if(!$value) {
  168. continue;
  169. }
  170. // to prevent SQL injection make sure our operator is
  171. // what we expect
  172. if ($op and $op != "AND" and $op != "OR" and $op != 'NOT') {
  173. $op = 'AND';
  174. }
  175. if ($op == 'NOT') {
  176. $op = 'AND NOT';
  177. }
  178. if (!$op) {
  179. $op = 'AND';
  180. }
  181. // get the scope type
  182. $values = array('cvterm_id' => $type_id);
  183. $cvterm = chado_select_record('cvterm', array('name'), $values);
  184. $type_name = '';
  185. if (count($cvterm) > 0) {
  186. $type_name = $cvterm[0]->name;
  187. }
  188. if ($type_name == 'Title') {
  189. $where .= " $op (lower(P.title) LIKE lower(:crit$i)) ";
  190. $args[":crit$i"] = '%' . $value . '%';
  191. }
  192. elseif ($type_name == 'Year') {
  193. $where .= " $op (lower(P.pyear) = lower(:crit$i)) ";
  194. $args[":crit$i"] = '%' . $value . '%';
  195. }
  196. elseif ($type_name == 'Volume') {
  197. $where .= " $op (lower(P.volume) = lower(:crit$i)) ";
  198. $args[":crit$i"] = '%' . $value . '%';
  199. }
  200. elseif ($type_name == 'Issue') {
  201. $where .= " $op (lower(P.issue) = lower(:crit$i)) ";
  202. $args[":crit$i"] = '%' . $value . '%';
  203. }
  204. elseif ($type_name == 'Journal Name') {
  205. $from .= " LEFT JOIN {pubprop} PP$i ON PP$i.pub_id = P.pub_id AND PP$i.type_id = :crit$i ";
  206. $where .= " $op ((lower(P.series_name) = lower(:crit$i) and CVT.name = 'Journal Article') OR
  207. (lower(PP$i.value) = lower(:crit$i))) ";
  208. $args[":crit$i"] = $type_id;
  209. }
  210. elseif ($type_name == 'Conference Name') {
  211. $from .= " LEFT JOIN {pubprop} PP$i ON PP$i.pub_id = P.pub_id AND PP$i.type_id = :crit$i ";
  212. $where .= " $op ((lower(P.series_name) = lower(:crit$i) and CVT.name = 'Conference Proceedings') OR
  213. (lower(PP$i.value) = lower(:crit$i))) ";
  214. $args[":crit$i"] = $type_id;
  215. }
  216. elseif ($type_name == 'Publication Type') {
  217. $where .= " $op (lower(CVT.name) = lower(:crit$i))";
  218. $args[":crit$i"] = $value;
  219. }
  220. elseif ($type_id == 0) { //'Any Field'
  221. $from .= " LEFT JOIN {pubprop} PP$i ON PP$i.pub_id = P.pub_id ";
  222. $where .= " $op (lower(PP$i.value) LIKE lower(:crit$i) OR
  223. lower(P.title) LIKE lower(:crit$i) OR
  224. lower(P.volumetitle) LIKE lower(:crit$i) OR
  225. lower(P.publisher) LIKE lower(:crit$i) OR
  226. lower(P.uniquename) LIKE lower(:crit$i) OR
  227. lower(P.pubplace) LIKE lower(:crit$i) OR
  228. lower(P.miniref) LIKE lower(:crit$i) OR
  229. lower(P.series_name) LIKE lower(:crit$i)) ";
  230. $args[":crit$i"] = '%' . $value . '%';
  231. }
  232. // for all other properties
  233. else {
  234. $from .= " LEFT JOIN {pubprop} PP$i ON PP$i.pub_id = P.pub_id AND PP$i.type_id = :type_id$i ";
  235. $where .= " $op (lower(PP$i.value) LIKE lower(:crit$i)) ";
  236. $args[":crit$i"] = '%' . $value . '%';
  237. $args[":type_id$i"] = $type_id;
  238. }
  239. }
  240. if($from_year and $to_year) {
  241. $where .= " AND (P.pyear ~ '....' AND to_number(P.pyear,'9999') >= :from$i AND to_number(P.pyear,'9999') <= :to$i) ";
  242. $args[":from$i"] = $from_year;
  243. $args[":to$i"] = $to_year;
  244. }
  245. $sql = "$select $from $where $order LIMIT " . (int) $limit . ' OFFSET ' . (int) $offset;
  246. $count = "SELECT count(*) FROM ($select $from $where $order) as t1";
  247. // first get the total number of matches
  248. $total_records = chado_query($count, $args)->fetchField();
  249. $results = chado_query($sql, $args);
  250. return $results;
  251. }
  252. /**
  253. * Retrieves a chado publication array
  254. *
  255. * @param $identifier
  256. * An array used to uniquely identify a publication. This array has the same
  257. * format as that used by the chado_generate_var(). The following keys can be
  258. * useful for uniquely identifying a publication as they should be unique:
  259. * - pub_id: the chado pub.pub_id primary key
  260. * - nid: the drupal nid of the publication
  261. * - uniquename: A value to matach with the pub.uniquename field
  262. * There are also some specially handled keys. They are:
  263. * - property: An array describing the property to select records for. It
  264. * should at least have either a 'type_name' key (if unique across cvs) or
  265. * 'type_id' key. Other supported keys include: 'cv_id', 'cv_name' (of the type),
  266. * 'value' and 'rank'
  267. * - dbxref: The database cross reference accession. It should be in the form
  268. * DB:ACCESSION, where DB is the database name and ACCESSION is the
  269. * unique publication identifier (e.g. PMID:4382934)
  270. * - dbxref_id: The dbxref.dbxref_id of the publication.
  271. * @param $options
  272. * An array of options. Supported keys include:
  273. * - Any keys supported by chado_generate_var(). See that function definition for
  274. * additional details.
  275. *
  276. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  277. * chado_select_record(). It should fully specify the pub record to be returned.
  278. *
  279. * @return
  280. * If a singe publication is retreived using the identifiers, then a publication
  281. * array will be returned. The array is of the same format returned by the
  282. * chado_generate_var() function. Otherwise, FALSE will be returned.
  283. *
  284. * @ingroup tripal_pub_api
  285. */
  286. function chado_get_publication($identifiers, $options = array()) {
  287. // Error Checking of parameters
  288. if (!is_array($identifiers)) {
  289. tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
  290. "chado_get_publication: The identifier passed in is expected to be an array with the key
  291. matching a column name in the pub table (ie: pub_id or name). You passed in %identifier.",
  292. array('%identifier'=> print_r($identifiers, TRUE))
  293. );
  294. }
  295. elseif (empty($identifiers)) {
  296. tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
  297. "chado_get_publication: You did not pass in anything to identify the publication you want. The identifier
  298. is expected to be an array with the key matching a column name in the pub table
  299. (ie: pub_id or name). You passed in %identifier.",
  300. array('%identifier'=> print_r($identifiers, TRUE))
  301. );
  302. }
  303. // If one of the identifiers is property then use chado_get_record_with_property()
  304. if (array_key_exists('property', $identifiers)) {
  305. $property = $identifiers['property'];
  306. unset($identifiers['property']);
  307. $pub = chado_get_record_with_property('pub', $property, $identifiers, $options);
  308. }
  309. elseif (array_key_exists('dbxref', $identifiers)) {
  310. if(preg_match('/^(.*?):(.*?)$/', $identifiers['dbxref'], $matches)) {
  311. $dbname = $matches[1];
  312. $accession = $matches[2];
  313. $values = array(
  314. 'dbxref_id' => array (
  315. 'accession' => $accession,
  316. 'db_id' => array(
  317. 'name' => $dbname
  318. ),
  319. ),
  320. );
  321. $pub_dbxref = chado_select_record('pub_dbxref', array('pub_id'), $values);
  322. if (count($pub_dbxref) > 0) {
  323. $pub = chado_generate_var('pub', array('pub_id' => $pub_dbxref[0]->pub_id), $options);
  324. }
  325. else {
  326. return FALSE;
  327. }
  328. }
  329. else {
  330. tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
  331. "chado_get_publication: The dbxref identifier is not correctly formatted.",
  332. array('%identifier'=> print_r($identifiers, TRUE))
  333. );
  334. }
  335. }
  336. elseif (array_key_exists('dbxref_id', $identifiers)) {
  337. // first get the pub_dbxref record
  338. $values = array('dbxref_id' => $identifiers['dbxref_id']);
  339. $pub_dbxref = chado_select_record('pub_dbxref', array('pub_id'), $values);
  340. // now get the pub
  341. if (count($pub_dbxref) > 0) {
  342. $pub = chado_generate_var('pub', array('pub_id' => $pub_dbxref[0]->pub_id), $options);
  343. }
  344. else {
  345. return FALSE;
  346. }
  347. }
  348. // Else we have a simple case and we can just use chado_generate_var to get the pub
  349. else {
  350. // Try to get the pub
  351. $pub = chado_generate_var('pub', $identifiers, $options);
  352. }
  353. // Ensure the pub is singular. If it's an array then it is not singular
  354. if (is_array($pub)) {
  355. tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
  356. "chado_get_publication: The identifiers did not find a single unique record. Identifiers passed: %identifier.",
  357. array('%identifier'=> print_r($identifiers, TRUE))
  358. );
  359. }
  360. // Report an error if $pub is FALSE since then chado_generate_var has failed
  361. elseif ($pub === FALSE) {
  362. tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
  363. "chado_get_publication: Could not find a publication using the identifiers
  364. provided. Check that the identifiers are correct. Identifiers passed: %identifier.",
  365. array('%identifier'=> print_r($identifiers, TRUE))
  366. );
  367. }
  368. // Else, as far we know, everything is fine so give them their pub :)
  369. else {
  370. return $pub;
  371. }
  372. }
  373. /**
  374. * The publication table of Chado only has a unique constraint for the
  375. * uniquename of the publiation, but in reality a publication can be considered
  376. * unique by a combination of the title, publication type, published year and
  377. * series name (e.g. journal name or conference name). The site administrator
  378. * can configure how publications are determined to be unique. This function
  379. * uses the configuration specified by the administrator to look for publications
  380. * that match the details specified by the $pub_details argument
  381. * and indicates if one ore more publications match the criteria.
  382. *
  383. * @param $pub_details
  384. * An associative array with details about the publications. The expected keys
  385. * are:
  386. * 'Title': The title of the publication
  387. * 'Year': The published year of the publication
  388. * 'Publication Type': An array of publication types. A publication can have more than one type.
  389. * 'Series Name': The series name of the publication
  390. * 'Journal Name': An alternative to 'Series Name' is 'Journal Name'
  391. * 'Citation': The publication citation (this is the value saved in the pub.uniquename field and must be unique)
  392. * If this key is present it will also be checked
  393. * 'Publication Dbxref': A database cross reference of the form DB:ACCESSION where DB is the name
  394. * of the database and ACCESSION is the unique identifier (e.g PMID:3483139)
  395. *
  396. * @return
  397. * An array containing the pub_id's of matching publications.
  398. */
  399. function chado_does_pub_exist($pub_details) {
  400. // first try to find the publication using the accession number if that key exists in the details array
  401. if (array_key_exists('Publication Dbxref', $pub_details)) {
  402. $pub = chado_get_publication(array('dbxref' => $pub_details['Publication Dbxref']));
  403. if($pub) {
  404. return array($pub->pub_id);
  405. }
  406. }
  407. // make sure the citation is unique
  408. if (array_key_exists('Citation', $pub_details)) {
  409. $pub = chado_get_publication(array('uniquename' => $pub_details['Citation']));
  410. if($pub) {
  411. return array($pub->pub_id);
  412. }
  413. }
  414. // get the publication type (use the first publication type)
  415. if (array_key_exists('Publication Type', $pub_details)) {
  416. $type_name = '';
  417. if(is_array($pub_details['Publication Type'])) {
  418. $type_name = $pub_details['Publication Type'][0];
  419. }
  420. else {
  421. $type_name = $pub_details['Publication Type'];
  422. }
  423. $identifiers = array(
  424. 'name' => $type_name,
  425. 'cv_id' => array(
  426. 'name' => 'tripal_pub',
  427. ),
  428. );
  429. $pub_type = cvterm_retrieve($identifiers);
  430. }
  431. else {
  432. tripal_report_error('tripal_pub', TRIPAL_ERROR, "chado_does_pub_exist(): The Publication Type is a " .
  433. "required property but is missing", array());
  434. return FALSE;
  435. }
  436. if (!$pub_type) {
  437. tripal_report_error('tripal_pub', TRIPAL_ERROR, "chado_does_pub_exist(): Cannot find publication type: '%type'",
  438. array('%type' => $pub_details['Publication Type'][0]));
  439. return FALSE;
  440. }
  441. // get the series name. The pub.series_name field is only 255 chars so we must truncate to be safe
  442. $series_name = '';
  443. if (array_key_exists('Series_Name', $pub_details)) {
  444. $series_name = substr($pub_details['Series Name'], 0, 255);
  445. }
  446. if (array_key_exists('Journal Name', $pub_details)) {
  447. $series_name = substr($pub_details['Journal Name'], 0, 255);
  448. }
  449. // make sure the publication is unique using the prefereed import duplication check
  450. $import_dups_check = variable_get('tripal_pub_import_duplicate_check', 'title_year_media');
  451. $pubs = array();
  452. switch ($import_dups_check) {
  453. case 'title_year':
  454. $identifiers = array(
  455. 'title' => $pub_details['Title'],
  456. 'pyear' => $pub_details['Year']
  457. );
  458. $pubs = chado_select_record('pub', array('pub_id'), $identifiers);
  459. break;
  460. case 'title_year_type':
  461. $identifiers = array(
  462. 'title' => $pub_details['Title'],
  463. 'pyear' => $pub_details['Year'],
  464. 'type_id' => $pub_type->cvterm_id,
  465. );
  466. $pubs = chado_select_record('pub', array('pub_id'), $identifiers);
  467. break;
  468. case 'title_year_media':
  469. $identifiers = array(
  470. 'title' => $pub_details['Title'],
  471. 'pyear' => $pub_details['Year'],
  472. 'series_name' => $series_name,
  473. );
  474. $pubs = chado_select_record('pub', array('pub_id'), $identifiers);
  475. break;
  476. }
  477. $return = array();
  478. foreach ($pubs as $pub) {
  479. $return[] = $pub->pub_id;
  480. }
  481. return $return;
  482. }
  483. /**
  484. * Updates publication records that currently exist in the Chado pub table
  485. * with the most recent data in the remote database.
  486. *
  487. * @param $do_contact
  488. * Set to TRUE if authors should automatically have a contact record added
  489. * to Chado. Contacts are added using the name provided by the remote
  490. * database.
  491. * @param $dbxref
  492. * The unique database ID for the record to update. This value must
  493. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  494. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  495. * for the record in the database.
  496. * @param $db
  497. * The name of the remote database to update. If this value is provided and
  498. * no dbxref then all of the publications currently in the Chado database
  499. * for this remote database will be updated.
  500. *
  501. * @ingroup tripal_pub_api
  502. */
  503. function chado_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
  504. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  505. "If the load fails or is terminated prematurely then the entire set of \n" .
  506. "insertions/updates is rolled back and will not be found in the database\n\n";
  507. $transaction = db_transaction();
  508. try {
  509. // get a list of all publications by their Dbxrefs that have supported databases
  510. $sql = "
  511. SELECT DB.name as db_name, DBX.accession
  512. FROM pub P
  513. INNER JOIN pub_dbxref PDBX ON P.pub_id = PDBX.pub_id
  514. INNER JOIN dbxref DBX ON DBX.dbxref_id = PDBX.dbxref_id
  515. INNER JOIN db DB ON DB.db_id = DBX.db_id
  516. ";
  517. $args = array();
  518. if ($dbxref and preg_match('/^(.*?):(.*?)$/', $dbxref, $matches)) {
  519. $dbname = $matches[1];
  520. $accession = $matches[2];
  521. $sql .= "WHERE DBX.accession = :accession and DB.name = :dbname ";
  522. $args[':accession'] = $accession;
  523. $args[':dbname'] = $dbname;
  524. }
  525. elseif ($db) {
  526. $sql .= " WHERE DB.name = :dbname ";
  527. $args[':dbname'] = $db;
  528. }
  529. $sql .= "ORDER BY DB.name, P.pub_id";
  530. $results = chado_query($sql, $args);
  531. $num_to_retrieve = 100;
  532. $i = 0; // count the number of IDs. When we hit $num_to_retrieve we'll do the query
  533. $curr_db = ''; // keeps track of the current current database
  534. $ids = array(); // the list of IDs for the database
  535. $search = array(); // the search array passed to the search function
  536. // iterate through the pub IDs
  537. while ($pub = $results->fetchObject()) {
  538. $accession = $pub->accession;
  539. $remote_db = $pub->db_name;
  540. // here we need to only update publications for databases we support
  541. $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
  542. if(!in_array($remote_db, $supported_dbs)) {
  543. continue;
  544. }
  545. $search = array(
  546. 'num_criteria' => 1,
  547. 'remote_db' => $remote_db,
  548. 'criteria' => array(
  549. '1' => array(
  550. 'search_terms' => "$remote_db:$accession",
  551. 'scope' => 'id',
  552. 'operation' => '',
  553. 'is_phrase' => 0,
  554. ),
  555. ),
  556. );
  557. $pubs = tripal_get_remote_pubs($remote_db, $search, 1, 0);
  558. tripal_pub_add_publications($pubs, $do_contact, TRUE);
  559. $i++;
  560. }
  561. // sync the newly added publications with Drupal
  562. print "Syncing publications with Drupal...\n";
  563. chado_node_sync_records('pub');
  564. // if the caller wants to create contacts then we should sync them
  565. if ($do_contact) {
  566. print "Syncing contacts with Drupal...\n";
  567. chado_node_sync_records('contact');
  568. }
  569. }
  570. catch (Exception $e) {
  571. print "\n"; // make sure we start errors on new line
  572. watchdog_exception('T_pub_import', $e);
  573. $transaction->rollback();
  574. print "FAILED: Rolling back database changes...\n";
  575. return;
  576. }
  577. print "Done.\n";
  578. }
  579. /**
  580. * Imports all publications for a given publication import setup.
  581. *
  582. * @param $import_id
  583. * The ID of the import setup to use
  584. * @param $job_id
  585. * The jobs management job_id for the job if this function is run as a job.
  586. *
  587. * @ingroup tripal_pub_api
  588. */
  589. function tripal_execute_pub_importer($import_id, $job_id = NULL) {
  590. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  591. "If the load fails or is terminated prematurely then the entire set of \n" .
  592. "insertions/updates is rolled back and will not be found in the database\n\n";
  593. // start the transaction
  594. $transaction = db_transaction();
  595. try {
  596. $page = 0;
  597. $do_contact = FALSE;
  598. $num_to_retrieve = 100;
  599. // get all of the loaders
  600. $args = array(':import_id' => $import_id);
  601. $sql = "SELECT * FROM {tripal_pub_import} WHERE pub_import_id = :import_id ";
  602. $import = db_query($sql, $args)->fetchObject();
  603. print "Executing Importer: '" . $import->name . "'\n";
  604. $criteria = unserialize($import->criteria);
  605. $remote_db = $criteria['remote_db'];
  606. $total_pubs = 0;
  607. do {
  608. // retrieve the pubs for this page. We'll retreive 100 at a time
  609. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  610. $pubs = $results['pubs'];
  611. $num_pubs = $rseults['total_records'];
  612. $total_pubs += $num_pubs;
  613. tripal_pub_add_publications($pubs, $import->do_contact);
  614. $page++;
  615. }
  616. // continue looping until we have a $pubs array that does not have
  617. // our requested numer of records. This means we've hit the end
  618. while (count($pubs) == $num_to_retrieve);
  619. // sync the newly added publications with Drupal. If the user
  620. // requested a report then we don't want to print any syncing information
  621. // so pass 'FALSE' to the sync call
  622. print "Syncing publications with Drupal...\n";
  623. chado_node_sync_records('pub');
  624. // if any of the importers wanted to create contacts from the authors then sync them
  625. if($import->do_contact) {
  626. print "Syncing contacts with Drupal...\n";
  627. chado_node_sync_records('contact');
  628. }
  629. tripal_set_job_progress($job_id, '100');
  630. }
  631. catch (Exception $e) {
  632. print "\n"; // make sure we start errors on new line
  633. watchdog_exception('T_pub_import', $e);
  634. $transaction->rollback();
  635. print "FAILED: Rolling back database changes...\n";
  636. return;
  637. }
  638. print "Done.\n";
  639. }
  640. /**
  641. * Imports all publications for all active import setups.
  642. *
  643. * @param $report_email
  644. * A list of email address, separated by commas, that should be notified
  645. * once importing has completed
  646. * @param $do_update
  647. * If set to TRUE then publications that already exist in the Chado database
  648. * will be updated, whereas if FALSE only new publications will be added
  649. *
  650. * @ingroup tripal_pub_api
  651. */
  652. function tripal_execute_active_pub_importers($report_email = FALSE, $do_update = FALSE) {
  653. $num_to_retrieve = 100;
  654. $page = 0;
  655. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  656. "If the load fails or is terminated prematurely then the entire set of \n" .
  657. "insertions/updates is rolled back and will not be found in the database\n\n";
  658. // start the transaction
  659. $transaction = db_transaction();
  660. try {
  661. // get all of the loaders
  662. $args = array();
  663. $sql = "SELECT * FROM {tripal_pub_import} WHERE disabled = 0 ";
  664. $results = db_query($sql, $args);
  665. $do_contact = FALSE;
  666. $reports = array();
  667. foreach ($results as $import) {
  668. $page = 0;
  669. print "Executing importer: '" . $import->name . "'\n";
  670. // keep track if any of the importers want to create contacts from authors
  671. if ($import->do_contact == 1) {
  672. $do_contact = TRUE;
  673. }
  674. $criteria = unserialize($import->criteria);
  675. $remote_db = $criteria['remote_db'];
  676. do {
  677. // retrieve the pubs for this page. We'll retreive 100 at a time
  678. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  679. $pubs = $results['pubs'];
  680. $reports[$import->name] = tripal_pub_add_publications($pubs, $import->do_contact, $do_update);
  681. $page++;
  682. }
  683. // continue looping until we have a $pubs array that does not have
  684. // our requested numer of records. This means we've hit the end
  685. while (count($pubs) == $num_to_retrieve);
  686. }
  687. // sync the newly added publications with Drupal. If the user
  688. // requested a report then we don't want to print any syncing information
  689. // so pass 'FALSE' to the sync call
  690. print "Syncing publications with Drupal...\n";
  691. chado_node_sync_records('pub');
  692. // iterate through each of the reports and generate a final report with HTML links
  693. $HTML_report = '';
  694. if ($report_email) {
  695. $HTML_report .= "<html>";
  696. global $base_url;
  697. foreach ($reports as $importer => $report) {
  698. $total = count($report['inserted']);
  699. $HTML_report .= "<b>$total new publications from importer: $importer</b><br><ol>\n";
  700. foreach ($report['inserted'] as $pub) {
  701. $item = $pub['Title'];
  702. if (array_key_exists('pub_id', $pub)) {
  703. $item = l($pub['Title'], "$base_url/pub/" . $pub['pub_id']);
  704. }
  705. $HTML_report .= "<li>$item</li>\n";
  706. }
  707. $HTML_report .= "</ol>\n";
  708. }
  709. $HTML_report .= "</html>";
  710. $site_email = variable_get('site_mail', '');
  711. $params = array(
  712. 'message' => $HTML_report
  713. );
  714. drupal_mail('tripal_pub', 'import_report', $report_email, language_default(), $params, $site_email, TRUE);
  715. }
  716. // if any of the importers wanted to create contacts from the authors then sync them
  717. if($do_contact) {
  718. print "Syncing contacts with Drupal...\n";
  719. chado_node_sync_records('contact');
  720. }
  721. }
  722. catch (Exception $e) {
  723. print "\n"; // make sure we start errors on new line
  724. watchdog_exception('T_pub_import', $e);
  725. $transaction->rollback();
  726. print "FAILED: Rolling back database changes...\n";
  727. return;
  728. }
  729. print "Done.\n";
  730. }
  731. /**
  732. * Imports a singe publication specified by a remote database cross reference.
  733. *
  734. * @param $pub_dbxref
  735. * The unique database ID for the record to update. This value must
  736. * be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
  737. * database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
  738. * for the record in the database.
  739. * @param $do_contact
  740. * Set to TRUE if authors should automatically have a contact record added
  741. * to Chado.
  742. * @param $do_update
  743. * If set to TRUE then the publication will be updated if it already exists
  744. * in the database.
  745. *
  746. * @ingroup tripal_pub_api
  747. */
  748. function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_update) {
  749. $num_to_retrieve = 1;
  750. $pager_id = 0;
  751. $page = 0;
  752. $num_pubs = 0;
  753. print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
  754. "If the load fails or is terminated prematurely then the entire set of \n" .
  755. "insertions/updates is rolled back and will not be found in the database\n\n";
  756. $transaction = db_transaction();
  757. try {
  758. if(preg_match('/^(.*?):(.*?)$/', $pub_dbxref, $matches)) {
  759. $dbname = $matches[1];
  760. $accession = $matches[2];
  761. $criteria = array(
  762. 'num_criteria' => 1,
  763. 'remote_db' => $dbname,
  764. 'criteria' => array(
  765. '1' => array(
  766. 'search_terms' => "$dbname:$accession",
  767. 'scope' => 'id',
  768. 'operation' => '',
  769. 'is_phrase' => 0,
  770. ),
  771. ),
  772. );
  773. $remote_db = $criteria['remote_db'];
  774. $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
  775. $pubs = $results['pubs'];
  776. $search_str = $results['search_str'];
  777. $total_records = $results['total_records'];
  778. $pub_id = tripal_pub_add_publications($pubs, $do_contact, $do_update);
  779. }
  780. // sync the newly added publications with Drupal
  781. print "Syncing publications with Drupal...\n";
  782. chado_node_sync_records('pub');
  783. // if any of the importers wanted to create contacts from the authors then sync them
  784. if($do_contact) {
  785. print "Syncing contacts with Drupal...\n";
  786. chado_node_sync_records('contact');
  787. }
  788. }
  789. catch (Exception $e) {
  790. print "\n"; // make sure we start errors on new line
  791. watchdog_exception('T_pub_import', $e);
  792. $transaction->rollback();
  793. print "FAILED: Rolling back database changes...\n";
  794. return;
  795. }
  796. print "Done.\n";
  797. }