TripalContentService_v0_1.inc 45 KB

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