tripal_ws.module 15 KB

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