TripalContentService_v0_1.inc 48 KB

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