TripalEntityService_v0_1.inc 44 KB

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