tripal_ws.module 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. $resource->addContextItem('entrypoint', 'hydra:entrypoint');
  177. $resource->setType('entrypoint');
  178. // Now add the member to the collection
  179. foreach ($services as $service_class) {
  180. tripal_load_include_web_service_class($service_class);
  181. $service = new $service_class($base_path);
  182. $version = $service->getVersion();
  183. $resource->addContextItem($service_class::$type, '');
  184. $resource->addProperty($service_class::$type, $service->getServicePath());
  185. }
  186. // For discoverability add the document webservice.
  187. $service->setResource($resource);
  188. $response = $service->getResponse();
  189. print drupal_json_encode($response);
  190. }
  191. /**
  192. * The callback function for all RESTful web services.
  193. *
  194. */
  195. function tripal_ws_services() {
  196. $ws_path = func_get_args();
  197. $params = $_GET;
  198. unset($params['q']);
  199. // The web services should never be cached.
  200. drupal_page_is_cacheable(FALSE);
  201. // Using the provided version number, determine which web services
  202. // verion to call.
  203. $version = array_shift($ws_path);
  204. if ($version and preg_match('/v\d+\.\d+/', $version)) {
  205. $api_url = 'ws/' . $version;
  206. // Add the file with the appropriate web services.
  207. module_load_include('inc', 'tripal_ws', 'includes/tripal_ws.rest_' . $version);
  208. $version = preg_replace('/\./', '_', $version);
  209. $function = 'tripal_ws_services_' . $version;
  210. $response = array();
  211. if (function_exists($function)) {
  212. $response = $function($api_url, $ws_path, $params);
  213. }
  214. }
  215. else {
  216. // TODO: What do we do if no version is provided?
  217. }
  218. drupal_add_http_header('Content-Type', 'application/json');
  219. print drupal_json_encode($response);
  220. }
  221. /**
  222. *
  223. * @param $entities
  224. * @param $type
  225. */
  226. function tripal_ws_entity_load($entities, $type) {
  227. foreach ($entities as $entity) {
  228. }
  229. }
  230. /**
  231. *
  232. * @param $site_id
  233. * @param $api_version
  234. * @param $ctype
  235. * @param $id
  236. *
  237. * @return
  238. */
  239. function tripal_ws_load_remote_entity($site_id, $api_version, $ctype, $id) {
  240. // Get the content type on this site
  241. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  242. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  243. $term = reset($term);
  244. $vocab = $term->vocab;
  245. $query = db_select('tripal_sites', 'ts');
  246. $query->fields('ts');
  247. $query->condition('id', $site_id);
  248. $site = $query->execute()->fetchObject();
  249. if (!$site) {
  250. return 'Could not find specified site.';
  251. }
  252. // Get the content from the web services of the remote site.
  253. $url = $site->url . "/ws/v0.1/content/" . $ctype . "/" . $id;
  254. $json = file_get_contents($url);
  255. $response = json_decode($json, TRUE);
  256. // Set the title for this page to match the title provided.
  257. drupal_set_title($response['label']);
  258. // Attribute this data to the proper source.
  259. $source_url = l($response['label'], $response['ItemPage'], array('attributes' => array('target' => '_blank')));
  260. $content = '<div><strong>Source:</strong> ' . $site->name . ': ' . $source_url . '</div>';
  261. // Fake an entity so we can display this content using the same
  262. // entity type on this site.
  263. $entity = new TripalEntity(array(), 'TripalEntity');
  264. $entity->id = 807;
  265. $entity->type = 'TripalEntity';
  266. $entity->bundle = $bundle->name;
  267. $entity->term_id = $term->id;
  268. $entity->title = $response['label'];
  269. $entity->uid = 1;
  270. $entity->status = 1;
  271. // Get the fields and create a list of those that are attached to the bundle.
  272. $fields = field_info_fields();
  273. $my_fields = array();
  274. foreach ($fields as $field) {
  275. if (isset($field['bundles']['TripalEntity'])) {
  276. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  277. if ($bundle_name == $bundle->name) {
  278. $my_fields[] = $field;
  279. }
  280. }
  281. }
  282. }
  283. // Add in the value for the 'content_type' field.
  284. $entity->content_type = array();
  285. $entity->content_type['und'][0]['value'] = $bundle->label;
  286. // For each field we know about that should be attached to our bundle,
  287. // see if we can find a corresponding entry in the results returned from
  288. // the web service call. If so, then add the field to our fake entity.
  289. foreach ($my_fields as $field) {
  290. // Get the semantic web term for this field.
  291. $field_name = $field['field_name'];
  292. $settings = $field['settings'];
  293. // If the field does not have a semantic web mapping, then skip it.
  294. if (!isset($settings['semantic_web'])) {
  295. continue;
  296. }
  297. // Convert the term into it's db and accession elements and look it up
  298. // for more details.
  299. list($vocabulary, $accession) = explode(':', $settings['semantic_web']);
  300. $term = tripal_get_term_details($vocabulary, $accession);
  301. // Convert the term to lowercase and remove spaces so we can compare
  302. // correctly.
  303. $term_name = strtolower(preg_replace('/ /', '_', $term['name']));
  304. // TODO: check for the term in the response makes the assumption
  305. // that the term is the same on both sides. This may not be true. The
  306. // acutal vocab and accession for both terms should be compared.
  307. if (isset($response[$term_name])) {
  308. // If this field is of type '@id' then this links out to another
  309. // URL where that information can be retrieved. We'll have to
  310. // handle that separately.
  311. if (isset($response['@context'][$term_name]['@type']) and
  312. $response['@context'][$term_name]['@type'] == '@id') {
  313. $subquery = json_decode(file_get_contents($response[$term_name]), TRUE);
  314. // If the result is a collection then we want to add each value with
  315. // it's own delta value.
  316. if (array_key_exists('@type', $subquery) and $subquery['@type'] == 'Collection') {
  317. $i = 0;
  318. $f = array();
  319. foreach ($subquery['member'] as $member) {
  320. $f['und'][$i]['value'] = $member;
  321. $i++;
  322. }
  323. $entity->$field_name = $f;
  324. }
  325. // If the result is not a collection then just add it.
  326. else {
  327. unset($subquery['@context']);
  328. unset($subquery['@id']);
  329. $f = array();
  330. $f['und'][0]['value'] = $subquery;
  331. $entity->$field_name = $f;
  332. }
  333. }
  334. // For all fields that are currently attached, add the field and
  335. // value to the entity.
  336. else {
  337. $f = array();
  338. $f['und'][0]['value'] = $response[$term_name];
  339. $entity->$field_name = $f;
  340. }
  341. }
  342. }
  343. // Generate the View for this entity
  344. $entities = array();
  345. $entities[] = $entity;
  346. $view = entity_view('TripalEntity', $entities);
  347. $content .= drupal_render($view['TripalEntity'][807]);
  348. return $content;
  349. }