TripalEntityService_v0_1.inc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. <?php
  2. class TripalEntityService_v0_1 extends TripalWebService {
  3. /**
  4. * The human-readable label for this web service.
  5. */
  6. public static $label = 'Content Types';
  7. /**
  8. * A bit of text to describe what this service provides.
  9. */
  10. public static $description = 'Provides acesss to the biological and ' .
  11. 'ancilliary data available on this site. Each content type represents ' .
  12. 'biological data that is defined in a controlled vocabulary (e.g. ' .
  13. 'Sequence Ontology term: gene (SO:0000704)).';
  14. /**
  15. * A machine-readable type for this service. This name must be unique
  16. * among all Tripal web services and is used to form the URL to access
  17. * this service.
  18. */
  19. public static $type = 'content';
  20. /**
  21. * Implements the constructor
  22. */
  23. public function __construct($base_path) {
  24. parent::__construct($base_path);
  25. }
  26. /**
  27. * @see TripalWebService::handleRequest()
  28. */
  29. public function handleRequest() {
  30. // Get the content type.
  31. $ctype = (count($this->path) > 0) ? $this->path[0] : '';
  32. $entity_id = (count($this->path) > 1) ? $this->path[1] : '';
  33. $expfield = (count($this->path) > 2) ? $this->path[2] : '';
  34. // If we have a content type then list all of the entities that belong
  35. // to it.
  36. if ($ctype and !$entity_id and !$expfield) {
  37. $this->doContentTypeList($ctype);
  38. }
  39. // If we have an entity ID then build the resource for a single entity.
  40. else if ($ctype and $entity_id and !$expfield) {
  41. $this->doEntity($ctype, $entity_id);
  42. }
  43. else if ($ctype and $entity_id and $expfield) {
  44. $this->doExpandedField($ctype, $entity_id, $expfield);
  45. }
  46. // Otherwise just list all of the available content types.
  47. else {
  48. $this->doAllTypesList();
  49. }
  50. }
  51. /**
  52. * Creates a resource for an expanded field of an entity.
  53. */
  54. private function doExpandedField($ctype, $entity_id, $expfield) {
  55. $service_path = $this->getServicePath() . '/' . urlencode($ctype) . '/' . $entity_id;
  56. $this->resource = new TripalWebServiceResource($service_path, $this->doc_path);
  57. // Get the TripalBundle, TripalTerm and TripalVocab for this type.
  58. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  59. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  60. $term = reset($term);
  61. $vocab = $term->vocab;
  62. // Get the TripalEntity
  63. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  64. $entity = reset($entity);
  65. // If we couldn't match this field argument to a field and entity then return
  66. if (!$entity) {
  67. throw new Exception("Cannot find this record.");
  68. }
  69. // Check that the user has access to this entity. If not then the
  70. // function call will throw an error.
  71. $this->checkAccess($entity);
  72. list($field, $instance, $term) = $this->findField($bundle, $expfield);
  73. // Next add in the ID and Type for this resources.
  74. $key = $term['name'];
  75. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  76. $this->resource->addContextItem($key_adj, $term['url']);
  77. $this->resource->setID(urlencode($key));
  78. $this->resource->setType($key_adj);
  79. // Attach the field and then add it's values to the response.
  80. field_attach_load($entity->type, array($entity->id => $entity),
  81. FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
  82. $this->addEntityField($key_adj, $term, $entity, $bundle, $field, $instance, $service_path, $expfield);
  83. }
  84. /**
  85. * Find the field whose term matches the one provied.
  86. */
  87. private function findField($bundle, $expfield) {
  88. $value = array();
  89. $instances = field_info_instances('TripalEntity', $bundle->name);
  90. foreach ($instances as $instance) {
  91. $field_name = $instance['field_name'];
  92. $field = field_info_field($field_name);
  93. $vocabulary = $instance['settings']['term_vocabulary'];
  94. $accession = $instance['settings']['term_accession'];
  95. $temp_term = tripal_get_term_details($vocabulary, $accession);
  96. if ($temp_term['name'] == $expfield) {
  97. return array($field, $instance, $temp_term);
  98. }
  99. }
  100. }
  101. /**
  102. * Creates a resource for a single entity.
  103. */
  104. private function doEntity($ctype, $entity_id) {
  105. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  106. $this->resource = new TripalWebServiceResource($service_path);
  107. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  108. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  109. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  110. $term = reset($term);
  111. $vocab = $term->vocab;
  112. // Add the vocabulary to the context.
  113. $this->resource->addContextItem($term->name, $term->url);
  114. // Get the TripalEntity.
  115. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  116. $entity = reset($entity);
  117. // If we couldn't match this field argument to a field and entity then return
  118. if (!$entity) {
  119. throw new Exception("Cannot find this record.");
  120. }
  121. // Check that the user has access to this entity. If not then the
  122. // function call will throw an error.
  123. $this->checkAccess($entity);
  124. $itemPage = tripal_get_term_details('schema', 'ItemPage');
  125. $label = tripal_get_term_details('rdfs', 'label');
  126. $this->resource->setID($entity_id);
  127. $this->resource->setType($term->name);
  128. $this->resource->addContextItem('label', $label['url']);
  129. $this->resource->addContextItem('ItemPage', $itemPage['url']);
  130. $this->resource->addProperty('label', $entity->title);
  131. $this->resource->addProperty('ItemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  132. $this->addEntityFields($entity, $bundle, $term, $service_path);
  133. // tripal_ws_services_v0_1_get_content_add_fields($entity, $bundle, $api_url, $response, $ws_path, $ctype, $entity_id, $params);
  134. // tripal_ws_services_v0_1_write_context($response, $ctype);
  135. }
  136. /**
  137. * Ensures that user's only have access to content they should see.
  138. *
  139. * Denies access to an entity if it is unpublished or if the user does
  140. * not have permission to see it.
  141. *
  142. * @param $entity
  143. * The full entity object.
  144. *
  145. * @throws Exception
  146. */
  147. private function checkAccess($entity) {
  148. global $user;
  149. if (!tripal_entity_access('view', $entity, $user, 'TripalEntity')) {
  150. throw new Exception("Permission Denied.");
  151. }
  152. // Don't show entities that aren't published
  153. if ($entity->status == 0) {
  154. throw new Exception("This record is currently unavailable.");
  155. }
  156. }
  157. /**
  158. * Adds the fields as properties of an entity resource.
  159. */
  160. private function addEntityFields($entity, $bundle, $term, $service_path) {
  161. // If the entity is set to hide fields that have no values then we
  162. // want to honor that in the web services too.
  163. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  164. // Get information about the fields attached to this bundle and sort them
  165. // in the order they were set for the display.
  166. $instances = field_info_instances('TripalEntity', $bundle->name);
  167. uasort($instances, function($a, $b) {
  168. $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  169. $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;
  170. if ($a_weight == $b_weight) {
  171. return 0;
  172. }
  173. return ($a_weight < $b_weight) ? -1 : 1;
  174. });
  175. // Iterate through the fields and add each value to the response.
  176. //$response['fields'] = $fields;
  177. foreach ($instances as $field_name => $instance) {
  178. // Skip hidden fields.
  179. if ($instance['display']['default']['type'] == 'hidden') {
  180. continue;
  181. }
  182. // Get the information about this field.
  183. $field = field_info_field($field_name);
  184. // By default, the label for the key in the output should be the
  185. // term from the vocabulary that the field is assigned. But in the
  186. // case that the field is not assigned a term, we must use the field name.
  187. $field_name = $instance['field_name'];
  188. $vocabulary = $instance['settings']['term_vocabulary'];
  189. $accession = $instance['settings']['term_accession'];
  190. $term = tripal_get_term_details($vocabulary, $accession);
  191. if (!$term) {
  192. continue;
  193. }
  194. $key = $term['name'];
  195. $key_adj = strtolower(preg_replace('/ /', '_', $key));
  196. // If this field should not be attached by default then just add a link
  197. // so that the caller can get the information separately.
  198. $instance_settings = $instance['settings'];
  199. if (array_key_exists('auto_attach', $instance['settings']) and
  200. $instance_settings['auto_attach'] == FALSE) {
  201. // Add a URL only if there are values. If there are no values then
  202. // don't add a URL which would make the end-user think they can get
  203. // that information.
  204. $items = field_get_items('TripalEntity', $entity, $field_name);
  205. if ($items and count($items) > 0 and $items[0]['value']) {
  206. $this->resource->addContextItem($key_adj, $term['url']);
  207. $this->resource->addProperty($key_adj, $service_path . '/' . $entity->id . '/' . urlencode($term['name']));
  208. }
  209. else {
  210. if ($hide_fields == 'show') {
  211. $this->resource->addContextItem($key_adj, $term['url']);
  212. $this->resource->addProperty($key_adj, NULL);
  213. }
  214. }
  215. continue;
  216. }
  217. // Get the details for this field for the JSON-LD response.
  218. $this->addEntityField($key_adj, $term, $entity, $bundle, $field, $instance, $service_path);
  219. }
  220. }
  221. /**
  222. * Adds the field as a property of the entity resource.
  223. */
  224. private function addEntityField($key, $term, $entity, $bundle, $field, $instance,
  225. $service_path, $expfield = NULL) {
  226. // If the entity is set to hide fields that have no values then we
  227. // want to honor that in the web services too.
  228. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  229. // Get the field settings.
  230. $field_name = $field['field_name'];
  231. $field_settings = $field['settings'];
  232. $items = field_get_items('TripalEntity', $entity, $field_name);
  233. if (!$items) {
  234. return;
  235. }
  236. // Give modules the opportunity to edit values for web services. This hook
  237. // really should be used sparingly. Where it helps is with non Tripal fields
  238. // that are added to a TripalEntity content type and it doesn't follow
  239. // the rules (e.g. Image field).
  240. drupal_alter('tripal_ws_value', $items, $field, $instance);
  241. $values = array();
  242. for ($i = 0; $i < count($items); $i++) {
  243. $values[$i] = $this->sanitizeFieldKeys($items[$i]['value'], $bundle, $service_path);
  244. }
  245. if ($hide_fields == 'hide' and empty($values[0])) {
  246. return;
  247. }
  248. // If the field cardinality is 1
  249. if ($field['cardinality'] == 1) {
  250. // If the value is an array and this is the field page then all of those
  251. // key/value pairs should be added directly to the response.
  252. if (is_array($values[0])) {
  253. if ($expfield) {
  254. foreach ($values[0] as $k => $v) {
  255. $this->resource->addProperty($k, $v);
  256. }
  257. }
  258. else {
  259. $this->resource->addContextItem($key, $term['url']);
  260. $this->resource->addProperty($key, $values[0]);
  261. }
  262. }
  263. // If the value is not an array it's a scalar so add it as is to the
  264. // response.
  265. else {
  266. $this->resource->addContextItem($key, $term['url']);
  267. $this->resource->addProperty($key, $values[0]);
  268. }
  269. }
  270. // If the field cardinality is > 1
  271. if ($field['cardinality'] != 1) {
  272. // If this is the expanded field page then we need to swap out
  273. // the resource for a collection.
  274. $response = new TripalWebServiceCollection($service_path . '/' . urlencode($expfield));
  275. $label = tripal_get_term_details('rdfs', 'label');
  276. $response->addContextItem('label', $label['url']);
  277. $response->addProperty('label', $instance['label']);
  278. $i = 0;
  279. foreach ($values as $delta => $element) {
  280. $member = new TripalWebServiceResource($service_path . '/' . urlencode($expfield));
  281. $member->setID($i);
  282. // Add the context of the parent resource because all of the keys
  283. // were santizied and set to match the proper context.
  284. $member->setContext($this->resource);
  285. $member->setType($key);
  286. foreach ($element as $key => $value) {
  287. $member->addProperty($key, $value);
  288. }
  289. $response->addMember($member);
  290. $i++;
  291. }
  292. if ($expfield) {
  293. $this->resource = $response;
  294. }
  295. else {
  296. $this->resource->addProperty($key, $response);
  297. }
  298. }
  299. }
  300. /**
  301. * Rewrites the keys of a field's items array for use with web services.
  302. */
  303. private function sanitizeFieldKeys($value, $bundle, $service_path) {
  304. // If the entity is set to hide fields that have no values then we
  305. // want to honor that in the web services too.
  306. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  307. $new_value = '';
  308. // If the value is an array rather than a scalar then map the sub elements
  309. // to controlled vocabulary terms.
  310. if (is_array($value)) {
  311. $temp = array();
  312. foreach ($value as $k => $v) {
  313. // exclude fields that have no values so we can hide them
  314. if (!isset($v) and $hide_fields == 'hide') {
  315. continue;
  316. }
  317. $matches = array();
  318. if (preg_match('/^(.+):(.+)$/', $k, $matches)) {
  319. $vocabulary = $matches[1];
  320. $accession = $matches[2];
  321. $term = tripal_get_term_details($vocabulary, $accession);
  322. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  323. if (is_array($v)) {
  324. $temp[$key_adj] = $this->sanitizeFieldKeys($v, $bundle, $service_path);
  325. }
  326. else {
  327. $temp[$key_adj] = $v;
  328. }
  329. $this->resource->addContextItem($key_adj, $term['url']);
  330. }
  331. else {
  332. // TODO: this is an error, if we get here then we have
  333. // a key that isn't using the proper format... what to do?
  334. }
  335. }
  336. $new_value = $temp;
  337. // Recurse through the values array and set the entity elements
  338. // and add the fields to the context.
  339. $this->sanitizeFieldEntity($new_value, $service_path);
  340. }
  341. else {
  342. $new_value = $value;
  343. }
  344. return $new_value;
  345. }
  346. /**
  347. * Rewrites any TripalEntity elements in the values array for use with WS.
  348. */
  349. private function sanitizeFieldEntity(&$items, $service_path) {
  350. if (!$items) {
  351. return;
  352. }
  353. foreach ($items as $key => $value) {
  354. if (is_array($value)) {
  355. $this->sanitizeFieldEntity($items[$key], $service_path);
  356. continue;
  357. }
  358. if ($key == 'entity') {
  359. list($item_etype, $item_eid) = explode(':', $items['entity']);
  360. if ($item_eid) {
  361. $item_entity = tripal_load_entity($item_etype, array($item_eid));
  362. $item_entity = reset($item_entity);
  363. $bundle = tripal_load_bundle_entity(array('name' => $item_entity->bundle));
  364. $items['@id'] = $this->getServicePath() . '/' . urlencode($bundle->label) . '/' . $item_eid;
  365. }
  366. unset($items['entity']);
  367. }
  368. }
  369. }
  370. /**
  371. * Creates a collection of resources for a given type.
  372. */
  373. private function doContentTypeList($ctype) {
  374. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  375. $label = tripal_get_term_details('rdfs', 'label');
  376. $this->resource = new TripalWebServiceCollection($service_path);
  377. $this->resource->addContextItem('label', $label['url']);
  378. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  379. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  380. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  381. $term = reset($term);
  382. // Set the label for this collection.
  383. $this->resource->addProperty('label', $bundle->label . " collection");
  384. // Iterate through the fields and create a $field_mapping array that makes
  385. // it easier to determine which filter criteria belongs to which field. The
  386. // key is the label for the field and the value is the field name. This way
  387. // user's can use the field label or the field name to form a query.
  388. $field_mapping = array();
  389. $fields = field_info_fields();
  390. foreach ($fields as $field) {
  391. if (array_key_exists('TripalEntity', $field['bundles'])) {
  392. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  393. if ($bundle_name == $bundle->name) {
  394. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  395. if (array_key_exists('term_accession', $instance['settings'])){
  396. $vocabulary = $instance['settings']['term_vocabulary'];
  397. $accession = $instance['settings']['term_accession'];
  398. $fterm = tripal_get_term_details($vocabulary, $accession);
  399. $key = $fterm['name'];
  400. $key = strtolower(preg_replace('/ /', '_', $key));
  401. $field_mapping[$key] = $field['field_name'];
  402. $field_mapping[$field['field_name']] = $field['field_name'];
  403. }
  404. }
  405. }
  406. }
  407. }
  408. // Convert the filters to their field names
  409. $new_params = array();
  410. $order = array();
  411. $order_dir = array();
  412. $URL_add = array();
  413. foreach ($this->params as $param => $value) {
  414. $URL_add[] = "$param=$value";
  415. // Ignore non filter parameters
  416. if ($param == 'page' or $param == 'limit') {
  417. continue;
  418. }
  419. // Handle order separately
  420. if ($param == 'order') {
  421. $temp = explode(',', $value);
  422. foreach ($temp as $key) {
  423. $matches = array();
  424. $dir = 'ASC';
  425. // The user can provide a direction by separating the field key and the
  426. // direction with a '|' character.
  427. if (preg_match('/^(.*)\|(.*)$/', $key, $matches)) {
  428. $key = $matches[1];
  429. if ($matches[2] == 'ASC' or $matches[2] == 'DESC') {
  430. $dir = $matches[2];
  431. }
  432. else {
  433. // TODO: handle error of providing an incorrect direction.
  434. }
  435. }
  436. if (array_key_exists($key, $field_mapping)) {
  437. $order[$field_mapping[$key]] = $key;
  438. $order_dir[] = $dir;
  439. }
  440. else {
  441. // TODO: handle error of providing a non existing field name.
  442. }
  443. }
  444. continue;
  445. }
  446. // Break apart any operators
  447. $key = $param;
  448. $op = '=';
  449. $matches = array();
  450. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  451. $key = $matches[1];
  452. $op = $matches[2];
  453. }
  454. // Break apart any subkeys and pull the first one as this is the parent
  455. // field.
  456. $subkeys = explode(',', $key);
  457. if (count($subkeys) > 0) {
  458. $key = $subkeys[0];
  459. }
  460. // Map the values in the filters to their appropriate field names.
  461. if (array_key_exists($key, $field_mapping)) {
  462. $key_field_name = $field_mapping[$key];
  463. $key_field = field_info_field($key_field_name);
  464. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  465. // Complex fields provied by the TripalField class may have sub
  466. // elements that support filtering. We need to see if the user
  467. // wants to filter on those.
  468. if (tripal_load_include_field_class($key_field_name)) {
  469. // To find out which fields are searchable we'll call the wsData()
  470. // function.
  471. $key_field = new $key_field_name($key_field, $key_instance);
  472. $searchable_keys = $key_field->webServicesData();
  473. $criteria = implode('.', $subkeys);
  474. if (array_key_exists($criteria, $searchable_keys)) {
  475. $new_params[$key_field_name][] = array(
  476. 'value' => $value,
  477. 'op' => $op,
  478. 'column' => $searchable_keys[$criteria]
  479. );
  480. }
  481. else {
  482. throw new Exception("The filter term, '$criteria', is not available for use.");
  483. }
  484. }
  485. // If this field is not a TripalField then it should just have
  486. // a simple value and we can query for that.
  487. else {
  488. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  489. $new_params[$key_field_name][] = array(
  490. 'value' => $value,
  491. 'op' => $op,
  492. 'column' => $key_field_id,
  493. );
  494. }
  495. }
  496. else {
  497. throw new Exception("The filter term, '$key', is not available for use.");
  498. }
  499. }
  500. // Get the list of entities for this bundle.
  501. $query = new TripalFieldQuery();
  502. $query->entityCondition('entity_type', 'TripalEntity');
  503. $query->entityCondition('bundle', $bundle->name);
  504. foreach($new_params as $field_name => $param_list) {
  505. foreach ($param_list as $param_index => $details) {
  506. $value = $details['value'];
  507. $column_name = $details['column'];
  508. switch ($details['op']) {
  509. case 'eq':
  510. $op = '=';
  511. break;
  512. case 'gt':
  513. $op = '>';
  514. break;
  515. case 'gte':
  516. $op = '>=';
  517. break;
  518. case 'lt':
  519. $op = '<';
  520. break;
  521. case 'lte':
  522. $op = '<=';
  523. break;
  524. case 'ne':
  525. $op = '<>';
  526. break;
  527. case 'contains':
  528. $op = 'CONTAINS';
  529. break;
  530. case 'starts':
  531. $op = 'STARTS WITH';
  532. break;
  533. default:
  534. $op = '=';
  535. }
  536. // We pass in the $column_name as an identifier for any sub fields
  537. // that are present for the fields.
  538. $query->fieldCondition($field_name, $column_name, $value, $op);
  539. }
  540. }
  541. // Perform the query just as a count first to get the number of records.
  542. $cquery = clone $query;
  543. $cquery->count();
  544. $num_records = $cquery->execute();
  545. if (!$num_records) {
  546. $num_records = 0;
  547. }
  548. // Add in the pager to the response.
  549. $response['totalItems'] = $num_records;
  550. $limit = array_key_exists('limit', $this->params) ? $this->params['limit'] : 25;
  551. $total_pages = ceil($num_records / $limit);
  552. $page = array_key_exists('page', $this->params) ? $this->params['page'] : 1;
  553. // Set the query order
  554. $order_keys = array_keys($order);
  555. for($i = 0; $i < count($order_keys); $i++) {
  556. $query->fieldOrderBy($order_keys[$i], $order[$order_keys[$i]], $order_dir[$i]);
  557. }
  558. // Set the query range
  559. $start = ($page - 1) * $limit;
  560. $query->range($start, $limit);
  561. // Now perform the query.
  562. $results = $query->execute();
  563. $this->resource->initPager($num_records, $limit, $page);
  564. // Iterate through the entities and add them to the list.
  565. foreach ($results['TripalEntity'] as $entity_id => $stub) {
  566. // We don't need all of the attached fields for an entity so, we'll
  567. // not use the entity_load() function. Instead just pull it from the
  568. // database table.
  569. $query = db_select('tripal_entity', 'TE');
  570. $query->join('tripal_term', 'TT', 'TE.term_id = TT.id');
  571. $query->fields('TE');
  572. $query->fields('TT', array('name'));
  573. $query->condition('TE.id', $entity_id);
  574. $entity = $query->execute()->fetchObject();
  575. $itemPage = tripal_get_term_details('schema', 'ItemPage');
  576. $label = tripal_get_term_details('rdfs', 'label');
  577. $member = new TripalWebServiceResource($service_path);
  578. $member->addContextItem('label', $label['url']);
  579. $member->addContextItem('ItemPage', $itemPage['url']);
  580. $member->addContextItem($term->name, $term->url);
  581. $member->setID($entity->id);
  582. $member->setType($term->name);
  583. $member->addProperty('label', $entity->title);
  584. $member->addProperty('ItemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  585. $this->resource->addMember($member);
  586. }
  587. }
  588. /**
  589. * Creates a resources that contains the list of content types.
  590. */
  591. private function doAllTypesList() {
  592. $service_path = $this->getServicePath();
  593. $label = tripal_get_term_details('rdfs', 'label');
  594. $this->resource = new TripalWebServiceCollection($service_path);
  595. $this->resource->addContextItem('label', $label['url']);
  596. $this->resource->addProperty('label', 'Content Types');
  597. // Get the list of published terms (these are the bundle IDs)
  598. $bundles = db_select('tripal_bundle', 'tb')
  599. ->fields('tb')
  600. ->orderBy('tb.label', 'ASC')
  601. ->execute();
  602. // Iterate through the terms and add an entry in the collection.
  603. $i = 0;
  604. while ($bundle = $bundles->fetchObject()) {
  605. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  606. $term = reset($entity);
  607. $vocab = $term->vocab;
  608. // Get the bundle description. If no description is provided then
  609. // use the term definition
  610. $description = tripal_get_bundle_variable('description', $bundle->id);
  611. if (!$description) {
  612. $description = $term->definition;
  613. }
  614. $member = new TripalWebServiceResource($service_path);
  615. $member->addContextItem($term->name, $term->url);
  616. $member->addContextItem('label', $label['url']);
  617. $member->addContextItem('description', 'hydra:description');
  618. $member->setID(urlencode($bundle->label));
  619. $member->setType($term->name);
  620. $member->addProperty('label', $bundle->label);
  621. $member->addProperty('description', $description);
  622. $this->resource->addMember($member);
  623. }
  624. }
  625. /**
  626. * @see TripalWebService::getSupportedClasses()
  627. */
  628. public function getSupportedClasses() {
  629. global $user;
  630. // An array of TripalWebServiceResources containing a
  631. // description of the supported classes.
  632. $supported_classes = array();
  633. // Get the list of published terms (these are the bundle IDs)
  634. $bundles = db_select('tripal_bundle', 'tb')
  635. ->fields('tb')
  636. ->orderBy('tb.label', 'ASC')
  637. ->execute();
  638. // Iterate through the terms and add an entry in the collection.
  639. $i = 0;
  640. while ($bundle = $bundles->fetchObject()) {
  641. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  642. $term = reset($entity);
  643. $vocab = $term->vocab;
  644. // Get the bundle description. If no description is provided then
  645. // use the term definition
  646. $description = tripal_get_bundle_variable('description', $bundle->id);
  647. if (!$description) {
  648. $description = $term->definition;
  649. }
  650. $supported = new TripalWebServiceResource($this->getServicePath());
  651. $supported->addContextItem('supportedOperation', 'hydra:supportedOperation');
  652. $supported->addContextItem('supportedProperty', 'hydra:supportedProperty');
  653. $supported->setID(urlencode($bundle->label));
  654. $supported->setType('hydra:Class');
  655. $supported->addProperty('hydra:title', $bundle->label);
  656. $supported->addProperty('hydra:description', $description);
  657. // Add in the supported operations for this content type.
  658. $operations = array();
  659. // If the user can view this content type.
  660. if (user_access('view ' . $bundle->name)) {
  661. // All content types allow GET (if the user has view permission).
  662. $get_op = new TripalWebServiceResource($this->getServicePath());
  663. $get_op->addContextItem('supportedOperation', 'hydra:supportedOperation');
  664. $get_op->addContextItem('method', 'hydra:method');
  665. $get_op->addContextItem('statusCodes', 'hydra:statusCodes');
  666. $get_op->addContextItem('label', 'rdfs:label');
  667. $get_op->addContextItem('description', 'rdfs:comment');
  668. $get_op->addContextItem('expects', array(
  669. "@id" => "hydra:expects",
  670. "@type" => "@id"
  671. ));
  672. $get_op->addContextItem('returns', array(
  673. "@id" => "hydra:returns",
  674. "@type" => "@id"
  675. ));
  676. $get_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_retrieve');
  677. $get_op->setType('hydra:Operation');
  678. $get_op->addProperty('method', 'GET');
  679. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  680. $get_op->addProperty('label', "Retrieves an " . $bundle->label . " entity.");
  681. }
  682. else {
  683. $get_op->addProperty('label', "Retrieves a " . $bundle->label . " entity.");
  684. }
  685. $get_op->addProperty('description', NULL);
  686. $get_op->addProperty('expects', NULL);
  687. $get_op->addProperty('returns', $term->url);
  688. $get_op->addProperty('statusCodes', array(
  689. array(
  690. 'code' => 404,
  691. 'description' => 'The ' . $bundle->label . ' could not be found using the provided ID.'
  692. ),
  693. ));
  694. $operations[] = $get_op;
  695. }
  696. // If the user can create this content type.
  697. if (user_access('create ' . $bundle->name)) {
  698. // All content types allow GET (if the user has view permission).
  699. $create_op = new TripalWebServiceResource($this->getServicePath());
  700. $create_op->addContextItem('method', 'hydra:method');
  701. $create_op->addContextItem('statusCodes', 'hydra:statusCodes');
  702. $create_op->addContextItem('label', 'rdfs:label');
  703. $create_op->addContextItem('description', 'rdfs:comment');
  704. $create_op->addContextItem('code', 'hydra:statusCode');
  705. $create_op->addContextItem('expects', array(
  706. "@id" => "hydra:expects",
  707. "@type" => "@id"
  708. ));
  709. $create_op->addContextItem('returns', array(
  710. "@id" => "hydra:returns",
  711. "@type" => "@id"
  712. ));
  713. $create_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_create');
  714. $create_op->setType('http://schema.org/CreateAction');
  715. $create_op->addProperty('method', 'POST');
  716. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  717. $create_op->addProperty('label', "Creates an " . $bundle->label . " entity.");
  718. }
  719. else {
  720. $create_op->addProperty('label', "Creates a " . $bundle->label . " entity.");
  721. }
  722. $create_op->addProperty('description', NULL);
  723. $create_op->addProperty('expects', $term->url);
  724. $create_op->addProperty('returns', $term->url);
  725. $create_op->addProperty('statusCodes', array(
  726. array(
  727. 'code' => 404,
  728. 'description' => 'The ' . $bundle->label . ' could not be created.'
  729. ),
  730. array(
  731. 'code' => 409,
  732. 'description' => 'The ' . $bundle->label . ' already exists.'
  733. ),
  734. ));
  735. $operations[] = $create_op;
  736. }
  737. // If the user can edit this content type.
  738. if (user_access('edit ' . $bundle->name)) {
  739. // All content types allow GET (if the user has view permission).
  740. $edit_op = new TripalWebServiceResource($this->getServicePath());
  741. $edit_op->addContextItem('method', 'hydra:method');
  742. $edit_op->addContextItem('statusCodes', 'hydra:statusCodes');
  743. $edit_op->addContextItem('label', 'rdfs:label');
  744. $edit_op->addContextItem('description', 'rdfs:comment');
  745. $edit_op->addContextItem('code', 'hydra:statusCode');
  746. $edit_op->addContextItem('expects', array(
  747. "@id" => "hydra:expects",
  748. "@type" => "@id"
  749. ));
  750. $edit_op->addContextItem('returns', array(
  751. "@id" => "hydra:returns",
  752. "@type" => "@id"
  753. ));
  754. $edit_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_update');
  755. $edit_op->setType('http://schema.org/UpdateAction');
  756. $edit_op->addProperty('method', 'PUT');
  757. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  758. $edit_op->addProperty('label', "Update and replace an " . $bundle->label . " entity.");
  759. }
  760. else {
  761. $edit_op->addProperty('label', "Update and replace a " . $bundle->label . " entity.");
  762. }
  763. $edit_op->addProperty('description', NULL);
  764. $edit_op->addProperty('expects', $term->url);
  765. $edit_op->addProperty('returns', $term->url);
  766. $edit_op->addProperty('statusCodes', array(
  767. array(
  768. 'code' => 404,
  769. 'description' => 'The ' . $bundle->label . ' could not be updated using the provided ID.'
  770. ),
  771. ));
  772. $operations[] = $edit_op;
  773. }
  774. // If the user can edit this content type.
  775. if (user_access('delete ' . $bundle->name)) {
  776. // All content types allow GET (if the user has view permission).
  777. $delete_op = new TripalWebServiceResource($this->getServicePath());
  778. $delete_op->addContextItem('method', 'hydra:method');
  779. $delete_op->addContextItem('statusCodes', 'hydra:statusCodes');
  780. $delete_op->addContextItem('label', 'rdfs:label');
  781. $delete_op->addContextItem('description', 'rdfs:comment');
  782. $delete_op->addContextItem('code', 'hydra:statusCode');
  783. $delete_op->addContextItem('expects', array(
  784. "@id" => "hydra:expects",
  785. "@type" => "@id"
  786. ));
  787. $delete_op->addContextItem('returns', array(
  788. "@id" => "hydra:returns",
  789. "@type" => "@id"
  790. ));
  791. $delete_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_delete');
  792. $delete_op->setType('http://schema.org/DeleteAction');
  793. $delete_op->addProperty('method', 'DELETE');
  794. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  795. $delete_op->addProperty('label', "Deletes an " . $bundle->label . " entity.");
  796. }
  797. else {
  798. $delete_op->addProperty('label', "Deletes a " . $bundle->label . " entity.");
  799. }
  800. $delete_op->addProperty('description', NULL);
  801. $delete_op->addProperty('expects', $term->url);
  802. $delete_op->addProperty('returns', $term->url);
  803. $delete_op->addProperty('statusCodes', array(
  804. array(
  805. 'code' => 404,
  806. 'description' => 'The ' . $bundle->label . ' could not be deleted using the provided ID.'
  807. ),
  808. ));
  809. $operations[] = $delete_op;
  810. }
  811. $supported->addProperty('supportedOperation', $operations);
  812. $supported_classes[] = $supported;
  813. }
  814. return $supported_classes;
  815. }
  816. }