TripalEntityService_v0_1.inc 40 KB

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