TripalContentService_v0_1.inc 50 KB

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