TripalContentService_v0_1.inc 49 KB

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