TripalEntityService_v0_1.inc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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);
  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. // Skip the remote__data field that is provided by the tripal_Ws
  185. // module.
  186. if ($field['type'] == 'remote__data') {
  187. continue;
  188. }
  189. // By default, the label for the key in the output should be the
  190. // term from the vocabulary that the field is assigned. But in the
  191. // case that the field is not assigned a term, we must use the field name.
  192. $field_name = $instance['field_name'];
  193. $vocabulary = $instance['settings']['term_vocabulary'];
  194. $accession = $instance['settings']['term_accession'];
  195. $term = tripal_get_term_details($vocabulary, $accession);
  196. if (!$term) {
  197. continue;
  198. }
  199. $key = $term['name'];
  200. $key_adj = strtolower(preg_replace('/ /', '_', $key));
  201. // If this field should not be attached by default then just add a link
  202. // so that the caller can get the information separately.
  203. $instance_settings = $instance['settings'];
  204. if (array_key_exists('auto_attach', $instance['settings']) and
  205. $instance_settings['auto_attach'] == FALSE) {
  206. // Add a URL only if there are values. If there are no values then
  207. // don't add a URL which would make the end-user think they can get
  208. // that information.
  209. $items = field_get_items('TripalEntity', $entity, $field_name);
  210. if ($items and count($items) > 0 and $items[0]['value']) {
  211. $this->resource->addContextItem($key_adj, $term['url']);
  212. $this->resource->addProperty($key_adj, $service_path . '/' . $entity->id . '/' . urlencode($term['name']));
  213. }
  214. else {
  215. if ($hide_fields == 'show') {
  216. $this->resource->addContextItem($key_adj, $term['url']);
  217. $this->resource->addProperty($key_adj, NULL);
  218. }
  219. }
  220. continue;
  221. }
  222. // Get the details for this field for the JSON-LD response.
  223. $this->addEntityField($key_adj, $term, $entity, $bundle, $field, $instance, $service_path);
  224. }
  225. }
  226. /**
  227. * Adds the field as a property of the entity resource.
  228. */
  229. private function addEntityField($key, $term, $entity, $bundle, $field, $instance,
  230. $service_path, $expfield = NULL) {
  231. // If the entity is set to hide fields that have no values then we
  232. // want to honor that in the web services too.
  233. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  234. // Get the field settings.
  235. $field_name = $field['field_name'];
  236. $field_settings = $field['settings'];
  237. $items = field_get_items('TripalEntity', $entity, $field_name);
  238. if (!$items) {
  239. return;
  240. }
  241. // Give modules the opportunity to edit values for web services. This hook
  242. // really should be used sparingly. Where it helps is with non Tripal fields
  243. // that are added to a TripalEntity content type and it doesn't follow
  244. // the rules (e.g. Image field).
  245. drupal_alter('tripal_ws_value', $items, $field, $instance);
  246. $values = array();
  247. for ($i = 0; $i < count($items); $i++) {
  248. $values[$i] = $this->sanitizeFieldKeys($items[$i]['value'], $bundle, $service_path);
  249. }
  250. if ($hide_fields == 'hide' and empty($values[0])) {
  251. return;
  252. }
  253. // If the field cardinality is 1
  254. if ($field['cardinality'] == 1) {
  255. // If the value is an array and this is the field page then all of those
  256. // key/value pairs should be added directly to the response.
  257. if (is_array($values[0])) {
  258. if ($expfield) {
  259. foreach ($values[0] as $k => $v) {
  260. $this->resource->addProperty($k, $v);
  261. }
  262. }
  263. else {
  264. $this->resource->addContextItem($key, $term['url']);
  265. $this->resource->addProperty($key, $values[0]);
  266. }
  267. }
  268. // If the value is not an array it's a scalar so add it as is to the
  269. // response.
  270. else {
  271. $this->resource->addContextItem($key, $term['url']);
  272. $this->resource->addProperty($key, $values[0]);
  273. }
  274. }
  275. // If the field cardinality is > 1
  276. if ($field['cardinality'] != 1) {
  277. // If this is the expanded field page then we need to swap out
  278. // the resource for a collection.
  279. $response = new TripalWebServiceCollection($service_path . '/' . urlencode($expfield), $this->params);
  280. $label = tripal_get_term_details('rdfs', 'label');
  281. $response->addContextItem('label', $label['url']);
  282. $response->addProperty('label', $instance['label']);
  283. $i = 0;
  284. foreach ($values as $delta => $element) {
  285. $member = new TripalWebServiceResource($service_path . '/' . urlencode($expfield));
  286. $member->setID($i);
  287. // Add the context of the parent resource because all of the keys
  288. // were santizied and set to match the proper context.
  289. $member->setContext($this->resource);
  290. $member->setType($key);
  291. foreach ($element as $key => $value) {
  292. $member->addProperty($key, $value);
  293. }
  294. $response->addMember($member);
  295. $i++;
  296. }
  297. if ($expfield) {
  298. $this->resource = $response;
  299. }
  300. else {
  301. $this->resource->addProperty($key, $response);
  302. }
  303. }
  304. }
  305. /**
  306. * Rewrites the keys of a field's items array for use with web services.
  307. */
  308. private function sanitizeFieldKeys($value, $bundle, $service_path) {
  309. // If the entity is set to hide fields that have no values then we
  310. // want to honor that in the web services too.
  311. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  312. $new_value = '';
  313. // If the value is an array rather than a scalar then map the sub elements
  314. // to controlled vocabulary terms.
  315. if (is_array($value)) {
  316. $temp = array();
  317. foreach ($value as $k => $v) {
  318. // exclude fields that have no values so we can hide them
  319. if (!isset($v) and $hide_fields == 'hide') {
  320. continue;
  321. }
  322. $matches = array();
  323. if (preg_match('/^(.+):(.+)$/', $k, $matches)) {
  324. $vocabulary = $matches[1];
  325. $accession = $matches[2];
  326. $term = tripal_get_term_details($vocabulary, $accession);
  327. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  328. if (is_array($v)) {
  329. $temp[$key_adj] = $this->sanitizeFieldKeys($v, $bundle, $service_path);
  330. }
  331. else {
  332. $temp[$key_adj] = $v;
  333. }
  334. $this->resource->addContextItem($key_adj, $term['url']);
  335. }
  336. else {
  337. // TODO: this is an error, if we get here then we have
  338. // a key that isn't using the proper format... what to do?
  339. }
  340. }
  341. $new_value = $temp;
  342. // Recurse through the values array and set the entity elements
  343. // and add the fields to the context.
  344. $this->sanitizeFieldEntity($new_value, $service_path);
  345. }
  346. else {
  347. $new_value = $value;
  348. }
  349. return $new_value;
  350. }
  351. /**
  352. * Rewrites any TripalEntity elements in the values array for use with WS.
  353. */
  354. private function sanitizeFieldEntity(&$items, $service_path) {
  355. if (!$items) {
  356. return;
  357. }
  358. foreach ($items as $key => $value) {
  359. if (is_array($value)) {
  360. $this->sanitizeFieldEntity($items[$key], $service_path);
  361. continue;
  362. }
  363. if ($key == 'entity') {
  364. list($item_etype, $item_eid) = explode(':', $items['entity']);
  365. if ($item_eid) {
  366. $item_entity = tripal_load_entity($item_etype, array($item_eid));
  367. $item_entity = reset($item_entity);
  368. $bundle = tripal_load_bundle_entity(array('name' => $item_entity->bundle));
  369. $items['@id'] = $this->getServicePath() . '/' . urlencode($bundle->label) . '/' . $item_eid;
  370. }
  371. unset($items['entity']);
  372. }
  373. }
  374. }
  375. /**
  376. * A helper function to make it easy to map between keys and their fields.
  377. *
  378. * @bundle
  379. * The bundle object. Fields attached to this bundle will be included
  380. * in the mapping array.
  381. * @return
  382. * An associative arrray that maps web servcies keys to fields and
  383. * fields to web services keys (reciprocol).
  384. */
  385. private function getFieldMapping($bundle) {
  386. // Iterate through the fields and create a $field_mapping array that makes
  387. // it easier to determine which filter criteria belongs to which field. The
  388. // key is the label for the field and the value is the field name. This way
  389. // user's can use the field label or the field name to form a query.
  390. $field_mapping = array();
  391. $fields = field_info_fields();
  392. foreach ($fields as $field) {
  393. if (array_key_exists('TripalEntity', $field['bundles'])) {
  394. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  395. if ($bundle_name == $bundle->name) {
  396. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  397. if (array_key_exists('term_accession', $instance['settings'])){
  398. $vocabulary = $instance['settings']['term_vocabulary'];
  399. $accession = $instance['settings']['term_accession'];
  400. $fterm = tripal_get_term_details($vocabulary, $accession);
  401. $key = $fterm['name'];
  402. $key = strtolower(preg_replace('/ /', '_', $key));
  403. $field_mapping[$key] = $field['field_name'];
  404. $field_mapping[$field['field_name']] = $field['field_name'];
  405. }
  406. }
  407. }
  408. }
  409. }
  410. return $field_mapping;
  411. }
  412. /**
  413. * Gets any order by statements provided by the user.
  414. *
  415. * @field_mapping
  416. * An array that maps WS keys to field names. As provided by the
  417. * getFieldMapping() function.
  418. * @return
  419. * An array of fields for ordering.
  420. *
  421. * @throws Exception
  422. */
  423. private function getOrderBy($field_mapping, $bundle) {
  424. $order_by = array();
  425. // Handle order separately.
  426. if (array_key_exists('order', $this->params)) {
  427. $order_params = $this->params['order'];
  428. $dir = 'ASC';
  429. // If the user provided more than one order statement then those are
  430. // separated by a semicolong.
  431. $items = explode(';', $order_params);
  432. foreach ($items as $key) {
  433. // The user can provide a direction by separating the field key and the
  434. // direction with a '|' character.
  435. $matches = array();
  436. if (preg_match('/^(.*)\|(.*)$/', $key, $matches)) {
  437. $key = $matches[1];
  438. if ($matches[2] == 'ASC' or $matches[2] == 'DESC') {
  439. $dir = $matches[2];
  440. }
  441. else {
  442. throw new Exception('Please provide "ASC" or "DESC" for the ordering direction');
  443. }
  444. }
  445. // Break apart any subkeys and pull the first one as this is the parent
  446. // field.
  447. $subkeys = explode(',', $key);
  448. if (count($subkeys) > 0) {
  449. $key = $subkeys[0];
  450. }
  451. if (array_key_exists($key, $field_mapping)) {
  452. $key_field_name = $field_mapping[$key];
  453. $key_field = field_info_field($key_field_name);
  454. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  455. // Complex fields provied by the TripalField class may have sub
  456. // elements that support filtering. We need to see if the user
  457. // wants to filter on those.
  458. $field_class = $key_field['type'];
  459. if (tripal_load_include_field_class($field_class)) {
  460. // To find out which fields are sortable we'll call the
  461. // webServicesData() function.
  462. $key_field = new $field_class($key_field, $key_instance);
  463. $ws_data = $key_field->webServicesData();
  464. $sortable_keys = $ws_data['sortable'];
  465. $criteria = implode('.', $subkeys);
  466. if (array_key_exists($criteria, $sortable_keys)) {
  467. $order_by[$key_field_name][] = array(
  468. 'column' => $sortable_keys[$criteria],
  469. 'dir' => $dir,
  470. );
  471. }
  472. else {
  473. throw new Exception("The value, '$criteria', is not available for sorting.");
  474. }
  475. }
  476. // If this field is not a TripalField then it should just have
  477. // a simple value and we can query for that.
  478. else {
  479. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  480. $order_by[$key_field_name][] = array(
  481. 'column' => $key_field_id,
  482. 'dir' => $dir,
  483. );
  484. }
  485. }
  486. else {
  487. throw new Exception("The value, '$key', is not available for sorting.");
  488. }
  489. }
  490. }
  491. // If there is no ordering that is set then set a default order.
  492. if (count(array_keys($order_by)) == 0) {
  493. $key_field_names = array();
  494. if (in_array('data__identifier', $field_mapping)) {
  495. $key_field_names['data__identifier'][] = 'identifier';
  496. }
  497. else if (in_array('schema__name', $field_mapping)) {
  498. $key_field_names['schema__name'][] = 'name';
  499. }
  500. else if (in_array('rdfs_label', $field_mapping)) {
  501. $key_field_names['rdfs_label'][] = 'label';
  502. }
  503. else if (in_array('taxrank__genus', $field_mapping)) {
  504. $key_field_names['taxrank__genus'][] = 'genus';
  505. $key_field_names['taxrank__species'][] = 'species';
  506. }
  507. foreach ($key_field_names as $key_field_name => $criteria) {
  508. $key_field = field_info_field($key_field_name);
  509. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  510. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  511. $field_class = $key_field['type'];
  512. if (tripal_load_include_field_class($field_class)) {
  513. // To find out which fields are sortable we'll call the
  514. // webServicesData() function.
  515. $key_field = new $field_class($key_field, $key_instance);
  516. $ws_data = $key_field->webServicesData();
  517. $sortable_keys = $ws_data['sortable'];
  518. if (array_key_exists($criteria, $sortable_keys)) {
  519. $order_by[$key_field_name][] = array(
  520. 'column' => $sortable_keys[$criteria],
  521. 'dir' => $dir,
  522. );
  523. }
  524. }
  525. // If this field is not a TripalField then it should just have
  526. // a simple value and we can query for that.
  527. else {
  528. $order_by[$key_field_name][] = array(
  529. 'column' => $key_field_id,
  530. 'dir' => 'ASC',
  531. );
  532. }
  533. }
  534. }
  535. return $order_by;
  536. }
  537. /**
  538. * Gets any filter by statements provided by the user.
  539. *
  540. * @field_mapping
  541. * An array that maps WS keys to field names. As provided by the
  542. * getFieldMapping() function.
  543. *
  544. * @return
  545. * An array of fields for filtering.
  546. *
  547. * @throws Exception
  548. */
  549. private function getFilters($field_mapping, $bundle) {
  550. $filters = array();
  551. // Iterate through the paramter list provided by user.
  552. foreach ($this->params as $param => $value) {
  553. // Ignore non filter parameters.
  554. if ($param == 'page' or $param == 'limit') {
  555. continue;
  556. }
  557. // Ignore the order parameter as that is handled by the getOrderBy()
  558. // function
  559. if ($param == 'order') {
  560. continue;
  561. }
  562. // Break apart any operators
  563. $key = $param;
  564. $op = '=';
  565. $matches = array();
  566. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  567. $key = $matches[1];
  568. $op = $matches[2];
  569. }
  570. // Break apart any subkeys and pull the first one as this is the parent
  571. // field.
  572. $subkeys = explode(',', $key);
  573. if (count($subkeys) > 0) {
  574. $key = $subkeys[0];
  575. }
  576. // Map the values in the filters to their appropriate field names.
  577. if (array_key_exists($key, $field_mapping)) {
  578. $key_field_name = $field_mapping[$key];
  579. $key_field = field_info_field($key_field_name);
  580. $key_instance = field_info_instance('TripalEntity', $key_field_name, $bundle->name);
  581. // Complex fields provied by the TripalField class may have sub
  582. // elements that support filtering. We need to see if the user
  583. // wants to filter on those.
  584. $field_class = $key_field['type'];
  585. if (tripal_load_include_field_class($field_class)) {
  586. // To find out which fields are searchable we'll call the wsData()
  587. // function.
  588. $key_field = new $field_class($key_field, $key_instance);
  589. $ws_data = $key_field->webServicesData();
  590. $searchable_keys = $ws_data['searchable'];
  591. $criteria = implode('.', $subkeys);
  592. if (array_key_exists($criteria, $searchable_keys)) {
  593. $filters[$key_field_name][] = array(
  594. 'value' => $value,
  595. 'op' => $op,
  596. 'column' => $searchable_keys[$criteria]
  597. );
  598. }
  599. else {
  600. throw new Exception("The filter term, '$criteria', is not available for use.");
  601. }
  602. }
  603. // If this field is not a TripalField then it should just have
  604. // a simple value and we can query for that.
  605. else {
  606. $key_field_id = $key_instance['settings']['term_vocabulary'] . ':' . $key_instance['settings']['term_accession'];
  607. $filters[$key_field_name][] = array(
  608. 'value' => $value,
  609. 'op' => $op,
  610. 'column' => $key_field_id,
  611. );
  612. }
  613. }
  614. else {
  615. throw new Exception("The filter term, '$key', is not available for use.");
  616. }
  617. }
  618. // Now convert the operation for each filter to one that is compatible
  619. // with TripalFieldQuery.
  620. foreach ($filters as $key_field_name => $key_filters) {
  621. foreach ($key_filters as $i => $filter) {
  622. $op = '=';
  623. switch ($filters[$key_field_name][$i]['op']) {
  624. case 'eq':
  625. $op = '=';
  626. break;
  627. case 'gt':
  628. $op = '>';
  629. break;
  630. case 'gte':
  631. $op = '>=';
  632. break;
  633. case 'lt':
  634. $op = '<';
  635. break;
  636. case 'lte':
  637. $op = '<=';
  638. break;
  639. case 'ne':
  640. $op = '<>';
  641. break;
  642. case 'contains':
  643. $op = 'CONTAINS';
  644. break;
  645. case 'starts':
  646. $op = 'STARTS WITH';
  647. break;
  648. default:
  649. $op = '=';
  650. }
  651. $filters[$key_field_name][$i]['op'] = $op;
  652. }
  653. }
  654. return $filters;
  655. }
  656. /**
  657. * Creates a collection of resources for a given type.
  658. */
  659. private function doContentTypeList($ctype) {
  660. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  661. $label = tripal_get_term_details('rdfs', 'label');
  662. $this->resource = new TripalWebServiceCollection($service_path, $this->params);
  663. $this->resource->addContextItem('label', $label['url']);
  664. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  665. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  666. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  667. $term = reset($term);
  668. // Set the label for this collection.
  669. $this->resource->addProperty('label', $bundle->label . " collection");
  670. // For quick lookup, get the mapping of WS keys to their appropriate fields.
  671. $field_mapping = $this->getFieldMapping($bundle);
  672. // Get arrays for filters and order by statements.
  673. $filters = $this->getFilters($field_mapping, $bundle);
  674. $order_by = $this->getOrderBy($field_mapping, $bundle);
  675. // Initialize the query to search for records for out bundle type
  676. // that are published.
  677. $query = new TripalFieldQuery();
  678. $query->entityCondition('entity_type', 'TripalEntity');
  679. $query->entityCondition('bundle', $bundle->name);
  680. $query->propertyCondition('status', 1);
  681. // Now iterate through the filters and add those.
  682. foreach ($filters as $key_field_name => $key_filters) {
  683. foreach ($key_filters as $i => $filter) {
  684. $column_name = $filter['column'];
  685. $value = $filter['value'];
  686. $op = $filter['op'];
  687. $query->fieldCondition($key_field_name, $column_name, $value, $op);
  688. }
  689. }
  690. // Now set the order by.
  691. foreach ($order_by as $key_field_name => $key_order) {
  692. foreach ($key_order as $i => $order) {
  693. $column_name = $order['column'];
  694. $dir = $order['dir'];
  695. $query->fieldOrderBy($key_field_name, $column_name, $dir);
  696. }
  697. }
  698. // Perform the query just as a count first to get the number of records.
  699. $cquery = clone $query;
  700. $cquery->count();
  701. $num_records = $cquery->execute();
  702. if (!$num_records) {
  703. $num_records = 0;
  704. }
  705. // Add in the pager to the response.
  706. $response['totalItems'] = $num_records;
  707. $limit = array_key_exists('limit', $this->params) ? $this->params['limit'] : 25;
  708. $total_pages = ceil($num_records / $limit);
  709. $page = array_key_exists('page', $this->params) ? $this->params['page'] : 1;
  710. // Set the query range
  711. $start = ($page - 1) * $limit;
  712. $query->range($start, $limit);
  713. // Now perform the query.
  714. $results = $query->execute();
  715. $this->resource->initPager($num_records, $limit, $page);
  716. // Check to make sure there are results.
  717. $entity_ids = array();
  718. if (isset($results['TripalEntity']) AND is_array($results['TripalEntity'])) {
  719. $entity_ids = $results['TripalEntity'];
  720. }
  721. // Iterate through the entities and add them to the output list.
  722. foreach ($entity_ids as $entity_id => $stub) {
  723. // We don't need all of the attached fields for an entity so, we'll
  724. // not use the entity_load() function. Instead just pull it from the
  725. // database table.
  726. $query = db_select('tripal_entity', 'TE');
  727. $query->join('tripal_term', 'TT', 'TE.term_id = TT.id');
  728. $query->fields('TE');
  729. $query->fields('TT', array('name'));
  730. $query->condition('TE.id', $entity_id);
  731. $entity = $query->execute()->fetchObject();
  732. $itemPage = tripal_get_term_details('schema', 'ItemPage');
  733. $label = tripal_get_term_details('rdfs', 'label');
  734. $member = new TripalWebServiceResource($service_path);
  735. $member->addContextItem('label', $label['url']);
  736. $member->addContextItem('ItemPage', $itemPage['url']);
  737. $member->addContextItem($term->name, $term->url);
  738. $member->setID($entity->id);
  739. $member->setType($term->name);
  740. $member->addProperty('label', $entity->title);
  741. $member->addProperty('ItemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  742. $this->resource->addMember($member);
  743. }
  744. }
  745. /**
  746. * Creates a resources that contains the list of content types.
  747. */
  748. private function doAllTypesList() {
  749. $service_path = $this->getServicePath();
  750. $label = tripal_get_term_details('rdfs', 'label');
  751. $this->resource = new TripalWebServiceCollection($service_path, $this->params);
  752. $this->resource->addContextItem('label', $label['url']);
  753. $this->resource->addProperty('label', 'Content Types');
  754. // Get the list of published terms (these are the bundle IDs)
  755. $bundles = db_select('tripal_bundle', 'tb')
  756. ->fields('tb')
  757. ->orderBy('tb.label', 'ASC')
  758. ->execute();
  759. // Iterate through the terms and add an entry in the collection.
  760. $i = 0;
  761. while ($bundle = $bundles->fetchObject()) {
  762. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  763. $term = reset($entity);
  764. $vocab = $term->vocab;
  765. $member = new TripalWebServiceResource($service_path);
  766. // If the term has no URL then we'll default to using thie site's
  767. // term lookup service.
  768. $url = $term->url;
  769. if (!$url) {
  770. $url = url('cv/lookup/' . $term->vocab->vocabulary . '/' . $term->accession , array('absolute' => TRUE));
  771. }
  772. $member->addContextItem($term->name, $url);
  773. $member->addContextItem('label', $label['url']);
  774. $member->addProperty('label', $bundle->label);
  775. $member->addContextItem('description', 'hydra:description');
  776. // Get the bundle description. If no description is provided then
  777. // use the term definition
  778. $description = tripal_get_bundle_variable('description', $bundle->id);
  779. if (!$description) {
  780. $description = $term->definition;
  781. }
  782. if (!$description) {
  783. $description = '';
  784. }
  785. $member->addProperty('description', $description);
  786. $member->setID(urlencode($bundle->label));
  787. $member->setType($term->name);
  788. $this->resource->addMember($member);
  789. }
  790. }
  791. /**
  792. * @see TripalWebService::getSupportedClasses()
  793. */
  794. public function getSupportedClasses() {
  795. global $user;
  796. // An array of TripalWebServiceResources containing a
  797. // description of the supported classes.
  798. $supported_classes = array();
  799. // Get the list of published terms (these are the bundle IDs)
  800. $bundles = db_select('tripal_bundle', 'tb')
  801. ->fields('tb')
  802. ->orderBy('tb.label', 'ASC')
  803. ->execute();
  804. // Iterate through the terms and add an entry in the collection.
  805. $i = 0;
  806. while ($bundle = $bundles->fetchObject()) {
  807. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  808. $term = reset($entity);
  809. $vocab = $term->vocab;
  810. // Get the bundle description. If no description is provided then
  811. // use the term definition
  812. $description = tripal_get_bundle_variable('description', $bundle->id);
  813. if (!$description) {
  814. $description = $term->definition;
  815. }
  816. $supported = new TripalWebServiceResource($this->getServicePath());
  817. $supported->addContextItem('supportedOperation', 'hydra:supportedOperation');
  818. $supported->addContextItem('supportedProperty', 'hydra:supportedProperty');
  819. $supported->setID(urlencode($bundle->label));
  820. $supported->setType('hydra:Class');
  821. $supported->addProperty('hydra:title', $bundle->label);
  822. $supported->addProperty('hydra:description', $description);
  823. // Add in the supported operations for this content type.
  824. $operations = array();
  825. // If the user can view this content type.
  826. if (user_access('view ' . $bundle->name)) {
  827. // All content types allow GET (if the user has view permission).
  828. $get_op = new TripalWebServiceResource($this->getServicePath());
  829. $get_op->addContextItem('supportedOperation', 'hydra:supportedOperation');
  830. $get_op->addContextItem('method', 'hydra:method');
  831. $get_op->addContextItem('statusCodes', 'hydra:statusCodes');
  832. $get_op->addContextItem('label', 'rdfs:label');
  833. $get_op->addContextItem('description', 'rdfs:comment');
  834. $get_op->addContextItem('expects', array(
  835. "@id" => "hydra:expects",
  836. "@type" => "@id"
  837. ));
  838. $get_op->addContextItem('returns', array(
  839. "@id" => "hydra:returns",
  840. "@type" => "@id"
  841. ));
  842. $get_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_retrieve');
  843. $get_op->setType('hydra:Operation');
  844. $get_op->addProperty('method', 'GET');
  845. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  846. $get_op->addProperty('label', "Retrieves an " . $bundle->label . " entity.");
  847. }
  848. else {
  849. $get_op->addProperty('label', "Retrieves a " . $bundle->label . " entity.");
  850. }
  851. $get_op->addProperty('description', NULL);
  852. $get_op->addProperty('expects', NULL);
  853. $get_op->addProperty('returns', $term->url);
  854. $get_op->addProperty('statusCodes', array(
  855. array(
  856. 'code' => 404,
  857. 'description' => 'The ' . $bundle->label . ' could not be found using the provided ID.'
  858. ),
  859. ));
  860. $operations[] = $get_op;
  861. }
  862. // If the user can create this content type.
  863. if (user_access('create ' . $bundle->name)) {
  864. // All content types allow GET (if the user has view permission).
  865. $create_op = new TripalWebServiceResource($this->getServicePath());
  866. $create_op->addContextItem('method', 'hydra:method');
  867. $create_op->addContextItem('statusCodes', 'hydra:statusCodes');
  868. $create_op->addContextItem('label', 'rdfs:label');
  869. $create_op->addContextItem('description', 'rdfs:comment');
  870. $create_op->addContextItem('code', 'hydra:statusCode');
  871. $create_op->addContextItem('expects', array(
  872. "@id" => "hydra:expects",
  873. "@type" => "@id"
  874. ));
  875. $create_op->addContextItem('returns', array(
  876. "@id" => "hydra:returns",
  877. "@type" => "@id"
  878. ));
  879. $create_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_create');
  880. $create_op->setType('http://schema.org/CreateAction');
  881. $create_op->addProperty('method', 'POST');
  882. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  883. $create_op->addProperty('label', "Creates an " . $bundle->label . " entity.");
  884. }
  885. else {
  886. $create_op->addProperty('label', "Creates a " . $bundle->label . " entity.");
  887. }
  888. $create_op->addProperty('description', NULL);
  889. $create_op->addProperty('expects', $term->url);
  890. $create_op->addProperty('returns', $term->url);
  891. $create_op->addProperty('statusCodes', array(
  892. array(
  893. 'code' => 404,
  894. 'description' => 'The ' . $bundle->label . ' could not be created.'
  895. ),
  896. array(
  897. 'code' => 409,
  898. 'description' => 'The ' . $bundle->label . ' already exists.'
  899. ),
  900. ));
  901. $operations[] = $create_op;
  902. }
  903. // If the user can edit this content type.
  904. if (user_access('edit ' . $bundle->name)) {
  905. // All content types allow GET (if the user has view permission).
  906. $edit_op = new TripalWebServiceResource($this->getServicePath());
  907. $edit_op->addContextItem('method', 'hydra:method');
  908. $edit_op->addContextItem('statusCodes', 'hydra:statusCodes');
  909. $edit_op->addContextItem('label', 'rdfs:label');
  910. $edit_op->addContextItem('description', 'rdfs:comment');
  911. $edit_op->addContextItem('code', 'hydra:statusCode');
  912. $edit_op->addContextItem('expects', array(
  913. "@id" => "hydra:expects",
  914. "@type" => "@id"
  915. ));
  916. $edit_op->addContextItem('returns', array(
  917. "@id" => "hydra:returns",
  918. "@type" => "@id"
  919. ));
  920. $edit_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_update');
  921. $edit_op->setType('http://schema.org/UpdateAction');
  922. $edit_op->addProperty('method', 'PUT');
  923. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  924. $edit_op->addProperty('label', "Update and replace an " . $bundle->label . " entity.");
  925. }
  926. else {
  927. $edit_op->addProperty('label', "Update and replace a " . $bundle->label . " entity.");
  928. }
  929. $edit_op->addProperty('description', NULL);
  930. $edit_op->addProperty('expects', $term->url);
  931. $edit_op->addProperty('returns', $term->url);
  932. $edit_op->addProperty('statusCodes', array(
  933. array(
  934. 'code' => 404,
  935. 'description' => 'The ' . $bundle->label . ' could not be updated using the provided ID.'
  936. ),
  937. ));
  938. $operations[] = $edit_op;
  939. }
  940. // If the user can edit this content type.
  941. if (user_access('delete ' . $bundle->name)) {
  942. // All content types allow GET (if the user has view permission).
  943. $delete_op = new TripalWebServiceResource($this->getServicePath());
  944. $delete_op->addContextItem('method', 'hydra:method');
  945. $delete_op->addContextItem('statusCodes', 'hydra:statusCodes');
  946. $delete_op->addContextItem('label', 'rdfs:label');
  947. $delete_op->addContextItem('description', 'rdfs:comment');
  948. $delete_op->addContextItem('code', 'hydra:statusCode');
  949. $delete_op->addContextItem('expects', array(
  950. "@id" => "hydra:expects",
  951. "@type" => "@id"
  952. ));
  953. $delete_op->addContextItem('returns', array(
  954. "@id" => "hydra:returns",
  955. "@type" => "@id"
  956. ));
  957. $delete_op->setID('_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_delete');
  958. $delete_op->setType('http://schema.org/DeleteAction');
  959. $delete_op->addProperty('method', 'DELETE');
  960. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  961. $delete_op->addProperty('label', "Deletes an " . $bundle->label . " entity.");
  962. }
  963. else {
  964. $delete_op->addProperty('label', "Deletes a " . $bundle->label . " entity.");
  965. }
  966. $delete_op->addProperty('description', NULL);
  967. $delete_op->addProperty('expects', $term->url);
  968. $delete_op->addProperty('returns', $term->url);
  969. $delete_op->addProperty('statusCodes', array(
  970. array(
  971. 'code' => 404,
  972. 'description' => 'The ' . $bundle->label . ' could not be deleted using the provided ID.'
  973. ),
  974. ));
  975. $operations[] = $delete_op;
  976. }
  977. $supported->addProperty('supportedOperation', $operations);
  978. $supported_classes[] = $supported;
  979. }
  980. return $supported_classes;
  981. }
  982. }