TripalContentService_v0_1.inc 48 KB

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