tripal_ws.module 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. drupal_add_http_header('Content-Type', 'application/json');
  97. try {
  98. $ws_path = func_get_args();
  99. $args = $_GET;
  100. unset($args['q']);
  101. // The web services should never be cached.
  102. drupal_page_is_cacheable(FALSE);
  103. // The Tripal web services bath will be:
  104. // [base_path]/web-services/[service name]/v[major_version].[minor_version]
  105. $matches = array();
  106. $service = '';
  107. $major_version = '';
  108. $minor_version = '';
  109. $list_services = FALSE;
  110. // If there is no path then we should list all of the services available.
  111. if (empty($ws_path)) {
  112. tripal_ws_list_services();
  113. return;
  114. }
  115. // A service path will have the service name in $ws_path[0] and the
  116. // version in $ws_path[1]. If we check that the version is correctly
  117. // formatted then we can look for the service class and invoke it.
  118. else if (preg_match("/^v(\d+)\.(\d+)$/", $ws_path[1], $matches)) {
  119. $service_type = $ws_path[0];
  120. $major_version = $matches[1];
  121. $minor_version = $matches[2];
  122. $service_version = 'v' . $major_version . '.' . $minor_version;
  123. }
  124. // If the URL doesn't match then return not found.
  125. else {
  126. throw new Exception("Unsupported service URL. Web service URLs must be of the following format: ");
  127. }
  128. // Get the service that matches the service_name
  129. $service = NULL;
  130. $services = tripal_get_web_services();
  131. foreach ($services as $service_class) {
  132. tripal_load_include_web_service_class($service_class);
  133. if ($service_class::$type == $service_type) {
  134. $service = new $service_class($service_path);
  135. if ($service->getVersion() == $service_version) {
  136. break;
  137. }
  138. $service = NULL;
  139. }
  140. }
  141. // If a service was not provided then return an error.
  142. if (!$service) {
  143. throw new Exception('The service type, "' . $service_type . '", is not available');
  144. }
  145. // Adjust the path to remove the service type and the version.
  146. $adj_path = $ws_path;
  147. array_shift($adj_path);
  148. array_shift($adj_path);
  149. // Now call the service to handle the request.
  150. $service->setPath($adj_path);
  151. $service->setParams($args);
  152. $service->handleRequest();
  153. $response = $service->getResponse();
  154. print drupal_json_encode($response);
  155. }
  156. catch (Exception $e) {
  157. $service = new TripalWebService($service_path);
  158. $service->setError($e->getMessage());
  159. $response = $service->getResponse();
  160. print drupal_json_encode($response);
  161. }
  162. }
  163. /**
  164. * Generates the list of services as the "home page" for Tripal web services.
  165. */
  166. function tripal_ws_list_services() {
  167. global $base_url;
  168. $base_path = $base_url . '/web-services';
  169. // Create an instance of the TriaplWebService class and use it to build
  170. // the entry point for the web serivces.
  171. $service = new TripalWebService($base_path);
  172. // Get the list of web service classes.
  173. $services = tripal_get_web_services();
  174. // Create the parent resource which is a collection.
  175. $resource = new TripalWebServiceResource($base_path);
  176. // Add the vocabulary to the context.
  177. tripal_load_include_web_service_class('TripalVocabService_v0_1');
  178. $service = new TripalVocabService_v0_1($base_path);
  179. $resource->addContextItem('vocab', $service->getServicePath());
  180. $resource->addContextItem('EntryPoint', 'vocab:EntryPoint');
  181. $resource->setType('EntryPoint');
  182. // Now add the services as properties.
  183. foreach ($services as $service_class) {
  184. tripal_load_include_web_service_class($service_class);
  185. if ($service_class == 'TripalVocabService_v0_1') {
  186. continue;
  187. }
  188. $service = new $service_class($base_path);
  189. $resource->addContextItem($service_class::$type, array(
  190. '@id' => 'vocab:EntryPoint/' . $service_class::$type,
  191. '@type' => '@id',
  192. ));
  193. $resource->addProperty($service_class::$type, $service->getServicePath());
  194. }
  195. $service->setResource($resource);
  196. $response = $service->getResponse();
  197. print drupal_json_encode($response);
  198. }
  199. /**
  200. * The callback function for all RESTful web services.
  201. *
  202. */
  203. function tripal_ws_services() {
  204. $ws_path = func_get_args();
  205. $params = $_GET;
  206. unset($params['q']);
  207. // The web services should never be cached.
  208. drupal_page_is_cacheable(FALSE);
  209. // Using the provided version number, determine which web services
  210. // verion to call.
  211. $version = array_shift($ws_path);
  212. if ($version and preg_match('/v\d+\.\d+/', $version)) {
  213. $api_url = 'ws/' . $version;
  214. // Add the file with the appropriate web services.
  215. module_load_include('inc', 'tripal_ws', 'includes/tripal_ws.rest_' . $version);
  216. $version = preg_replace('/\./', '_', $version);
  217. $function = 'tripal_ws_services_' . $version;
  218. $response = array();
  219. if (function_exists($function)) {
  220. $response = $function($api_url, $ws_path, $params);
  221. }
  222. }
  223. else {
  224. // TODO: What do we do if no version is provided?
  225. }
  226. drupal_add_http_header('Content-Type', 'application/json');
  227. print drupal_json_encode($response);
  228. }
  229. /**
  230. *
  231. * @param $site_id
  232. * @param $api_version
  233. * @param $ctype
  234. * @param $id
  235. *
  236. * @return
  237. */
  238. function tripal_ws_load_remote_entity($site_id, $api_version, $ctype, $id) {
  239. // Get the content type on this site
  240. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  241. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  242. $term = reset($term);
  243. $vocab = $term->vocab;
  244. $query = db_select('tripal_sites', 'ts');
  245. $query->fields('ts');
  246. $query->condition('id', $site_id);
  247. $site = $query->execute()->fetchObject();
  248. if (!$site) {
  249. return 'Could not find specified site.';
  250. }
  251. // Get the content from the web services of the remote site.
  252. $url = $site->url . "/ws/v0.1/content/" . $ctype . "/" . $id;
  253. $json = file_get_contents($url);
  254. $response = json_decode($json, TRUE);
  255. // Set the title for this page to match the title provided.
  256. drupal_set_title($response['label']);
  257. // Attribute this data to the proper source.
  258. $source_url = l($response['label'], $response['ItemPage'], array('attributes' => array('target' => '_blank')));
  259. $content = '<div><strong>Source:</strong> ' . $site->name . ': ' . $source_url . '</div>';
  260. // Fake an entity so we can display this content using the same
  261. // entity type on this site.
  262. $entity = new TripalEntity(array(), 'TripalEntity');
  263. $entity->id = 807;
  264. $entity->type = 'TripalEntity';
  265. $entity->bundle = $bundle->name;
  266. $entity->term_id = $term->id;
  267. $entity->title = $response['label'];
  268. $entity->uid = 1;
  269. $entity->status = 1;
  270. // Get the fields and create a list of those that are attached to the bundle.
  271. $fields = field_info_fields();
  272. $my_fields = array();
  273. foreach ($fields as $field) {
  274. if (isset($field['bundles']['TripalEntity'])) {
  275. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  276. if ($bundle_name == $bundle->name) {
  277. $my_fields[] = $field;
  278. }
  279. }
  280. }
  281. }
  282. // Add in the value for the 'content_type' field.
  283. $entity->content_type = array();
  284. $entity->content_type['und'][0]['value'] = $bundle->label;
  285. // For each field we know about that should be attached to our bundle,
  286. // see if we can find a corresponding entry in the results returned from
  287. // the web service call. If so, then add the field to our fake entity.
  288. foreach ($my_fields as $field) {
  289. // Get the semantic web term for this field.
  290. $field_name = $field['field_name'];
  291. $settings = $field['settings'];
  292. // If the field does not have a semantic web mapping, then skip it.
  293. if (!isset($settings['semantic_web'])) {
  294. continue;
  295. }
  296. // Convert the term into it's db and accession elements and look it up
  297. // for more details.
  298. list($vocabulary, $accession) = explode(':', $settings['semantic_web']);
  299. $term = tripal_get_term_details($vocabulary, $accession);
  300. // Convert the term to lowercase and remove spaces so we can compare
  301. // correctly.
  302. $term_name = strtolower(preg_replace('/ /', '_', $term['name']));
  303. // TODO: check for the term in the response makes the assumption
  304. // that the term is the same on both sides. This may not be true. The
  305. // acutal vocab and accession for both terms should be compared.
  306. if (isset($response[$term_name])) {
  307. // If this field is of type '@id' then this links out to another
  308. // URL where that information can be retrieved. We'll have to
  309. // handle that separately.
  310. if (isset($response['@context'][$term_name]['@type']) and
  311. $response['@context'][$term_name]['@type'] == '@id') {
  312. $subquery = json_decode(file_get_contents($response[$term_name]), TRUE);
  313. // If the result is a collection then we want to add each value with
  314. // it's own delta value.
  315. if (array_key_exists('@type', $subquery) and $subquery['@type'] == 'Collection') {
  316. $i = 0;
  317. $f = array();
  318. foreach ($subquery['member'] as $member) {
  319. $f['und'][$i]['value'] = $member;
  320. $i++;
  321. }
  322. $entity->$field_name = $f;
  323. }
  324. // If the result is not a collection then just add it.
  325. else {
  326. unset($subquery['@context']);
  327. unset($subquery['@id']);
  328. $f = array();
  329. $f['und'][0]['value'] = $subquery;
  330. $entity->$field_name = $f;
  331. }
  332. }
  333. // For all fields that are currently attached, add the field and
  334. // value to the entity.
  335. else {
  336. $f = array();
  337. $f['und'][0]['value'] = $response[$term_name];
  338. $entity->$field_name = $f;
  339. }
  340. }
  341. }
  342. // Generate the View for this entity
  343. $entities = array();
  344. $entities[] = $entity;
  345. $view = entity_view('TripalEntity', $entities);
  346. $content .= drupal_render($view['TripalEntity'][807]);
  347. return $content;
  348. }