TripalEntityService_v0_1.inc 41 KB

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