TripalEntityService_v0_1.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. class TripalEntityService_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::handleRequest()
  28. */
  29. public function handleRequest() {
  30. // Get the content type.
  31. $ctype = (count($this->path) > 0) ? $this->path[0] : '';
  32. $entity_id = (count($this->path) > 1) ? $this->path[1] : '';
  33. $expfield = (count($this->path) > 2) ? $this->path[2] : '';
  34. // If we have a content type then list all of the entities that belong
  35. // to it.
  36. if ($ctype and !$entity_id and !$expfield) {
  37. $this->doContentTypeList($ctype);
  38. }
  39. // If we have an entity ID then build the resource for a single entity.
  40. else if ($ctype and $entity_id and !$expfield) {
  41. $this->doEntity($ctype, $entity_id);
  42. }
  43. else if ($ctype and $entity_id and $expfield) {
  44. $this->doExpandedField($ctype, $entity_id, $expfield);
  45. }
  46. // Otherwise just list all of the available content types.
  47. else {
  48. $this->doAllTypesList();
  49. }
  50. }
  51. /**
  52. * Creates a resource for an expanded field of an entity.
  53. */
  54. private function doExpandedField($ctype, $entity_id, $expfield) {
  55. $service_path = $this->getServicePath() . '/' . urlencode($ctype) . '/' . $entity_id;
  56. $this->resource = new TripalWebServiceResource($service_path);
  57. // Get the TripalBundle, TripalTerm and TripalVocab for this type.
  58. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  59. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  60. $term = reset($term);
  61. $vocab = $term->vocab;
  62. // Get the TripalEntity
  63. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  64. $entity = reset($entity);
  65. // If we couldn't match this field argument to a field and entity then return
  66. if (!$entity) {
  67. throw new Exception("Canno find this entity.");
  68. }
  69. list($field, $instance, $term) = $this->findField($bundle, $expfield);
  70. // Next add in the ID and Type for this resources.
  71. $key = $term['name'];
  72. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  73. $this->resource->addContextItem($key_adj, $term['url']);
  74. $this->resource->setID(urlencode($key));
  75. $this->resource->setType($key_adj);
  76. // Attach the field and then add it's values to the response.
  77. field_attach_load($entity->type, array($entity->id => $entity),
  78. FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
  79. $this->addEntityField($key_adj, $entity, $field, $instance, $service_path, $expfield);
  80. }
  81. /**
  82. * Find the field whose term matches the one provied.
  83. */
  84. private function findField($bundle, $expfield) {
  85. $value = array();
  86. $instances = field_info_instances('TripalEntity', $bundle->name);
  87. foreach ($instances as $instance) {
  88. $field_name = $instance['field_name'];
  89. $field = field_info_field($field_name);
  90. $vocabulary = $instance['settings']['term_vocabulary'];
  91. $accession = $instance['settings']['term_accession'];
  92. $temp_term = tripal_get_term_details($vocabulary, $accession);
  93. if ($temp_term['name'] == $expfield) {
  94. return array($field, $instance, $temp_term);
  95. }
  96. }
  97. }
  98. /**
  99. * Creates a resource for a single entity.
  100. */
  101. private function doEntity($ctype, $entity_id) {
  102. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  103. $this->resource = new TripalWebServiceResource($service_path);
  104. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  105. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  106. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  107. $term = reset($term);
  108. $vocab = $term->vocab;
  109. // Add the vocabulary to the context.
  110. $this->resource->addContextItem($vocab->vocabulary, $term->urlprefix);
  111. $this->resource->addContextItem($term->name, $term->url);
  112. // Get the TripalEntity
  113. $entity = tripal_load_entity('TripalEntity', array('id' => $entity_id));
  114. $entity = reset($entity);
  115. $this->resource->setID($entity_id);
  116. $this->resource->setType($term->name);
  117. $this->resource->addContextItem('label', 'rdfs:label');
  118. $this->resource->addContextItem('itemPage', 'schema:itemPage');
  119. $this->resource->addProperty('label', $entity->title);
  120. $this->resource->addProperty('itemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  121. $this->addEntityFields($entity, $bundle, $term, $service_path);
  122. // tripal_ws_services_v0_1_get_content_add_fields($entity, $bundle, $api_url, $response, $ws_path, $ctype, $entity_id, $params);
  123. // tripal_ws_services_v0_1_write_context($response, $ctype);
  124. }
  125. /**
  126. * Adds the fields as properties of an entity resource.
  127. */
  128. private function addEntityFields($entity, $bundle, $term, $service_path) {
  129. // Get information about the fields attached to this bundle and sort them
  130. // in the order they were set for the display.
  131. $instances = field_info_instances('TripalEntity', $bundle->name);
  132. uasort($instances, function($a, $b) {
  133. $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  134. $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;
  135. if ($a_weight == $b_weight) {
  136. return 0;
  137. }
  138. return ($a_weight < $b_weight) ? -1 : 1;
  139. });
  140. // Iterate through the fields and add each value to the response.
  141. //$response['fields'] = $fields;
  142. foreach ($instances as $field_name => $instance) {
  143. // Skip hidden fields.
  144. if ($instance['display']['default']['type'] == 'hidden') {
  145. continue;
  146. }
  147. // Get the information about this field.
  148. $field = field_info_field($field_name);
  149. // By default, the label for the key in the output should be the
  150. // term from the vocabulary that the field is assigned. But in the
  151. // case that the field is not assigned a term, we must use the field name.
  152. $field_name = $instance['field_name'];
  153. $vocabulary = $instance['settings']['term_vocabulary'];
  154. $accession = $instance['settings']['term_accession'];
  155. $term = tripal_get_term_details($vocabulary, $accession);
  156. if ($term) {
  157. $key = $term['name'];
  158. $key_adj = strtolower(preg_replace('/ /', '_', $key));
  159. // The term schema:url also points to a recource so we need
  160. // to make sure we set the type to be '@id'.
  161. if ($vocabulary == 'schema' and $accession == 'url') {
  162. $this->resource->addContextItem($key_adj, array(
  163. '@id' => $term['url'],
  164. '@type' => '@id',
  165. ));
  166. }
  167. else {
  168. $this->resource->addContextItem($key_adj, $term['url']);
  169. }
  170. }
  171. else {
  172. continue;
  173. }
  174. // If this field should not be attached by default then just add a link
  175. // so that the caller can get the information separately.
  176. $instance_settings = $instance['settings'];
  177. if (array_key_exists('auto_attach', $instance['settings']) and
  178. $instance_settings['auto_attach'] == FALSE) {
  179. $this->resource->addContextItem($key_adj, array(
  180. '@id' => '', //$response['@context'][$key_adj],
  181. '@type' => '@id'
  182. ));
  183. // Add a URL only if there are values. If there are no values then
  184. // don't add a URL which would make the end-user think they can get
  185. // that information.
  186. $items = field_get_items('TripalEntity', $entity, $field_name);
  187. if ($items and count($items) > 0 and $items[0]['value']) {
  188. $this->resource->addProperty($key_adj, $service_path . '/' . $entity->id . '/' . urlencode($key));
  189. }
  190. else {
  191. $this->resource->addProperty($key_adj, NULL);
  192. }
  193. continue;
  194. }
  195. // Get the details for this field for the JSON-LD response.
  196. $this->addEntityField($key_adj, $entity, $field, $instance, $service_path);
  197. }
  198. }
  199. /**
  200. * Adds the field as a property of the entity resource.
  201. */
  202. private function addEntityField($key, $entity, $field, $instance, $service_path, $expfield = NULL) {
  203. // Get the field settings.
  204. $field_name = $field['field_name'];
  205. $field_settings = $field['settings'];
  206. $items = field_get_items('TripalEntity', $entity, $field_name);
  207. if (!$items) {
  208. return;
  209. }
  210. // Give modules the opportunity to edit values for web services. This hook
  211. // really should be used sparingly. Where it helps is with non Tripal fields
  212. // that are added to a TripalEntity content type and it doesn't follow
  213. // the rules (e.g. Image field).
  214. drupal_alter('tripal_ws_value', $items, $field, $instance);
  215. $values = array();
  216. for ($i = 0; $i < count($items); $i++) {
  217. $values[$i] = $this->sanitizeFieldKeys($items[$i]['value'], $service_path);
  218. }
  219. // If the field cardinality is 1
  220. if ($field[cardinality] == 1) {
  221. // If the value is an array and this is the field page then all of those
  222. // key/value pairs should be added directly to the response.
  223. if (is_array($values[0])) {
  224. if ($expfield) {
  225. foreach ($values[0] as $k => $v) {
  226. $this->resource->addProperty($k, $v);
  227. }
  228. }
  229. else {
  230. $this->resource->addProperty($key, $values[0]);
  231. }
  232. }
  233. // If the value is not an array it's a scalar so add it as is to the
  234. // response.
  235. else {
  236. $this->resource->addProperty($key, $values[0]);
  237. }
  238. }
  239. // If the field cardinality is > 1
  240. if ($field[cardinality] != 1) {
  241. // If this is the expanded field page then we need to swap out
  242. // the resource for a collection.
  243. if ($expfield) {
  244. $this->resource = new TripalWebServiceCollection($service_path . '/' . urlencode($expfield));
  245. $this->resource->addContextItem('label', 'rdfs:label');
  246. $this->resource->addProperty('label', $instance['label']);
  247. foreach ($values as $delta => $element) {
  248. $member = new TripalWebServiceResource($service_path);
  249. foreach ($element as $key => $value) {
  250. $member->addContextItem($key, '');
  251. $member->addProperty($key, $value);
  252. }
  253. $this->resource->addMember($member);
  254. }
  255. }
  256. else {
  257. $response[$key] = array(
  258. '@type' => 'Collection',
  259. 'totalItems' => count($values),
  260. 'label' => $instance['label'],
  261. 'member' => $values,
  262. );
  263. }
  264. }
  265. }
  266. /**
  267. * Rewrites the keys of a field's items array for use with web services.
  268. */
  269. private function sanitizeFieldKeys($value, $service_path) {
  270. $new_value = '';
  271. // If the value is an array rather than a scalar then map the sub elements
  272. // to controlled vocabulary terms.
  273. if (is_array($value)) {
  274. $temp = array();
  275. foreach ($value as $k => $v) {
  276. $matches = array();
  277. if (preg_match('/^(.+):(.+)$/', $k, $matches)) {
  278. $vocabulary = $matches[1];
  279. $accession = $matches[2];
  280. $term = tripal_get_term_details($vocabulary, $accession);
  281. $key_adj = strtolower(preg_replace('/ /', '_', $term['name']));
  282. if (is_array($v)) {
  283. $temp[$key_adj] = $this->sanitizeFieldKeys($v, $service_path);
  284. }
  285. else {
  286. $temp[$key_adj] = $v !== "" ? $v : NULL;
  287. }
  288. // The term schema:url also points to a recource so we need
  289. // to make sure we set the type to be '@id'.
  290. if ($vocabulary == 'schema' and $accession == 'url') {
  291. $this->resource->addContextItem($key_adj, array(
  292. '@id' => $term['url'],
  293. '@type' => '@id',
  294. ));
  295. }
  296. else {
  297. $this->resource->addContextItem($key_adj, $term['url']);
  298. }
  299. }
  300. else {
  301. $temp[$k] = $v;
  302. }
  303. }
  304. $new_value = $temp;
  305. // Recurse through the values array and set the entity elements
  306. // and add the fields to the context.
  307. $this->sanitizeFieldEntity($new_value, $service_path);
  308. }
  309. else {
  310. $new_value = $value !== "" ? $value : NULL;
  311. }
  312. return $new_value;
  313. }
  314. /**
  315. * Rewrites any TripalEntity elements in the values array for use with WS.
  316. */
  317. private function sanitizeFieldEntity(&$items, $service_path) {
  318. if (!$items) {
  319. return;
  320. }
  321. foreach ($items as $key => $value) {
  322. if (is_array($value)) {
  323. $this->sanitizeFieldEntity($items[$key], $response, $api_url);
  324. continue;
  325. }
  326. if ($key == 'entity') {
  327. list($item_etype, $item_eid) = explode(':', $items['entity']);
  328. if ($item_eid) {
  329. $item_entity = tripal_load_entity($item_etype, array($item_eid));
  330. $item_entity = reset($item_entity);
  331. $bundle = tripal_load_bundle_entity(array('name' => $item_entity->bundle));
  332. $items['@id'] = url($api_url . '/content/' . $bundle->label . '/' . $item_eid, array('absolute' => TRUE));
  333. }
  334. unset($items['entity']);
  335. }
  336. }
  337. }
  338. /**
  339. * Creates a collection of resources for a given type.
  340. */
  341. private function doContentTypeList($ctype) {
  342. $service_path = $this->getServicePath() . '/' . urlencode($ctype);
  343. $this->resource = new TripalWebServiceCollection($service_path);
  344. $this->resource->addContextItem('label', 'rdfs:label');
  345. // Get the TripalBundle, TripalTerm and TripalVocab type for this type.
  346. $bundle = tripal_load_bundle_entity(array('label' => $ctype));
  347. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  348. $term = reset($term);
  349. // Set the label for this collection.
  350. $this->resource->addProperty('label', $bundle->label . " collection");
  351. // Iterate through the fields and create a $field_mapping array that makes
  352. // it easier to determine which filter criteria belongs to which field. The
  353. // key is the label for the field and the value is the field name. This way
  354. // user's can use the field label or the field name to form a query.
  355. $field_mapping = array();
  356. $fields = field_info_fields();
  357. foreach ($fields as $field) {
  358. if (array_key_exists('TripalEntity', $field['bundles'])) {
  359. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  360. if ($bundle_name == $bundle->name) {
  361. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  362. if (array_key_exists('term_accession', $instance['settings'])){
  363. $vocabulary = $instance['settings']['term_vocabulary'];
  364. $accession = $instance['settings']['term_accession'];
  365. $fterm = tripal_get_term_details($vocabulary, $accession);
  366. $key = $fterm['name'];
  367. $key = strtolower(preg_replace('/ /', '_', $key));
  368. $field_mapping[$key] = $field['field_name'];
  369. $field_mapping[$field['field_name']] = $field['field_name'];
  370. }
  371. }
  372. }
  373. }
  374. }
  375. // Convert the filters to their field names
  376. $new_params = array();
  377. $order = array();
  378. $order_dir = array();
  379. $URL_add = array();
  380. foreach ($this->params as $param => $value) {
  381. $URL_add[] = "$param=$value";
  382. // Ignore non filter parameters
  383. if ($param == 'page' or $param == 'limit') {
  384. continue;
  385. }
  386. // Handle order separately
  387. if ($param == 'order') {
  388. $temp = explode(',', $value);
  389. foreach ($temp as $key) {
  390. $matches = array();
  391. $dir = 'ASC';
  392. // The user can provide a direction by separating the field key and the
  393. // direction with a '|' character.
  394. if (preg_match('/^(.*)\|(.*)$/', $key, $matches)) {
  395. $key = $matches[1];
  396. if ($matches[2] == 'ASC' or $matches[2] == 'DESC') {
  397. $dir = $matches[2];
  398. }
  399. else {
  400. // TODO: handle error of providing an incorrect direction.
  401. }
  402. }
  403. if (array_key_exists($key, $field_mapping)) {
  404. $order[$field_mapping[$key]] = $key;
  405. $order_dir[] = $dir;
  406. }
  407. else {
  408. // TODO: handle error of providing a non existing field name.
  409. }
  410. }
  411. continue;
  412. }
  413. // Break apart any operators
  414. $key = $param;
  415. $op = '=';
  416. $matches = array();
  417. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  418. $key = $matches[1];
  419. $op = $matches[2];
  420. }
  421. // Break apart any subkeys and pull the first one out for the term name key.
  422. $subkeys = explode(',', $key);
  423. if (count($subkeys) > 0) {
  424. $key = array_shift($subkeys);
  425. }
  426. $column_name = $key;
  427. // Map the values in the filters to their appropriate field names.
  428. if (array_key_exists($key, $field_mapping)) {
  429. $field_name = $field_mapping[$key];
  430. if (count($subkeys) > 0) {
  431. $column_name .= '.' . implode('.', $subkeys);
  432. }
  433. $new_params[$field_name]['value'] = $value;
  434. $new_params[$field_name]['op'] = $op;
  435. $new_params[$field_name]['column'] = $column_name;
  436. }
  437. else {
  438. throw new Exception("The filter term, '$key', is not available for use.");
  439. }
  440. }
  441. // Get the list of entities for this bundle.
  442. $query = new TripalFieldQuery();
  443. $query->entityCondition('entity_type', 'TripalEntity');
  444. $query->entityCondition('bundle', $bundle->name);
  445. foreach($new_params as $field_name => $details) {
  446. $value = $details['value'];
  447. $column_name = $details['column'];
  448. switch ($details['op']) {
  449. case 'eq':
  450. $op = '=';
  451. break;
  452. case 'gt':
  453. $op = '>';
  454. break;
  455. case 'gte':
  456. $op = '>=';
  457. break;
  458. case 'lt':
  459. $op = '<';
  460. break;
  461. case 'lte':
  462. $op = '<=';
  463. break;
  464. case 'ne':
  465. $op = '<>';
  466. break;
  467. case 'contains':
  468. $op = 'CONTAINS';
  469. break;
  470. case 'starts':
  471. $op = 'STARTS WITH';
  472. break;
  473. default:
  474. $op = '=';
  475. }
  476. // We pass in the $column_name as an identifier for any sub fields
  477. // that are present for the fields.
  478. $query->fieldCondition($field_name, $column_name, $value, $op);
  479. }
  480. // Perform the query just as a count first to get the number of records.
  481. $cquery = clone $query;
  482. $cquery->count();
  483. $num_records = $cquery->execute();
  484. if (!$num_records) {
  485. $num_records = 0;
  486. }
  487. // Add in the pager to the response.
  488. $response['totalItems'] = $num_records;
  489. $limit = array_key_exists('limit', $this->params) ? $this->params['limit'] : 25;
  490. $total_pages = ceil($num_records / $limit);
  491. $page = array_key_exists('page', $this->params) ? $this->params['page'] : 1;
  492. // Set the query order
  493. $order_keys = array_keys($order);
  494. for($i = 0; $i < count($order_keys); $i++) {
  495. $query->fieldOrderBy($order_keys[$i], $order[$order_keys[$i]], $order_dir[$i]);
  496. }
  497. // Set the query range
  498. $start = ($page - 1) * $limit;
  499. $query->range($start, $limit);
  500. // Now perform the query.
  501. $results = $query->execute();
  502. //$this->resource->initPager($num_records, $params['limit']);
  503. $this->resource->initPager($num_records, $limit);
  504. // Iterate through the entities and add them to the list.
  505. foreach ($results['TripalEntity'] as $entity_id => $stub) {
  506. // We don't need all of the attached fields for an entity so, we'll
  507. // not use the entity_load() function. Instead just pull it from the
  508. // database table.
  509. $query = db_select('tripal_entity', 'TE');
  510. $query->join('tripal_term', 'TT', 'TE.term_id = TT.id');
  511. $query->fields('TE');
  512. $query->fields('TT', array('name'));
  513. $query->condition('TE.id', $entity_id);
  514. $entity = $query->execute()->fetchObject();
  515. $member = new TripalWebServiceResource($service_path);
  516. $member->addContextItem('label', 'rdfs:label');
  517. $member->addContextItem('itemPage', 'schema:itemPage');
  518. $member->addContextItem($term->name, $term->url);
  519. $member->setID($entity->id);
  520. $member->setType($term->name);
  521. $member->addProperty('label', $entity->title);
  522. $member->addProperty('itemPage', url('/bio_data/' . $entity->id, array('absolute' => TRUE)));
  523. $this->resource->addMember($member);
  524. }
  525. }
  526. /**
  527. * Creates a resources that contains the list of content types.
  528. */
  529. private function doAllTypesList() {
  530. $service_path = $this->getServicePath();
  531. $this->resource = new TripalWebServiceCollection($service_path);
  532. $this->resource->addContextItem('label', 'rdfs:label');
  533. $this->resource->addProperty('label', 'Content Types');
  534. // Get the list of published terms (these are the bundle IDs)
  535. $bundles = db_select('tripal_bundle', 'tb')
  536. ->fields('tb')
  537. ->orderBy('tb.label', 'ASC')
  538. ->execute();
  539. // Iterate through the terms and add an entry in the collection.
  540. $i = 0;
  541. while ($bundle = $bundles->fetchObject()) {
  542. $entity = entity_load('TripalTerm', array('id' => $bundle->term_id));
  543. $term = reset($entity);
  544. $vocab = $term->vocab;
  545. // Get the bundle description. If no description is provided then
  546. // use the term definition
  547. $description = tripal_get_bundle_variable('description', $bundle->id);
  548. if (!$description) {
  549. $description = $term->definition;
  550. }
  551. $member = new TripalWebServiceResource($service_path);
  552. $member->addContextItem($term->name, $term->url);
  553. $member->addContextItem('label', 'rdfs:label');
  554. $member->addContextItem('description', 'hydra:description');
  555. $member->setID(urlencode($bundle->label));
  556. $member->setType($term->name);
  557. $member->addProperty('label', $bundle->label);
  558. $member->addProperty('description', $description);
  559. $this->resource->addMember($member);
  560. }
  561. }
  562. }