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