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