tripal_ws.api.inc 29 KB

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