TripalEntityService_v0_1.inc 40 KB

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