TripalContentService_v0_1.inc 48 KB

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