tripal_core.ws_hal.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. function tripal_core_chado_hal_api() {
  3. global $base_url;
  4. // Set some initial variables.
  5. $response = array();
  6. $result = array();
  7. $status = 'success';
  8. $version = 'v0.1';
  9. $message = '';
  10. $api_url = "$base_url/ws/chado/$version";
  11. $page_limit = 25;
  12. $pager_id = 0;
  13. // Lump everything ito a try block so that if there is a problem we can
  14. // throw an error and have that returned in the response.
  15. try {
  16. $id = 0;
  17. $action = '';
  18. // If we don't have a table name then return the list of all tables.
  19. if (!arg(3)) {
  20. $tables = chado_get_table_names(FALSE);
  21. foreach ($tables as $table) {
  22. $result['_links']['chado_tables'][] = array('href' => "$api_url/$table");
  23. }
  24. // $tables = chado_get_custom_table_names(FALSE);
  25. // foreach ($tables as $table) {
  26. // $result['_links']['custom_tables'][] = array('href' => "$api_url/$table");
  27. // }
  28. // $tables = chado_get_mview_table_names();
  29. // foreach ($tables as $table) {
  30. // $result['_links']['mviews'][] = array('href' => "$api_url/$table");
  31. // }
  32. }
  33. else {
  34. // GET THE BASE TABLE TO QUERY
  35. // The table name is always specifid as the 3rd argument in the
  36. // current Drupal path.
  37. $table_name = arg(3);
  38. if (!chado_table_exists($table_name)) {
  39. throw new Exception("Table, '$table_name', is not a valid table.");
  40. }
  41. $schema = chado_get_schema($table_name);
  42. $pkey = $schema['primary key'][0];
  43. // GET THE RECORD AND THE ACTION TO PERFORM
  44. // If the fourth argument is numeric then the user is requesting a
  45. // record from the table. Otherwise the users is specifying an
  46. // action to perform on the table.
  47. if (is_numeric(arg(4))) {
  48. $id = arg(4);
  49. if (arg(5)) {
  50. $action = arg(5);
  51. }
  52. }
  53. else {
  54. $action = arg(4);
  55. }
  56. // Get any URL query arguments
  57. $query = drupal_get_query_parameters();
  58. switch ($action) {
  59. case 'schema':
  60. $result = $schema;
  61. break;
  62. case 'add':
  63. case 'edit':
  64. case 'delete':
  65. throw new Exception("Action, '$action', is currently not supported.");
  66. break;
  67. default:
  68. // Specify the values for selecing records.
  69. $values = array();
  70. if ($id) {
  71. $values[$pkey] = $id;
  72. }
  73. // Specify the options for retrieving data.
  74. $options = array(
  75. 'return_array' => 1,
  76. 'pager' => array(
  77. 'limit' => $page_limit,
  78. 'element' => $pager_id
  79. ),
  80. );
  81. // Generate the chado variable.
  82. $var = chado_generate_var($table_name, $values, $options);
  83. // If we have more than one record returned then this is a collection and
  84. // we should create the appropriate JSON for a collection.
  85. if (count($var) > 1) {
  86. // Get the total number of records
  87. $total = chado_pager_get_count($pager_id);
  88. $curr_page = array_key_exists('page', $query) ? $query['page'] : 0;
  89. $first_page = '0';
  90. $last_page = ceil($total / $page_limit) - 1;
  91. $result['_links']['first'] = array('href' => "$api_url/$table_name");
  92. if ($curr_page > 0) {
  93. $prev_page = $curr_page - 1;
  94. if ($prev_page != $first_page) {
  95. $result['_links']['previous'] = array('href' => "$api_url/$table_name?page=$prev_page");
  96. }
  97. else {
  98. $result['_links']['previous'] = $result['_links']['first'];
  99. }
  100. }
  101. if ($curr_page < $last_page) {
  102. $next_page = $curr_page + 1;
  103. $result['_links']['next'] = array('href' => "$api_url/$table_name?page=$next_page");
  104. }
  105. if ($last_page > $first_page) {
  106. $result['_links']['last'] = array('href' => "$api_url/$table_name?page=$last_page");
  107. }
  108. // Add the number of elements for this collection
  109. $result['count'] = count($var);
  110. $result['total'] = (integer) $total;
  111. $result['current_page'] = (integer) $curr_page;
  112. $result['items_per_page'] = $page_limit;
  113. // Do any expansion requested.
  114. if ($action == 'expand') {
  115. $var = tripal_core_chado_ws_api_expand_object($var, $query);
  116. }
  117. // recursively reformat the expanded objects to match HAL requirements.
  118. foreach ($var as $item) {
  119. $item = tripal_core_chado_ws_api_format_object($table_name, $item, $schema, $api_url, $query);
  120. $result['_embedded'][$table_name][] = $item;
  121. }
  122. }
  123. // If we only have one record then add it as a single record to the JSON.
  124. else {
  125. $item = $var[0];
  126. // Do any expansion requested.
  127. if ($action == 'expand') {
  128. $item = tripal_core_chado_ws_api_expand_object($item, $query);
  129. }
  130. // recursively reformat the expanded objects to match HAL requirements.
  131. $item = tripal_core_chado_ws_api_format_object($table_name, $item, $schema, $api_url, $query);
  132. $result = $item;
  133. }
  134. }
  135. }
  136. }
  137. catch (Exception $e) {
  138. watchdog('tripal_ws', $e->getMessage(), array(), WATCHDOG_ERROR);
  139. $message = $e->getMessage();
  140. $status = 'error';
  141. $result = array();
  142. }
  143. // The responses follow the same format as the AGAVE API with a
  144. // status, message, version and all data in the "result" object.
  145. $response['status'] = $status;
  146. $response['message'] = $message;
  147. $response['version'] = $version;
  148. $response['source'] = array(
  149. 'site_name' => variable_get('site_name', "Unspecified"),
  150. 'site_url' => $base_url,
  151. 'site_slogan' => variable_get('site_slogan', "Unspecified"),
  152. 'site_email' => variable_get('site_mail', "Unspecified"),
  153. );
  154. $response['result'] = $result;
  155. print drupal_json_output($response);
  156. }
  157. /**
  158. *
  159. * @param unknown $object
  160. * @param unknown $query
  161. */
  162. function tripal_core_chado_ws_api_expand_object($var, $query) {
  163. $page_limit = 25;
  164. $pager_id = 0;
  165. $options = array(
  166. 'return_array' => 1,
  167. 'pager' => array(
  168. 'limit' => $page_limit,
  169. 'element' => $pager_id
  170. ),
  171. );
  172. // If the user has requested to expand any fields then do that
  173. if (array_key_exists('table', $query)) {
  174. $expand_tables = explode(',', $query['table']);
  175. foreach($expand_tables as $table) {
  176. // Does the table exist?
  177. if(!chado_table_exists($table)) {
  178. throw new Exception("Table, '$table', is not a valid table and thus cannot be expanded.");
  179. }
  180. // Expand the variable.
  181. // $var = chado_expand_var($var, 'table', $table, $options);
  182. }
  183. }
  184. if (array_key_exists('field', $query)) {
  185. $expand_fields = explode(',', $query['field']);
  186. foreach($expand_fields as $field) {
  187. // TODO: check to make sure the field exists
  188. $var = chado_expand_var($var, 'field', $field);
  189. }
  190. }
  191. if (array_key_exists('fkey', $query)) {
  192. $expand_fkeys = explode(',', $query['fkey']);
  193. foreach($expand_fkeys as $fkey) {
  194. // TODO: check to make sure the fkey exists
  195. // $var = chado_expand_var($var, 'foreign_key', $fkey);
  196. }
  197. }
  198. return $var;
  199. }
  200. /**
  201. *
  202. * @param $object
  203. * @param $schema
  204. * @param $api_url
  205. */
  206. function tripal_core_chado_ws_api_format_object($table_name, $object, $schema, $api_url, $query) {
  207. global $base_url;
  208. $pkey = $schema['primary key'][0];
  209. $id = $object->$pkey;
  210. // Add the self link first
  211. if ($id) {
  212. $object->_links['self'] = array('href' => "$api_url/$table_name/$id");
  213. $object->_links['show_expansion'] = array('href' => "$api_url/$table_name/$id?show_expansion=1");
  214. }
  215. else {
  216. $object->_links['self'] = array('href' => "$api_url/$table_name");
  217. $object->_links['show_expansion'] = array('href' => "$api_url/$table_name?show_expansion=1");
  218. }
  219. // Add the links for the table.
  220. $object->_links["tables"] = array('href' => "$api_url");
  221. $object->_links["schema"] = array('href' => "$api_url/$table_name/schema");
  222. // Add links for editing, insert, delete but only if user has permission.
  223. // TODO: how do we set permissions?
  224. $object->_links["add"] = array('href' => "$api_url/$table_name/add");
  225. // Add the links if an id is available.
  226. if ($id) {
  227. $object->_links["edit"] = array('href' => "$api_url/$table_name/$id/edit");
  228. $object->_links["delete"] = array('href' => "$api_url/$table_name/$id/delete");
  229. }
  230. // Add the link to the Drupal page if a node exists.
  231. if (property_exists($object, 'nid')) {
  232. $object->_links["view"] = array('href' => $base_url . url("node/$object->nid"));
  233. // Unset the node ID because it's really only needed within the context
  234. // of the local Drupal site.
  235. unset($object->nid);
  236. }
  237. // It doesn't make sense to allow expansion of node information outside
  238. // of the context of the local Drupal site so remove this object.
  239. unset($object->expandable_nodes);
  240. // Only include links for expanding if the option to exclude them has not
  241. // been passed.
  242. if (!array_key_exists('show_expansion', $query)) {
  243. unset($object->expandable_fields);
  244. unset($object->expandable_foreign_keys);
  245. unset($object->expandable_tables);
  246. }
  247. // Deal with the expandable tables/fields/fkeys/nodes. Sometimes there are
  248. // specified in PHP with explicit numerical indexes and sometimes not. But,
  249. // the JSON converter will maintain the indexes if present which creates
  250. // an inconsistent look. So, we use the array_values function to just
  251. // get the list.
  252. if (array_key_exists('expandable_tables', $object)) {
  253. $object->expandable_tables = array_values($object->expandable_tables);
  254. if (count($object->expandable_tables) > 0) {
  255. // $object->_links["expand_table"][] = array('href' => "$api_url/$table_name/expand?table={table}[,{table}...]");
  256. // $object->_links["expand_table"][] = array('href' => "$api_url/$table_name/$id/expand?table={table}[,{table}...]");
  257. }
  258. else {
  259. unset($object->expandable_tables);
  260. }
  261. }
  262. if (array_key_exists('expandable_fields', $object)) {
  263. $object->expandable_fields = array_values($object->expandable_fields);
  264. if (count($object->expandable_fields) > 0) {
  265. $object->_links["expand_field"][] = array('href' => "$api_url/$table_name/expand?field={field}[,{field}...]");
  266. $object->_links["expand_field"][] = array('href' => "$api_url/$table_name/$id/expand?field={field}[,{field}...]");
  267. }
  268. else {
  269. unset($object->expandable_fields);
  270. }
  271. }
  272. if (array_key_exists('expandable_foreign_keys', $object)) {
  273. $object->expandable_foreign_keys = array_values($object->expandable_foreign_keys);
  274. if (count($object->expandable_foreign_keys) > 0) {
  275. $object->_links["expand_fkey"][] = array('href' => "$api_url/$table_name/expand?fkey={fkey}[,{fkey}...]");
  276. $object->_links["expand_fkey"][] = array('href' => "$api_url/$table_name/$id/expand?fkey={fkey}[,{fkey}...]");
  277. }
  278. else {
  279. unset($object->expandable_foreign_keys);
  280. }
  281. }
  282. //print_r($object);
  283. // iterate through the items in the object and see if they in turn are
  284. // objects. If so, then recurse.
  285. foreach ($object as $key => $value) {
  286. if (is_array($value)) {
  287. foreach ($value as $subitem) {
  288. if (property_exists($subitem, 'tablename')) {
  289. $table_name = $subitem->tablename;
  290. $schema = chado_get_schema($table_name);
  291. if ($schema) {
  292. tripal_core_chado_ws_api_format_element($table_name, $key, $subitem, $schema, $api_url, $query);
  293. }
  294. else {
  295. throw new Exception("Table, '$table_name', is not a valid table.");
  296. }
  297. }
  298. }
  299. }
  300. // If any values are objects then recurse and format them correctly.
  301. if (is_object($value)) {
  302. if (property_exists($value, 'tablename')) {
  303. $table_name = $value->tablename;
  304. $schema = chado_get_schema($table_name);
  305. if ($schema) {
  306. tripal_core_chado_ws_api_format_element($table_name, $key, $value, $schema, $api_url, $query);
  307. }
  308. else {
  309. throw new Exception("Table, '$table_name', is not a valid table.");
  310. }
  311. }
  312. }
  313. }
  314. if (array_key_exists('no_links', $query)) {
  315. unset($object->_links);
  316. }
  317. return $object;
  318. }
  319. /**
  320. * Transforms a single element from into HAL JSON format.
  321. *
  322. *
  323. * @param $object
  324. * An object from the variable returned from chado_generate_var array
  325. *
  326. * @throws Exception
  327. */
  328. function tripal_core_chado_ws_api_format_element($table_name, $field, $value, $schema, $api_url, $query) {
  329. // Replace the object with the actual value if it exists. If there is
  330. // no key value then this is probably an expanded table so just unset
  331. if (property_exists($value, $field)) {
  332. $object->$field = $value->$field;
  333. }
  334. else {
  335. unset($object->$field);
  336. }
  337. // Recursively format the object.
  338. $value = tripal_core_chado_ws_api_format_object($table_name, $value, $schema, $api_url, $query);
  339. // Add the object as an "_embedded" object of the JSON.
  340. if (property_exists($object,'_embedded') and
  341. array_key_exists($table_name, $object->_embedded)) {
  342. // If the element is already an array then add to it, otherwise
  343. // convert it into an array.
  344. if (is_array($object->_embedded[$table_name])) {
  345. $object->_embedded[$table_name][] = $value;
  346. }
  347. else {
  348. $first = $object->_embedded[$table_name];
  349. $object->_embedded[$table_name] = array();
  350. $object->_embedded[$table_name] = $first;
  351. $object->_embedded[$table_name][] = $value;
  352. }
  353. }
  354. // This is the first time this embedded table has been seen
  355. // there fore, add the value as a single element.
  356. else {
  357. $object->_embedded[$table_name] = $value;
  358. }
  359. }