TripalContentService_v0_1.inc 49 KB

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