tripal_ws.module 13 KB

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