tripal_ws.module 15 KB

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