PageRenderTime 75ms CodeModel.GetById 29ms RepoModel.GetById 2ms app.codeStats 0ms

/lib/api.php

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