api.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@owncloud.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Tom Needham <tom@owncloud.com>
  18. * @author Vincent Petry <pvince81@owncloud.com>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. use OCP\API;
  36. use OCP\AppFramework\Http;
  37. class OC_API {
  38. /**
  39. * API authentication levels
  40. */
  41. /** @deprecated Use \OCP\API::GUEST_AUTH instead */
  42. const GUEST_AUTH = 0;
  43. /** @deprecated Use \OCP\API::USER_AUTH instead */
  44. const USER_AUTH = 1;
  45. /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
  46. const SUBADMIN_AUTH = 2;
  47. /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
  48. const ADMIN_AUTH = 3;
  49. /**
  50. * API Response Codes
  51. */
  52. /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
  53. const RESPOND_UNAUTHORISED = 997;
  54. /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
  55. const RESPOND_SERVER_ERROR = 996;
  56. /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
  57. const RESPOND_NOT_FOUND = 998;
  58. /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
  59. const RESPOND_UNKNOWN_ERROR = 999;
  60. /**
  61. * api actions
  62. */
  63. protected static $actions = array();
  64. private static $logoutRequired = false;
  65. private static $isLoggedIn = false;
  66. /**
  67. * registers an api call
  68. * @param string $method the http method
  69. * @param string $url the url to match
  70. * @param callable $action the function to run
  71. * @param string $app the id of the app registering the call
  72. * @param int $authLevel the level of authentication required for the call
  73. * @param array $defaults
  74. * @param array $requirements
  75. */
  76. public static function register($method, $url, $action, $app,
  77. $authLevel = API::USER_AUTH,
  78. $defaults = array(),
  79. $requirements = array()) {
  80. $name = strtolower($method).$url;
  81. $name = str_replace(array('/', '{', '}'), '_', $name);
  82. if(!isset(self::$actions[$name])) {
  83. $oldCollection = OC::$server->getRouter()->getCurrentCollection();
  84. OC::$server->getRouter()->useCollection('ocs');
  85. OC::$server->getRouter()->create($name, $url)
  86. ->method($method)
  87. ->defaults($defaults)
  88. ->requirements($requirements)
  89. ->action('OC_API', 'call');
  90. self::$actions[$name] = array();
  91. OC::$server->getRouter()->useCollection($oldCollection);
  92. }
  93. self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
  94. }
  95. /**
  96. * handles an api call
  97. * @param array $parameters
  98. */
  99. public static function call($parameters) {
  100. $request = \OC::$server->getRequest();
  101. $method = $request->getMethod();
  102. // Prepare the request variables
  103. if($method === 'PUT') {
  104. $parameters['_put'] = $request->getParams();
  105. } else if($method === 'DELETE') {
  106. $parameters['_delete'] = $request->getParams();
  107. }
  108. $name = $parameters['_route'];
  109. // Foreach registered action
  110. $responses = array();
  111. $appManager = \OC::$server->getAppManager();
  112. foreach(self::$actions[$name] as $action) {
  113. // Check authentication and availability
  114. if(!self::isAuthorised($action)) {
  115. $responses[] = array(
  116. 'app' => $action['app'],
  117. 'response' => new \OC\OCS\Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
  118. 'shipped' => $appManager->isShipped($action['app']),
  119. );
  120. continue;
  121. }
  122. if(!is_callable($action['action'])) {
  123. $responses[] = array(
  124. 'app' => $action['app'],
  125. 'response' => new \OC\OCS\Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
  126. 'shipped' => $appManager->isShipped($action['app']),
  127. );
  128. continue;
  129. }
  130. // Run the action
  131. $responses[] = array(
  132. 'app' => $action['app'],
  133. 'response' => call_user_func($action['action'], $parameters),
  134. 'shipped' => $appManager->isShipped($action['app']),
  135. );
  136. }
  137. $response = self::mergeResponses($responses);
  138. $format = self::requestedFormat();
  139. if (self::$logoutRequired) {
  140. \OC::$server->getUserSession()->logout();
  141. }
  142. self::respond($response, $format);
  143. }
  144. /**
  145. * merge the returned result objects into one response
  146. * @param array $responses
  147. * @return \OC\OCS\Result
  148. */
  149. public static function mergeResponses($responses) {
  150. // Sort into shipped and third-party
  151. $shipped = array(
  152. 'succeeded' => array(),
  153. 'failed' => array(),
  154. );
  155. $thirdparty = array(
  156. 'succeeded' => array(),
  157. 'failed' => array(),
  158. );
  159. foreach($responses as $response) {
  160. if($response['shipped'] || ($response['app'] === 'core')) {
  161. if($response['response']->succeeded()) {
  162. $shipped['succeeded'][$response['app']] = $response;
  163. } else {
  164. $shipped['failed'][$response['app']] = $response;
  165. }
  166. } else {
  167. if($response['response']->succeeded()) {
  168. $thirdparty['succeeded'][$response['app']] = $response;
  169. } else {
  170. $thirdparty['failed'][$response['app']] = $response;
  171. }
  172. }
  173. }
  174. // Remove any error responses if there is one shipped response that succeeded
  175. if(!empty($shipped['failed'])) {
  176. // Which shipped response do we use if they all failed?
  177. // They may have failed for different reasons (different status codes)
  178. // Which response code should we return?
  179. // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
  180. // Merge failed responses if more than one
  181. $data = array();
  182. foreach($shipped['failed'] as $failure) {
  183. $data = array_merge_recursive($data, $failure['response']->getData());
  184. }
  185. $picked = reset($shipped['failed']);
  186. $code = $picked['response']->getStatusCode();
  187. $meta = $picked['response']->getMeta();
  188. $headers = $picked['response']->getHeaders();
  189. $response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
  190. return $response;
  191. } elseif(!empty($shipped['succeeded'])) {
  192. $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
  193. } elseif(!empty($thirdparty['failed'])) {
  194. // Merge failed responses if more than one
  195. $data = array();
  196. foreach($thirdparty['failed'] as $failure) {
  197. $data = array_merge_recursive($data, $failure['response']->getData());
  198. }
  199. $picked = reset($thirdparty['failed']);
  200. $code = $picked['response']->getStatusCode();
  201. $meta = $picked['response']->getMeta();
  202. $headers = $picked['response']->getHeaders();
  203. $response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
  204. return $response;
  205. } else {
  206. $responses = $thirdparty['succeeded'];
  207. }
  208. // Merge the successful responses
  209. $data = [];
  210. $codes = [];
  211. $header = [];
  212. foreach($responses as $response) {
  213. if($response['shipped']) {
  214. $data = array_merge_recursive($response['response']->getData(), $data);
  215. } else {
  216. $data = array_merge_recursive($data, $response['response']->getData());
  217. }
  218. $header = array_merge_recursive($header, $response['response']->getHeaders());
  219. $codes[] = ['code' => $response['response']->getStatusCode(),
  220. 'meta' => $response['response']->getMeta()];
  221. }
  222. // Use any non 100 status codes
  223. $statusCode = 100;
  224. $statusMessage = null;
  225. foreach($codes as $code) {
  226. if($code['code'] != 100) {
  227. $statusCode = $code['code'];
  228. $statusMessage = $code['meta']['message'];
  229. break;
  230. }
  231. }
  232. return new \OC\OCS\Result($data, $statusCode, $statusMessage, $header);
  233. }
  234. /**
  235. * authenticate the api call
  236. * @param array $action the action details as supplied to OC_API::register()
  237. * @return bool
  238. */
  239. private static function isAuthorised($action) {
  240. $level = $action['authlevel'];
  241. switch($level) {
  242. case API::GUEST_AUTH:
  243. // Anyone can access
  244. return true;
  245. case API::USER_AUTH:
  246. // User required
  247. return self::loginUser();
  248. case API::SUBADMIN_AUTH:
  249. // Check for subadmin
  250. $user = self::loginUser();
  251. if(!$user) {
  252. return false;
  253. } else {
  254. $userObject = \OC::$server->getUserSession()->getUser();
  255. if($userObject === null) {
  256. return false;
  257. }
  258. $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
  259. $admin = OC_User::isAdminUser($user);
  260. if($isSubAdmin || $admin) {
  261. return true;
  262. } else {
  263. return false;
  264. }
  265. }
  266. case API::ADMIN_AUTH:
  267. // Check for admin
  268. $user = self::loginUser();
  269. if(!$user) {
  270. return false;
  271. } else {
  272. return OC_User::isAdminUser($user);
  273. }
  274. default:
  275. // oops looks like invalid level supplied
  276. return false;
  277. }
  278. }
  279. /**
  280. * http basic auth
  281. * @return string|false (username, or false on failure)
  282. */
  283. private static function loginUser() {
  284. if(self::$isLoggedIn === true) {
  285. return \OC_User::getUser();
  286. }
  287. // reuse existing login
  288. $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
  289. if ($loggedIn === true) {
  290. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  291. // Do not allow access to OCS until the 2FA challenge was solved successfully
  292. return false;
  293. }
  294. $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
  295. if ($ocsApiRequest) {
  296. // initialize the user's filesystem
  297. \OC_Util::setupFS(\OC_User::getUser());
  298. self::$isLoggedIn = true;
  299. return OC_User::getUser();
  300. }
  301. return false;
  302. }
  303. // basic auth - because OC_User::login will create a new session we shall only try to login
  304. // if user and pass are set
  305. $userSession = \OC::$server->getUserSession();
  306. $request = \OC::$server->getRequest();
  307. try {
  308. if ($userSession->tryTokenLogin($request)
  309. || $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  310. self::$logoutRequired = true;
  311. } else {
  312. return false;
  313. }
  314. // initialize the user's filesystem
  315. \OC_Util::setupFS(\OC_User::getUser());
  316. self::$isLoggedIn = true;
  317. return \OC_User::getUser();
  318. } catch (\OC\User\LoginException $e) {
  319. return false;
  320. }
  321. }
  322. /**
  323. * respond to a call
  324. * @param \OC\OCS\Result $result
  325. * @param string $format the format xml|json
  326. */
  327. public static function respond($result, $format='xml') {
  328. $request = \OC::$server->getRequest();
  329. // Send 401 headers if unauthorised
  330. if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
  331. // If request comes from JS return dummy auth request
  332. if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
  333. header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
  334. } else {
  335. header('WWW-Authenticate: Basic realm="Authorisation Required"');
  336. }
  337. header('HTTP/1.0 401 Unauthorized');
  338. }
  339. foreach($result->getHeaders() as $name => $value) {
  340. header($name . ': ' . $value);
  341. }
  342. $meta = $result->getMeta();
  343. $data = $result->getData();
  344. if (self::isV2($request)) {
  345. $statusCode = self::mapStatusCodes($result->getStatusCode());
  346. if (!is_null($statusCode)) {
  347. $meta['statuscode'] = $statusCode;
  348. OC_Response::setStatus($statusCode);
  349. }
  350. }
  351. self::setContentType($format);
  352. $body = self::renderResult($format, $meta, $data);
  353. echo $body;
  354. }
  355. /**
  356. * @param XMLWriter $writer
  357. */
  358. private static function toXML($array, $writer) {
  359. foreach($array as $k => $v) {
  360. if ($k[0] === '@') {
  361. $writer->writeAttribute(substr($k, 1), $v);
  362. continue;
  363. } else if (is_numeric($k)) {
  364. $k = 'element';
  365. }
  366. if(is_array($v)) {
  367. $writer->startElement($k);
  368. self::toXML($v, $writer);
  369. $writer->endElement();
  370. } else {
  371. $writer->writeElement($k, $v);
  372. }
  373. }
  374. }
  375. /**
  376. * @return string
  377. */
  378. public static function requestedFormat() {
  379. $formats = array('json', 'xml');
  380. $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
  381. return $format;
  382. }
  383. /**
  384. * Based on the requested format the response content type is set
  385. * @param string $format
  386. */
  387. public static function setContentType($format = null) {
  388. $format = is_null($format) ? self::requestedFormat() : $format;
  389. if ($format === 'xml') {
  390. header('Content-type: text/xml; charset=UTF-8');
  391. return;
  392. }
  393. if ($format === 'json') {
  394. header('Content-Type: application/json; charset=utf-8');
  395. return;
  396. }
  397. header('Content-Type: application/octet-stream; charset=utf-8');
  398. }
  399. /**
  400. * @param \OCP\IRequest $request
  401. * @return bool
  402. */
  403. protected static function isV2(\OCP\IRequest $request) {
  404. $script = $request->getScriptName();
  405. return substr($script, -11) === '/ocs/v2.php';
  406. }
  407. /**
  408. * @param integer $sc
  409. * @return int
  410. */
  411. public static function mapStatusCodes($sc) {
  412. switch ($sc) {
  413. case API::RESPOND_NOT_FOUND:
  414. return Http::STATUS_NOT_FOUND;
  415. case API::RESPOND_SERVER_ERROR:
  416. return Http::STATUS_INTERNAL_SERVER_ERROR;
  417. case API::RESPOND_UNKNOWN_ERROR:
  418. return Http::STATUS_INTERNAL_SERVER_ERROR;
  419. case API::RESPOND_UNAUTHORISED:
  420. // already handled for v1
  421. return null;
  422. case 100:
  423. return Http::STATUS_OK;
  424. }
  425. // any 2xx, 4xx and 5xx will be used as is
  426. if ($sc >= 200 && $sc < 600) {
  427. return $sc;
  428. }
  429. return Http::STATUS_BAD_REQUEST;
  430. }
  431. /**
  432. * @param string $format
  433. * @return string
  434. */
  435. public static function renderResult($format, $meta, $data) {
  436. $response = array(
  437. 'ocs' => array(
  438. 'meta' => $meta,
  439. 'data' => $data,
  440. ),
  441. );
  442. if ($format == 'json') {
  443. return OC_JSON::encode($response);
  444. }
  445. $writer = new XMLWriter();
  446. $writer->openMemory();
  447. $writer->setIndent(true);
  448. $writer->startDocument();
  449. self::toXML($response, $writer);
  450. $writer->endDocument();
  451. return $writer->outputMemory(true);
  452. }
  453. }