tripal_ws.module 14 KB

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