TripalEntityService_v0_1.inc 41 KB

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