tripal_ws.api.inc 29 KB

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