TripalContentService_v0_1.inc 51 KB

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