server/lib/private/legacy/api.php

499 lines
14 KiB
PHP
Raw Normal View History

<?php
2015-10-05 18:54:56 +00:00
/**
2016-07-21 15:07:57 +00:00
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
2015-10-05 18:54:56 +00:00
* @author Bart Visscher <bartv@thisnet.nl>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
2016-05-26 17:56:05 +00:00
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@owncloud.com>
2016-07-21 15:07:57 +00:00
* @author Joas Schilling <coding@schilljs.com>
2015-10-05 18:54:56 +00:00
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
2016-05-26 17:56:05 +00:00
* @author Lukas Reschke <lukas@statuscode.ch>
2015-10-05 18:54:56 +00:00
* @author Michael Gapczynski <GapczynskiM@gmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
2016-07-21 16:13:36 +00:00
* @author Robin Appelman <robin@icewind.nl>
2016-07-21 15:07:57 +00:00
* @author Roeland Jago Douma <roeland@famdouma.nl>
2015-10-05 18:54:56 +00:00
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Tom Needham <tom@owncloud.com>
* @author Vincent Petry <pvince81@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
use OCP\API;
use OCP\AppFramework\Http;
2012-07-28 21:50:40 +00:00
class OC_API {
/**
* API authentication levels
*/
/** @deprecated Use \OCP\API::GUEST_AUTH instead */
const GUEST_AUTH = 0;
/** @deprecated Use \OCP\API::USER_AUTH instead */
const USER_AUTH = 1;
/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
const SUBADMIN_AUTH = 2;
/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
const ADMIN_AUTH = 3;
2014-01-13 11:27:05 +00:00
/**
* API Response Codes
*/
/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
const RESPOND_UNAUTHORISED = 997;
/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
const RESPOND_SERVER_ERROR = 996;
/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
const RESPOND_NOT_FOUND = 998;
/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
const RESPOND_UNKNOWN_ERROR = 999;
2014-01-13 11:27:05 +00:00
2012-07-28 21:50:40 +00:00
/**
* api actions
*/
protected static $actions = array();
private static $logoutRequired = false;
2014-12-17 19:22:51 +00:00
private static $isLoggedIn = false;
2014-01-13 11:27:05 +00:00
2012-07-28 21:50:40 +00:00
/**
* 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
*/
2014-01-13 11:27:05 +00:00
public static function register($method, $url, $action, $app,
$authLevel = API::USER_AUTH,
2012-07-31 21:26:15 +00:00
$defaults = array(),
$requirements = array()) {
2012-07-28 21:50:40 +00:00
$name = strtolower($method).$url;
2012-07-30 18:52:47 +00:00
$name = str_replace(array('/', '{', '}'), '_', $name);
if(!isset(self::$actions[$name])) {
$oldCollection = OC::$server->getRouter()->getCurrentCollection();
OC::$server->getRouter()->useCollection('ocs');
OC::$server->getRouter()->create($name, $url)
->method($method)
->defaults($defaults)
->requirements($requirements)
2012-07-28 21:50:40 +00:00
->action('OC_API', 'call');
self::$actions[$name] = array();
OC::$server->getRouter()->useCollection($oldCollection);
2012-07-28 21:50:40 +00:00
}
self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
2012-07-28 21:50:40 +00:00
}
2014-01-13 11:27:05 +00:00
2012-07-28 21:50:40 +00:00
/**
* handles an api call
* @param array $parameters
*/
public static function call($parameters) {
$request = \OC::$server->getRequest();
2015-03-01 10:46:39 +00:00
$method = $request->getMethod();
2012-09-17 12:08:17 +00:00
// Prepare the request variables
2015-03-01 10:46:39 +00:00
if($method === 'PUT') {
$parameters['_put'] = $request->getParams();
2015-03-01 10:46:39 +00:00
} else if($method === 'DELETE') {
$parameters['_delete'] = $request->getParams();
2012-09-17 12:08:17 +00:00
}
2012-07-30 19:03:41 +00:00
$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, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
'shipped' => OC_App::isShipped($action['app']),
);
continue;
2013-01-14 19:30:39 +00:00
}
if(!is_callable($action['action'])) {
$responses[] = array(
'app' => $action['app'],
'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
'shipped' => OC_App::isShipped($action['app']),
);
continue;
}
// Run the action
$responses[] = array(
'app' => $action['app'],
'response' => call_user_func($action['action'], $parameters),
'shipped' => OC_App::isShipped($action['app']),
);
}
$response = self::mergeResponses($responses);
2014-03-11 23:35:19 +00:00
$format = self::requestedFormat();
if (self::$logoutRequired) {
\OC::$server->getUserSession()->logout();
}
2013-05-02 12:51:53 +00:00
self::respond($response, $format);
2012-07-28 21:50:40 +00:00
}
2014-01-13 11:27:05 +00:00
/**
* merge the returned result objects into one response
* @param array $responses
* @return OC_OCS_Result
*/
public static function mergeResponses($responses) {
// Sort into shipped and third-party
$shipped = array(
2013-02-09 12:50:19 +00:00
'succeeded' => array(),
'failed' => array(),
);
$thirdparty = array(
'succeeded' => array(),
'failed' => array(),
);
2013-01-14 19:30:39 +00:00
foreach($responses as $response) {
if($response['shipped'] || ($response['app'] === 'core')) {
if($response['response']->succeeded()) {
$shipped['succeeded'][$response['app']] = $response;
} else {
$shipped['failed'][$response['app']] = $response;
}
} else {
if($response['response']->succeeded()) {
$thirdparty['succeeded'][$response['app']] = $response;
} else {
$thirdparty['failed'][$response['app']] = $response;
}
}
}
// Remove any error responses if there is one shipped response that succeeded
if(!empty($shipped['failed'])) {
// Which shipped response do we use if they all failed?
// They may have failed for different reasons (different status codes)
// Which response code should we return?
// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
// Merge failed responses if more than one
$data = array();
foreach($shipped['failed'] as $failure) {
$data = array_merge_recursive($data, $failure['response']->getData());
}
$picked = reset($shipped['failed']);
$code = $picked['response']->getStatusCode();
2014-01-13 11:27:05 +00:00
$meta = $picked['response']->getMeta();
2015-08-10 19:33:50 +00:00
$headers = $picked['response']->getHeaders();
$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
return $response;
} elseif(!empty($shipped['succeeded'])) {
$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
} elseif(!empty($thirdparty['failed'])) {
// Merge failed responses if more than one
$data = array();
foreach($thirdparty['failed'] as $failure) {
$data = array_merge_recursive($data, $failure['response']->getData());
}
$picked = reset($thirdparty['failed']);
$code = $picked['response']->getStatusCode();
2014-01-13 11:27:05 +00:00
$meta = $picked['response']->getMeta();
2015-08-10 19:33:50 +00:00
$headers = $picked['response']->getHeaders();
$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
return $response;
} else {
$responses = $thirdparty['succeeded'];
}
// Merge the successful responses
2015-08-10 19:33:50 +00:00
$data = [];
$codes = [];
$header = [];
2014-04-21 13:44:54 +00:00
foreach($responses as $response) {
if($response['shipped']) {
$data = array_merge_recursive($response['response']->getData(), $data);
} else {
$data = array_merge_recursive($data, $response['response']->getData());
}
2015-08-10 19:33:50 +00:00
$header = array_merge_recursive($header, $response['response']->getHeaders());
$codes[] = ['code' => $response['response']->getStatusCode(),
'meta' => $response['response']->getMeta()];
}
// Use any non 100 status codes
$statusCode = 100;
2014-01-13 11:27:05 +00:00
$statusMessage = null;
foreach($codes as $code) {
2014-01-13 11:27:05 +00:00
if($code['code'] != 100) {
$statusCode = $code['code'];
$statusMessage = $code['meta']['message'];
break;
}
}
2015-08-10 19:33:50 +00:00
return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
}
2014-01-13 11:27:05 +00:00
/**
* 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 API::GUEST_AUTH:
// Anyone can access
return true;
case API::USER_AUTH:
// User required
return self::loginUser();
case API::SUBADMIN_AUTH:
// Check for subadmin
$user = self::loginUser();
if(!$user) {
return false;
} else {
2015-10-27 13:09:45 +00:00
$userObject = \OC::$server->getUserSession()->getUser();
if($userObject === null) {
return false;
}
$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
$admin = OC_User::isAdminUser($user);
2015-10-27 13:09:45 +00:00
if($isSubAdmin || $admin) {
return true;
} else {
return false;
}
}
case API::ADMIN_AUTH:
// Check for admin
$user = self::loginUser();
if(!$user) {
return false;
} else {
return OC_User::isAdminUser($user);
}
default:
// oops looks like invalid level supplied
return false;
}
2014-01-13 11:27:05 +00:00
}
/**
* http basic auth
2016-02-17 15:13:37 +00:00
* @return string|false (username, or false on failure)
*/
2014-12-17 19:22:51 +00:00
private static function loginUser() {
if(self::$isLoggedIn === true) {
return \OC_User::getUser();
}
2014-03-07 19:06:06 +00:00
// reuse existing login
2016-04-27 07:38:30 +00:00
$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
if ($loggedIn === true) {
if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
// Do not allow access to OCS until the 2FA challenge was solved successfully
return false;
}
$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
if ($ocsApiRequest) {
// initialize the user's filesystem
\OC_Util::setupFS(\OC_User::getUser());
2014-12-17 19:22:51 +00:00
self::$isLoggedIn = true;
return OC_User::getUser();
}
return false;
2014-03-07 19:06:06 +00:00
}
// basic auth - because OC_User::login will create a new session we shall only try to login
// if user and pass are set
2016-04-27 07:38:30 +00:00
$userSession = \OC::$server->getUserSession();
2016-04-29 12:00:07 +00:00
$request = \OC::$server->getRequest();
2016-04-27 07:38:30 +00:00
try {
if ($userSession->tryTokenLogin($request)
|| $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
self::$logoutRequired = true;
} else {
return false;
}
2016-04-27 07:38:30 +00:00
// initialize the user's filesystem
\OC_Util::setupFS(\OC_User::getUser());
2016-04-27 07:38:30 +00:00
self::$isLoggedIn = true;
2016-04-27 07:38:30 +00:00
return \OC_User::getUser();
} catch (\OC\User\LoginException $e) {
return false;
}
}
2014-01-13 11:27:05 +00:00
2012-07-28 21:50:40 +00:00
/**
* respond to a call
* @param OC_OCS_Result $result
* @param string $format the format xml|json
*/
public static function respond($result, $format='xml') {
2016-02-15 14:38:37 +00:00
$request = \OC::$server->getRequest();
// Send 401 headers if unauthorised
if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
2016-02-15 14:38:37 +00:00
// If request comes from JS return dummy auth request
if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
} else {
header('WWW-Authenticate: Basic realm="Authorisation Required"');
}
header('HTTP/1.0 401 Unauthorized');
}
foreach($result->getHeaders() as $name => $value) {
header($name . ': ' . $value);
}
$meta = $result->getMeta();
$data = $result->getData();
2016-02-15 14:38:37 +00:00
if (self::isV2($request)) {
$statusCode = self::mapStatusCodes($result->getStatusCode());
if (!is_null($statusCode)) {
$meta['statuscode'] = $statusCode;
OC_Response::setStatus($statusCode);
}
}
2015-08-03 19:03:11 +00:00
self::setContentType($format);
$body = self::renderResult($format, $meta, $data);
2015-08-03 19:03:11 +00:00
echo $body;
2012-07-28 21:50:40 +00:00
}
2012-08-01 17:48:51 +00:00
/**
* @param XMLWriter $writer
*/
private static function toXML($array, $writer) {
2012-08-01 17:48:51 +00:00
foreach($array as $k => $v) {
if ($k[0] === '@') {
$writer->writeAttribute(substr($k, 1), $v);
continue;
} else if (is_numeric($k)) {
2012-08-02 15:48:09 +00:00
$k = 'element';
}
if(is_array($v)) {
2012-08-01 17:48:51 +00:00
$writer->startElement($k);
self::toXML($v, $writer);
$writer->endElement();
} else {
$writer->writeElement($k, $v);
}
}
}
2014-01-13 11:27:05 +00:00
2014-03-11 23:35:19 +00:00
/**
* @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
* @param string $format
2014-03-11 23:35:19 +00:00
*/
2015-08-03 19:03:11 +00:00
public static function setContentType($format = null) {
$format = is_null($format) ? self::requestedFormat() : $format;
2014-03-11 23:35:19 +00:00
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');
}
/**
* @param \OCP\IRequest $request
* @return bool
*/
protected static function isV2(\OCP\IRequest $request) {
$script = $request->getScriptName();
2014-03-11 23:35:19 +00:00
return substr($script, -11) === '/ocs/v2.php';
}
/**
* @param integer $sc
* @return int
*/
public static function mapStatusCodes($sc) {
switch ($sc) {
case API::RESPOND_NOT_FOUND:
return Http::STATUS_NOT_FOUND;
case API::RESPOND_SERVER_ERROR:
return Http::STATUS_INTERNAL_SERVER_ERROR;
case API::RESPOND_UNKNOWN_ERROR:
return Http::STATUS_INTERNAL_SERVER_ERROR;
case API::RESPOND_UNAUTHORISED:
// already handled for v1
return null;
case 100:
return Http::STATUS_OK;
}
// any 2xx, 4xx and 5xx will be used as is
if ($sc >= 200 && $sc < 600) {
return $sc;
}
return Http::STATUS_BAD_REQUEST;
}
2015-08-03 19:03:11 +00:00
/**
* @param string $format
* @return string
*/
public static function renderResult($format, $meta, $data) {
2015-08-03 19:03:11 +00:00
$response = array(
'ocs' => array(
'meta' => $meta,
'data' => $data,
2015-08-03 19:03:11 +00:00
),
);
if ($format == 'json') {
return OC_JSON::encode($response);
}
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(true);
$writer->startDocument();
self::toXML($response, $writer);
$writer->endDocument();
return $writer->outputMemory(true);
}
2012-07-30 19:03:41 +00:00
}