TripalContentService_v0_1.inc 49 KB

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