api.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. foreach(self::$actions[$name] as $action) {
  112. // Check authentication and availability
  113. if(!self::isAuthorised($action)) {
  114. $responses[] = array(
  115. 'app' => $action['app'],
  116. 'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
  117. 'shipped' => OC_App::isShipped($action['app']),
  118. );
  119. continue;
  120. }
  121. if(!is_callable($action['action'])) {
  122. $responses[] = array(
  123. 'app' => $action['app'],
  124. 'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
  125. 'shipped' => OC_App::isShipped($action['app']),
  126. );
  127. continue;
  128. }
  129. // Run the action
  130. $responses[] = array(
  131. 'app' => $action['app'],
  132. 'response' => call_user_func($action['action'], $parameters),
  133. 'shipped' => OC_App::isShipped($action['app']),
  134. );
  135. }
  136. $response = self::mergeResponses($responses);
  137. $format = self::requestedFormat();
  138. if (self::$logoutRequired) {
  139. \OC::$server->getUserSession()->logout();
  140. }
  141. self::respond($response, $format);
  142. }
  143. /**
  144. * merge the returned result objects into one response
  145. * @param array $responses
  146. * @return OC_OCS_Result
  147. */
  148. public static function mergeResponses($responses) {
  149. // Sort into shipped and third-party
  150. $shipped = array(
  151. 'succeeded' => array(),
  152. 'failed' => array(),
  153. );
  154. $thirdparty = array(
  155. 'succeeded' => array(),
  156. 'failed' => array(),
  157. );
  158. foreach($responses as $response) {
  159. if($response['shipped'] || ($response['app'] === 'core')) {
  160. if($response['response']->succeeded()) {
  161. $shipped['succeeded'][$response['app']] = $response;
  162. } else {
  163. $shipped['failed'][$response['app']] = $response;
  164. }
  165. } else {
  166. if($response['response']->succeeded()) {
  167. $thirdparty['succeeded'][$response['app']] = $response;
  168. } else {
  169. $thirdparty['failed'][$response['app']] = $response;
  170. }
  171. }
  172. }
  173. // Remove any error responses if there is one shipped response that succeeded
  174. if(!empty($shipped['failed'])) {
  175. // Which shipped response do we use if they all failed?
  176. // They may have failed for different reasons (different status codes)
  177. // Which response code should we return?
  178. // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
  179. // Merge failed responses if more than one
  180. $data = array();
  181. foreach($shipped['failed'] as $failure) {
  182. $data = array_merge_recursive($data, $failure['response']->getData());
  183. }
  184. $picked = reset($shipped['failed']);
  185. $code = $picked['response']->getStatusCode();
  186. $meta = $picked['response']->getMeta();
  187. $headers = $picked['response']->getHeaders();
  188. $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
  189. return $response;
  190. } elseif(!empty($shipped['succeeded'])) {
  191. $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
  192. } elseif(!empty($thirdparty['failed'])) {
  193. // Merge failed responses if more than one
  194. $data = array();
  195. foreach($thirdparty['failed'] as $failure) {
  196. $data = array_merge_recursive($data, $failure['response']->getData());
  197. }
  198. $picked = reset($thirdparty['failed']);
  199. $code = $picked['response']->getStatusCode();
  200. $meta = $picked['response']->getMeta();
  201. $headers = $picked['response']->getHeaders();
  202. $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
  203. return $response;
  204. } else {
  205. $responses = $thirdparty['succeeded'];
  206. }
  207. // Merge the successful responses
  208. $data = [];
  209. $codes = [];
  210. $header = [];
  211. foreach($responses as $response) {
  212. if($response['shipped']) {
  213. $data = array_merge_recursive($response['response']->getData(), $data);
  214. } else {
  215. $data = array_merge_recursive($data, $response['response']->getData());
  216. }
  217. $header = array_merge_recursive($header, $response['response']->getHeaders());
  218. $codes[] = ['code' => $response['response']->getStatusCode(),
  219. 'meta' => $response['response']->getMeta()];
  220. }
  221. // Use any non 100 status codes
  222. $statusCode = 100;
  223. $statusMessage = null;
  224. foreach($codes as $code) {
  225. if($code['code'] != 100) {
  226. $statusCode = $code['code'];
  227. $statusMessage = $code['meta']['message'];
  228. break;
  229. }
  230. }
  231. return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
  232. }
  233. /**
  234. * authenticate the api call
  235. * @param array $action the action details as supplied to OC_API::register()
  236. * @return bool
  237. */
  238. private static function isAuthorised($action) {
  239. $level = $action['authlevel'];
  240. switch($level) {
  241. case API::GUEST_AUTH:
  242. // Anyone can access
  243. return true;
  244. case API::USER_AUTH:
  245. // User required
  246. return self::loginUser();
  247. case API::SUBADMIN_AUTH:
  248. // Check for subadmin
  249. $user = self::loginUser();
  250. if(!$user) {
  251. return false;
  252. } else {
  253. $userObject = \OC::$server->getUserSession()->getUser();
  254. if($userObject === null) {
  255. return false;
  256. }
  257. $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
  258. $admin = OC_User::isAdminUser($user);
  259. if($isSubAdmin || $admin) {
  260. return true;
  261. } else {
  262. return false;
  263. }
  264. }
  265. case API::ADMIN_AUTH:
  266. // Check for admin
  267. $user = self::loginUser();
  268. if(!$user) {
  269. return false;
  270. } else {
  271. return OC_User::isAdminUser($user);
  272. }
  273. default:
  274. // oops looks like invalid level supplied
  275. return false;
  276. }
  277. }
  278. /**
  279. * http basic auth
  280. * @return string|false (username, or false on failure)
  281. */
  282. private static function loginUser() {
  283. if(self::$isLoggedIn === true) {
  284. return \OC_User::getUser();
  285. }
  286. // reuse existing login
  287. $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
  288. if ($loggedIn === true) {
  289. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  290. // Do not allow access to OCS until the 2FA challenge was solved successfully
  291. return false;
  292. }
  293. $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
  294. if ($ocsApiRequest) {
  295. // initialize the user's filesystem
  296. \OC_Util::setupFS(\OC_User::getUser());
  297. self::$isLoggedIn = true;
  298. return OC_User::getUser();
  299. }
  300. return false;
  301. }
  302. // basic auth - because OC_User::login will create a new session we shall only try to login
  303. // if user and pass are set
  304. $userSession = \OC::$server->getUserSession();
  305. $request = \OC::$server->getRequest();
  306. try {
  307. if ($userSession->tryTokenLogin($request)
  308. || $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  309. self::$logoutRequired = true;
  310. } else {
  311. return false;
  312. }
  313. // initialize the user's filesystem
  314. \OC_Util::setupFS(\OC_User::getUser());
  315. self::$isLoggedIn = true;
  316. return \OC_User::getUser();
  317. } catch (\OC\User\LoginException $e) {
  318. return false;
  319. }
  320. }
  321. /**
  322. * respond to a call
  323. * @param OC_OCS_Result $result
  324. * @param string $format the format xml|json
  325. */
  326. public static function respond($result, $format='xml') {
  327. $request = \OC::$server->getRequest();
  328. // Send 401 headers if unauthorised
  329. if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
  330. // If request comes from JS return dummy auth request
  331. if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
  332. header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
  333. } else {
  334. header('WWW-Authenticate: Basic realm="Authorisation Required"');
  335. }
  336. header('HTTP/1.0 401 Unauthorized');
  337. }
  338. foreach($result->getHeaders() as $name => $value) {
  339. header($name . ': ' . $value);
  340. }
  341. $meta = $result->getMeta();
  342. $data = $result->getData();
  343. if (self::isV2($request)) {
  344. $statusCode = self::mapStatusCodes($result->getStatusCode());
  345. if (!is_null($statusCode)) {
  346. $meta['statuscode'] = $statusCode;
  347. OC_Response::setStatus($statusCode);
  348. }
  349. }
  350. self::setContentType($format);
  351. $body = self::renderResult($format, $meta, $data);
  352. echo $body;
  353. }
  354. /**
  355. * @param XMLWriter $writer
  356. */
  357. private static function toXML($array, $writer) {
  358. foreach($array as $k => $v) {
  359. if ($k[0] === '@') {
  360. $writer->writeAttribute(substr($k, 1), $v);
  361. continue;
  362. } else if (is_numeric($k)) {
  363. $k = 'element';
  364. }
  365. if(is_array($v)) {
  366. $writer->startElement($k);
  367. self::toXML($v, $writer);
  368. $writer->endElement();
  369. } else {
  370. $writer->writeElement($k, $v);
  371. }
  372. }
  373. }
  374. /**
  375. * @return string
  376. */
  377. public static function requestedFormat() {
  378. $formats = array('json', 'xml');
  379. $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
  380. return $format;
  381. }
  382. /**
  383. * Based on the requested format the response content type is set
  384. * @param string $format
  385. */
  386. public static function setContentType($format = null) {
  387. $format = is_null($format) ? self::requestedFormat() : $format;
  388. if ($format === 'xml') {
  389. header('Content-type: text/xml; charset=UTF-8');
  390. return;
  391. }
  392. if ($format === 'json') {
  393. header('Content-Type: application/json; charset=utf-8');
  394. return;
  395. }
  396. header('Content-Type: application/octet-stream; charset=utf-8');
  397. }
  398. /**
  399. * @param \OCP\IRequest $request
  400. * @return bool
  401. */
  402. protected static function isV2(\OCP\IRequest $request) {
  403. $script = $request->getScriptName();
  404. return substr($script, -11) === '/ocs/v2.php';
  405. }
  406. /**
  407. * @param integer $sc
  408. * @return int
  409. */
  410. public static function mapStatusCodes($sc) {
  411. switch ($sc) {
  412. case API::RESPOND_NOT_FOUND:
  413. return Http::STATUS_NOT_FOUND;
  414. case API::RESPOND_SERVER_ERROR:
  415. return Http::STATUS_INTERNAL_SERVER_ERROR;
  416. case API::RESPOND_UNKNOWN_ERROR:
  417. return Http::STATUS_INTERNAL_SERVER_ERROR;
  418. case API::RESPOND_UNAUTHORISED:
  419. // already handled for v1
  420. return null;
  421. case 100:
  422. return Http::STATUS_OK;
  423. }
  424. // any 2xx, 4xx and 5xx will be used as is
  425. if ($sc >= 200 && $sc < 600) {
  426. return $sc;
  427. }
  428. return Http::STATUS_BAD_REQUEST;
  429. }
  430. /**
  431. * @param string $format
  432. * @return string
  433. */
  434. public static function renderResult($format, $meta, $data) {
  435. $response = array(
  436. 'ocs' => array(
  437. 'meta' => $meta,
  438. 'data' => $data,
  439. ),
  440. );
  441. if ($format == 'json') {
  442. return OC_JSON::encode($response);
  443. }
  444. $writer = new XMLWriter();
  445. $writer->openMemory();
  446. $writer->setIndent(true);
  447. $writer->startDocument();
  448. self::toXML($response, $writer);
  449. $writer->endDocument();
  450. return $writer->outputMemory(true);
  451. }
  452. }