tripal_ws.module 14 KB

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