TripalEntityService_v0_1.inc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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), $this->params);
  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. * A helper function to make it easy to map between keys and their fields.
  372. *
  373. * @bundle
  374. * The bundle object. Fields attached to this bundle will be included
  375. * in the mapping array.
  376. * @return
  377. * An associative arrray that maps web servcies keys to fields and
  378. * fields to web services keys (reciprocol).
  379. */
  380. private function getFieldMapping($bundle) {
  381. // Iterate through the fields and create a $field_mapping array that makes
  382. // it easier to determine which filter criteria belongs to which field. The
  383. // key is the label for the field and the value is the field name. This way
  384. // user's can use the field label or the field name to form a query.
  385. $field_mapping = array();
  386. $fields = field_info_fields();
  387. foreach ($fields as $field) {
  388. if (array_key_exists('TripalEntity', $field['bundles'])) {
  389. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  390. if ($bundle_name == $bundle->name) {
  391. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  392. if (array_key_exists('term_accession', $instance['settings'])){
  393. $vocabulary = $instance['settings']['term_vocabulary'];
  394. $accession = $instance['settings']['term_accession'];
  395. $fterm = tripal_get_term_details($vocabulary, $accession);
  396. $key = $fterm['name'];
  397. $key = strtolower(preg_replace('/ /', '_', $key));
  398. $field_mapping[$key] = $field['field_name'];
  399. $field_mapping[$field['field_name']] = $field['field_name'];
  400. }
  401. }
  402. }
  403. }
  404. }
  405. return $field_mapping;
  406. }
  407. /**
  408. * Gets any order by statements provided by the user.
  409. *
  410. * @field_mapping
  411. * An array that maps WS keys to field names. As provided by the
  412. * getFieldMapping() function.
  413. * @return
  414. * An array of fields for ordering.
  415. *
  416. * @throws Exception
  417. */
  418. private function getOrderBy($field_mapping, $bundle) {
  419. $order_by = array();
  420. // Handle order separately.
  421. if (array_key_exists('order', $this->params)) {
  422. $order_params = $this->params['order'];
  423. $dir = 'ASC';
  424. // If the user provided more than one order statement then those are
  425. // separated by a semicolong.
  426. $items = explode(';', $order_params);
  427. foreach ($items as $key) {
  428. // The user can provide a direction by separating the field key and the
  429. // direction with a '|' character.
  430. $matches = array();
  431. if (preg_match('/^(.*)\|(.*)$/', $key, $matches)) {
  432. $key = $matches[1];
  433. if ($matches[2] == 'ASC' or $matches[2] == 'DESC') {
  434. $dir = $matches[2];
  435. }
  436. else {
  437. throw new Exception('Please provide "ASC" or "DESC" for the ordering direction');
  438. }
  439. }
  440. // Break apart any subkeys and pull the first one as this is the parent
  441. // field.
  442. $subkeys = explode(',', $key);
  443. if (count($subkeys) > 0) {
  444. $key = $subkeys[0];
  445. }
  446. if (array_key_exists($key, $field_mapping)) {
  447. $key_field_name = $field_mapping[$key];
  448. $key_field = field_info_field($key_field_name);
  449. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  450. // Complex fields provied by the TripalField class may have sub
  451. // elements that support filtering. We need to see if the user
  452. // wants to filter on those.
  453. $field_class = $key_field['type'];
  454. if (tripal_load_include_field_class($field_class)) {
  455. // To find out which fields are sortable we'll call the
  456. // webServicesData() function.
  457. $key_field = new $field_class($key_field, $key_instance);
  458. $ws_data = $key_field->webServicesData();
  459. $sortable_keys = $ws_data['sortable'];
  460. $criteria = implode('.', $subkeys);
  461. if (array_key_exists($criteria, $sortable_keys)) {
  462. $order_by[$key_field_name][] = array(
  463. 'column' => $sortable_keys[$criteria],
  464. 'dir' => $dir,
  465. );
  466. }
  467. else {
  468. throw new Exception("The value, '$criteria', is not available for sorting.");
  469. }
  470. }
  471. // If this field is not a TripalField then it should just have
  472. // a simple value and we can query for that.
  473. else {
  474. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  475. $order_by[$key_field_name][] = array(
  476. 'column' => $key_field_id,
  477. 'dir' => $dir,
  478. );
  479. }
  480. }
  481. else {
  482. throw new Exception("The value, '$key', is not available for sorting.");
  483. }
  484. }
  485. }
  486. // If there is no ordering that is set then set a default order.
  487. if (count(array_keys($order_by)) == 0) {
  488. $key_field_names = array();
  489. if (in_array('data__identifier', $field_mapping)) {
  490. $key_field_names['data__identifier'][] = 'identifier';
  491. }
  492. else if (in_array('schema__name', $field_mapping)) {
  493. $key_field_names['schema__name'][] = 'name';
  494. }
  495. else if (in_array('rdfs_label', $field_mapping)) {
  496. $key_field_names['rdfs_label'][] = 'label';
  497. }
  498. else if (in_array('taxrank__genus', $field_mapping)) {
  499. $key_field_names['taxrank__genus'][] = 'genus';
  500. $key_field_names['taxrank__species'][] = 'species';
  501. }
  502. foreach ($key_field_names as $key_field_name => $criteria) {
  503. $key_field = field_info_field($key_field_name);
  504. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  505. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  506. $field_class = $key_field['type'];
  507. if (tripal_load_include_field_class($field_class)) {
  508. // To find out which fields are sortable we'll call the
  509. // webServicesData() function.
  510. $key_field = new $field_class($key_field, $key_instance);
  511. $ws_data = $key_field->webServicesData();
  512. $sortable_keys = $ws_data['sortable'];
  513. if (array_key_exists($criteria, $sortable_keys)) {
  514. $order_by[$key_field_name][] = array(
  515. 'column' => $sortable_keys[$criteria],
  516. 'dir' => $dir,
  517. );
  518. }
  519. }
  520. // If this field is not a TripalField then it should just have
  521. // a simple value and we can query for that.
  522. else {
  523. $order_by[$key_field_name][] = array(
  524. 'column' => $key_field_id,
  525. 'dir' => 'ASC',
  526. );
  527. }
  528. }
  529. }
  530. return $order_by;
  531. }
  532. /**
  533. * Gets any filter by statements provided by the user.
  534. *
  535. * @field_mapping
  536. * An array that maps WS keys to field names. As provided by the
  537. * getFieldMapping() function.
  538. *
  539. * @return
  540. * An array of fields for filtering.
  541. *
  542. * @throws Exception
  543. */
  544. private function getFilters($field_mapping, $bundle) {
  545. $filters = array();
  546. // Iterate through the paramter list provided by user.
  547. foreach ($this->params as $param => $value) {
  548. // Ignore non filter parameters.
  549. if ($param == 'page' or $param == 'limit') {
  550. continue;
  551. }
  552. // Ignore the order parameter as that is handled by the getOrderBy()
  553. // function
  554. if ($param == 'order') {
  555. continue;
  556. }
  557. // Break apart any operators
  558. $key = $param;
  559. $op = '=';
  560. $matches = array();
  561. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  562. $key = $matches[1];
  563. $op = $matches[2];
  564. }
  565. // Break apart any subkeys and pull the first one as this is the parent
  566. // field.
  567. $subkeys = explode(',', $key);
  568. if (count($subkeys) > 0) {
  569. $key = $subkeys[0];
  570. }
  571. // Map the values in the filters to their appropriate field names.
  572. if (array_key_exists($key, $field_mapping)) {
  573. $key_field_name = $field_mapping[$key];
  574. $key_field = field_info_field($key_field_name);
  575. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  576. // Complex fields provied by the TripalField class may have sub
  577. // elements that support filtering. We need to see if the user
  578. // wants to filter on those.
  579. $field_class = $key_field['type'];
  580. if (tripal_load_include_field_class($field_class)) {
  581. // To find out which fields are searchable we'll call the wsData()
  582. // function.
  583. $key_field = new $field_class($key_field, $key_instance);
  584. $ws_data = $key_field->webServicesData();
  585. $searchable_keys = $ws_data['searchable'];
  586. $criteria = implode('.', $subkeys);
  587. if (array_key_exists($criteria, $searchable_keys)) {
  588. $filters[$key_field_name][] = array(
  589. 'value' => $value,
  590. 'op' => $op,
  591. 'column' => $searchable_keys[$criteria]
  592. );
  593. }
  594. else {
  595. throw new Exception("The filter term, '$criteria', is not available for use.");
  596. }
  597. }
  598. // If this field is not a TripalField then it should just have
  599. // a simple value and we can query for that.
  600. else {
  601. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  602. $filters[$key_field_name][] = array(
  603. 'value' => $value,
  604. 'op' => $op,
  605. 'column' => $key_field_id,
  606. );
  607. }
  608. }
  609. else {
  610. throw new Exception("The filter term, '$key', is not available for use.");
  611. }
  612. }
  613. // Now convert the operation for each filter to one that is compatible
  614. // with TripalFieldQuery.
  615. foreach ($filters as $key_field_name => $key_filters) {
  616. foreach ($key_filters as $i => $filter) {
  617. $op = '=';
  618. switch ($filters[$key_field_name][$i]['op']) {
  619. case 'eq':
  620. $op = '=';
  621. break;
  622. case 'gt':
  623. $op = '>';
  624. break;
  625. case 'gte':
  626. $op = '>=';
  627. break;
  628. case 'lt':
  629. $op = '<';
  630. break;
  631. case 'lte':
  632. $op = '<=';
  633. break;
  634. case 'ne':
  635. $op = '<>';
  636. break;
  637. case 'contains':
  638. $op = 'CONTAINS';
  639. break;
  640. case 'starts':
  641. $op = 'STARTS WITH';
  642. break;
  643. default:
  644. $op = '=';
  645. }
  646. $filters[$key_field_name][$i]['op'] = $op;
  647. }
  648. }
  649. return $filters;
  650. }
  651. /**
  652. * Creates a collection of resources for a given type.
  653. */
  654. private function doContentTypeList($ctype) {
  655. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  656. $label = tripal_get_term_details('rdfs', 'label');
  657. $this->resource = new TripalWebServiceCollection($service_path, $this->params);
  658. $this->resource->addContextItem('label', $label['url']);
  659. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  660. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  661. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  662. $term = reset($term);
  663. // Set the label for this collection.
  664. $this->resource->addProperty('label', $bundle->label . " collection");
  665. // For quick lookup, get the mapping of WS keys to their appropriate fields.
  666. $field_mapping = $this->getFieldMapping($bundle);
  667. // Get arrays for filters and order by statements.
  668. $filters = $this->getFilters($field_mapping, $bundle);
  669. $order_by = $this->getOrderBy($field_mapping, $bundle);
  670. // Initialize the query to search for records for out bundle type
  671. // that are published.
  672. $query = new TripalFieldQuery();
  673. $query->entityCondition('entity_type', 'TripalEntity');
  674. $query->entityCondition('bundle', $bundle->name);
  675. $query->propertyCondition('status', 1);
  676. // Now iterate through the filters and add those.
  677. foreach ($filters as $key_field_name => $key_filters) {
  678. foreach ($key_filters as $i => $filter) {
  679. $column_name = $filter['column'];
  680. $value = $filter['value'];
  681. $op = $filter['op'];
  682. $query->fieldCondition($key_field_name, $column_name, $value, $op);
  683. }
  684. }
  685. // Now set the order by.
  686. foreach ($order_by as $key_field_name => $key_order) {
  687. foreach ($key_order as $i => $order) {
  688. $column_name = $order['column'];
  689. $dir = $order['dir'];
  690. $query->fieldOrderBy($key_field_name, $column_name, $dir);
  691. }
  692. }
  693. // Perform the query just as a count first to get the number of records.
  694. $cquery = clone $query;
  695. $cquery->count();
  696. $num_records = $cquery->execute();
  697. if (!$num_records) {
  698. $num_records = 0;
  699. }
  700. // Add in the pager to the response.
  701. $response['totalItems'] = $num_records;
  702. $limit = array_key_exists('limit', $this->params) ? $this->params['limit'] : 25;
  703. $total_pages = ceil($num_records / $limit);
  704. $page = array_key_exists('page', $this->params) ? $this->params['page'] : 1;
  705. // Set the query range
  706. $start = ($page - 1) * $limit;
  707. $query->range($start, $limit);
  708. // Now perform the query.
  709. $results = $query->execute();
  710. $this->resource->initPager($num_records, $limit, $page);
  711. // Iterate through the entities and add them to the output list.
  712. foreach ($results['TripalEntity'] as $entity_id => $stub) {
  713. // We don't need all of the attached fields for an entity so, we'll
  714. // not use the entity_load() function. Instead just pull it from the
  715. // database table.
  716. $query = db_select('tripal_entity', 'TE');
  717. $query->join('tripal_term', 'TT', 'TE.term_id = TT.id');
  718. $query->fields('TE');
  719. $query->fields('TT', array('name'));
  720. $query->condition('TE.id', $entity_id);
  721. $entity = $query->execute()->fetchObject();
  722. $itemPage = tripal_get_term_details('schema', 'ItemPage');
  723. $label = tripal_get_term_details('rdfs', 'label');
  724. $member = new TripalWebServiceResource($service_path);
  725. $member->addContextItem('label', $label['url']);
  726. $member->addContextItem('ItemPage', $itemPage['url']);
  727. $member->addContextItem($term->name, $term->url);
  728. $member->setID($entity->id);
  729. $member->setType($term->name);
  730. $member->addProperty('label', $entity->title);
  731. $member->addProperty('ItemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  732. $this->resource->addMember($member);
  733. }
  734. }
  735. /**
  736. * Creates a resources that contains the list of content types.
  737. */
  738. private function doAllTypesList() {
  739. $service_path = $this->getServicePath();
  740. $label = tripal_get_term_details('rdfs', 'label');
  741. $this->resource = new TripalWebServiceCollection($service_path, $this->params);
  742. $this->resource->addContextItem('label', $label['url']);
  743. $this->resource->addProperty('label', 'Content Types');
  744. // Get the list of published terms (these are the bundle IDs)
  745. $bundles = db_select('tripal_bundle', 'tb')
  746. ->fields('tb')
  747. ->orderBy('tb.label', 'ASC')
  748. ->execute();
  749. // Iterate through the terms and add an entry in the collection.
  750. $i = 0;
  751. while ($bundle = $bundles->fetchObject()) {
  752. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  753. $term = reset($entity);
  754. $vocab = $term->vocab;
  755. $member = new TripalWebServiceResource($service_path);
  756. // If the term has no URL then we'll default to using thie site's
  757. // term lookup service.
  758. $url = $term->url;
  759. if (!$url) {
  760. $url = url('cv/lookup/' . $term->vocab->vocabulary . '/' . $term->accession , array('absolute' => TRUE));
  761. }
  762. $member->addContextItem($term->name, $url);
  763. $member->addContextItem('label', $label['url']);
  764. $member->addProperty('label', $bundle->label);
  765. $member->addContextItem('description', 'hydra:description');
  766. // Get the bundle description. If no description is provided then
  767. // use the term definition
  768. $description = tripal_get_bundle_variable('description', $bundle->id);
  769. if (!$description) {
  770. $description = $term->definition;
  771. }
  772. if (!$description) {
  773. $description = '';
  774. }
  775. $member->addProperty('description', $description);
  776. $member->setID(urlencode($bundle->label));
  777. $member->setType($term->name);
  778. $this->resource->addMember($member);
  779. }
  780. }
  781. /**
  782. * @see TripalWebService::getSupportedClasses()
  783. */
  784. public function getSupportedClasses() {
  785. global $user;
  786. // An array of TripalWebServiceResources containing a
  787. // description of the supported classes.
  788. $supported_classes = array();
  789. // Get the list of published terms (these are the bundle IDs)
  790. $bundles = db_select('tripal_bundle', 'tb')
  791. ->fields('tb')
  792. ->orderBy('tb.label', 'ASC')
  793. ->execute();
  794. // Iterate through the terms and add an entry in the collection.
  795. $i = 0;
  796. while ($bundle = $bundles->fetchObject()) {
  797. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  798. $term = reset($entity);
  799. $vocab = $term->vocab;
  800. // Get the bundle description. If no description is provided then
  801. // use the term definition
  802. $description = tripal_get_bundle_variable('description', $bundle->id);
  803. if (!$description) {
  804. $description = $term->definition;
  805. }
  806. $supported = new TripalWebServiceResource($this->getServicePath());
  807. $supported->addContextItem('supportedOperation', 'hydra:supportedOperation');
  808. $supported->addContextItem('supportedProperty', 'hydra:supportedProperty');
  809. $supported->setID(urlencode($bundle->label));
  810. $supported->setType('hydra:Class');
  811. $supported->addProperty('hydra:title', $bundle->label);
  812. $supported->addProperty('hydra:description', $description);
  813. // Add in the supported operations for this content type.
  814. $operations = array();
  815. // If the user can view this content type.
  816. if (user_access('view ' . $bundle->name)) {
  817. // All content types allow GET (if the user has view permission).
  818. $get_op = new TripalWebServiceResource($this->getServicePath());
  819. $get_op->addContextItem('supportedOperation', 'hydra:supportedOperation');
  820. $get_op->addContextItem('method', 'hydra:method');
  821. $get_op->addContextItem('statusCodes', 'hydra:statusCodes');
  822. $get_op->addContextItem('label', 'rdfs:label');
  823. $get_op->addContextItem('description', 'rdfs:comment');
  824. $get_op->addContextItem('expects', array(
  825. "@id" => "hydra:expects",
  826. "@type" => "@id"
  827. ));
  828. $get_op->addContextItem('returns', array(
  829. "@id" => "hydra:returns",
  830. "@type" => "@id"
  831. ));
  832. $get_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_retrieve');
  833. $get_op->setType('hydra:Operation');
  834. $get_op->addProperty('method', 'GET');
  835. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  836. $get_op->addProperty('label', "Retrieves an " . $bundle->label . " entity.");
  837. }
  838. else {
  839. $get_op->addProperty('label', "Retrieves a " . $bundle->label . " entity.");
  840. }
  841. $get_op->addProperty('description', NULL);
  842. $get_op->addProperty('expects', NULL);
  843. $get_op->addProperty('returns', $term->url);
  844. $get_op->addProperty('statusCodes', array(
  845. array(
  846. 'code' => 404,
  847. 'description' => 'The ' . $bundle->label . ' could not be found using the provided ID.'
  848. ),
  849. ));
  850. $operations[] = $get_op;
  851. }
  852. // If the user can create this content type.
  853. if (user_access('create ' . $bundle->name)) {
  854. // All content types allow GET (if the user has view permission).
  855. $create_op = new TripalWebServiceResource($this->getServicePath());
  856. $create_op->addContextItem('method', 'hydra:method');
  857. $create_op->addContextItem('statusCodes', 'hydra:statusCodes');
  858. $create_op->addContextItem('label', 'rdfs:label');
  859. $create_op->addContextItem('description', 'rdfs:comment');
  860. $create_op->addContextItem('code', 'hydra:statusCode');
  861. $create_op->addContextItem('expects', array(
  862. "@id" => "hydra:expects",
  863. "@type" => "@id"
  864. ));
  865. $create_op->addContextItem('returns', array(
  866. "@id" => "hydra:returns",
  867. "@type" => "@id"
  868. ));
  869. $create_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_create');
  870. $create_op->setType('http://schema.org/CreateAction');
  871. $create_op->addProperty('method', 'POST');
  872. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  873. $create_op->addProperty('label', "Creates an " . $bundle->label . " entity.");
  874. }
  875. else {
  876. $create_op->addProperty('label', "Creates a " . $bundle->label . " entity.");
  877. }
  878. $create_op->addProperty('description', NULL);
  879. $create_op->addProperty('expects', $term->url);
  880. $create_op->addProperty('returns', $term->url);
  881. $create_op->addProperty('statusCodes', array(
  882. array(
  883. 'code' => 404,
  884. 'description' => 'The ' . $bundle->label . ' could not be created.'
  885. ),
  886. array(
  887. 'code' => 409,
  888. 'description' => 'The ' . $bundle->label . ' already exists.'
  889. ),
  890. ));
  891. $operations[] = $create_op;
  892. }
  893. // If the user can edit this content type.
  894. if (user_access('edit ' . $bundle->name)) {
  895. // All content types allow GET (if the user has view permission).
  896. $edit_op = new TripalWebServiceResource($this->getServicePath());
  897. $edit_op->addContextItem('method', 'hydra:method');
  898. $edit_op->addContextItem('statusCodes', 'hydra:statusCodes');
  899. $edit_op->addContextItem('label', 'rdfs:label');
  900. $edit_op->addContextItem('description', 'rdfs:comment');
  901. $edit_op->addContextItem('code', 'hydra:statusCode');
  902. $edit_op->addContextItem('expects', array(
  903. "@id" => "hydra:expects",
  904. "@type" => "@id"
  905. ));
  906. $edit_op->addContextItem('returns', array(
  907. "@id" => "hydra:returns",
  908. "@type" => "@id"
  909. ));
  910. $edit_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_update');
  911. $edit_op->setType('http://schema.org/UpdateAction');
  912. $edit_op->addProperty('method', 'PUT');
  913. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  914. $edit_op->addProperty('label', "Update and replace an " . $bundle->label . " entity.");
  915. }
  916. else {
  917. $edit_op->addProperty('label', "Update and replace a " . $bundle->label . " entity.");
  918. }
  919. $edit_op->addProperty('description', NULL);
  920. $edit_op->addProperty('expects', $term->url);
  921. $edit_op->addProperty('returns', $term->url);
  922. $edit_op->addProperty('statusCodes', array(
  923. array(
  924. 'code' => 404,
  925. 'description' => 'The ' . $bundle->label . ' could not be updated using the provided ID.'
  926. ),
  927. ));
  928. $operations[] = $edit_op;
  929. }
  930. // If the user can edit this content type.
  931. if (user_access('delete ' . $bundle->name)) {
  932. // All content types allow GET (if the user has view permission).
  933. $delete_op = new TripalWebServiceResource($this->getServicePath());
  934. $delete_op->addContextItem('method', 'hydra:method');
  935. $delete_op->addContextItem('statusCodes', 'hydra:statusCodes');
  936. $delete_op->addContextItem('label', 'rdfs:label');
  937. $delete_op->addContextItem('description', 'rdfs:comment');
  938. $delete_op->addContextItem('code', 'hydra:statusCode');
  939. $delete_op->addContextItem('expects', array(
  940. "@id" => "hydra:expects",
  941. "@type" => "@id"
  942. ));
  943. $delete_op->addContextItem('returns', array(
  944. "@id" => "hydra:returns",
  945. "@type" => "@id"
  946. ));
  947. $delete_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_delete');
  948. $delete_op->setType('http://schema.org/DeleteAction');
  949. $delete_op->addProperty('method', 'DELETE');
  950. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  951. $delete_op->addProperty('label', "Deletes an " . $bundle->label . " entity.");
  952. }
  953. else {
  954. $delete_op->addProperty('label', "Deletes a " . $bundle->label . " entity.");
  955. }
  956. $delete_op->addProperty('description', NULL);
  957. $delete_op->addProperty('expects', $term->url);
  958. $delete_op->addProperty('returns', $term->url);
  959. $delete_op->addProperty('statusCodes', array(
  960. array(
  961. 'code' => 404,
  962. 'description' => 'The ' . $bundle->label . ' could not be deleted using the provided ID.'
  963. ),
  964. ));
  965. $operations[] = $delete_op;
  966. }
  967. $supported->addProperty('supportedOperation', $operations);
  968. $supported_classes[] = $supported;
  969. }
  970. return $supported_classes;
  971. }
  972. }