tripal_ws.api.inc 29 KB

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