TripalContentService_v0_1.inc 48 KB

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