tripal_ws.api.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. 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', array('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', array('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(array(
  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-servcies/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-servcies/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. array('!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 servcies 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. array('!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. * @return
  294. * The JSON-LD context mapping array, or FALSE if the context could not
  295. * be retrieved.
  296. *
  297. * @ingroup tripal_ws_api
  298. */
  299. function tripal_get_remote_context($context_url, $cache_id) {
  300. if (!$context_url) {
  301. throw new Exception('PLease provide a context_url for the tripal_get_remote_context function.');
  302. }
  303. if (!$cache_id) {
  304. throw new Exception('PLease provide unique $cache_id for the tripal_get_remote_context function.');
  305. }
  306. if ($cache = cache_get($cache_id)) {
  307. return $cache->data;
  308. }
  309. $context = drupal_http_request($context_url);
  310. if (!$context) {
  311. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  312. 'There was a poblem retrieving the context from the remote site: !context_url.',
  313. array('!context_url' => $context_url));
  314. return FALSE;
  315. }
  316. $context = drupal_json_decode($context->data);
  317. $context = $context['@context'];
  318. cache_set($cache_id, $context);
  319. return $context;
  320. }
  321. /**
  322. * Retrieves the JSON-LD context for a bundle or field on a remote Tripal site.
  323. *
  324. * The $site_id, $bundle_accession and $field_accession variables are not
  325. * needed to retrieve the context, but are used for caching the context to
  326. * make subsequent calls execute faster. This function is meant to be used
  327. * only for the 'content' service provided by Tripal.
  328. *
  329. * @param $site_id
  330. * The numeric site ID for the remote Tripal site.
  331. * @param $context_url
  332. * The Full URL for the context file on the remote Tripal site. This URL
  333. * can be found in the '@context' key of any response from a remote Tripal
  334. * web services call.
  335. * @param $bundle_accession
  336. * The controlled vocabulary term accession for the content type
  337. * on the remote Tripal site.
  338. * @param $field_accession
  339. * The controlled vocabulary term accession for the property (i.e. field) of
  340. * the Class (i.e. content type).
  341. * @return
  342. * The JSON-LD context mapping array.
  343. *
  344. * @ingroup tripal_ws_api
  345. */
  346. function tripal_get_remote_content_context($site_id, $context_url, $bundle_accession, $field_accession = '') {
  347. $cache_id = substr('trp_ws_context_' . $site_id . '-' . $bundle_accession . '-' . $field_accession, 0, 254);
  348. $context = tripal_get_remote_context($context_url, $cache_id);
  349. return $context;
  350. }
  351. /**
  352. * Clears the cached remote site documentation and context.
  353. *
  354. * When querying a remote website, the site's API documenation and page context
  355. * is cached to make re-use of that information easier in the future. This
  356. * function can be used to clear those caches.
  357. *
  358. * @param $site_id
  359. * The numeric site ID for the remote Tripal site.
  360. *
  361. * @ingroup tripal_ws_api
  362. */
  363. function tripal_clear_remote_cache($site_id) {
  364. if (!$site_id) {
  365. throw new Exception('Please provide a numeric site ID for the tripal_clear_remote_cache function.');
  366. }
  367. cache_clear_all('trp_ws_context_' . $site_id , 'cache', TRUE);
  368. cache_clear_all('trp_ws_doc_' . $site_id , 'cache', TRUE);
  369. }
  370. /**
  371. * Retrieves the API documentation for a remote Tripal web service.
  372. *
  373. * @param $site_id
  374. * The numeric site ID for the remote Tripal site.
  375. * @return
  376. * The vocabulary of a remote Tripal web service, or FALSE if an error
  377. * occured.
  378. *
  379. * @ingroup tripal_ws_api
  380. */
  381. function tripal_get_remote_API_doc($site_id) {
  382. $site_doc = '';
  383. if (!$site_id) {
  384. throw new Exception('Please provide a numeric site ID for the tripal_get_remote_API_doc function.');
  385. }
  386. $cache_name = 'trp_ws_doc_' . $site_id;
  387. if ($cache = cache_get($cache_name)) {
  388. return $cache->data;
  389. }
  390. // Get the site url from the tripal_sites table.
  391. $remote_site = db_select('tripal_sites', 'ts')
  392. ->fields('ts')
  393. ->condition('ts.id', $site_id)
  394. ->execute()
  395. ->fetchObject();
  396. if (!$remote_site) {
  397. throw new Exception(t('Cannot find a remote site with id: "!id"', array('!id' => $site_id)));
  398. }
  399. // Build the URL to the remote web services.
  400. $ws_version = $remote_site->version;
  401. $ws_url = $remote_site->url;
  402. $ws_url = trim($ws_url, '/');
  403. $ws_url .= '/web-services/doc/' . $ws_version;
  404. // Build and make the request.
  405. $options = [];
  406. $data = drupal_http_request($ws_url, $options);
  407. if (!$data) {
  408. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  409. t('Could not connect to the remote web service.'));
  410. return FALSE;
  411. }
  412. // If the data object has an error then this is some sort of
  413. // connection error (not a Tripal web servcies error).
  414. if (property_exists($data, 'error')) {
  415. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  416. 'Remote web services document reports the following error: !error. Using URL: !url',
  417. array('!error' => $error, '!url' => $ws_url));
  418. return FALSE;
  419. }
  420. // We got a response, so convert it to a PHP array.
  421. $site_doc = drupal_json_decode($data->data);
  422. // Check if there was a Tripal Web Services error.
  423. if (array_key_exists('error', $data)) {
  424. $error = '</pre>' . print_r($data['error'], TRUE) . '</pre>';
  425. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  426. 'Tripal Remote web services document reports the following error: !error. Using URL: !url',
  427. array('!error' => $error, '!url' => $ws_url));
  428. return FALSE;
  429. }
  430. cache_set($cache_name, $site_doc);
  431. return $site_doc;
  432. }
  433. /**
  434. * Queries a remote site for an array of bulk entity ids.
  435. *
  436. * This function returns an array of "fake" entities containing values
  437. * for fields specified.
  438. *
  439. * @param $remote_entity_ids
  440. * Array of the remote ids.
  441. * @param $site_id
  442. * The numeric site ID for the remote Tripal site.
  443. * @param $bundle_accession
  444. * The controlled vocabulary term accession for the content type
  445. * on the remote Tripal site.
  446. * @param $field_ids
  447. * The controlled vocabulary term accessions for the fields available
  448. * on the remote content type. Any remote fields that matches these IDs will
  449. * be added to the entity returned.
  450. * @return
  451. * An array of fake entity objects where the key is the entity_id and
  452. * the value is the object.
  453. *
  454. * @ingroup tripal_ws_api
  455. */
  456. function tripal_load_remote_entities($remote_entity_ids, $site_id, $bundle_accession, $field_ids) {
  457. if (!$remote_entity_ids) {
  458. throw new Exception('Please provide the list of remote entity ids for the tripal_load_remote_entities function.');
  459. }
  460. if (!is_array($remote_entity_ids)) {
  461. throw new Exception('Please provide an array for the remote entity ids for the tripal_load_remote_entities function.');
  462. }
  463. if (!$site_id) {
  464. throw new Exception('Please provide a numeric site ID for the tripal_load_remote_entities function.');
  465. }
  466. if (!$bundle_accession) {
  467. throw new Exception('Please provide the bundle accession for the tripal_load_remote_entities function.');
  468. }
  469. if (!$field_ids) {
  470. throw new Exception('Please provide the list of field IDs for the tripal_load_remote_entities function.');
  471. }
  472. if (!is_array($field_ids)) {
  473. throw new Exception('Please provide an array for the field IDs for the tripal_load_remote_entities function.');
  474. }
  475. // Get the site documentation (loads from cache if already retrieved).
  476. $site_doc = tripal_get_remote_API_doc($site_id);
  477. // Generate an array for the query and then execute it.
  478. $query = 'page=1&limit=' . count($remote_entity_ids) .
  479. '&ids=' . urlencode(implode(",", $remote_entity_ids)) .
  480. '&fields=' . urlencode(implode(",", $field_ids));
  481. $results = tripal_get_remote_content($site_id, $bundle_accession, $query);
  482. // If we encountered an error just return;
  483. if (array_key_exists('error', $results)) {
  484. return FALSE;
  485. }
  486. // Get the context JSON for this remote entity, we'll use it to map
  487. $context_url = $results['@context'];
  488. $context = tripal_get_remote_content_context($site_id, $context_url, $bundle_accession);
  489. if (!$context) {
  490. return $entity;
  491. }
  492. $total_items = $results['totalItems'];
  493. $members = $results['member'];
  494. $entities = array();
  495. foreach($members as $member) {
  496. // Start building the fake entity.
  497. $entity_id = preg_replace('/^.*?(\d+)$/', '$1', $member['@id']);
  498. $entity = new stdClass();
  499. $entity->entityType = 'TripalEntity';
  500. $entity->entityInfo = [];
  501. $entity->id = $entity_id;
  502. $entity->type = 'TripalEntity';
  503. $entity->bundle = $bundle_accession;
  504. $entity->site_id = $site_id;
  505. $member = _tripal_update_remote_entity_field($member, $context, 1);
  506. foreach ($member as $field_id => $value) {
  507. $field = tripal_get_remote_field_info($site_id, $bundle_accession, $field_id);
  508. $instance = tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_id);
  509. $field_name = $field['field_name'];
  510. $entity->{$field_name}['und'][0]['value'] = $value;
  511. }
  512. $entities[$entity_id] = $entity;
  513. }
  514. return $entities;
  515. }
  516. /**
  517. * Queries a remote site for an entity.
  518. *
  519. * This function returns a "fake" entity containing values for all fields
  520. * specified.
  521. *
  522. * @param $remote_entity_id
  523. * A remote entity ID.
  524. * @param $site_id
  525. * The numeric site ID for the remote Tripal site.
  526. * @param $bundle_accession
  527. * The controlled vocabulary term accession for the content type
  528. * on the remote Tripal site.
  529. * @param $field_ids
  530. * The controlled vocabulary term accessions for the fields available
  531. * on the remote content type. Any remote fields that matches these IDs will
  532. * be added to the entity returned.
  533. * @return
  534. * A fake entity object.
  535. *
  536. * @ingroup tripal_ws_api
  537. */
  538. function tripal_load_remote_entity($remote_entity_id, $site_id, $bundle_accession, $field_ids) {
  539. // Get the site documentation (loads from cache if already retrieved).
  540. $site_doc = tripal_get_remote_API_doc($site_id);
  541. // Get the remote entity and create the fake entity.
  542. $remote_entity = tripal_get_remote_content($site_id, $bundle_accession . '/' . $remote_entity_id);
  543. // If we encountered an error just return;
  544. if (array_key_exists('error', $results)) {
  545. return FALSE;
  546. }
  547. // Start building the fake entity.
  548. $entity = new stdClass();
  549. $entity->entityType = 'TripalEntity';
  550. $entity->entityInfo = [];
  551. $entity->id = $remote_entity_id;
  552. $entity->type = 'TripalEntity';
  553. $entity->bundle = $bundle_accession;
  554. $entity->site_id = $site_id;
  555. // Get the context JSON for this remote entity, we'll use it to map
  556. $context_url = $remote_entity['@context'];
  557. $context = tripal_get_remote_content_context($site_id, $context_url, $bundle_accession);
  558. if (!$context) {
  559. return $entity;
  560. }
  561. // Iterate through the fields and the those values to the entity.
  562. foreach ($field_ids as $field_id) {
  563. $field = tripal_get_remote_field_info($site_id, $bundle_accession, $field_id);
  564. $instance = tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_id);
  565. $field_name = $field['field_name'];
  566. $field_key = '';
  567. foreach ($context as $k => $v) {
  568. if (!is_array($v) and $v == $field_id) {
  569. $field_key = $k;
  570. }
  571. }
  572. // If the field is not in this remote bundle then add an empty value.
  573. if (!$field_key) {
  574. $entity->{$field_name}['und'][0]['value'] = '';
  575. continue;
  576. }
  577. if (!array_key_exists($field_key, $remote_entity)) {
  578. $entity->{$field_name}['und'][0]['value'] = '';
  579. continue;
  580. }
  581. // If the key is for a field that is not "auto attached' then we need
  582. // to get that field through a separate call.
  583. $attached = TRUE;
  584. if (array_key_exists($field_id, $context) and is_array($context[$field_id]) and
  585. array_key_exists('@type', $context[$field_id]) and $context[$field_id]['@type'] == '@id'){
  586. $attached = FALSE;
  587. }
  588. // Set the value for this field.
  589. $value = '';
  590. if (is_array($remote_entity[$field_key])) {
  591. $value = _tripal_update_remote_entity_field($remote_entity[$field_key], $context, 1);
  592. }
  593. else {
  594. $value = $remote_entity[$field_key];
  595. }
  596. // If the field is not attached then we have to query another level.
  597. if (!$attached) {
  598. $field_data = drupal_http_request($value);
  599. if (!$field_data) {
  600. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  601. 'There was a poblem retrieving the unattached field, "!field:", for the remote entity: !entity_id.',
  602. array('!field' => $field_id, '!entity_id' => $remote_entity_id));
  603. $value = '';
  604. }
  605. $field_data = drupal_json_decode($field_data->data);
  606. // Get the context for this field so we can map the keys to the
  607. // controlled vocabulary accessions. If it fails then skip this field.
  608. $field_context_url = $field_data['@context'];
  609. $field_context = tripal_get_remote_content_context($site_id, $field_context_url, $bundle_accession, $field_id);
  610. if (!$field_context) {
  611. continue;
  612. }
  613. $value = _tripal_update_remote_entity_field($field_data, $field_context);
  614. }
  615. $entity->{$field_name}['und'][0]['value'] = $value;
  616. }
  617. return $entity;
  618. }
  619. /**
  620. * A helper function for the tripal_get_remote_entity() function.
  621. *
  622. * This function converts the field's key elements to their
  623. * vocabulary term accessions.
  624. *
  625. * @param $field_data
  626. * The field array as returned by web services.
  627. * @param $context
  628. * The web service JSON-LD context for the bundle to which the field belongs.
  629. *
  630. * @ingroup tripal_ws_api
  631. */
  632. function _tripal_update_remote_entity_field($field_data, $context, $depth = 0) {
  633. // Check if this is an array.
  634. if ($field_data['@type'] == 'Collection') {
  635. $members = array();
  636. foreach ($field_data['member'] as $member) {
  637. $next_depth = $depth + 1;
  638. $members[] = _tripal_update_remote_entity_field($member, $context, $next_depth);
  639. }
  640. // If we only have one item then just return it as a single item.
  641. // TODO: we may need to check cardinality of the field and be more
  642. // strict about how we return the value.
  643. if ($field_data['totalItems'] == 1){
  644. return $members[0];
  645. }
  646. else {
  647. return $members;
  648. }
  649. }
  650. $value = array();
  651. foreach ($field_data as $k => $v) {
  652. // Skip the JSON-LD keys.
  653. if ($k == '@id' or $k == '@type' or $k == '@context') {
  654. continue;
  655. }
  656. // Find the term accession for this element, and if the key's value is an
  657. // array then recurse.
  658. $accession = $context[$k];
  659. if (is_array($v)) {
  660. $next_depth = $depth + 1;
  661. $subvalue = _tripal_update_remote_entity_field($v, $context, $next_depth);
  662. $value[$accession] = $subvalue;
  663. }
  664. else {
  665. $value[$accession] = $v;
  666. }
  667. }
  668. return $value;
  669. }
  670. /**
  671. * Behaves similar to the field_info_field() function but for remote fields.
  672. *
  673. * Returns a "fake" field info array for fields attached to content types
  674. * on remote Tripal sites.
  675. *
  676. * @param $site_id
  677. * The numeric site ID for the remote Tripal site.
  678. * @param $bundle_accession
  679. * The controlled vocabulary term accession for the content type
  680. * on the remote Tripal site.
  681. * @param $field_accession
  682. * The controlled vocabulary term accession for the property (i.e. field) of
  683. * the Class (i.e. content type).
  684. * @return
  685. * An array similar to that returned by the field_info_field function
  686. * of Drupal for local fields.
  687. *
  688. * @ingroup tripal_ws_api
  689. */
  690. function tripal_get_remote_field_info($site_id, $bundle_accession, $field_accession){
  691. // Get the site documentation (loads from cache if already retrieved).
  692. $site_doc = tripal_get_remote_API_doc($site_id);
  693. // Get the property from the document for this field.
  694. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  695. // Now create the fake field and instance.
  696. list($vocab, $accession) = explode(':', $field_accession);
  697. $field_name = 'tripal_remote_site_' . $site_id . '_' . $field_accession;
  698. $field = array(
  699. 'field_name' => $field_name,
  700. 'type' => $field_name,
  701. 'storage' => array(
  702. 'type' => 'tripal_remote_site'
  703. ),
  704. );
  705. return $field;
  706. }
  707. /**
  708. * Behaves similar to the field_info_instance() function but for remote fields.
  709. *
  710. * Returns a "fake" instance info array for fields attached to content types
  711. * on remote Tripal sites.
  712. *
  713. * @param $site_id
  714. * The numeric site ID for the remote Tripal site.
  715. * @param $bundle_accession
  716. * The controlled vocabulary term accession for the content type
  717. * on the remote Tripal site.
  718. * @param $field_accession
  719. * The controlled vocabulary term accession for the property (i.e. field) of
  720. * the Class (i.e. content type).
  721. * @return
  722. * An array similar to that returned by the field_info_instance function
  723. * of Drupal for local fields.
  724. *
  725. * @ingroup tripal_ws_api
  726. */
  727. function tripal_get_remote_field_instance_info($site_id, $bundle_accession, $field_accession){
  728. // Get the site documentation (loads from cache if already retrieved).
  729. $site_doc = tripal_get_remote_API_doc($site_id);
  730. // Get the property from the document for this field.
  731. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  732. list($vocab, $accession) = explode(':', $field_accession);
  733. $field_name = 'tripal_remote_site_' . $site_id . '_' . $field_accession;
  734. list($vocab, $accession) = explode(':', $field_accession);
  735. $instance = array(
  736. 'label' => $property['hydra:title'],
  737. 'description' => $property['hydra:description'],
  738. 'formatters' => $property['tripal_formatters'],
  739. 'settings' => array(
  740. 'term_vocabulary' => $vocab,
  741. 'term_accession' => $accession
  742. ),
  743. 'field_name' => $field_name,
  744. 'entity_type' => 'TripalEntity',
  745. 'bundle_name' => $bundle_accession,
  746. );
  747. return $instance;
  748. }
  749. /**
  750. * Retreive the content type information from a remote Tripal site.
  751. *
  752. * The array returned is equivalent to the Hydra Vocabulary "supportedClass"
  753. * stanza.
  754. *
  755. * @param $site_id
  756. * The numeric site ID for the remote Tripal site.
  757. * @param $bundle_accession
  758. * The controlled vocabulary term accession for the content type
  759. * on the remote Tripal site.
  760. * @return
  761. * A PHP array corresponding to the Hydra Class stanza (i.e. a content type).
  762. * Returns NULL if the class ID cannot be found.
  763. *
  764. * @ingroup tripal_ws_api
  765. */
  766. function tripal_get_remote_content_doc($site_id, $bundle_accession){
  767. // Get the site documentation (loads from cache if already retrieved).
  768. $site_doc = tripal_get_remote_API_doc($site_id);
  769. // Get the class that matches this bundle.
  770. $classes = $site_doc['supportedClass'];
  771. $class = NULL;
  772. foreach ($classes as $item) {
  773. if ($item['@id'] == $bundle_accession) {
  774. return $item;
  775. }
  776. }
  777. return NULL;
  778. }
  779. /**
  780. * Retrieves the field information for a content type from a remote Tripal site.
  781. *
  782. * The array returned is equivalent to the Hydra Vocabulary "supportedProperty"
  783. * stanza that belongs to a Hydra Class (content type).
  784. *
  785. * @param $site_id
  786. * The numeric site ID for the remote Tripal site.
  787. * @param $bundle_accession
  788. * The controlled vocabulary term accession for the content type
  789. * on the remote Tripal site.
  790. * @param $field_accession
  791. * The controlled vocabulary term accession for the property (i.e. field) of
  792. * the Class (i.e. content type).
  793. * @return
  794. * A PHP array corresponding to the Hydra property stanza (field) that
  795. * belongs to the given Class (i.e. a content type). Retruns NULL if the
  796. * property cannot be found.
  797. *
  798. * @ingroup tripal_ws_api
  799. */
  800. function tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession){
  801. // Get the site documentation (loads from cache if already retrieved).
  802. $site_doc = tripal_get_remote_API_doc($site_id);
  803. $class = tripal_get_remote_content_doc($site_id, $bundle_accession);
  804. $properties = $class['supportedProperty'];
  805. foreach ($properties as $item) {
  806. if ($item['property'] == $field_accession) {
  807. return $item;
  808. }
  809. }
  810. return NULL;
  811. }
  812. /**
  813. * Retrieves the list of download formatters for a remote field.
  814. *
  815. * All Tripal fields support the abilty for inclusion in files that can
  816. * downloaded. This function is used to identify what formatters these
  817. * fields are appropriate for. If those download formatter classes exist
  818. * on this site then the field can be used with that formatter.
  819. *
  820. * @param $site_id
  821. * The numeric site ID for the remote Tripal site.
  822. * @param $bundle_accession
  823. * The controlled vocabulary term accession for the content type
  824. * on the remote Tripal site.
  825. * @param $field_accession
  826. * The controlled vocabulary term accession for the property (i.e. field) of
  827. * the Class (i.e. content type).
  828. * @return
  829. * An array of field downloader class names that are compoatible with the
  830. * field and which exist on this site.
  831. *
  832. * @ingroup tripal_ws_api
  833. */
  834. function tripal_get_remote_field_formatters($site_id, $bundle_accession, $field_accession) {
  835. $flist = array();
  836. // Get the site documentation (loads from cache if already retrieved).
  837. $site_doc = tripal_get_remote_API_doc($site_id);
  838. $property = tripal_get_remote_field_doc($site_id, $bundle_accession, $field_accession);
  839. if (!$property) {
  840. return $flist;
  841. }
  842. $formatters = $property['tripal_formatters'];
  843. foreach($formatters as $formatter) {
  844. if (tripal_load_include_downloader_class($formatter)) {
  845. $flist[$formatter] = $formatter::$full_label;
  846. }
  847. }
  848. return $flist;
  849. }