TripalEntityService_v0_1.inc 41 KB

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