TripalContentService_v0_1.inc 48 KB

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