tripal_ws.rest_v0.1.inc 35 KB

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