TripalEntityService_v0_1.inc 40 KB

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