tripal_ws.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. /**
  3. * @file
  4. * The Tripal Web Service Module
  5. */
  6. /**
  7. * @defgroup tripal_ws Tripal Web Services Module
  8. * @ingroup tripal
  9. * @{
  10. * The Tripal Web Services module provides functionality for managing RESTful
  11. * web services based on the W3C Hydra standard.
  12. * @}
  13. */
  14. /**
  15. * @defgroup tripal_api Tripal API
  16. * @ingroup tripal
  17. * @{
  18. * Tripal provides an application programming interface (API) to support
  19. * customizations and creation of new extensions.
  20. * @
  21. */
  22. require_once "api/tripal_ws.api.inc";
  23. require_once "includes/tripal_ws.field_storage.inc";
  24. require_once "includes/tripal_ws.fields.inc";
  25. require_once "includes/TripalWebService.inc";
  26. require_once "includes/TripalWebServiceResource.inc";
  27. require_once "includes/TripalWebServiceCollection.inc";
  28. // Web Services Fields
  29. require_once "includes/TripalFields/WebServicesField.inc";
  30. require_once "includes/TripalFields/WebServicesFieldWidget.inc";
  31. require_once "includes/TripalFields/WebServicesFieldFormatter.inc";
  32. /**
  33. * Implements hook_init()
  34. */
  35. function tripal_ws_init() {
  36. global $base_url;
  37. $version = 'v0.1';
  38. $api_url = $base_url . '/ws/' . $version;
  39. $vocab = tripal_get_vocabulary_details('hydra');
  40. // Following the WC3 Hydra documentation, we want to add LINK to the header
  41. // of the site that indicates where the API documentation can be found.
  42. // This allows a hydra-enabled client to discover the API and use it.
  43. $attributes = array(
  44. 'rel' => $vocab['sw_url'] . 'apiDocumentation',
  45. 'href' => $api_url . '/ws-doc/',
  46. );
  47. drupal_add_html_head_link($attributes, $header = FALSE);
  48. }
  49. /**
  50. * Implements hook_menu().
  51. * Defines all menu items needed by Tripal Core
  52. *
  53. * @ingroup tripal_ws
  54. */
  55. function tripal_ws_menu() {
  56. // Web Services API callbacks.
  57. $items['web-services'] = array(
  58. 'title' => 'Tripal Web Services API',
  59. 'page callback' => 'tripal_ws_get_services',
  60. 'access arguments' => array('access content'),
  61. 'type' => MENU_CALLBACK,
  62. );
  63. $items['remote/%/%/%/%'] = array(
  64. 'page callback' => 'tripal_ws_load_remote_entity',
  65. 'page arguments' => array(1, 2, 3, 4),
  66. 'access arguments' => array('access content'),
  67. 'type' => MENU_CALLBACK,
  68. );
  69. // Tripal Web Services setting groups
  70. $items['admin/tripal/storage/ws'] = array(
  71. 'title' => 'Remote Tripal Sites',
  72. 'description' => t("Create mashups of content using data from this site and remote Tripal sites."),
  73. 'weight' => 20,
  74. 'page callback' => 'system_admin_menu_block_page',
  75. 'access arguments' => array('administer tripal'),
  76. 'file' => 'system.admin.inc',
  77. 'file path' => drupal_get_path('module', 'system'),
  78. );
  79. $items['admin/tripal/storage/ws/tripal_sites'] = array(
  80. 'title' => 'Configuration',
  81. 'description' => t('Provides information about other Tripal sites.
  82. This allows data exchange and communication betwen Tripal
  83. enabled sites through the web services.'),
  84. 'page callback' => 'drupal_get_form',
  85. 'page arguments' => array('tripal_ws_tripal_sites_form'),
  86. 'access arguments' => array('administer tripal'),
  87. 'type' => MENU_NORMAL_ITEM,
  88. 'weight' => 0,
  89. 'file' => 'includes/tripal_ws.admin.inc',
  90. 'file path' => drupal_get_path('module', 'tripal_ws'),
  91. );
  92. $items['admin/tripal/storage/ws/tripal_sites/edit'] = array(
  93. 'title' => 'Add Tripal Site',
  94. 'description' => 'Add a Tripal site',
  95. 'page callback' => 'drupal_get_form',
  96. 'page arguments' => array('tripal_ws_tripal_sites_edit_form'),
  97. 'access arguments' => array('administer tripal'),
  98. 'file' => 'includes/tripal_ws.admin.inc',
  99. 'file path' => drupal_get_path('module', 'tripal_ws'),
  100. 'type' => MENU_LOCAL_ACTION,
  101. 'weight' => 2
  102. );
  103. $items['admin/tripal/storage/ws/tripal_sites/remove/%'] = array(
  104. 'title' => 'Remove Tripal Site',
  105. 'description' => 'Remove a Tripal site',
  106. 'page callback' => 'drupal_get_form',
  107. 'page arguments' => array('tripal_ws_tripal_sites_remove_form', 6),
  108. 'access arguments' => array('administer tripal'),
  109. 'file' => 'includes/tripal_ws.admin.inc',
  110. 'file path' => drupal_get_path('module', 'tripal_ws'),
  111. 'type' => MENU_CALLBACK,
  112. 'weight' => 2
  113. );
  114. return $items;
  115. }
  116. /**
  117. * The callback function for all RESTful web services.
  118. *
  119. */
  120. function tripal_ws_get_services() {
  121. global $base_url;
  122. $service_path = $base_url . '/web-services';
  123. // This should go out as ld+json
  124. drupal_add_http_header('Content-Type', 'application/ld+json');
  125. // Add a link header for the vocabulary service so that clients
  126. // know where to find the docs.
  127. tripal_load_include_web_service_class('TripalVocabService_v0_1');
  128. $service = new TripalVocabService_v0_1($service_path);
  129. $vocab = tripal_get_vocabulary_details('hydra');
  130. drupal_add_http_header('Link', '<' . $service->getServicePath() . '>; rel="' . $vocab['sw_url'] . 'apiDocumentation"');
  131. drupal_add_http_header('Cache-Control', "no-cache");
  132. try {
  133. $ws_path = func_get_args();
  134. $args = $_GET;
  135. unset($args['q']);
  136. // The web services should never be cached.
  137. drupal_page_is_cacheable(FALSE);
  138. // The Tripal web services bath will be:
  139. // [base_path]/web-services/[service name]/v[major_version].[minor_version]
  140. $matches = array();
  141. $service = '';
  142. $major_version = '';
  143. $minor_version = '';
  144. $list_services = FALSE;
  145. // If there is no path then we should list all of the services available.
  146. if (empty($ws_path)) {
  147. tripal_ws_list_services();
  148. return;
  149. }
  150. // A service path will have the service name in $ws_path[0] and the
  151. // version in $ws_path[1]. If we check that the version is correctly
  152. // formatted then we can look for the service class and invoke it.
  153. else if (preg_match("/^v(\d+)\.(\d+)$/", $ws_path[1], $matches)) {
  154. $service_type = $ws_path[0];
  155. $major_version = $matches[1];
  156. $minor_version = $matches[2];
  157. $service_version = 'v' . $major_version . '.' . $minor_version;
  158. }
  159. // If the URL doesn't match then return not found.
  160. else {
  161. throw new Exception("Unsupported service URL. Web service URLs must be of the following format: ");
  162. }
  163. // Get the service that matches the service_name
  164. $service = NULL;
  165. $services = tripal_get_web_services();
  166. foreach ($services as $service_class) {
  167. tripal_load_include_web_service_class($service_class);
  168. if ($service_class::$type == $service_type) {
  169. $service = new $service_class($service_path);
  170. if ($service->getVersion() == $service_version) {
  171. break;
  172. }
  173. $service = NULL;
  174. }
  175. }
  176. // If a service was not provided then return an error.
  177. if (!$service) {
  178. throw new Exception('The service type, "' . $service_type . '", is not available');
  179. }
  180. // Adjust the path to remove the service type and the version.
  181. $adj_path = $ws_path;
  182. array_shift($adj_path);
  183. array_shift($adj_path);
  184. // Now call the service to handle the request.
  185. $service->setPath($adj_path);
  186. $service->setParams($args);
  187. $service->handleRequest();
  188. $response = $service->getResponse();
  189. print drupal_json_encode($response);
  190. }
  191. catch (Exception $e) {
  192. $service = new TripalWebService($service_path);
  193. $service->setError($e->getMessage());
  194. $response = $service->getResponse();
  195. print drupal_json_encode($response);
  196. }
  197. }
  198. /**
  199. * Generates the list of services as the "home page" for Tripal web services.
  200. */
  201. function tripal_ws_list_services() {
  202. global $base_url;
  203. $base_path = $base_url . '/web-services';
  204. // Create an instance of the TriaplWebService class and use it to build
  205. // the entry point for the web serivces.
  206. $service = new TripalWebService($base_path);
  207. // Get the list of web service classes.
  208. $services = tripal_get_web_services();
  209. // Create the parent resource which is a collection.
  210. $resource = new TripalWebServiceResource($base_path);
  211. // Add the vocabulary to the context.
  212. tripal_load_include_web_service_class('TripalVocabService_v0_1');
  213. $service = new TripalVocabService_v0_1($base_path);
  214. $resource->addContextItem('vocab', $service->getServicePath() . '#');
  215. $resource->addContextItem('EntryPoint', 'vocab:EntryPoint');
  216. $resource->setType('EntryPoint');
  217. // Now add the services as properties.
  218. foreach ($services as $service_class) {
  219. tripal_load_include_web_service_class($service_class);
  220. if ($service_class == 'TripalVocabService_v0_1') {
  221. continue;
  222. }
  223. $service = new $service_class($base_path);
  224. $resource->addContextItem($service_class::$type, array(
  225. '@id' => 'vocab:EntryPoint/' . $service_class::$type,
  226. '@type' => '@id',
  227. ));
  228. $resource->addProperty($service_class::$type, $service->getServicePath());
  229. }
  230. $service->setResource($resource);
  231. $response = $service->getResponse();
  232. print drupal_json_encode($response);
  233. }
  234. /**
  235. * The callback function for all RESTful web services.
  236. *
  237. */
  238. function tripal_ws_services() {
  239. $ws_path = func_get_args();
  240. $params = $_GET;
  241. unset($params['q']);
  242. // The web services should never be cached.
  243. drupal_page_is_cacheable(FALSE);
  244. // Using the provided version number, determine which web services
  245. // verion to call.
  246. $version = array_shift($ws_path);
  247. if ($version and preg_match('/v\d+\.\d+/', $version)) {
  248. $api_url = 'ws/' . $version;
  249. // Add the file with the appropriate web services.
  250. module_load_include('inc', 'tripal_ws', 'includes/tripal_ws.rest_' . $version);
  251. $version = preg_replace('/\./', '_', $version);
  252. $function = 'tripal_ws_services_' . $version;
  253. $response = array();
  254. if (function_exists($function)) {
  255. $response = $function($api_url, $ws_path, $params);
  256. }
  257. }
  258. else {
  259. // TODO: What do we do if no version is provided?
  260. }
  261. drupal_add_http_header('Content-Type', 'application/ld+json');
  262. print drupal_json_encode($response);
  263. }
  264. /**
  265. *
  266. * @param $site_id
  267. * @param $api_version
  268. * @param $ctype
  269. * @param $id
  270. *
  271. * @return
  272. */
  273. function tripal_ws_load_remote_entity($site_id, $api_version, $ctype, $id) {
  274. // Get the content type on this site
  275. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  276. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  277. $term = reset($term);
  278. $vocab = $term->vocab;
  279. $query = db_select('tripal_sites', 'ts');
  280. $query->fields('ts');
  281. $query->condition('id', $site_id);
  282. $site = $query->execute()->fetchObject();
  283. if (!$site) {
  284. return 'Could not find specified site.';
  285. }
  286. // Get the content from the web services of the remote site.
  287. $url = $site->url . "/ws/v0.1/content/" . $ctype . "/" . $id;
  288. $json = file_get_contents($url);
  289. $response = json_decode($json, TRUE);
  290. // Set the title for this page to match the title provided.
  291. drupal_set_title($response['label']);
  292. // Attribute this data to the proper source.
  293. $source_url = l($response['label'], $response['ItemPage'], array('attributes' => array('target' => '_blank')));
  294. $content = '<div><strong>Source:</strong> ' . $site->name . ': ' . $source_url . '</div>';
  295. // Fake an entity so we can display this content using the same
  296. // entity type on this site.
  297. $entity = new TripalEntity(array(), 'TripalEntity');
  298. $entity->id = 807;
  299. $entity->type = 'TripalEntity';
  300. $entity->bundle = $bundle->name;
  301. $entity->term_id = $term->id;
  302. $entity->title = $response['label'];
  303. $entity->uid = 1;
  304. $entity->status = 1;
  305. // Get the fields and create a list of those that are attached to the bundle.
  306. $fields = field_info_fields();
  307. $my_fields = array();
  308. foreach ($fields as $field) {
  309. if (isset($field['bundles']['TripalEntity'])) {
  310. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  311. if ($bundle_name == $bundle->name) {
  312. $my_fields[] = $field;
  313. }
  314. }
  315. }
  316. }
  317. // Add in the value for the 'content_type' field.
  318. $entity->content_type = array();
  319. $entity->content_type['und'][0]['value'] = $bundle->label;
  320. // For each field we know about that should be attached to our bundle,
  321. // see if we can find a corresponding entry in the results returned from
  322. // the web service call. If so, then add the field to our fake entity.
  323. foreach ($my_fields as $field) {
  324. // Get the semantic web term for this field.
  325. $field_name = $field['field_name'];
  326. $settings = $field['settings'];
  327. // If the field does not have a semantic web mapping, then skip it.
  328. if (!isset($settings['semantic_web'])) {
  329. continue;
  330. }
  331. // Convert the term into it's db and accession elements and look it up
  332. // for more details.
  333. list($vocabulary, $accession) = explode(':', $settings['semantic_web']);
  334. $term = tripal_get_term_details($vocabulary, $accession);
  335. // Convert the term to lowercase and remove spaces so we can compare
  336. // correctly.
  337. $term_name = strtolower(preg_replace('/ /', '_', $term['name']));
  338. // TODO: check for the term in the response makes the assumption
  339. // that the term is the same on both sides. This may not be true. The
  340. // acutal vocab and accession for both terms should be compared.
  341. if (isset($response[$term_name])) {
  342. // If this field is of type '@id' then this links out to another
  343. // URL where that information can be retrieved. We'll have to
  344. // handle that separately.
  345. if (isset($response['@context'][$term_name]['@type']) and
  346. $response['@context'][$term_name]['@type'] == '@id') {
  347. $subquery = json_decode(file_get_contents($response[$term_name]), TRUE);
  348. // If the result is a collection then we want to add each value with
  349. // it's own delta value.
  350. if (array_key_exists('@type', $subquery) and $subquery['@type'] == 'Collection') {
  351. $i = 0;
  352. $f = array();
  353. foreach ($subquery['member'] as $member) {
  354. $f['und'][$i]['value'] = $member;
  355. $i++;
  356. }
  357. $entity->$field_name = $f;
  358. }
  359. // If the result is not a collection then just add it.
  360. else {
  361. unset($subquery['@context']);
  362. unset($subquery['@id']);
  363. $f = array();
  364. $f['und'][0]['value'] = $subquery;
  365. $entity->$field_name = $f;
  366. }
  367. }
  368. // For all fields that are currently attached, add the field and
  369. // value to the entity.
  370. else {
  371. $f = array();
  372. $f['und'][0]['value'] = $response[$term_name];
  373. $entity->$field_name = $f;
  374. }
  375. }
  376. }
  377. // Generate the View for this entity
  378. $entities = array();
  379. $entities[] = $entity;
  380. $view = entity_view('TripalEntity', $entities);
  381. $content .= drupal_render($view['TripalEntity'][807]);
  382. return $content;
  383. }
  384. function tripal_ws_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  385. if ($form['#instance']['entity_type'] == 'TripalEntity') {
  386. $form['field']['cardinality']['#access'] = FALSE;
  387. }
  388. }
  389. /*
  390. * Returns the decoded json data for a specific field.
  391. */
  392. function tripal_ws_remote_data_single_field_pull($field, $entity_url){
  393. $options = array();
  394. $full_url = $entity_url . '/' . $field;
  395. $data = drupal_http_request($full_url, $options);
  396. if(!empty($data)){
  397. $data = drupal_json_decode($data->data);
  398. }
  399. return $data;
  400. }
  401. /**
  402. * Implements hook_entity_info_alter()
  403. *
  404. * Add the web services display as a view mode.
  405. */
  406. function tripal_ws_entity_info_alter(&$entity_info) {
  407. // Set the controller class for nodes to an alternate implementation of the
  408. // DrupalEntityController interface.
  409. $entity_info['TripalEntity']['view modes'] += array(
  410. 'tripal_ws' => array(
  411. 'label' => t('Tripal Web Services'),
  412. 'custom settings' => FALSE,
  413. ),
  414. );
  415. }