tripal_ws.rest_v0.1.inc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. <?php
  2. /**
  3. *
  4. */
  5. function tripal_ws_services_v0_1($api_url, $ws_path, $params) {
  6. // Set some initial variables.
  7. $response = array();
  8. $version = 'v0.1';
  9. // Set some defaults for the response.
  10. $response['@context'] = array();
  11. // Lump everything ito a try block so that if there is a problem we can
  12. // throw an error and have that returned in the response.
  13. try {
  14. // The services is the first argument
  15. $service = (count($ws_path) > 0) ? $ws_path[0] : '';
  16. switch ($service) {
  17. case 'doc':
  18. tripal_ws_services_v0_1_handle_doc_service($api_url, $response);
  19. break;
  20. case 'content':
  21. tripal_ws_services_v0_1_handle_content_service($api_url, $response, $ws_path, $params);
  22. break;
  23. case 'vocab':
  24. tripal_ws_services_v0_1_handle_vocab_service($api_url, $response, $ws_path);
  25. break;
  26. default:
  27. tripal_ws_services_v0_1_handle_no_service($api_url, $response);
  28. }
  29. }
  30. catch (Exception $e) {
  31. watchdog('tripal_ws', $e->getMessage(), array(), WATCHDOG_ERROR);
  32. $message = $e->getMessage();
  33. drupal_add_http_header('Status', '400 Bad Request');
  34. }
  35. return $response;
  36. }
  37. /**
  38. *
  39. * @param $api_url
  40. * @param $response
  41. * @param $ws_path
  42. */
  43. function tripal_ws_services_v0_1_handle_content_service($api_url, &$response, $ws_path, $params) {
  44. // Get the content type.
  45. $ctype = (count($ws_path) > 1) ? $ws_path[1] : '';
  46. $entity_id = (count($ws_path) > 2) ? $ws_path[2] : '';
  47. // If we have no content type then list all of the available content types.
  48. if (!$ctype) {
  49. tripal_ws_services_v0_1_get_content_types($api_url, $response);
  50. }
  51. // If we don't have an entity ID then show a paged list of entities with
  52. // the given type.
  53. else if ($ctype and !$entity_id) {
  54. tripal_ws_services_v0_1_get_content_type($api_url, $response, $ws_path, $ctype, $params);
  55. }
  56. // If we have a content type and an entity ID then show the entity
  57. else {
  58. tripal_ws_services_v0_1_get_content($api_url, $response, $ws_path, $ctype, $entity_id, $params);
  59. }
  60. }
  61. /**
  62. *
  63. * @param $api_url
  64. * @param $response
  65. * @param $ws_path
  66. */
  67. function tripal_ws_services_v0_1_handle_vocab_service($api_url, &$response, $ws_path) {
  68. // Get the vocab name.
  69. $vocabulary = (count($ws_path) > 1) ? $ws_path[1] : '';
  70. $accession = (count($ws_path) > 2) ? $ws_path[2] : '';
  71. // If we have no $vocabulary type then list all of the available vocabs.
  72. if (!$vocabulary) {
  73. tripal_ws_services_v0_1_get_vocabs($api_url, $response);
  74. }
  75. // If we don't have a $vocabulary then show a paged list of terms.
  76. else if ($vocabulary and !$accession) {
  77. tripal_ws_services_v0_1_get_vocab($api_url, $response, $ws_path, $vocabulary);
  78. }
  79. // If we have a content type and an entity ID then show the entity
  80. else if ($vocabulary and $accession) {
  81. tripal_ws_services_v0_1_get_term($api_url, $response, $ws_path, $vocabulary, $accession);
  82. }
  83. }
  84. /**
  85. *
  86. * @param $api_url
  87. * @param $response
  88. */
  89. function tripal_ws_services_v0_1_get_vocabs($api_url, &$response) {
  90. // First, add the vocabularies used into the @context section.
  91. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  92. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  93. // Next add in the ID for tihs resource.
  94. $response['@id'] = url($api_url . '/vocab', array('absolute' => TRUE));
  95. // Start the list.
  96. $response['@type'] = 'Collection';
  97. $response['totalItems'] = 0;
  98. $response['label'] = 'Content Types';
  99. $response['member'] = array();
  100. $vocabs = db_select('tripal_vocab', 'tv')
  101. ->fields('tv')
  102. ->execute();
  103. // Iterate through the vocabularies and add an entry in the collection.
  104. $i = 0;
  105. while ($vocab = $vocabs->fetchObject()) {
  106. // Add the bundle as a content type.
  107. $response['member'][] = array(
  108. '@id' => url($api_url . '/vocab/' . urlencode($vocab->vocabulary), array('absolute' => TRUE)),
  109. '@type' => 'vocabulary',
  110. 'vocabulary' => $vocab->vocabulary,
  111. );
  112. $i++;
  113. }
  114. $response['totalItems'] = $i;
  115. // Lastly, add in the terms used into the @context section.
  116. $response['@context']['Collection'] = 'hydra:Collection';
  117. $response['@context']['totalItems'] = 'hydra:totalItems';
  118. $response['@context']['member'] = 'hydra:member';
  119. $response['@context']['label'] = 'rdfs:label';
  120. $response['@context']['description'] = 'hydra:description';
  121. tripal_ws_services_v0_1_write_context($response, $ctype);
  122. }
  123. /**
  124. *
  125. * @param $api_url
  126. * @param $response
  127. * @param $ws_path
  128. */
  129. function tripal_ws_services_v0_1_get_vocab($api_url, &$response, $ws_path, $vocabulary) {
  130. // First, add the vocabularies used into the @context section.
  131. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  132. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  133. $response['@context']['schema'] = 'https://schema.org/';
  134. // Next add in the ID for tihs resource.
  135. $response['@id'] = url($api_url . '/vocab/' . $vocabulary, array('absolute' => TRUE));
  136. // Get the vocabulary
  137. $vocab = tripal_load_vocab_entity(array('vocabulary' => $vocabulary));
  138. // Start the list.
  139. $response['@type'] = 'Collection';
  140. $response['totalItems'] = 0;
  141. $response['label'] = vocabulary . " vocabulary collection";
  142. $response['comment'] = 'The following list of terms may not be the full ' .
  143. 'list for the vocabulary. The terms listed here are only those ' .
  144. 'that have associated content on this site.';
  145. // Get the list of terms for this vocab.
  146. $query = db_select('tripal_term', 'tt')
  147. ->fields('tt', array('id'))
  148. ->condition('vocab_id', $vocab->id)
  149. ->orderBy('accession', 'DESC');
  150. // Iterate through the entities and add them to the list.
  151. $terms = $query->execute();
  152. $i = 0;
  153. while($term = $terms->fetchObject()) {
  154. $term = tripal_load_term_entity(array('term_id' => $term->id));
  155. $response['member'][] = array(
  156. '@id' => url($api_url . '/vocab/' . urlencode($vocabulary) . '/' . urlencode($term->accession), array('absolute' => TRUE)),
  157. '@type' => 'vocabulary_term',
  158. 'vocabulary' => $vocab->vocabulary,
  159. 'accession' => $term->accession,
  160. 'name' => $term->name,
  161. 'definition' => $term->definition,
  162. );
  163. $i++;
  164. }
  165. $response['totalItems'] = $i;
  166. // Lastly, add in the terms used into the @context section.
  167. $response['@context']['Collection'] = 'hydra:Collection';
  168. $response['@context']['totalItems'] = 'hydra:totalItems';
  169. $response['@context']['member'] = 'hydra:member';
  170. $response['@context']['label'] = 'rdfs:label';
  171. $response['@context']['comment'] = 'rdfs:comment';
  172. $response['@context']['itemPage'] = 'schema:itemPage';
  173. tripal_ws_services_v0_1_write_context($response, $ctype);
  174. }
  175. /**
  176. *
  177. * @param $api_url
  178. * @param $response
  179. * @param $ws_path
  180. */
  181. function tripal_ws_services_v0_1_get_term($api_url, &$response, $ws_path, $vocabulary, $accession) {
  182. // First, add the vocabularies used into the @context section.
  183. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  184. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  185. $response['@context']['schema'] = 'https://schema.org/';
  186. // Get the term.
  187. $term = tripal_load_term_entity(array('vocabulary' => $vocabulary, 'accession' => $accession));
  188. // Next add in the ID and Type for this resources.
  189. $response['@id'] = url($api_url . '/vocab/' . urlencode($vocabulary) . '/' . urlencode($accession), array('absolute' => TRUE));
  190. $response['@type'] = 'vocabulary_term';
  191. $response['label'] = $term->name;
  192. $response['vocabulary'] = $vocabulary;
  193. $response['accession'] = $accession;
  194. $response['name'] = $term->name;
  195. $response['definition'] = $term->definition;
  196. if ($term->url) {
  197. $response['URL'] = $term->url;
  198. }
  199. // Lastly, add in the terms used into the @context section.
  200. $response['@context']['label'] = 'rdfs:label';
  201. $response['@context']['itemPage'] = 'schema:itemPage';
  202. tripal_ws_services_v0_1_write_context($response, $ctype);
  203. }
  204. /**
  205. * Provides a collection (list) of all of the content types.
  206. *
  207. * @param $api_url
  208. * @param $response
  209. */
  210. function tripal_ws_services_v0_1_get_content_types($api_url, &$response) {
  211. // First, add the vocabularies used into the @context section.
  212. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  213. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  214. // Next add in the ID for tihs resource.
  215. $response['@id'] = url($api_url . '/content', array('absolute' => TRUE));
  216. // Start the list.
  217. $response['@type'] = 'Collection';
  218. $response['totalItems'] = 0;
  219. $response['label'] = 'Content Types';
  220. $response['member'] = array();
  221. // Get the list of published terms (these are the bundle IDs)
  222. $bundles = db_select('tripal_bundle', 'tb')
  223. ->fields('tb')
  224. ->orderBy('tb.label', 'ASC')
  225. ->execute();
  226. // Iterate through the terms and add an entry in the collection.
  227. $i = 0;
  228. while ($bundle = $bundles->fetchObject()) {
  229. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  230. $term = reset($entity);
  231. $vocab = $term->vocab;
  232. $response['@context'][$term->name] = $term->url;
  233. // Get the bundle description. If no description is provided then
  234. // use the term definition
  235. $description = tripal_get_bundle_variable('description', $bundle->id);
  236. if (!$description) {
  237. $description = $term->definition;
  238. }
  239. // Add the bundle as a content type.
  240. $response['member'][] = array(
  241. '@id' => url($api_url . '/content/' . urlencode($bundle->label), array('absolute' => TRUE)),
  242. '@type' => $term->name,
  243. 'label' => $bundle->label,
  244. 'description' => $description,
  245. );
  246. $i++;
  247. }
  248. $response['totalItems'] = $i;
  249. // Lastly, add in the terms used into the @context section.
  250. $response['@context']['Collection'] = 'hydra:Collection';
  251. $response['@context']['totalItems'] = 'hydra:totalItems';
  252. $response['@context']['member'] = 'hydra:member';
  253. $response['@context']['label'] = 'rdfs:label';
  254. $response['@context']['description'] = 'hydra:description';
  255. tripal_ws_services_v0_1_write_context($response, $ctype);
  256. }
  257. /**
  258. *
  259. * @param $api_url
  260. * @param $response
  261. * @param $ws_path
  262. */
  263. function tripal_ws_services_v0_1_get_content_type($api_url, &$response, $ws_path, $ctype, $params) {
  264. // First, add the vocabularies used into the @context section.
  265. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  266. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  267. // Next add in the ID for this resource.
  268. $URL = url($api_url . '/content/' . $ctype, array('absolute' => TRUE));
  269. $response['@id'] = $URL;
  270. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  271. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  272. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  273. $term = reset($term);
  274. $response['@context'][$term->name] = $term->url;
  275. // Start the list.
  276. $response['@type'] = 'Collection';
  277. $response['totalItems'] = 0;
  278. $response['label'] = $bundle->label . " collection";
  279. // Iterate through the fields and create a $field_mapping array that makes
  280. // it easier to determine which filter criteria belongs to which field. The
  281. // key is the label for the field and the value is the field name. This way
  282. // user's can use the field label or the field name to form a query.
  283. $field_mapping = array();
  284. $fields = field_info_fields();
  285. foreach ($fields as $field) {
  286. if (array_key_exists('TripalEntity', $field['bundles'])) {
  287. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  288. if ($bundle_name == $bundle->name) {
  289. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  290. if (array_key_exists('term_accession', $instance['settings'])){
  291. $vocabulary = $instance['settings']['term_vocabulary'];
  292. $accession = $instance['settings']['term_accession'];
  293. $term = tripal_get_term_details($vocabulary, $accession);
  294. $key = $term['name'];
  295. $key = strtolower(preg_replace('/ /', '_', $key));
  296. $field_mapping[$key] = $field['field_name'];
  297. $field_mapping[$field['field_name']] = $field['field_name'];
  298. }
  299. }
  300. }
  301. }
  302. }
  303. // Convert the filters to their field names
  304. $new_params = array();
  305. $order = array();
  306. $order_dir = array();
  307. $URL_add = array();
  308. foreach ($params as $param => $value) {
  309. $URL_add[] = "$param=$value";
  310. // Ignore non filter parameters
  311. if ($param == 'page' or $param == 'limit') {
  312. continue;
  313. }
  314. // Handle order separately
  315. if ($param == 'order') {
  316. $temp = explode(',', $value);
  317. foreach ($temp as $key) {
  318. $matches = array();
  319. $dir = 'ASC';
  320. // The user can provide a direction by separating the field key and the
  321. // direction with a '|' character.
  322. if (preg_match('/^(.*)\|(.*)$/', $key, $matches)) {
  323. $key = $matches[1];
  324. if ($matches[2] == 'ASC' or $matches[2] == 'DESC') {
  325. $dir = $matches[2];
  326. }
  327. else {
  328. // TODO: handle error of providing an incorrect direction.
  329. }
  330. }
  331. if (array_key_exists($key, $field_mapping)) {
  332. $order[$field_mapping[$key]] = $key;
  333. $order_dir[] = $dir;
  334. }
  335. else {
  336. // TODO: handle error of providing a non existing field name.
  337. }
  338. }
  339. continue;
  340. }
  341. // Break apart any operators
  342. $key = $param;
  343. $op = '=';
  344. $matches = array();
  345. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  346. $key = $matches[1];
  347. $op = $matches[2];
  348. }
  349. // Break apart any subkeys and pull the first one out for the term name key.
  350. $subkeys = explode(',', $key);
  351. if (count($subkeys) > 0) {
  352. $key = array_shift($subkeys);
  353. }
  354. $column_name = $key;
  355. // Map the values in the filters to their appropriate field names.
  356. if (array_key_exists($key, $field_mapping)) {
  357. $field_name = $field_mapping[$key];
  358. if (count($subkeys) > 0) {
  359. $column_name .= '.' . implode('.', $subkeys);
  360. }
  361. $new_params[$field_name]['value'] = $value;
  362. $new_params[$field_name]['op'] = $op;
  363. $new_params[$field_name]['column'] = $column_name;
  364. }
  365. else {
  366. throw new Exception("The filter term, '$key', is not available for use.");
  367. }
  368. }
  369. // Get the list of entities for this bundle.
  370. $query = new TripalFieldQuery();
  371. $query->entityCondition('entity_type', 'TripalEntity');
  372. $query->entityCondition('bundle', $bundle->name);
  373. foreach($new_params as $field_name => $details) {
  374. $value = $details['value'];
  375. $column_name = $details['column'];
  376. switch ($details['op']) {
  377. case 'eq':
  378. $op = '=';
  379. break;
  380. case 'gt':
  381. $op = '>';
  382. break;
  383. case 'gte':
  384. $op = '>=';
  385. break;
  386. case 'lt':
  387. $op = '<';
  388. break;
  389. case 'lte':
  390. $op = '<=';
  391. break;
  392. case 'ne':
  393. $op = '<>';
  394. break;
  395. case 'contains':
  396. $op = 'CONTAINS';
  397. break;
  398. case 'starts':
  399. $op = 'STARTS WITH';
  400. break;
  401. default:
  402. $op = '=';
  403. }
  404. //print_r(array($field_name, $column_name, $value, $op));
  405. // We pass in the $column_name as an identifier for any sub fields
  406. // that are present for the fields.
  407. $query->fieldCondition($field_name, $column_name, $value, $op);
  408. }
  409. // Perform the query just as a count first to get the number of records.
  410. $cquery = clone $query;
  411. $cquery->count();
  412. $num_records = $cquery->execute();
  413. $num_records = count($num_records['TripalEntity']);
  414. if (!$num_records) {
  415. $num_records = 0;
  416. }
  417. // Add in the pager to the response.
  418. $response['totalItems'] = $num_records;
  419. $limit = array_key_exists('limit', $params) ? $params['limit'] : 25;
  420. $total_pages = ceil($num_records / $limit);
  421. $page = array_key_exists('page', $params) ? $params['page'] : 1;
  422. if ($num_records > 0) {
  423. $response['view'] = array(
  424. '@id' => $URL . '?' . implode('&', array_merge($URL_add, array("page=$page", "limit=$limit"))),
  425. '@type' => 'PartialCollectionView',
  426. 'first' => $URL . '?' . implode('&', array_merge($URL_add, array("page=1", "limit=$limit"))),
  427. 'last' => $URL . '?' . implode('&', array_merge($URL_add, array("page=$total_pages", "limit=$limit"))),
  428. );
  429. $prev = $page - 1;
  430. $next = $page + 1;
  431. if ($prev > 0) {
  432. $response['view']['previous'] = $URL . '?' . implode('&', array_merge($URL_add, array("page=$prev", "limit=$limit")));
  433. }
  434. if ($next < $total_pages) {
  435. $response['view']['next'] = $URL . '?' . implode('&', array_merge($URL_add, array("page=$next", "limit=$limit")));
  436. }
  437. }
  438. // Set the query order
  439. $order_keys = array_keys($order);
  440. for($i = 0; $i < count($order_keys); $i++) {
  441. $query->fieldOrderBy($order_keys[$i], $order[$order_keys[$i]], $order_dir[$i]);
  442. }
  443. // Set the query range
  444. $start = ($page - 1) * $limit;
  445. $query->range($start, $limit);
  446. // Now perform the query.
  447. $results = $query->execute();
  448. // Iterate through the entities and add them to the list.
  449. $i = 0;
  450. foreach ($results['TripalEntity'] as $entity_id => $stub) {
  451. $vocabulary = '';
  452. $term_name = '';
  453. // We don't need all of the attached fields for an entity so, we'll
  454. // not use the entity_load() function. Instead just pull it from the
  455. // database table.
  456. $query = db_select('tripal_entity', 'TE');
  457. $query->join('tripal_term', 'TT', 'TE.term_id = TT.id');
  458. $query->fields('TE');
  459. $query->fields('TT', array('name'));
  460. $query->condition('TE.id', $entity_id);
  461. $entity = $query->execute()->fetchObject();
  462. //$entity = tripal_load_entity('TripalEntity', array($entity->id));
  463. $response['member'][] = array(
  464. '@id' => url($api_url . '/content/' . urlencode($ctype) . '/' . $entity->id, array('absolute' => TRUE)),
  465. '@type' => $entity->name,
  466. 'label' => $entity->title,
  467. 'itemPage' => url('/bio_data/' . $entity->id, array('absolute' => TRUE)),
  468. );
  469. $i++;
  470. }
  471. // Lastly, add in the terms used into the @context section.
  472. $response['@context']['Collection'] = 'hydra:Collection';
  473. $response['@context']['totalItems'] = 'hydra:totalItems';
  474. $response['@context']['member'] = 'hydra:member';
  475. $response['@context']['label'] = 'rdfs:label';
  476. $response['@context']['itemPage'] = 'schema:itemPage';
  477. // $response['operation'][] = array(
  478. // '@type' => 'hydra:CreateResourceOperation',
  479. // 'hydra:method' => 'PUT'
  480. // );
  481. // $response['query'] = array(
  482. // '@id' => $response['@id'],
  483. // '@type' => 'IriTemplate',
  484. // "template" => $response['@id'] . "{?name,}",
  485. // "mapping" => array(
  486. // array(
  487. // "hydra:variable" => 'name',
  488. // "hydra:property" => 'name',
  489. // )
  490. // )
  491. // );
  492. tripal_ws_services_v0_1_write_context($response, $ctype);
  493. }
  494. /**
  495. *
  496. * @param unknown $response
  497. * @param unknown $ws_path
  498. * @param unknown $ctype
  499. * @param unknown $entity_id
  500. * @param unknown $params
  501. */
  502. function tripal_ws_services_v0_1_get_content_add_fields($entity, $bundle, $api_url, &$response, $ws_path, $ctype, $entity_id, $params) {
  503. // Get information about the fields attached to this bundle and sort them
  504. // in the order they were set for the display.
  505. $instances = field_info_instances('TripalEntity', $bundle->name);
  506. uasort($instances, function($a, $b) {
  507. $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  508. $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;
  509. if ($a_weight == $b_weight) {
  510. return 0;
  511. }
  512. return ($a_weight < $b_weight) ? -1 : 1;
  513. });
  514. // Iterate through the fields and add each value to the response.
  515. //$response['fields'] = $fields;
  516. foreach ($instances as $field_name => $instance) {
  517. // Ignore the content_type field provided by Tripal.
  518. if ($field_name == 'content_type') {
  519. continue;
  520. }
  521. // Skip hidden fields.
  522. if ($instance['display']['default']['type'] == 'hidden') {
  523. continue;
  524. }
  525. // Get the information about this field. It will have settings different
  526. // from the instance.
  527. $field = field_info_field($field_name);
  528. // By default, the label for the key in the output should be the
  529. // term from the vocabulary that the field is assigned. But in the
  530. // case that the field is not assigned a term, we must use the field name.
  531. $field_name = $instance['field_name'];
  532. $vocabulary = $instance['settings']['term_vocabulary'];
  533. $accession = $instance['settings']['term_accession'];
  534. $term = tripal_get_term_details($vocabulary, $accession);
  535. if ($term) {
  536. $key = $term['name'];
  537. $key_adj = strtolower(preg_replace('/ /', '_', $key));
  538. // The term schema:url also points to a recource so we need
  539. // to make sure we set the type to be '@id'.
  540. if ($vocabulary == 'schema' and $accession == 'url') {
  541. $response['@context'][$key_adj] = array(
  542. '@id' => $term['url'],
  543. '@type' => '@id',
  544. );
  545. }
  546. else {
  547. $response['@context'][$key_adj] = $term['url'];
  548. }
  549. }
  550. else {
  551. continue;
  552. }
  553. // If this field should not be attached by default then just add a link
  554. // so that the caller can get the information separately.
  555. $instance_settings = $instance['settings'];
  556. if (array_key_exists('auto_attach', $instance['settings']) and
  557. $instance_settings['auto_attach'] == FALSE) {
  558. $response['@context'][$key_adj] = array(
  559. '@id' => $response['@context'][$key_adj],
  560. '@type' => '@id'
  561. );
  562. // Add a URL only if there are values. If there are no values then
  563. // don't add a URL which would make the end-user think they can get
  564. // that information.
  565. $items = field_get_items('TripalEntity', $entity, $field_name);
  566. if ($items and count($items) > 0 and $items[0]['value']) {
  567. $response[$key_adj] = url($api_url . '/content/' . $ctype . '/' . $entity->id . '/' . urlencode($key), array('absolute' => TRUE));
  568. }
  569. else {
  570. $response[$key_adj] = NULL;
  571. }
  572. continue;
  573. }
  574. // Get the details for this field for the JSON-LD response.
  575. tripal_ws_services_v0_1_get_content_add_field($key_adj, $entity, $field, $instance, $api_url, $response);
  576. }
  577. // Lastly, add in the terms used into the @context section.
  578. $response['@context']['label'] = 'https://www.w3.org/TR/rdf-schema/#ch_label';
  579. $response['@context']['itemPage'] = 'https://schema.org/ItemPage';
  580. // $response['operation'][] = array(
  581. // '@type' => 'hydra:DeleteResourceOperation',
  582. // 'hydra:method' => 'DELETE'
  583. // );
  584. // $response['operation'][] = array(
  585. // '@type' => 'hydra:ReplaceResourceOperation',
  586. // 'hydra:method' => 'POST'
  587. // );
  588. }
  589. /**
  590. *
  591. * @param unknown $field_arg
  592. * @param unknown $api_url
  593. * @param unknown $response
  594. * @param unknown $ws_path
  595. * @param unknown $ctype
  596. * @param unknown $entity_id
  597. * @param unknown $params
  598. */
  599. function tripal_ws_services_v0_1_get_content_find_field($field_arg, $ctype, $entity_id) {
  600. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  601. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  602. $entity = reset($entity);
  603. $term = NULL;
  604. // Find the field whose term matches the one provied.
  605. $value = array();
  606. $instances = field_info_instances('TripalEntity', $bundle->name);
  607. foreach ($instances as $instance) {
  608. $field_name = $instance['field_name'];
  609. $field = field_info_field($field_name);
  610. $vocabulary = $instance['settings']['term_vocabulary'];
  611. $accession = $instance['settings']['term_accession'];
  612. $temp_term = tripal_get_term_details($vocabulary, $accession);
  613. if ($temp_term['name'] == $field_arg) {
  614. return array($entity, $bundle, $field, $instance, $temp_term);
  615. }
  616. }
  617. }
  618. /**
  619. *
  620. * @param unknown $api_url
  621. * @param unknown $response
  622. * @param unknown $ws_path
  623. * @param unknown $ctype
  624. * @param unknown $entity_id
  625. * @param unknown $params
  626. * @return number
  627. */
  628. function tripal_ws_services_v0_1_get_content($api_url, &$response, $ws_path, $ctype, $entity_id, $params) {
  629. // First, add the vocabularies used into the @context section.
  630. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  631. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  632. // If we have an argument in the 4th element (3rd index) then the user
  633. // is requesting to expand the details of a field that was not
  634. // initially attached to the enity.
  635. $field_arg = '';
  636. if (array_key_exists(3, $ws_path)) {
  637. $field_arg = urldecode($ws_path[3]);
  638. list($entity, $bundle, $field, $instance, $term) = tripal_ws_services_v0_1_get_content_find_field($field_arg, $ctype, $entity_id);
  639. // If we couldn't match this field argument to a field and entity then return
  640. if (!$entity or !$field) {
  641. return;
  642. }
  643. // Next add in the ID and Type for this resources.
  644. $key = $term['name'];
  645. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  646. $response['@context'][$key_adj] = $term['url'];
  647. $response['@id'] = url($api_url . '/content/' . $ctype . '/' . $entity->id . '/' . urlencode($key), array('absolute' => TRUE));
  648. // Attach the field and then add it's values to the response.
  649. field_attach_load($entity->type, array($entity->id => $entity),
  650. FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
  651. tripal_ws_services_v0_1_get_content_add_field($key_adj, $entity, $field, $instance, $api_url, $response, TRUE);
  652. tripal_ws_services_v0_1_write_context($response, $ctype);
  653. return;
  654. }
  655. // If we don't have a 4th argument then we're loading the base record.
  656. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  657. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  658. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  659. $term = reset($term);
  660. $vocab = $term->vocab;
  661. // Add the vocabulary for this content type to the @context section.
  662. if (!array_key_exists($vocab->vocabulary, $response['@context'])) {
  663. // If there is no URL prefix then use this API's vocabulary API
  664. if (property_exists($term, 'urlprefix')) {
  665. $response['@context'][$vocab->vocabulary] = $term->urlprefix;
  666. }
  667. else {
  668. $response['@context'][$vocab->vocabulary] = url($api_url . '/vocab/' . $vocab->vocabulary . '/', array('absolute' => TRUE));
  669. }
  670. }
  671. // Get the TripalEntity
  672. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  673. $entity = reset($entity);
  674. // Next add in the ID and Type for this resources.
  675. $response['@id'] = url($api_url . '/content/' . $ctype . '/' . $entity_id, array('absolute' => TRUE));
  676. $response['@type'] = $term->name;
  677. $response['@context'][$term->name] = $term->url;
  678. $response['label'] = $entity->title;
  679. $response['itemPage'] = url('/bio_data/' . $entity->id, array('absolute' => TRUE));
  680. tripal_ws_services_v0_1_get_content_add_fields($entity, $bundle, $api_url, $response, $ws_path, $ctype, $entity_id, $params);
  681. tripal_ws_services_v0_1_write_context($response, $ctype);
  682. }
  683. /**
  684. *
  685. * @param $response
  686. * @param $ctype
  687. */
  688. function tripal_ws_services_v0_1_write_context(&$response, $ctype) {
  689. // Save the response '@context' into a temporary file
  690. $context = array('@context' => $response['@context']);
  691. $file_name = drupal_tempnam(file_default_scheme() . '://', 'tws_context-') . '.json';
  692. $context_file = file_save_data(json_encode($context), $file_name, FILE_EXISTS_REPLACE );
  693. // Mark the file as temporary by setting it's status
  694. $context_file->status = 0;
  695. file_save($context_file);
  696. // Return the response with the '@context' section replaced with the file URL.
  697. $response['@context'] = file_create_url($context_file->uri);
  698. }
  699. /**
  700. *
  701. */
  702. function tripal_ws_services_v0_1_get_content_add_field($key, $entity, $field, $instance, $api_url, &$response, $is_field_page = NULL) {
  703. // Get the field settings.
  704. $field_name = $field['field_name'];
  705. $field_settings = $field['settings'];
  706. $items = field_get_items('TripalEntity', $entity, $field_name);
  707. if (!$items) {
  708. return;
  709. }
  710. // Give modules the opportunity to edit values for web services. This hook
  711. // really should be used sparingly. Where it helps is with non Tripal fields
  712. // that are added to a TripalEntity content type and it doesn't follow
  713. // the rules (e.g. Image field).
  714. drupal_alter('tripal_ws_value', $items, $field, $instance);
  715. $values = array();
  716. for ($i = 0; $i < count($items); $i++) {
  717. $values[$i] = tripal_ws_services_v0_1_rewrite_field_items_keys($items[$i]['value'], $response, $api_url);
  718. }
  719. // Add the $values array to the WS response.
  720. // If we only have one value then set the response with just the value.
  721. if (count($values) == 1) {
  722. // If the value is an array and this is the field page then all of those
  723. // key/value pairs should be added directly to the response.
  724. if (is_array($values[0])) {
  725. if ($is_field_page) {
  726. foreach ($values[0] as $k => $v) {
  727. $response[$k] = $v;
  728. }
  729. }
  730. else {
  731. $response[$key] = $values[0];
  732. }
  733. }
  734. // If the value is not an array it's a scalar so add it as is to the
  735. // response.
  736. else {
  737. $response[$key] = $values[0];
  738. }
  739. }
  740. // If we have more than one value then set the response to be a collection.
  741. if (count($values) > 1) {
  742. // If this is the field page then the Collection is added directly to the
  743. // response, otherwise, it's added under the field $key.
  744. if ($is_field_page) {
  745. $response['@type'] = 'Collection';
  746. $response['totalItems'] = count($values);
  747. $response['label'] = $instance['label'];
  748. $response['member'] = $values;
  749. }
  750. else {
  751. $response[$key] = array(
  752. '@type' => 'Collection',
  753. 'totalItems' => count($values),
  754. 'label' => $instance['label'],
  755. 'member' => $values,
  756. );
  757. }
  758. }
  759. }
  760. /**
  761. *
  762. */
  763. function tripal_ws_services_v0_1_rewrite_field_items_keys($value, &$response, $api_url) {
  764. $new_value = '';
  765. // If the value is an array rather than a scalar then map the sub elements
  766. // to controlled vocabulary terms.
  767. if (is_array($value)) {
  768. $temp = array();
  769. foreach ($value as $k => $v) {
  770. $matches = array();
  771. if (preg_match('/^(.+):(.+)$/', $k, $matches)) {
  772. $vocabulary = $matches[1];
  773. $accession = $matches[2];
  774. $term = tripal_get_term_details($vocabulary, $accession);
  775. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  776. if (is_array($v)) {
  777. $temp[$key_adj] = tripal_ws_services_v0_1_rewrite_field_items_keys($v, $response, $api_url);
  778. }
  779. else {
  780. $temp[$key_adj] = $v !== "" ? $v : NULL;
  781. }
  782. // The term schema:url also points to a recource so we need
  783. // to make sure we set the type to be '@id'.
  784. if ($vocabulary == 'schema' and $accession == 'url') {
  785. $response['@context'][$key_adj] = array(
  786. '@id' => $term['url'],
  787. '@type' => '@id',
  788. );
  789. }
  790. else {
  791. $response['@context'][$key_adj] = $term['url'];
  792. }
  793. }
  794. else {
  795. $temp[$k] = $v;
  796. }
  797. }
  798. $new_value = $temp;
  799. // Recurse through the values array and set the entity elements
  800. // and add the fields to the context.
  801. tripal_ws_services_v0_1_rewrite_field_items_entity($new_value, $response, $api_url);
  802. }
  803. else {
  804. $new_value = $value !== "" ? $value : NULL;
  805. }
  806. return $new_value;
  807. }
  808. /**
  809. *
  810. */
  811. function tripal_ws_services_v0_1_rewrite_field_items_entity(&$items, &$response, $api_url) {
  812. if (!$items) {
  813. return;
  814. }
  815. foreach ($items as $key => $value) {
  816. if (is_array($value)) {
  817. tripal_ws_services_v0_1_rewrite_field_items_entity($items[$key], $response, $api_url);
  818. continue;
  819. }
  820. if ($key == 'entity') {
  821. list($item_etype, $item_eid) = explode(':', $items['entity']);
  822. if ($item_eid) {
  823. $item_entity = tripal_load_entity($item_etype, array($item_eid));
  824. $item_entity = reset($item_entity);
  825. $bundle = tripal_load_bundle_entity(array('name' => $item_entity->bundle));
  826. $items['@id'] = url($api_url . '/content/' . $bundle->label . '/' . $item_eid, array('absolute' => TRUE));
  827. }
  828. unset($items['entity']);
  829. }
  830. }
  831. }
  832. /**
  833. * Provides the Hydra compatible apiDocumentation page that describes this API.
  834. *
  835. * @param $api_url
  836. * @param $response
  837. */
  838. function tripal_ws_services_v0_1_handle_doc_service($api_url, &$response) {
  839. // First, add the vocabularies used into the @context section.
  840. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  841. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  842. // Next add in the ID for tihs resource.
  843. $site_name = variable_get('site_name', '');
  844. $response['@id'] = url($api_url . '/doc/', array('absolute' => TRUE));
  845. $response['title'] = $site_name . ": RESTful Web Services API";
  846. $response['entrypoint'] = url($api_url, array('absolute' => TRUE));
  847. $response['description'] = "A fully queryable REST API using JSON-LD and " .
  848. "discoverable using the WC3 Hydra specification.";
  849. // Lastly, add in the terms used into the @context section.
  850. $response['@context']['title'] = 'hydra:title';
  851. $response['@context']['entrypoint'] = array(
  852. "@id" => "hydra:entrypoint",
  853. "@type" => "@id",
  854. );
  855. $response['@context']['description'] = 'hydra:description';
  856. tripal_ws_services_v0_1_write_context($response, $ctype);
  857. }
  858. /**
  859. * This function specifies the types of resources avaiable via the API.
  860. *
  861. * @param $api_url
  862. * @param $response
  863. * @param $ws_path
  864. */
  865. function tripal_ws_services_v0_1_handle_no_service($api_url, &$response) {
  866. // First, add the vocabularies used into the @context section.
  867. $response['@context']['rdfs'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  868. $response['@context']['hydra'] = 'http://www.w3.org/ns/hydra/core#';
  869. $response['@context']['dc'] = 'http://purl.org/dc/dcmitype/';
  870. $response['@context']['schema'] = 'https://schema.org/';
  871. // Next add in the ID for tihs resource.
  872. $response['@id'] = url($api_url, array('absolute' => TRUE));
  873. // Start the list.
  874. $response['@type'] = 'Collection';
  875. $response['totalItems'] = 0;
  876. $response['label'] = 'Services';
  877. $response['member'] = array();
  878. // Start the list.
  879. $response['member'][] = array(
  880. '@id' => url($api_url . '/content/', array('absolute' => TRUE)),
  881. '@type' => 'Service',
  882. 'label' => 'Content Types',
  883. 'description' => 'Provides acesss to the biological and ' .
  884. 'ancilliary data available on this site. Each content type ' .
  885. 'represents biological data that is defined in a controlled vocabulary '.
  886. '(e.g. Sequence Ontology term: gene (SO:0000704)).',
  887. );
  888. $response['member'][] = array(
  889. '@id' => url($api_url . '/doc/', array('absolute' => TRUE)),
  890. '@type' => 'Service',
  891. 'label' => 'API Documentation',
  892. 'description' => 'The WC3 Hydra compatible documentation for this API.',
  893. );
  894. $response['member'][] = array(
  895. '@id' => url($api_url . '/vocab/', array('absolute' => TRUE)),
  896. '@type' => 'Service',
  897. 'label' => 'Vocabulary',
  898. 'description' => 'Defines in-house locally defined vocabulary terms that ' .
  899. 'have been added specifically for this site. These terms are typically ' .
  900. 'added because no other appropriate term exists in another community-vetted '.
  901. 'controlled vocabulary.',
  902. );
  903. $response['totalItems'] = count($response['member']);
  904. $response['@context']['Collection'] = 'hydra:Collection';
  905. $response['@context']['totalItems'] = 'hydra:totalItems';
  906. $response['@context']['member'] = 'hydra:member';
  907. $response['@context']['Service'] = 'dc:Service';
  908. $response['@context']['label'] = 'rdfs:label';
  909. $response['@context']['description'] = 'hydra:description';
  910. }
  911. /**
  912. * Implements hook_tripal_ws_value_alter().
  913. *
  914. * The hook_tripal_ws_value_alter is a hook created by the Tripal WS module.
  915. * It allows the modules to adjust the values of a field for display in
  916. * web services. This hook should be used sparingly. It is meant primarily
  917. * to adjust 3rd Party (non Tripal) fields so that they work with web
  918. * services.
  919. */
  920. function tripal_ws_tripal_ws_value_alter(&$items, $field, $instance) {
  921. // The image module doesn't properly set the 'value' field, so we'll do it
  922. // here.
  923. if($field['type'] == 'image' and $field['module'] == 'image') {
  924. foreach ($items as $delta => $details) {
  925. if ($items[$delta] and array_key_exists('uri', $items[$delta])) {
  926. $items[$delta]['value']['schema:url'] = file_create_url($items[$delta]['uri']);
  927. }
  928. }
  929. }
  930. }