OCS.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Remote\Api;
  7. use GuzzleHttp\Exception\ClientException;
  8. use OC\ForbiddenException;
  9. use OC\Remote\User;
  10. use OCP\AppFramework\OCSController;
  11. use OCP\Remote\Api\ICapabilitiesApi;
  12. use OCP\Remote\Api\IUserApi;
  13. class OCS extends ApiBase implements ICapabilitiesApi, IUserApi {
  14. /**
  15. * @param string $method
  16. * @param string $url
  17. * @param array $body
  18. * @param array $query
  19. * @param array $headers
  20. * @return array
  21. * @throws ForbiddenException
  22. * @throws NotFoundException
  23. * @throws \Exception
  24. */
  25. protected function request($method, $url, array $body = [], array $query = [], array $headers = []) {
  26. try {
  27. $response = json_decode(parent::request($method, 'ocs/v2.php/' . $url, $body, $query, $headers), true);
  28. } catch (ClientException $e) {
  29. if ($e->getResponse()->getStatusCode() === 404) {
  30. throw new NotFoundException();
  31. } elseif ($e->getResponse()->getStatusCode() === 403 || $e->getResponse()->getStatusCode() === 401) {
  32. throw new ForbiddenException();
  33. } else {
  34. throw $e;
  35. }
  36. }
  37. if (!isset($response['ocs']) || !isset($response['ocs']['meta'])) {
  38. throw new \Exception('Invalid ocs response');
  39. }
  40. if ($response['ocs']['meta']['statuscode'] === OCSController::RESPOND_UNAUTHORISED) {
  41. throw new ForbiddenException();
  42. }
  43. if ($response['ocs']['meta']['statuscode'] === OCSController::RESPOND_NOT_FOUND) {
  44. throw new NotFoundException();
  45. }
  46. if ($response['ocs']['meta']['status'] !== 'ok') {
  47. throw new \Exception('Unknown ocs error ' . $response['ocs']['meta']['message']);
  48. }
  49. return $response['ocs']['data'];
  50. }
  51. /**
  52. * @param array $data
  53. * @param string $type
  54. * @param string[] $keys
  55. * @throws \Exception
  56. */
  57. private function checkResponseArray(array $data, $type, array $keys) {
  58. foreach ($keys as $key) {
  59. if (!array_key_exists($key, $data)) {
  60. throw new \Exception('Invalid ' . $type . ' response, expected field ' . $key . ' not found');
  61. }
  62. }
  63. }
  64. public function getUser($userId) {
  65. $result = $this->request('get', 'cloud/users/' . $userId);
  66. $this->checkResponseArray($result, 'user', User::EXPECTED_KEYS);
  67. return new User($result);
  68. }
  69. /**
  70. * @return array The capabilities in the form of [$appId => [$capability => $value]]
  71. */
  72. public function getCapabilities() {
  73. $result = $this->request('get', 'cloud/capabilities');
  74. return $result['capabilities'];
  75. }
  76. }