api.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Tom Needham
  6. * @author Michael Gapczynski
  7. * @author Bart Visscher
  8. * @copyright 2012 Tom Needham tom@owncloud.com
  9. * @copyright 2012 Michael Gapczynski mtgap@owncloud.com
  10. * @copyright 2012 Bart Visscher bartv@thisnet.nl
  11. *
  12. * This library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  14. * License as published by the Free Software Foundation; either
  15. * version 3 of the License, or any later version.
  16. *
  17. * This library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public
  23. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. class OC_API {
  27. /**
  28. * API authentication levels
  29. */
  30. const GUEST_AUTH = 0;
  31. const USER_AUTH = 1;
  32. const SUBADMIN_AUTH = 2;
  33. const ADMIN_AUTH = 3;
  34. /**
  35. * API Response Codes
  36. */
  37. const RESPOND_UNAUTHORISED = 997;
  38. const RESPOND_SERVER_ERROR = 996;
  39. const RESPOND_NOT_FOUND = 998;
  40. const RESPOND_UNKNOWN_ERROR = 999;
  41. /**
  42. * api actions
  43. */
  44. protected static $actions = array();
  45. private static $logoutRequired = false;
  46. /**
  47. * registers an api call
  48. * @param string $method the http method
  49. * @param string $url the url to match
  50. * @param callable $action the function to run
  51. * @param string $app the id of the app registering the call
  52. * @param int $authLevel the level of authentication required for the call
  53. * @param array $defaults
  54. * @param array $requirements
  55. */
  56. public static function register($method, $url, $action, $app,
  57. $authLevel = OC_API::USER_AUTH,
  58. $defaults = array(),
  59. $requirements = array()) {
  60. $name = strtolower($method).$url;
  61. $name = str_replace(array('/', '{', '}'), '_', $name);
  62. if(!isset(self::$actions[$name])) {
  63. $oldCollection = OC::$server->getRouter()->getCurrentCollection();
  64. OC::$server->getRouter()->useCollection('ocs');
  65. OC::$server->getRouter()->create($name, $url)
  66. ->method($method)
  67. ->defaults($defaults)
  68. ->requirements($requirements)
  69. ->action('OC_API', 'call');
  70. self::$actions[$name] = array();
  71. OC::$server->getRouter()->useCollection($oldCollection);
  72. }
  73. self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
  74. }
  75. /**
  76. * handles an api call
  77. * @param array $parameters
  78. */
  79. public static function call($parameters) {
  80. // Prepare the request variables
  81. if($_SERVER['REQUEST_METHOD'] == 'PUT') {
  82. parse_str(file_get_contents("php://input"), $parameters['_put']);
  83. } else if($_SERVER['REQUEST_METHOD'] == 'DELETE') {
  84. parse_str(file_get_contents("php://input"), $parameters['_delete']);
  85. }
  86. $name = $parameters['_route'];
  87. // Foreach registered action
  88. $responses = array();
  89. foreach(self::$actions[$name] as $action) {
  90. // Check authentication and availability
  91. if(!self::isAuthorised($action)) {
  92. $responses[] = array(
  93. 'app' => $action['app'],
  94. 'response' => new OC_OCS_Result(null, OC_API::RESPOND_UNAUTHORISED, 'Unauthorised'),
  95. 'shipped' => OC_App::isShipped($action['app']),
  96. );
  97. continue;
  98. }
  99. if(!is_callable($action['action'])) {
  100. $responses[] = array(
  101. 'app' => $action['app'],
  102. 'response' => new OC_OCS_Result(null, OC_API::RESPOND_NOT_FOUND, 'Api method not found'),
  103. 'shipped' => OC_App::isShipped($action['app']),
  104. );
  105. continue;
  106. }
  107. // Run the action
  108. $responses[] = array(
  109. 'app' => $action['app'],
  110. 'response' => call_user_func($action['action'], $parameters),
  111. 'shipped' => OC_App::isShipped($action['app']),
  112. );
  113. }
  114. $response = self::mergeResponses($responses);
  115. $format = self::requestedFormat();
  116. if (self::$logoutRequired) {
  117. OC_User::logout();
  118. }
  119. self::respond($response, $format);
  120. }
  121. /**
  122. * merge the returned result objects into one response
  123. * @param array $responses
  124. * @return array|\OC_OCS_Result
  125. */
  126. public static function mergeResponses($responses) {
  127. // Sort into shipped and thirdparty
  128. $shipped = array(
  129. 'succeeded' => array(),
  130. 'failed' => array(),
  131. );
  132. $thirdparty = array(
  133. 'succeeded' => array(),
  134. 'failed' => array(),
  135. );
  136. foreach($responses as $response) {
  137. if($response['shipped'] || ($response['app'] === 'core')) {
  138. if($response['response']->succeeded()) {
  139. $shipped['succeeded'][$response['app']] = $response;
  140. } else {
  141. $shipped['failed'][$response['app']] = $response;
  142. }
  143. } else {
  144. if($response['response']->succeeded()) {
  145. $thirdparty['succeeded'][$response['app']] = $response;
  146. } else {
  147. $thirdparty['failed'][$response['app']] = $response;
  148. }
  149. }
  150. }
  151. // Remove any error responses if there is one shipped response that succeeded
  152. if(!empty($shipped['failed'])) {
  153. // Which shipped response do we use if they all failed?
  154. // They may have failed for different reasons (different status codes)
  155. // Which reponse code should we return?
  156. // Maybe any that are not OC_API::RESPOND_SERVER_ERROR
  157. // Merge failed responses if more than one
  158. $data = array();
  159. foreach($shipped['failed'] as $failure) {
  160. $data = array_merge_recursive($data, $failure['response']->getData());
  161. }
  162. $picked = reset($shipped['failed']);
  163. $code = $picked['response']->getStatusCode();
  164. $meta = $picked['response']->getMeta();
  165. $response = new OC_OCS_Result($data, $code, $meta['message']);
  166. return $response;
  167. } elseif(!empty($shipped['succeeded'])) {
  168. $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
  169. } elseif(!empty($thirdparty['failed'])) {
  170. // Merge failed responses if more than one
  171. $data = array();
  172. foreach($thirdparty['failed'] as $failure) {
  173. $data = array_merge_recursive($data, $failure['response']->getData());
  174. }
  175. $picked = reset($thirdparty['failed']);
  176. $code = $picked['response']->getStatusCode();
  177. $meta = $picked['response']->getMeta();
  178. $response = new OC_OCS_Result($data, $code, $meta['message']);
  179. return $response;
  180. } else {
  181. $responses = $thirdparty['succeeded'];
  182. }
  183. // Merge the successful responses
  184. $data = array();
  185. foreach($responses as $response) {
  186. if($response['shipped']) {
  187. $data = array_merge_recursive($response['response']->getData(), $data);
  188. } else {
  189. $data = array_merge_recursive($data, $response['response']->getData());
  190. }
  191. $codes[] = array('code' => $response['response']->getStatusCode(),
  192. 'meta' => $response['response']->getMeta());
  193. }
  194. // Use any non 100 status codes
  195. $statusCode = 100;
  196. $statusMessage = null;
  197. foreach($codes as $code) {
  198. if($code['code'] != 100) {
  199. $statusCode = $code['code'];
  200. $statusMessage = $code['meta']['message'];
  201. break;
  202. }
  203. }
  204. $result = new OC_OCS_Result($data, $statusCode, $statusMessage);
  205. return $result;
  206. }
  207. /**
  208. * authenticate the api call
  209. * @param array $action the action details as supplied to OC_API::register()
  210. * @return bool
  211. */
  212. private static function isAuthorised($action) {
  213. $level = $action['authlevel'];
  214. switch($level) {
  215. case OC_API::GUEST_AUTH:
  216. // Anyone can access
  217. return true;
  218. break;
  219. case OC_API::USER_AUTH:
  220. // User required
  221. return self::loginUser();
  222. break;
  223. case OC_API::SUBADMIN_AUTH:
  224. // Check for subadmin
  225. $user = self::loginUser();
  226. if(!$user) {
  227. return false;
  228. } else {
  229. $subAdmin = OC_SubAdmin::isSubAdmin($user);
  230. $admin = OC_User::isAdminUser($user);
  231. if($subAdmin || $admin) {
  232. return true;
  233. } else {
  234. return false;
  235. }
  236. }
  237. break;
  238. case OC_API::ADMIN_AUTH:
  239. // Check for admin
  240. $user = self::loginUser();
  241. if(!$user) {
  242. return false;
  243. } else {
  244. return OC_User::isAdminUser($user);
  245. }
  246. break;
  247. default:
  248. // oops looks like invalid level supplied
  249. return false;
  250. break;
  251. }
  252. }
  253. /**
  254. * http basic auth
  255. * @return string|false (username, or false on failure)
  256. */
  257. private static function loginUser(){
  258. // reuse existing login
  259. $loggedIn = OC_User::isLoggedIn();
  260. $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
  261. if ($loggedIn === true && $ocsApiRequest) {
  262. // initialize the user's filesystem
  263. \OC_Util::setUpFS(\OC_User::getUser());
  264. return OC_User::getUser();
  265. }
  266. // basic auth
  267. $authUser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
  268. $authPw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
  269. $return = OC_User::login($authUser, $authPw);
  270. if ($return === true) {
  271. self::$logoutRequired = true;
  272. // initialize the user's filesystem
  273. \OC_Util::setUpFS(\OC_User::getUser());
  274. return $authUser;
  275. }
  276. return false;
  277. }
  278. /**
  279. * respond to a call
  280. * @param OC_OCS_Result $result
  281. * @param string $format the format xml|json
  282. */
  283. public static function respond($result, $format='xml') {
  284. // Send 401 headers if unauthorised
  285. if($result->getStatusCode() === self::RESPOND_UNAUTHORISED) {
  286. header('WWW-Authenticate: Basic realm="Authorisation Required"');
  287. header('HTTP/1.0 401 Unauthorized');
  288. }
  289. $response = array(
  290. 'ocs' => array(
  291. 'meta' => $result->getMeta(),
  292. 'data' => $result->getData(),
  293. ),
  294. );
  295. if ($format == 'json') {
  296. OC_JSON::encodedPrint($response);
  297. } else if ($format == 'xml') {
  298. header('Content-type: text/xml; charset=UTF-8');
  299. $writer = new XMLWriter();
  300. $writer->openMemory();
  301. $writer->setIndent( true );
  302. $writer->startDocument();
  303. self::toXML($response, $writer);
  304. $writer->endDocument();
  305. echo $writer->outputMemory(true);
  306. }
  307. }
  308. /**
  309. * @param XMLWriter $writer
  310. */
  311. private static function toXML($array, $writer) {
  312. foreach($array as $k => $v) {
  313. if ($k[0] === '@') {
  314. $writer->writeAttribute(substr($k, 1), $v);
  315. continue;
  316. } else if (is_numeric($k)) {
  317. $k = 'element';
  318. }
  319. if(is_array($v)) {
  320. $writer->startElement($k);
  321. self::toXML($v, $writer);
  322. $writer->endElement();
  323. } else {
  324. $writer->writeElement($k, $v);
  325. }
  326. }
  327. }
  328. /**
  329. * @return string
  330. */
  331. public static function requestedFormat() {
  332. $formats = array('json', 'xml');
  333. $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
  334. return $format;
  335. }
  336. /**
  337. * Based on the requested format the response content type is set
  338. */
  339. public static function setContentType() {
  340. $format = \OC_API::requestedFormat();
  341. if ($format === 'xml') {
  342. header('Content-type: text/xml; charset=UTF-8');
  343. return;
  344. }
  345. if ($format === 'json') {
  346. header('Content-Type: application/json; charset=utf-8');
  347. return;
  348. }
  349. header('Content-Type: application/octet-stream; charset=utf-8');
  350. }
  351. }