TripalContentService_v0_1.inc 48 KB

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