TripalEntityService_v0_1.inc 42 KB

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