tripal_ws.api.inc 28 KB

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