tripal_ws.api.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * This file provides the Tripal Web Services API: a set of functions for
  6. * interacting with the Tripal Web Services.
  7. */
  8. /**
  9. * @defgroup tripal_ws_api Web Services
  10. *
  11. * @ingroup tripal_api
  12. * {@
  13. * The Tripal Web Services API provides a set of functions for interacting
  14. * with the Tripal Web Services.
  15. * @}
  16. */
  17. /**
  18. * Adjust the values of a field for display in web services.
  19. *
  20. * This hook should be used sparingly. It is meant primarily to adjust 3rd
  21. * Party (non Tripal) fields so that they work with web
  22. * services. The caller should adjust the $items array as needed.
  23. * This change only affects the value displayed in web services. Web services
  24. * expect that every field have a 'value' element for each of the items. If a
  25. * field for some reason does not have a 'value' element then this hook will
  26. * allow setting of that element.
  27. *
  28. * @param $items
  29. * The list of items for the field.
  30. * @param $field
  31. * The field array.
  32. * @param $instance
  33. * The field instance array.
  34. *
  35. * @ingroup tripal_ws_api
  36. */
  37. function hook_tripal_ws_value(&$items, $field, $instance) {
  38. // The image module doesn't properly set the 'value' field, so we'll do it
  39. // here.
  40. if($field['type'] == 'image' and $field['module'] == 'image') {
  41. foreach ($items as $delta => $details) {
  42. if ($items[$delta] and array_key_exists('uri', $items[$delta])) {
  43. $items[$delta]['value']['schema:url'] = file_create_url($items[$delta]['uri']);
  44. }
  45. }
  46. }
  47. }
  48. /**
  49. * Retrieves a list of TripalWebService implementations.
  50. *
  51. * The TripalWebService classes can be added by a site developer that wishes
  52. * to create a new Tripal compatible web serivce. The class file should
  53. * be placed in the [module]/includes/TripalWebService directory. Tripal will
  54. * support any service as long as it is in this directory and extends the
  55. * TripalWebService class.
  56. *
  57. * @return
  58. * A list of TripalWebService names.
  59. *
  60. * @ingroup tripal_ws_api
  61. */
  62. function tripal_get_web_services() {
  63. $services = array();
  64. $modules = module_list(TRUE);
  65. foreach ($modules as $module) {
  66. // Find all of the files in the tripal_chado/includes/fields directory.
  67. $service_path = drupal_get_path('module', $module) . '/includes/TripalWebService';
  68. $service_files = file_scan_directory($service_path, '/.inc$/');
  69. // Iterate through the fields, include the file and run the info function.
  70. foreach ($service_files as $file) {
  71. $class = $file->name;
  72. module_load_include('inc', $module, 'includes/TripalWebService/' . $class);
  73. if (class_exists($class) and is_subclass_of($class, 'TripalWebService')) {
  74. $services[] = $class;
  75. }
  76. }
  77. }
  78. return $services;
  79. }
  80. /**
  81. * Loads the TripalWebService class file into scope.
  82. *
  83. * @param $class
  84. * The TripalWebService class to include.
  85. *
  86. * @return
  87. * TRUE if the field type class file was found, FALSE otherwise.
  88. *
  89. * @ingroup tripal_ws_api
  90. */
  91. function tripal_load_include_web_service_class($class) {
  92. $modules = module_list(TRUE);
  93. foreach ($modules as $module) {
  94. $file_path = realpath(".") . '/' . drupal_get_path('module', $module) . '/includes/TripalWebService/' . $class . '.inc';
  95. if (file_exists($file_path)) {
  96. module_load_include('inc', $module, 'includes/TripalWebService/' . $class);
  97. if (class_exists($class)) {
  98. return TRUE;
  99. }
  100. }
  101. }
  102. return FALSE;
  103. }
  104. /**
  105. * Adds a new site to the web services table.
  106. *
  107. * @param $name
  108. * Name of site to be included.
  109. * @param $url
  110. * URL of site to be added.
  111. * @param $version
  112. * Version of the API being used. default to 1
  113. * @param $description
  114. * A description of the site and any additional info that
  115. * would be helpful for admins.
  116. *
  117. * @return
  118. * TRUE if the site is successfully added, FALSE otherwise.
  119. *
  120. * @ingroup tripal_ws_api
  121. */
  122. function tripal_add_site($name, $url, $version, $description) {
  123. $check_url = NULL;
  124. $check_name = NULL;
  125. $write_to_db = TRUE;
  126. // When inserting a record.
  127. $check_url =
  128. db_select('tripal_sites', 'ts')
  129. ->fields('ts', array('id'))
  130. ->condition('url', $url)
  131. ->condition('version', $version)
  132. ->execute()
  133. ->fetchField();
  134. $check_name =
  135. db_select('tripal_sites', 'ts')
  136. ->fields('ts', array('id'))
  137. ->condition('name', $name)
  138. ->execute()
  139. ->fetchField();
  140. if ($check_url) {
  141. drupal_set_message(t('The URL and version is used by another site.'), 'error');
  142. $write_to_db = FALSE;
  143. }
  144. if ($check_name) {
  145. drupal_set_message(t('The name is used by another site.'), 'error');
  146. $write_to_db = FALSE;
  147. }
  148. if ($write_to_db === TRUE) {
  149. db_insert('tripal_sites')
  150. ->fields(array(
  151. 'name' => $name,
  152. 'url' => $url,
  153. 'version' => $version,
  154. 'description' => $description
  155. ))
  156. ->execute();
  157. drupal_set_message(t('Tripal site \'' . $name . '\' has been added.'));
  158. return $write_to_db;
  159. }
  160. return $write_to_db;
  161. }
  162. /**
  163. * Remove a site from the web services table.
  164. *
  165. * @param $record_id
  166. * ID of the record to be deleted.
  167. *
  168. * @return
  169. * TRUE if the record was successfully deleted, FALSE otherwise.
  170. *
  171. * @ingroup tripal_ws_api
  172. */
  173. function tripal_remove_site($record_id) {
  174. if ($record_id) {
  175. db_delete('tripal_sites')
  176. ->condition('id', $record_id)
  177. ->execute();
  178. drupal_set_message('The Tripal site \'' . $record_id . '\' has been removed.');
  179. return TRUE;
  180. }
  181. return FALSE;
  182. }
  183. /**
  184. * Constructs a URL for a remote Tripal web service.
  185. *
  186. * @param $remote_site
  187. * A remote Tripal site object.
  188. * @param $path
  189. * The web service path for the content (excluding
  190. * 'web-servcies/vX.x/content'). To retrieve the full content listing
  191. * leave this paramter empty.
  192. * @param $query
  193. * An query string to appear after the ? in a URL.
  194. *
  195. * @return
  196. * The full URL within the content service.
  197. */
  198. function tripal_build_remote_content_url($remote_site, $path = '', $query = '') {
  199. // Build the URL to the remote web services.
  200. $ws_version = $remote_site->version;
  201. $ws_url = $remote_site->url;
  202. $ws_url = trim($ws_url, '/');
  203. $ws_url .= '/web-services/content/' . $ws_version . '/' . $path;
  204. // Build the Query and make and substitions needed.
  205. if ($query) {
  206. $ws_url = $ws_url . '?' . $query;
  207. }
  208. return $ws_url;
  209. }
  210. /**
  211. * Makes a request to the "content" service of a remote Tripal web site.
  212. *
  213. * @param $site_id
  214. * The numeric site ID for the remote Tripal site.
  215. * @param $path
  216. * The web service path for the content (excluding
  217. * 'web-servcies/vX.x/content'). To retrieve the full content listing
  218. * leave this paramter empty.
  219. * @param $query
  220. * An query string to appear after the ? in a URL.
  221. *
  222. * @return
  223. * The JSON response formatted in a PHP array or FALSE if a problem occured.
  224. *
  225. * @ingroup tripal_ws_api
  226. */
  227. function tripal_get_remote_content($site_id, $path = '', $query = '') {
  228. if (!$site_id) {
  229. throw new Exception('Please provide a numeric site ID for the tripal_get_remote_content function.');
  230. }
  231. // Fetch the record for this site id.
  232. $remote_site = db_select('tripal_sites', 'ts')
  233. ->fields('ts')
  234. ->condition('ts.id', $site_id)
  235. ->execute()
  236. ->fetchObject();
  237. if (!$remote_site) {
  238. $data = [
  239. 'error' => t('Could not find a remote tripal site using the id provided: !id.',
  240. array('!id' => $site_id))
  241. ];
  242. _tripal_report_ws_error($data);
  243. return $data;
  244. }
  245. // Make the remote query.
  246. $ws_url = tripal_build_remote_content_url($remote_site, $path, $query);
  247. $data = drupal_http_request($ws_url);
  248. if (!$data) {
  249. $data = [
  250. 'error' => t('Could not connect to the remote web service using the url: !url',
  251. ['!url' => $ws_url])
  252. ];
  253. _tripal_report_ws_error($data);
  254. return $data;
  255. }
  256. // If the data object has an error then this is some sort of
  257. // connection error (not a Tripal web servcies error).
  258. if (property_exists($data, 'error')) {
  259. $data = [
  260. 'error' => $data->error
  261. ];
  262. _tripal_report_ws_error($data);
  263. return $data;
  264. }
  265. // We got a response, so convert it to a PHP array.
  266. $data = drupal_json_decode($data->data);
  267. // Check if there was a Tripal Web Services error.
  268. if (array_key_exists('error', $data)) {
  269. _tripal_report_ws_error($data);
  270. }
  271. return $data;
  272. }
  273. /**
  274. * A helper function for reporting an error when retrieving remote content.
  275. *
  276. * @param $data
  277. * A data array containing at a minimum the 'error' key containing the
  278. * error message.
  279. */
  280. function _tripal_report_ws_error($data) {
  281. $error = '</pre>' . print_r($data['error'], TRUE) . '</pre>';
  282. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  283. 'Tripal remote web services reports the following error: !error.',
  284. array('!error' => $error));
  285. }
  286. /**
  287. * Retrieves the JSON-LD context for any remote Tripal web service.
  288. *
  289. * @param $context_url
  290. * The Full URL for the context file on the remote Tripal site. This URL
  291. * can be found in the '@context' key of any response from a remote Tripal
  292. * web services call.
  293. * @param $cache_id
  294. * A unique ID for caching of this context result to speed furture
  295. * queries.
  296. * @return
  297. * The JSON-LD context mapping array, or FALSE if the context could not
  298. * be retrieved.
  299. *
  300. * @ingroup tripal_ws_api
  301. */
  302. function tripal_get_remote_context($context_url, $cache_id) {
  303. if (!$context_url) {
  304. throw new Exception('PLease provide a context_url for the tripal_get_remote_context function.');
  305. }
  306. if (!$cache_id) {
  307. throw new Exception('PLease provide unique $cache_id for the tripal_get_remote_context function.');
  308. }
  309. if ($cache = cache_get($cache_id)) {
  310. return $cache->data;
  311. }
  312. $context = drupal_http_request($context_url);
  313. if (!$context) {
  314. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  315. 'There was a poblem retrieving the context from the remote site: !context_url.',
  316. array('!context_url' => $context_url));
  317. return FALSE;
  318. }
  319. $context = drupal_json_decode($context->data);
  320. $context = $context['@context'];
  321. cache_set($cache_id, $context);
  322. return $context;
  323. }
  324. /**
  325. * Retrieves the JSON-LD context for a bundle or field on a remote Tripal site.
  326. *
  327. * The $site_id, $bundle_accession and $field_accession variables are not
  328. * needed to retrieve the context, but are used for caching the context to
  329. * make subsequent calls execute faster. This function is meant to be used
  330. * only for the 'content' service provided by Tripal.
  331. *
  332. * @param $site_id
  333. * The numeric site ID for the remote Tripal site.
  334. * @param $context_url
  335. * The Full URL for the context file on the remote Tripal site. This URL
  336. * can be found in the '@context' key of any response from a remote Tripal
  337. * web services call.
  338. * @param $bundle_accession
  339. * The controlled vocabulary term accession for the content type
  340. * on the remote Tripal site.
  341. * @param $field_accession
  342. * The controlled vocabulary term accession for the property (i.e. field) of
  343. * the Class (i.e. content type).
  344. * @return
  345. * The JSON-LD context mapping array.
  346. *
  347. * @ingroup tripal_ws_api
  348. */
  349. function tripal_get_remote_content_context($site_id, $context_url, $bundle_accession, $field_accession = '') {
  350. $cache_id = substr('trp_ws_context_' . $site_id . '-' . $bundle_accession . '-' . $field_accession, 0, 254);
  351. $context = tripal_get_remote_context($context_url, $cache_id);
  352. return $context;
  353. }
  354. /**
  355. * Clears the cached remote site documentation and context.
  356. *
  357. * When querying a remote website, the site's API documenation and page context
  358. * is cached to make re-use of that information easier in the future. This
  359. * function can be used to clear those caches.
  360. *
  361. * @param $site_id
  362. * The numeric site ID for the remote Tripal site.
  363. *
  364. * @ingroup tripal_ws_api
  365. */
  366. function tripal_clear_remote_cache($site_id) {
  367. if (!$site_id) {
  368. throw new Exception('Please provide a numeric site ID for the tripal_clear_remote_cache function.');
  369. }
  370. cache_clear_all('trp_ws_context_' . $site_id , 'cache', TRUE);
  371. cache_clear_all('trp_ws_doc_' . $site_id , 'cache', TRUE);
  372. }
  373. /**
  374. * Retrieves the API documentation for a remote Tripal web service.
  375. *
  376. * @param $site_id
  377. * The numeric site ID for the remote Tripal site.
  378. * @return
  379. * The vocabulary of a remote Tripal web service, or FALSE if an error
  380. * occured.
  381. *
  382. * @ingroup tripal_ws_api
  383. */
  384. function tripal_get_remote_API_doc($site_id) {
  385. $site_doc = '';
  386. if (!$site_id) {
  387. throw new Exception('Please provide a numeric site ID for the tripal_get_remote_API_doc function.');
  388. }
  389. $cache_name = 'trp_ws_doc_' . $site_id;
  390. if ($cache = cache_get($cache_name)) {
  391. return $cache->data;
  392. }
  393. // Get the site url from the tripal_sites table.
  394. $remote_site = db_select('tripal_sites', 'ts')
  395. ->fields('ts')
  396. ->condition('ts.id', $site_id)
  397. ->execute()
  398. ->fetchObject();
  399. if (!$remote_site) {
  400. throw new Exception(t('Cannot find a remote site with id: "!id"', array('!id' => $site_id)));
  401. }
  402. // Build the URL to the remote web services.
  403. $ws_version = $remote_site->version;
  404. $ws_url = $remote_site->url;
  405. $ws_url = trim($ws_url, '/');
  406. $ws_url .= '/web-services/doc/' . $ws_version;
  407. // Build and make the request.
  408. $options = [];
  409. $data = drupal_http_request($ws_url, $options);
  410. if (!$data) {
  411. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  412. t('Could not connect to the remote web service.'));
  413. return FALSE;
  414. }
  415. // If the data object has an error then this is some sort of
  416. // connection error (not a Tripal web servcies error).
  417. if (property_exists($data, 'error')) {
  418. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  419. 'Remote web services document reports the following error: !error. Using URL: !url',
  420. array('!error' => $error, '!url' => $ws_url));
  421. return FALSE;
  422. }
  423. // We got a response, so convert it to a PHP array.
  424. $site_doc = drupal_json_decode($data->data);
  425. // Check if there was a Tripal Web Services error.
  426. if (array_key_exists('error', $data)) {
  427. $error = '</pre>' . print_r($data['error'], TRUE) . '</pre>';
  428. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  429. 'Tripal Remote web services document reports the following error: !error. Using URL: !url',
  430. array('!error' => $error, '!url' => $ws_url));
  431. return FALSE;
  432. }
  433. cache_set($cache_name, $site_doc);
  434. return $site_doc;
  435. }
  436. /**
  437. * Queries a remote site for an array of bulk entity ids.
  438. *
  439. * This function returns an array of "fake" entities containing values
  440. * for fields specified.
  441. *
  442. * @param $remote_entity_ids
  443. * Array of the remote ids.
  444. * @param $site_id
  445. * The numeric site ID for the remote Tripal site.
  446. * @param $bundle_accession
  447. * The controlled vocabulary term accession for the content type
  448. * on the remote Tripal site.
  449. * @param $field_ids
  450. * The controlled vocabulary term accessions for the fields available
  451. * on the remote content type. Any remote fields that matches these IDs will
  452. * be added to the entity returned.
  453. * @return
  454. * An array of fake entity objects where the key is the entity_id and
  455. * the value is the object.
  456. *
  457. * @ingroup tripal_ws_api
  458. */
  459. function tripal_load_remote_entities($remote_entity_ids, $site_id, $bundle_accession, $field_ids) {
  460. if (!$remote_entity_ids) {
  461. throw new Exception('Please provide the list of remote entity ids for the tripal_load_remote_entities function.');
  462. }
  463. if (!is_array($remote_entity_ids)) {
  464. throw new Exception('Please provide an array for the remote entity ids for the tripal_load_remote_entities function.');
  465. }
  466. if (!$site_id) {
  467. throw new Exception('Please provide a numeric site ID for the tripal_load_remote_entities function.');
  468. }
  469. if (!$bundle_accession) {
  470. throw new Exception('Please provide the bundle accession for the tripal_load_remote_entities function.');
  471. }
  472. if (!$field_ids) {
  473. throw new Exception('Please provide the list of field IDs for the tripal_load_remote_entities function.');
  474. }
  475. if (!is_array($field_ids)) {
  476. throw new Exception('Please provide an array for the field IDs for the tripal_load_remote_entities function.');
  477. }
  478. // Get the site documentation (loads from cache if already retrieved).
  479. $site_doc = tripal_get_remote_API_doc($site_id);
  480. // Generate an array for the query and then execute it.
  481. $query = 'page=1&limit=' . count($remote_entity_ids) .
  482. '&ids=' . urlencode(implode(",", $remote_entity_ids)) .
  483. '&fields=' . urlencode(implode(",", $field_ids));
  484. $results = tripal_get_remote_content($site_id, $bundle_accession, $query);
  485. // If we encountered an error just return;
  486. if (array_key_exists('error', $results)) {
  487. return FALSE;
  488. }
  489. // Get the context JSON for this remote entity, we'll use it to map
  490. $context_url = $results['@context'];
  491. $context = tripal_get_remote_content_context($site_id, $context_url, $bundle_accession);
  492. if (!$context) {
  493. return $entity;
  494. }
  495. $total_items = $results['totalItems'];
  496. $members = $results['member'];
  497. $entities = array();
  498. foreach($members as $member) {
  499. // Start building the fake entity.
  500. $entity_id = preg_replace('/^.*?(\d+)$/', '$1', $member['@id']);
  501. $entity = new stdClass();
  502. $entity->entityType = 'TripalEntity';
  503. $entity->entityInfo = [];
  504. $entity->id = $entity_id;
  505. $entity->type = 'TripalEntity';
  506. $entity->bundle = $bundle_accession;
  507. $entity->site_id = $site_id;
  508. $member = _tripal_update_remote_entity_field($member, $context, 1);
  509. foreach ($member as $field_id => $value) {
  510. $field = tripal_get_remote_field_info($site_id, $bundle_accession, $field_id);
  511. $instance = tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_id);
  512. $field_name = $field['field_name'];
  513. $entity->{$field_name}['und'][0]['value'] = $value;
  514. }
  515. $entities[$entity_id] = $entity;
  516. }
  517. return $entities;
  518. }
  519. /**
  520. * Queries a remote site for an entity.
  521. *
  522. * This function returns a "fake" entity containing values for all fields
  523. * specified.
  524. *
  525. * @param $remote_entity_id
  526. * A remote entity ID.
  527. * @param $site_id
  528. * The numeric site ID for the remote Tripal site.
  529. * @param $bundle_accession
  530. * The controlled vocabulary term accession for the content type
  531. * on the remote Tripal site.
  532. * @param $field_ids
  533. * The controlled vocabulary term accessions for the fields available
  534. * on the remote content type. Any remote fields that matches these IDs will
  535. * be added to the entity returned.
  536. * @return
  537. * A fake entity object.
  538. *
  539. * @ingroup tripal_ws_api
  540. */
  541. function tripal_load_remote_entity($remote_entity_id, $site_id, $bundle_accession, $field_ids) {
  542. // Get the site documentation (loads from cache if already retrieved).
  543. $site_doc = tripal_get_remote_API_doc($site_id);
  544. // Get the remote entity and create the fake entity.
  545. $remote_entity = tripal_get_remote_content($site_id, $bundle_accession . '/' . $remote_entity_id);
  546. // If we encountered an error just return;
  547. if (array_key_exists('error', $results)) {
  548. return FALSE;
  549. }
  550. // Start building the fake entity.
  551. $entity = new stdClass();
  552. $entity->entityType = 'TripalEntity';
  553. $entity->entityInfo = [];
  554. $entity->id = $remote_entity_id;
  555. $entity->type = 'TripalEntity';
  556. $entity->bundle = $bundle_accession;
  557. $entity->site_id = $site_id;
  558. // Get the context JSON for this remote entity, we'll use it to map
  559. $context_url = $remote_entity['@context'];
  560. $context = tripal_get_remote_content_context($site_id, $context_url, $bundle_accession);
  561. if (!$context) {
  562. return $entity;
  563. }
  564. // Iterate through the fields and the those values to the entity.
  565. foreach ($field_ids as $field_id) {
  566. $field = tripal_get_remote_field_info($site_id, $bundle_accession, $field_id);
  567. $instance = tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_id);
  568. $field_name = $field['field_name'];
  569. $field_key = '';
  570. foreach ($context as $k => $v) {
  571. if (!is_array($v) and $v == $field_id) {
  572. $field_key = $k;
  573. }
  574. }
  575. // If the field is not in this remote bundle then add an empty value.
  576. if (!$field_key) {
  577. $entity->{$field_name}['und'][0]['value'] = '';
  578. continue;
  579. }
  580. if (!array_key_exists($field_key, $remote_entity)) {
  581. $entity->{$field_name}['und'][0]['value'] = '';
  582. continue;
  583. }
  584. // If the key is for a field that is not "auto attached' then we need
  585. // to get that field through a separate call.
  586. $attached = TRUE;
  587. if (array_key_exists($field_id, $context) and is_array($context[$field_id]) and
  588. array_key_exists('@type', $context[$field_id]) and $context[$field_id]['@type'] == '@id'){
  589. $attached = FALSE;
  590. }
  591. // Set the value for this field.
  592. $value = '';
  593. if (is_array($remote_entity[$field_key])) {
  594. $value = _tripal_update_remote_entity_field($remote_entity[$field_key], $context, 1);
  595. }
  596. else {
  597. $value = $remote_entity[$field_key];
  598. }
  599. // If the field is not attached then we have to query another level.
  600. if (!$attached) {
  601. $field_data = drupal_http_request($value);
  602. if (!$field_data) {
  603. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  604. 'There was a poblem retrieving the unattached field, "!field:", for the remote entity: !entity_id.',
  605. array('!field' => $field_id, '!entity_id' => $remote_entity_id));
  606. $value = '';
  607. }
  608. $field_data = drupal_json_decode($field_data->data);
  609. // Get the context for this field so we can map the keys to the
  610. // controlled vocabulary accessions. If it fails then skip this field.
  611. $field_context_url = $field_data['@context'];
  612. $field_context = tripal_get_remote_content_context($site_id, $field_context_url, $bundle_accession, $field_id);
  613. if (!$field_context) {
  614. continue;
  615. }
  616. $value = _tripal_update_remote_entity_field($field_data, $field_context);
  617. }
  618. $entity->{$field_name}['und'][0]['value'] = $value;
  619. }
  620. return $entity;
  621. }
  622. /**
  623. * A helper function for the tripal_get_remote_entity() function.
  624. *
  625. * This function converts the field's key elements to their
  626. * vocabulary term accessions.
  627. *
  628. * @param $field_data
  629. * The field array as returned by web services.
  630. * @param $context
  631. * The web service JSON-LD context for the bundle to which the field belongs.
  632. *
  633. * @ingroup tripal_ws_api
  634. */
  635. function _tripal_update_remote_entity_field($field_data, $context, $depth = 0) {
  636. // Check if this is an array.
  637. if ($field_data['@type'] == 'Collection') {
  638. $members = array();
  639. foreach ($field_data['member'] as $member) {
  640. $next_depth = $depth + 1;
  641. $members[] = _tripal_update_remote_entity_field($member, $context, $next_depth);
  642. }
  643. // If we only have one item then just return it as a single item.
  644. // TODO: we may need to check cardinality of the field and be more
  645. // strict about how we return the value.
  646. if ($field_data['totalItems'] == 1){
  647. return $members[0];
  648. }
  649. else {
  650. return $members;
  651. }
  652. }
  653. $value = array();
  654. foreach ($field_data as $k => $v) {
  655. // Skip the JSON-LD keys.
  656. if ($k == '@id' or $k == '@type' or $k == '@context') {
  657. continue;
  658. }
  659. // Find the term accession for this element, and if the key's value is an
  660. // array then recurse.
  661. $accession = $context[$k];
  662. if (is_array($v)) {
  663. $next_depth = $depth + 1;
  664. $subvalue = _tripal_update_remote_entity_field($v, $context, $next_depth);
  665. $value[$accession] = $subvalue;
  666. }
  667. else {
  668. $value[$accession] = $v;
  669. }
  670. }
  671. return $value;
  672. }
  673. /**
  674. * Behaves similar to the field_info_field() function but for remote fields.
  675. *
  676. * Returns a "fake" field info array for fields attached to content types
  677. * on remote Tripal sites.
  678. *
  679. * @param $site_id
  680. * The numeric site ID for the remote Tripal site.
  681. * @param $bundle_accession
  682. * The controlled vocabulary term accession for the content type
  683. * on the remote Tripal site.
  684. * @param $field_accession
  685. * The controlled vocabulary term accession for the property (i.e. field) of
  686. * the Class (i.e. content type).
  687. * @return
  688. * An array similar to that returned by the field_info_field function
  689. * of Drupal for local fields.
  690. *
  691. * @ingroup tripal_ws_api
  692. */
  693. function tripal_get_remote_field_info($site_id, $bundle_accession, $field_accession){
  694. // Get the site documentation (loads from cache if already retrieved).
  695. $site_doc = tripal_get_remote_API_doc($site_id);
  696. // Get the property from the document for this field.
  697. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  698. // Now create the fake field and instance.
  699. list($vocab, $accession) = explode(':', $field_accession);
  700. $field_name = 'tripal_remote_site_' . $site_id . '_' . $field_accession;
  701. $field = array(
  702. 'field_name' => $field_name,
  703. 'type' => $field_name,
  704. 'storage' => array(
  705. 'type' => 'tripal_remote_site'
  706. ),
  707. );
  708. return $field;
  709. }
  710. /**
  711. * Behaves similar to the field_info_instance() function but for remote fields.
  712. *
  713. * Returns a "fake" instance info array for fields attached to content types
  714. * on remote Tripal sites.
  715. *
  716. * @param $site_id
  717. * The numeric site ID for the remote Tripal site.
  718. * @param $bundle_accession
  719. * The controlled vocabulary term accession for the content type
  720. * on the remote Tripal site.
  721. * @param $field_accession
  722. * The controlled vocabulary term accession for the property (i.e. field) of
  723. * the Class (i.e. content type).
  724. * @return
  725. * An array similar to that returned by the field_info_instance function
  726. * of Drupal for local fields.
  727. *
  728. * @ingroup tripal_ws_api
  729. */
  730. function tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_accession){
  731. // Get the site documentation (loads from cache if already retrieved).
  732. $site_doc = tripal_get_remote_API_doc($site_id);
  733. // Get the property from the document for this field.
  734. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  735. list($vocab, $accession) = explode(':', $field_accession);
  736. $field_name = 'tripal_remote_site_' . $site_id . '_' . $field_accession;
  737. list($vocab, $accession) = explode(':', $field_accession);
  738. $instance = array(
  739. 'label' => $property['hydra:title'],
  740. 'description' => $property['hydra:description'],
  741. 'formatters' => $property['tripal_formatters'],
  742. 'settings' => array(
  743. 'term_vocabulary' => $vocab,
  744. 'term_accession' => $accession
  745. ),
  746. 'field_name' => $field_name,
  747. 'entity_type' => 'TripalEntity',
  748. 'bundle_name' => $bundle_accession,
  749. );
  750. return $instance;
  751. }
  752. /**
  753. * Retreive the content type information from a remote Tripal site.
  754. *
  755. * The array returned is equivalent to the Hydra Vocabulary "supportedClass"
  756. * stanza.
  757. *
  758. * @param $site_id
  759. * The numeric site ID for the remote Tripal site.
  760. * @param $bundle_accession
  761. * The controlled vocabulary term accession for the content type
  762. * on the remote Tripal site.
  763. * @return
  764. * A PHP array corresponding to the Hydra Class stanza (i.e. a content type).
  765. * Returns NULL if the class ID cannot be found.
  766. *
  767. * @ingroup tripal_ws_api
  768. */
  769. function tripal_get_remote_content_doc($site_id, $bundle_accession){
  770. // Get the site documentation (loads from cache if already retrieved).
  771. $site_doc = tripal_get_remote_API_doc($site_id);
  772. // Get the class that matches this bundle.
  773. $classes = $site_doc['supportedClass'];
  774. $class = NULL;
  775. foreach ($classes as $item) {
  776. if ($item['@id'] == $bundle_accession) {
  777. return $item;
  778. }
  779. }
  780. return NULL;
  781. }
  782. /**
  783. * Retrieves the field information for a content type from a remote Tripal site.
  784. *
  785. * The array returned is equivalent to the Hydra Vocabulary "supportedProperty"
  786. * stanza that belongs to a Hydra Class (content type).
  787. *
  788. * @param $site_id
  789. * The numeric site ID for the remote Tripal site.
  790. * @param $bundle_accession
  791. * The controlled vocabulary term accession for the content type
  792. * on the remote Tripal site.
  793. * @param $field_accession
  794. * The controlled vocabulary term accession for the property (i.e. field) of
  795. * the Class (i.e. content type).
  796. * @return
  797. * A PHP array corresponding to the Hydra property stanza (field) that
  798. * belongs to the given Class (i.e. a content type). Retruns NULL if the
  799. * property cannot be found.
  800. *
  801. * @ingroup tripal_ws_api
  802. */
  803. function tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession){
  804. // Get the site documentation (loads from cache if already retrieved).
  805. $site_doc = tripal_get_remote_API_doc($site_id);
  806. $class = tripal_get_remote_content_doc($site_id, $bundle_accession);
  807. $properties = $class['supportedProperty'];
  808. foreach ($properties as $item) {
  809. if ($item['property'] == $field_accession) {
  810. return $item;
  811. }
  812. }
  813. return NULL;
  814. }
  815. /**
  816. * Retrieves the list of download formatters for a remote field.
  817. *
  818. * All Tripal fields support the abilty for inclusion in files that can
  819. * downloaded. This function is used to identify what formatters these
  820. * fields are appropriate for. If those download formatter classes exist
  821. * on this site then the field can be used with that formatter.
  822. *
  823. * @param $site_id
  824. * The numeric site ID for the remote Tripal site.
  825. * @param $bundle_accession
  826. * The controlled vocabulary term accession for the content type
  827. * on the remote Tripal site.
  828. * @param $field_accession
  829. * The controlled vocabulary term accession for the property (i.e. field) of
  830. * the Class (i.e. content type).
  831. * @return
  832. * An array of field downloader class names that are compoatible with the
  833. * field and which exist on this site.
  834. *
  835. * @ingroup tripal_ws_api
  836. */
  837. function tripal_get_remote_field_formatters($site_id, $bundle_accession, $field_accession) {
  838. $flist = array();
  839. // Get the site documentation (loads from cache if already retrieved).
  840. $site_doc = tripal_get_remote_API_doc($site_id);
  841. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  842. if (!$property) {
  843. return $flist;
  844. }
  845. $formatters = $property['tripal_formatters'];
  846. foreach($formatters as $formatter) {
  847. if (tripal_load_include_downloader_class($formatter)) {
  848. $flist[$formatter] = $formatter::$full_label;
  849. }
  850. }
  851. return $flist;
  852. }