TripalContentService_v0_1.inc 50 KB

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