TripalContentService_v0_1.inc 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  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. // Check the label by replacing non alpha-numeric characters with
  60. // an underscore and is case-insensitive
  61. $label = preg_replace('/[^\w]/', '_', $bundle->label);
  62. if (preg_match("/^$label$/i", $ctype)) {
  63. $ctype = $bundle->label;
  64. $found = TRUE;
  65. }
  66. // Check if this is an accession.
  67. if ($ctype == $bundle->vocabulary . ':' . $bundle->accession) {
  68. $ctype = $bundle->label;
  69. $found = TRUE;
  70. }
  71. }
  72. if (!$found) {
  73. throw new Exception('Invalid content type: ' . $ctype);
  74. }
  75. }
  76. // If we have a content type then list all of the entities that belong
  77. // to it.
  78. if ($ctype and !$entity_id and !$expfield) {
  79. $this->doEntityList($ctype);
  80. }
  81. // If we have an entity ID then build the resource for a single entity.
  82. else if ($ctype and $entity_id and !$expfield) {
  83. $this->doEntity($ctype, $entity_id);
  84. }
  85. else if ($ctype and $entity_id and $expfield) {
  86. $this->doExpandedField($ctype, $entity_id, $expfield);
  87. }
  88. // Otherwise just list all of the available content types.
  89. else {
  90. $this->doContentTypesList();
  91. }
  92. }
  93. /**
  94. * Creates a resource for an expanded field of an entity.
  95. */
  96. private function doExpandedField($ctype, $entity_id, $expfield) {
  97. $service_path = $this->getServicePath() . '/' . urlencode($ctype) . '/' . $entity_id;
  98. $this->resource = new TripalWebServiceResource($service_path);
  99. // Get the TripalBundle, TripalTerm and TripalVocab for this type.
  100. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  101. // Find the field that matches the field name provided by the user.
  102. list($field, $instance, $term) = $this->findField($bundle, $expfield);
  103. if (!$field) {
  104. throw new Exception("Could not find a matching field for the name: $expfield");
  105. }
  106. // Get the TripalEntity
  107. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id), FALSE, array($field['id']));
  108. $entity = reset($entity);
  109. // If we couldn't find the entity then fail.
  110. if (!$entity) {
  111. throw new Exception("Cannot find the record with id $entity_id.");
  112. }
  113. // Check that the user has access to this entity. If not then the
  114. // function call will throw an error.
  115. $this->checkAccess($entity);
  116. // Next add in the ID and Type for this resources.
  117. $this->setResourceType($this->resource, $term);
  118. $this->resource->setID(urlencode($term['name']));
  119. if (!property_exists($entity, $field['field_name'])) {
  120. // Attach the field and then add its values to the response.
  121. field_attach_load($entity->type, array($entity->id => $entity),
  122. FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
  123. }
  124. $this->addEntityField($this->resource, $term, $entity, $bundle, $field, $instance, $service_path, $expfield);
  125. }
  126. /**
  127. * Find the field whose term matches the one provied.
  128. */
  129. private function findField($bundle, $expfield) {
  130. $value = array();
  131. $instances = field_info_instances('TripalEntity', $bundle->name);
  132. foreach ($instances as $instance) {
  133. $field_name = $instance['field_name'];
  134. $field = field_info_field($field_name);
  135. $field_type = $field['type'];
  136. // Skip fields of remote data.
  137. if ($field_type == 'remote__data') {
  138. continue;
  139. }
  140. $vocabulary = $instance['settings']['term_vocabulary'];
  141. $accession = $instance['settings']['term_accession'];
  142. $temp_term = tripal_get_term_details($vocabulary, $accession);
  143. // See if the name provided matches the field name after a bit of
  144. // cleanup.
  145. if (strtolower(preg_replace('/[^\w]/', '_', $temp_term['name'])) == strtolower($expfield)) {
  146. return array($field, $instance, $temp_term);
  147. }
  148. // Alternatively if the CV term accession matches then we're good too.
  149. if ($vocabulary . ':' . $accession == $expfield) {
  150. return array($field, $instance, $temp_term);
  151. }
  152. }
  153. }
  154. /**
  155. * Creates a resource for a single entity.
  156. */
  157. private function doEntity($ctype, $entity_id) {
  158. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  159. $this->resource = new TripalWebServiceResource($service_path);
  160. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  161. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  162. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  163. $term = reset($term);
  164. // Convert the $term to a simple array
  165. $term = tripal_get_term_details($term->vocab->vocabulary, $term->accession);
  166. // Add the vocabulary to the context.
  167. $this->resource->addContextItem($term['name'], $term['url']);
  168. // Get the TripalEntity.
  169. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  170. $entity = reset($entity);
  171. // If we couldn't match this field argument to a field and entity then return
  172. if (!$entity) {
  173. throw new Exception("Cannot find this record.");
  174. }
  175. // Check that the user has access to this entity. If not then the
  176. // function call will throw an error.
  177. $this->checkAccess($entity);
  178. $itemPage = tripal_get_term_details('schema', 'ItemPage');
  179. $label = tripal_get_term_details('rdfs', 'label');
  180. $this->resource->setID($entity_id);
  181. $this->setResourceType($this->resource, $term);
  182. $this->addResourceProperty($this->resource, $label, $entity->title);
  183. $this->addResourceProperty($this->resource, $itemPage, url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  184. // Add in the entitie's fields.
  185. $this->addEntityFields($this->resource, $entity, $bundle, $term, $service_path);
  186. }
  187. /**
  188. * Ensures that user's only have access to content they should see.
  189. *
  190. * Denies access to an entity if it is unpublished or if the user does
  191. * not have permission to see it.
  192. *
  193. * @param $entity
  194. * The full entity object.
  195. *
  196. * @throws Exception
  197. */
  198. private function checkAccess($entity) {
  199. global $user;
  200. if (!tripal_entity_access('view', $entity, $user, 'TripalEntity')) {
  201. throw new Exception("Permission Denied.");
  202. }
  203. // Don't show entities that aren't published
  204. if ($entity->status == 0) {
  205. throw new Exception("This record is currently unavailable.");
  206. }
  207. }
  208. /**
  209. * Adds the fields as properties of an entity resource.
  210. */
  211. private function addEntityFields($resource, $entity, $bundle, $term, $service_path) {
  212. // If the entity is set to hide fields that have no values then we
  213. // want to honor that in the web services too.
  214. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  215. // Get information about the fields attached to this bundle and sort them
  216. // in the order they were set for the display.
  217. $instances = field_info_instances('TripalEntity', $bundle->name);
  218. // Sort the instances by their weight.
  219. uasort($instances, function($a, $b) {
  220. $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  221. $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;
  222. if ($a_weight == $b_weight) {
  223. return 0;
  224. }
  225. return ($a_weight < $b_weight) ? -1 : 1;
  226. });
  227. // Iterate through the fields and add each value to the response.
  228. //$response['fields'] = $fields;
  229. foreach ($instances as $field_name => $instance) {
  230. // Skip hidden fields.
  231. if ($instance['display']['default']['type'] == 'hidden') {
  232. continue;
  233. }
  234. // Get the information about this field.
  235. $field = field_info_field($field_name);
  236. // If the field has the $no_data turned on then we should exclude it.
  237. if (tripal_load_include_field_class($field['type'])) {
  238. $field_class = $field['type'];
  239. if ($field_class::$no_data) {
  240. return;
  241. }
  242. }
  243. // Skip the remote__data field that is provided by the tripal_ws
  244. // module.
  245. if ($field['type'] == 'remote__data') {
  246. continue;
  247. }
  248. // By default, the label for the key in the output should be the
  249. // term from the vocabulary that the field is assigned. But in the
  250. // case that the field is not assigned a term, we must use the field name.
  251. $field_name = $instance['field_name'];
  252. $vocabulary = $instance['settings']['term_vocabulary'];
  253. $accession = $instance['settings']['term_accession'];
  254. $term = tripal_get_term_details($vocabulary, $accession);
  255. if (!$term) {
  256. continue;
  257. }
  258. // If this field should not be attached by default then just add a link
  259. // so that the caller can get the information separately.
  260. $instance_settings = $instance['settings'];
  261. if (array_key_exists('auto_attach', $instance['settings']) and
  262. $instance_settings['auto_attach'] == FALSE) {
  263. // Add a URL only if there are values. If there are no values then
  264. // don't add a URL which would make the end-user think they can get
  265. // that information.
  266. $items = field_get_items('TripalEntity', $entity, $field_name);
  267. $term_key = $this->getContextTerm($term, array('lowercase', 'spacing'));
  268. $resource->addContextItem($term_key, $vocabulary . ':' . $accession);
  269. $resource->addContextItem($vocabulary . ':' . $accession, array(
  270. '@id' => $term['url'],
  271. '@type' => '@id'
  272. ));
  273. if ($items and count($items) > 0 and $items[0]['value']) {
  274. $this->addResourceProperty($resource, $term, $service_path . '/' . $entity->id . '/' . urlencode($term['name']), array('lowercase', 'spacing'));
  275. }
  276. else {
  277. if ($hide_fields == 'show') {
  278. $this->addResourceProperty($resource, $term, NULL, array('lowercase', 'spacing'));
  279. }
  280. }
  281. continue;
  282. }
  283. // Get the details for this field for the JSON-LD response.
  284. $this->addEntityField($resource, $term, $entity, $bundle, $field, $instance, $service_path);
  285. }
  286. }
  287. /**
  288. * Adds the field as a property of the entity resource.
  289. */
  290. private function addEntityField($resource, $term, $entity, $bundle, $field, $instance,
  291. $service_path, $expfield = NULL) {
  292. // If the entity is set to hide fields that have no values then we
  293. // want to honor that in the web services too.
  294. $hide_fields = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  295. // Get the field settings.
  296. $field_name = $field['field_name'];
  297. $field_settings = $field['settings'];
  298. $items = field_get_items('TripalEntity', $entity, $field_name);
  299. if (!$items) {
  300. return;
  301. }
  302. // Give modules the opportunity to edit values for web services. This hook
  303. // really should be used sparingly. Where it helps is with non Tripal fields
  304. // that are added to a TripalEntity content type and it doesn't follow
  305. // the rules (e.g. Image field).
  306. drupal_alter('tripal_ws_value', $items, $field, $instance);
  307. $values = array();
  308. for ($i = 0; $i < count($items); $i++) {
  309. if (array_key_exists('value', $items[$i])) {
  310. $values[$i] = $this->sanitizeFieldKeys($resource, $items[$i]['value'], $bundle, $service_path);
  311. }
  312. elseif ($field['type'] == 'image') {
  313. $url = file_create_url($items[$i]['uri']);
  314. $values[$i] = $this->sanitizeFieldKeys($resource, $url, $bundle, $service_path);
  315. }
  316. else {
  317. // TODO: handle this case.
  318. }
  319. }
  320. if ($hide_fields == 'hide' 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. $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, 'hide');
  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 == 'hide') {
  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. }