TripalContentService_v0_1.inc 49 KB

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