tripal_ws.module 14 KB

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