TripalContentService_v0_1.inc 48 KB

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