TripalContentService_v0_1.inc 48 KB

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