api.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. OC::getRouter()->useCollection('ocs');
  64. OC::getRouter()->create($name, $url)
  65. ->method($method)
  66. ->defaults($defaults)
  67. ->requirements($requirements)
  68. ->action('OC_API', 'call');
  69. self::$actions[$name] = array();
  70. }
  71. self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
  72. }
  73. /**
  74. * handles an api call
  75. * @param array $parameters
  76. */
  77. public static function call($parameters) {
  78. // Prepare the request variables
  79. if($_SERVER['REQUEST_METHOD'] == 'PUT') {
  80. parse_str(file_get_contents("php://input"), $parameters['_put']);
  81. } else if($_SERVER['REQUEST_METHOD'] == 'DELETE') {
  82. parse_str(file_get_contents("php://input"), $parameters['_delete']);
  83. }
  84. $name = $parameters['_route'];
  85. // Foreach registered action
  86. $responses = array();
  87. foreach(self::$actions[$name] as $action) {
  88. // Check authentication and availability
  89. if(!self::isAuthorised($action)) {
  90. $responses[] = array(
  91. 'app' => $action['app'],
  92. 'response' => new OC_OCS_Result(null, OC_API::RESPOND_UNAUTHORISED, 'Unauthorised'),
  93. );
  94. continue;
  95. }
  96. if(!is_callable($action['action'])) {
  97. $responses[] = array(
  98. 'app' => $action['app'],
  99. 'response' => new OC_OCS_Result(null, OC_API::RESPOND_NOT_FOUND, 'Api method not found'),
  100. );
  101. continue;
  102. }
  103. // Run the action
  104. $responses[] = array(
  105. 'app' => $action['app'],
  106. 'response' => call_user_func($action['action'], $parameters),
  107. );
  108. }
  109. $response = self::mergeResponses($responses);
  110. $formats = array('json', 'xml');
  111. $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
  112. if (self::$logoutRequired) {
  113. OC_User::logout();
  114. }
  115. self::respond($response, $format);
  116. }
  117. /**
  118. * merge the returned result objects into one response
  119. * @param array $responses
  120. */
  121. private static function mergeResponses($responses) {
  122. $response = array();
  123. // Sort into shipped and thirdparty
  124. $shipped = array(
  125. 'succeeded' => array(),
  126. 'failed' => array(),
  127. );
  128. $thirdparty = array(
  129. 'succeeded' => array(),
  130. 'failed' => array(),
  131. );
  132. foreach($responses as $response) {
  133. if(OC_App::isShipped($response['app']) || ($response['app'] === 'core')) {
  134. if($response['response']->succeeded()) {
  135. $shipped['succeeded'][$response['app']] = $response['response'];
  136. } else {
  137. $shipped['failed'][$response['app']] = $response['response'];
  138. }
  139. } else {
  140. if($response['response']->succeeded()) {
  141. $thirdparty['succeeded'][$response['app']] = $response['response'];
  142. } else {
  143. $thirdparty['failed'][$response['app']] = $response['response'];
  144. }
  145. }
  146. }
  147. // Remove any error responses if there is one shipped response that succeeded
  148. if(!empty($shipped['succeeded'])) {
  149. $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
  150. } else if(!empty($shipped['failed'])) {
  151. // Which shipped response do we use if they all failed?
  152. // They may have failed for different reasons (different status codes)
  153. // Which reponse code should we return?
  154. // Maybe any that are not OC_API::RESPOND_SERVER_ERROR
  155. $response = reset($shipped['failed']);
  156. return $response;
  157. } elseif(!empty($thirdparty['failed'])) {
  158. // Return the third party failure result
  159. $response = reset($thirdparty['failed']);
  160. return $response;
  161. } else {
  162. $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
  163. }
  164. // Merge the successful responses
  165. $meta = array();
  166. $data = array();
  167. foreach($responses as $app => $response) {
  168. if(OC_App::isShipped($app)) {
  169. $data = array_merge_recursive($response->getData(), $data);
  170. } else {
  171. $data = array_merge_recursive($data, $response->getData());
  172. }
  173. }
  174. $result = new OC_OCS_Result($data, 100);
  175. return $result;
  176. }
  177. /**
  178. * authenticate the api call
  179. * @param array $action the action details as supplied to OC_API::register()
  180. * @return bool
  181. */
  182. private static function isAuthorised($action) {
  183. $level = $action['authlevel'];
  184. switch($level) {
  185. case OC_API::GUEST_AUTH:
  186. // Anyone can access
  187. return true;
  188. break;
  189. case OC_API::USER_AUTH:
  190. // User required
  191. return self::loginUser();
  192. break;
  193. case OC_API::SUBADMIN_AUTH:
  194. // Check for subadmin
  195. $user = self::loginUser();
  196. if(!$user) {
  197. return false;
  198. } else {
  199. $subAdmin = OC_SubAdmin::isSubAdmin($user);
  200. $admin = OC_User::isAdminUser($user);
  201. if($subAdmin || $admin) {
  202. return true;
  203. } else {
  204. return false;
  205. }
  206. }
  207. break;
  208. case OC_API::ADMIN_AUTH:
  209. // Check for admin
  210. $user = self::loginUser();
  211. if(!$user) {
  212. return false;
  213. } else {
  214. return OC_User::isAdminUser($user);
  215. }
  216. break;
  217. default:
  218. // oops looks like invalid level supplied
  219. return false;
  220. break;
  221. }
  222. }
  223. /**
  224. * http basic auth
  225. * @return string|false (username, or false on failure)
  226. */
  227. private static function loginUser(){
  228. // basic auth
  229. $authUser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
  230. $authPw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
  231. $return = OC_User::login($authUser, $authPw);
  232. if ($return === true) {
  233. self::$logoutRequired = true;
  234. return $authUser;
  235. }
  236. // reuse existing login
  237. $loggedIn = OC_User::isLoggedIn();
  238. if ($loggedIn === true) {
  239. return OC_User::getUser();
  240. }
  241. return false;
  242. }
  243. /**
  244. * respond to a call
  245. * @param OC_OCS_Result $result
  246. * @param string $format the format xml|json
  247. */
  248. private static function respond($result, $format='xml') {
  249. // Send 401 headers if unauthorised
  250. if($result->getStatusCode() === self::RESPOND_UNAUTHORISED) {
  251. header('WWW-Authenticate: Basic realm="Authorisation Required"');
  252. header('HTTP/1.0 401 Unauthorized');
  253. }
  254. $response = array(
  255. 'ocs' => array(
  256. 'meta' => $result->getMeta(),
  257. 'data' => $result->getData(),
  258. ),
  259. );
  260. if ($format == 'json') {
  261. OC_JSON::encodedPrint($response);
  262. } else if ($format == 'xml') {
  263. header('Content-type: text/xml; charset=UTF-8');
  264. $writer = new XMLWriter();
  265. $writer->openMemory();
  266. $writer->setIndent( true );
  267. $writer->startDocument();
  268. self::toXML($response, $writer);
  269. $writer->endDocument();
  270. echo $writer->outputMemory(true);
  271. }
  272. }
  273. private static function toXML($array, $writer) {
  274. foreach($array as $k => $v) {
  275. if ($k[0] === '@') {
  276. $writer->writeAttribute(substr($k, 1), $v);
  277. continue;
  278. } else if (is_numeric($k)) {
  279. $k = 'element';
  280. }
  281. if(is_array($v)) {
  282. $writer->startElement($k);
  283. self::toXML($v, $writer);
  284. $writer->endElement();
  285. } else {
  286. $writer->writeElement($k, $v);
  287. }
  288. }
  289. }
  290. }