TripalEntityService_v0_1.inc 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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 (a list) of available content types.',
  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. // Create the details array for the class.
  871. $class_id = $this->getServicePath() . '/' . urlencode($bundle->label);
  872. $details = array(
  873. 'id' => $term->url,
  874. 'title' => $bundle->label,
  875. 'description' => $description,
  876. );
  877. // Add in the supported operations for this content type.
  878. $operations = array();
  879. // If the user can view this content type.
  880. if (user_access('view ' . $bundle->name)) {
  881. $label = "Retrieves a " . $bundle->label . " entity.";
  882. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  883. $label = "Retrieves an " . $bundle->label . " entity.";
  884. }
  885. $operations['GET'] = array(
  886. 'label' => $label,
  887. 'description' => NULL,
  888. 'returns' => $class_id,
  889. 'type' => '_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_retrieve',
  890. );
  891. }
  892. // If the user can edit this content type.
  893. if (user_access('edit ' . $bundle->name)) {
  894. $label = "Update and replace a " . $bundle->label . " entity.";
  895. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  896. $label = "Update and replace an " . $bundle->label . " entity.";
  897. }
  898. $operations['PUT'] = array(
  899. 'label' => $label,
  900. 'description' => NULL,
  901. 'returns' => $class_id,
  902. 'type' => '_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_update',
  903. );
  904. }
  905. // If the user can edit this content type.
  906. if (user_access('delete ' . $bundle->name)) {
  907. $label = "Deletes a " . $bundle->label . " entity.";
  908. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  909. $label = "Deletes an " . $bundle->label . " entity.";
  910. }
  911. $operations['DELETE'] = array(
  912. 'label' => $label,
  913. 'description' => NULL,
  914. 'returns' => $class_id,
  915. 'type' => '_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_delete',
  916. );
  917. }
  918. $properties = array();
  919. $this->addDocClass($details, $operations, $properties);
  920. // Now add the bundle collection class.
  921. $this->addDocBundleCollectionClass($bundle);
  922. } // end while ($bundle = $bundles->fetchObject()) { ...
  923. }
  924. /**
  925. * Every content type (bundle) needs a collection class in the documentation.
  926. */
  927. private function addDocBundleCollectionClass($bundle) {
  928. $details = array(
  929. 'id' => 'vocab:' . urlencode($bundle->label) . 'Collection',
  930. 'title' => $bundle->label . ' Collection',
  931. 'subClassOf' => 'hydra:Collection',
  932. 'description' => 'A collection (or list) of ' . $bundle->label . ' resources.',
  933. );
  934. $vocab = tripal_get_vocabulary_details('hydra');
  935. $url = preg_replace('/{accession}/', 'member', $vocab['urlprefix']);
  936. $propeties = array();
  937. $propeties[] = array(
  938. 'type' => $url,
  939. 'title' => 'member',
  940. 'description' => "The list of available " . $bundle->label . '(s).',
  941. "required" => null,
  942. "readonly" => FALSE,
  943. "writeonly" => FALSE,
  944. );
  945. $url = preg_replace('/{accession}/', 'totalItems', $vocab['urlprefix']);
  946. $propeties[] = array(
  947. "type" => $url,
  948. "title" => "totalItems",
  949. "description" => "The total number of resources.",
  950. "required" => null,
  951. "readonly" => FALSE,
  952. "writeonly" => FALSE
  953. );
  954. $url = preg_replace('/{accession}/', 'label', $vocab['urlprefix']);
  955. $propeties[] = array(
  956. "type" => $url,
  957. "title" => "label",
  958. "description" => "A label or name for the resource.",
  959. "required" => null,
  960. "readonly" => FALSE,
  961. "writeonly" => FALSE
  962. );
  963. $class_id = $this->getServicePath() . '/' . urlencode($bundle->label);
  964. $operations = array();
  965. $operations['GET'] = array(
  966. 'label' => 'Retrieves a list of all ' . $bundle->label . ' resources.',
  967. 'description' => NULL,
  968. 'expects' => NULL,
  969. 'returns' => $class_id,
  970. 'type' => '_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_retrieve',
  971. );
  972. // If the user can create this content type then we allow a POST on the
  973. // collection type.
  974. if (user_access('create ' . $bundle->name)) {
  975. $label = "Creates a " . $bundle->label;
  976. if (preg_match('/^[aeiou]/i', $bundle->label)) {
  977. $label = "Creates an " . $bundle->label;
  978. }
  979. $operations['POST'] = array(
  980. 'label' => $label,
  981. 'description' => NULL,
  982. 'expects' => $class_id,
  983. 'returns' => $class_id,
  984. 'type' => '_:' . preg_replace('/[^\w]/', '_', strtolower($bundle->label)) . '_create',
  985. 'statusCodes' => array(
  986. array(
  987. "code" => 201,
  988. "description" => "If the " . $bundle->label . " was created successfully."
  989. ),
  990. ),
  991. );
  992. }
  993. $this->addDocClass($details, $operations, $propeties);
  994. }
  995. }