TripalContentService_v0_1.inc 49 KB

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