migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,92 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
/**
* Base class to inherit your controllers from that are used for RESTful APIs
* @since 7.0.0
*/
abstract class ApiController extends Controller {
private $corsMethods;
private $corsAllowedHeaders;
private $corsMaxAge;
/**
* constructor of the controller
* @param string $appName the name of the app
* @param IRequest $request an instance of the request
* @param string $corsMethods comma separated string of HTTP verbs which
* should be allowed for websites or webapps when calling your API, defaults to
* 'PUT, POST, GET, DELETE, PATCH'
* @param string $corsAllowedHeaders comma separated string of HTTP headers
* which should be allowed for websites or webapps when calling your API,
* defaults to 'Authorization, Content-Type, Accept'
* @param int $corsMaxAge number in seconds how long a preflighted OPTIONS
* request should be cached, defaults to 1728000 seconds
* @since 7.0.0
*/
public function __construct($appName,
IRequest $request,
$corsMethods = 'PUT, POST, GET, DELETE, PATCH',
$corsAllowedHeaders = 'Authorization, Content-Type, Accept',
$corsMaxAge = 1728000) {
parent::__construct($appName, $request);
$this->corsMethods = $corsMethods;
$this->corsAllowedHeaders = $corsAllowedHeaders;
$this->corsMaxAge = $corsMaxAge;
}
/**
* This method implements a preflighted cors response for you that you can
* link to for the options request
*
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
* @since 7.0.0
*/
#[NoCSRFRequired]
#[PublicPage]
public function preflightedCors() {
if (isset($this->request->server['HTTP_ORIGIN'])) {
$origin = $this->request->server['HTTP_ORIGIN'];
} else {
$origin = '*';
}
$response = new Response();
$response->addHeader('Access-Control-Allow-Origin', $origin);
$response->addHeader('Access-Control-Allow-Methods', $this->corsMethods);
$response->addHeader('Access-Control-Max-Age', (string)$this->corsMaxAge);
$response->addHeader('Access-Control-Allow-Headers', $this->corsAllowedHeaders);
$response->addHeader('Access-Control-Allow-Credentials', 'false');
return $response;
}
}
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use OC\AppFramework\Routing\RouteConfig;
use OC\Route\Router;
use OC\ServerContainer;
use OCP\Route\IRouter;
/**
* Class App
*
* Any application must inherit this call - all controller instances to be used are
* to be registered using IContainer::registerService
* @since 6.0.0
*/
class App {
/** @var IAppContainer */
private $container;
/**
* Turns an app id into a namespace by convention. The id is split at the
* underscores, all parts are CamelCased and reassembled. e.g.:
* some_app_id -> OCA\SomeAppId
* @param string $appId the app id
* @param string $topNamespace the namespace which should be prepended to
* the transformed app id, defaults to OCA\
* @return string the starting namespace for the app
* @since 8.0.0
*/
public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string {
return \OC\AppFramework\App::buildAppNamespace($appId, $topNamespace);
}
/**
* @param string $appName
* @param array $urlParams an array with variables extracted from the routes
* @since 6.0.0
*/
public function __construct(string $appName, array $urlParams = []) {
$runIsSetupDirectly = \OC::$server->getConfig()->getSystemValueBool('debug')
&& (PHP_VERSION_ID < 70400 || (PHP_VERSION_ID >= 70400 && !ini_get('zend.exception_ignore_args')));
if ($runIsSetupDirectly) {
$applicationClassName = get_class($this);
$e = new \RuntimeException('App class ' . $applicationClassName . ' is not setup via query() but directly');
$setUpViaQuery = false;
$classNameParts = explode('\\', trim($applicationClassName, '\\'));
foreach ($e->getTrace() as $step) {
if (isset($step['class'], $step['function'], $step['args'][0]) &&
$step['class'] === ServerContainer::class &&
$step['function'] === 'query' &&
$step['args'][0] === $applicationClassName) {
$setUpViaQuery = true;
break;
} elseif (isset($step['class'], $step['function'], $step['args'][0]) &&
$step['class'] === ServerContainer::class &&
$step['function'] === 'getAppContainer' &&
$step['args'][1] === $classNameParts[1]) {
$setUpViaQuery = true;
break;
}
}
if (!$setUpViaQuery && $applicationClassName !== \OCP\AppFramework\App::class) {
\OC::$server->getLogger()->logException($e, [
'app' => $appName,
]);
}
}
try {
$this->container = \OC::$server->getRegisteredAppContainer($appName);
} catch (QueryException $e) {
$this->container = new \OC\AppFramework\DependencyInjection\DIContainer($appName, $urlParams);
}
}
/**
* @return IAppContainer
* @since 6.0.0
*/
public function getContainer(): IAppContainer {
return $this->container;
}
/**
* This function is to be called to create single routes and restful routes based on the given $routes array.
*
* Example code in routes.php of tasks app (it will register two restful resources):
* $routes = array(
* 'resources' => array(
* 'lists' => array('url' => '/tasklists'),
* 'tasks' => array('url' => '/tasklists/{listId}/tasks')
* )
* );
*
* $a = new TasksApp();
* $a->registerRoutes($this, $routes);
*
* @param \OCP\Route\IRouter $router
* @param array $routes
* @since 6.0.0
* @suppress PhanAccessMethodInternal
* @deprecated 20.0.0 Just return an array from your routes.php
*/
public function registerRoutes(IRouter $router, array $routes) {
if (!($router instanceof Router)) {
throw new \RuntimeException('Can only setup routes with real router');
}
$routeConfig = new RouteConfig($this->container, $router, $routes);
$routeConfig->register();
}
/**
* This function is called by the routing component to fire up the frameworks dispatch mechanism.
*
* Example code in routes.php of the task app:
* $this->create('tasks_index', '/')->get()->action(
* function($params){
* $app = new TaskApp($params);
* $app->dispatch('PageController', 'index');
* }
* );
*
*
* Example for for TaskApp implementation:
* class TaskApp extends \OCP\AppFramework\App {
*
* public function __construct($params){
* parent::__construct('tasks', $params);
*
* $this->getContainer()->registerService('PageController', function(IAppContainer $c){
* $a = $c->query('API');
* $r = $c->query('Request');
* return new PageController($a, $r);
* });
* }
* }
*
* @param string $controllerName the name of the controller under which it is
* stored in the DI container
* @param string $methodName the method that you want to call
* @since 6.0.0
*/
public function dispatch(string $controllerName, string $methodName) {
\OC\AppFramework\App::main($controllerName, $methodName, $this->container);
}
}
@@ -0,0 +1,262 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Tim Obert <tobert@w-commerce.de>
* @author TimObert <tobert@w-commerce.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework;
use OCP\AppFramework\Http\Attribute\BruteForceProtection;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\Attribute\UseSession;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
/**
* Base controller for interactive public shares
*
* It will verify if the user is properly authenticated to the share. If not the
* user will be redirected to an authentication page.
*
* Use this for a controller that is to be called directly by a user. So the
* normal public share page for files/calendars etc.
*
* @since 14.0.0
*/
abstract class AuthPublicShareController extends PublicShareController {
/** @var IURLGenerator */
protected $urlGenerator;
/**
* @since 14.0.0
*/
public function __construct(string $appName,
IRequest $request,
ISession $session,
IURLGenerator $urlGenerator) {
parent::__construct($appName, $request, $session);
$this->urlGenerator = $urlGenerator;
}
/**
* @PublicPage
* @NoCSRFRequired
*
* Show the authentication page
* The form has to submit to the authenticate method route
*
* @since 14.0.0
*/
#[NoCSRFRequired]
#[PublicPage]
public function showAuthenticate(): TemplateResponse {
return new TemplateResponse('core', 'publicshareauth', [], 'guest');
}
/**
* The template to show when authentication failed
*
* @since 14.0.0
*/
protected function showAuthFailed(): TemplateResponse {
return new TemplateResponse('core', 'publicshareauth', ['wrongpw' => true], 'guest');
}
/**
* The template to show after user identification
*
* @since 24.0.0
*/
protected function showIdentificationResult(bool $success): TemplateResponse {
return new TemplateResponse('core', 'publicshareauth', ['identityOk' => $success], 'guest');
}
/**
* Validates that the provided identity is allowed to receive a temporary password
*
* @since 24.0.0
*/
protected function validateIdentity(?string $identityToken = null): bool {
return false;
}
/**
* Generates a password
*
* @since 24.0.0
*/
protected function generatePassword(): void {
}
/**
* Verify the password
*
* @since 24.0.0
*/
protected function verifyPassword(string $password): bool {
return false;
}
/**
* Function called after failed authentication
*
* You can use this to do some logging for example
*
* @since 14.0.0
*/
protected function authFailed() {
}
/**
* Function called after successful authentication
*
* You can use this to do some logging for example
*
* @since 14.0.0
*/
protected function authSucceeded() {
}
/**
* @UseSession
* @PublicPage
* @BruteForceProtection(action=publicLinkAuth)
*
* Authenticate the share
*
* @since 14.0.0
*/
#[BruteForceProtection(action: 'publicLinkAuth')]
#[PublicPage]
#[UseSession]
final public function authenticate(string $password = '', string $passwordRequest = 'no', string $identityToken = '') {
// Already authenticated
if ($this->isAuthenticated()) {
return $this->getRedirect();
}
// Is user requesting a temporary password?
if ($passwordRequest == '') {
if ($this->validateIdentity($identityToken)) {
$this->generatePassword();
$response = $this->showIdentificationResult(true);
return $response;
} else {
$response = $this->showIdentificationResult(false);
$response->throttle();
return $response;
}
}
if (!$this->verifyPassword($password)) {
$this->authFailed();
$response = $this->showAuthFailed();
$response->throttle();
return $response;
}
$this->session->regenerateId(true, true);
$response = $this->getRedirect();
$this->session->set('public_link_authenticated_token', $this->getToken());
$this->session->set('public_link_authenticated_password_hash', $this->getPasswordHash());
$this->authSucceeded();
return $response;
}
/**
* Default landing page
*
* @since 14.0.0
*/
abstract public function showShare(): TemplateResponse;
/**
* @since 14.0.0
*/
final public function getAuthenticationRedirect(string $redirect): RedirectResponse {
return new RedirectResponse(
$this->urlGenerator->linkToRoute($this->getRoute('showAuthenticate'), ['token' => $this->getToken(), 'redirect' => $redirect])
);
}
/**
* @since 14.0.0
*/
private function getRoute(string $function): string {
$app = strtolower($this->appName);
$class = (new \ReflectionClass($this))->getShortName();
if (substr($class, -10) === 'Controller') {
$class = substr($class, 0, -10);
}
return $app .'.'. $class .'.'. $function;
}
/**
* @since 14.0.0
*/
private function getRedirect(): RedirectResponse {
//Get all the stored redirect parameters:
$params = $this->session->get('public_link_authenticate_redirect');
$route = $this->getRoute('showShare');
if ($params === null) {
$params = [
'token' => $this->getToken(),
];
} else {
$params = json_decode($params, true);
if (isset($params['_route'])) {
$route = $params['_route'];
unset($params['_route']);
}
// If the token doesn't match the rest of the arguments can't be trusted either
if (isset($params['token']) && $params['token'] !== $this->getToken()) {
$params = [
'token' => $this->getToken(),
];
}
// We need a token
if (!isset($params['token'])) {
$params = [
'token' => $this->getToken(),
];
}
}
return new RedirectResponse($this->urlGenerator->linkToRoute($route, $params));
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
/**
* @copyright 2020 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Bootstrap;
use OCP\AppFramework\IAppContainer;
use OCP\IServerContainer;
use Psr\Container\ContainerExceptionInterface;
use Throwable;
/**
* @since 20.0.0
*/
interface IBootContext {
/**
* Get hold of the app's container
*
* Useful to register and query app-specific services
*
* @return IAppContainer
* @since 20.0.0
*/
public function getAppContainer(): IAppContainer;
/**
* Get hold of the server DI container
*
* Useful to register and query system-wide services
*
* @return IServerContainer
* @since 20.0.0
*/
public function getServerContainer(): IServerContainer;
/**
* Invoke the given callable and inject all parameters based on their types
* and names
*
* Note: when used with methods, make sure they are public or use \Closure::fromCallable
* to wrap the private method call, e.g.
* * `$context->injectFn([$obj, 'publicMethod'])`
* * `$context->injectFn([$this, 'publicMethod'])`
* * `$context->injectFn(\Closure::fromCallable([$this, 'privateMethod']))`
*
* Note: the app container will be queried
*
* @param callable $fn
* @throws ContainerExceptionInterface if at least one of the parameter can't be resolved
* @throws Throwable any error the function invocation might cause
* @return mixed|null the return value of the invoked function, if any
* @since 20.0.0
*/
public function injectFn(callable $fn);
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
/**
* @copyright 2020 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Bootstrap;
/**
* @since 20.0.0
*/
interface IBootstrap {
/**
* @param IRegistrationContext $context
*
* @since 20.0.0
*/
public function register(IRegistrationContext $context): void;
/**
* Boot the application
*
* At this stage you can assume that all services are registered and the DI
* container(s) are ready to be queried.
*
* This is also the state where an optional `appinfo/app.php` was loaded.
*
* @param IBootContext $context
*
* @since 20.0.0
*/
public function boot(IBootContext $context): void;
}
@@ -0,0 +1,394 @@
<?php
declare(strict_types=1);
/**
* @copyright 2020 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Bootstrap;
use OCP\AppFramework\IAppContainer;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\Calendar\ICalendarProvider;
use OCP\Capabilities\ICapability;
use OCP\Collaboration\Reference\IReferenceProvider;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Template\ICustomTemplateProvider;
use OCP\IContainer;
use OCP\Notification\INotifier;
use OCP\Preview\IProviderV2;
use OCP\SpeechToText\ISpeechToTextProvider;
use OCP\TextProcessing\IProvider as ITextProcessingProvider;
use OCP\TextToImage\IProvider as ITextToImageProvider;
use OCP\Translation\ITranslationProvider;
/**
* The context object passed to IBootstrap::register
*
* @since 20.0.0
* @see IBootstrap::register()
*/
interface IRegistrationContext {
/**
* @param string $capability
* @psalm-param class-string<ICapability> $capability
* @see IAppContainer::registerCapability
*
* @since 20.0.0
*/
public function registerCapability(string $capability): void;
/**
* Register an implementation of \OCP\Support\CrashReport\IReporter that
* will receive unhandled exceptions and throwables
*
* @param string $reporterClass
* @psalm-param class-string<\OCP\Support\CrashReport\IReporter> $reporterClass
* @return void
* @since 20.0.0
*/
public function registerCrashReporter(string $reporterClass): void;
/**
* Register an implementation of \OCP\Dashboard\IWidget that
* will handle the implementation of a dashboard widget
*
* @param string $widgetClass
* @psalm-param class-string<\OCP\Dashboard\IWidget> $widgetClass
* @return void
* @since 20.0.0
*/
public function registerDashboardWidget(string $widgetClass): void;
/**
* Register a service
*
* @param string $name
* @param callable $factory
* @psalm-param callable(\Psr\Container\ContainerInterface): mixed $factory
* @param bool $shared
*
* @return void
* @see IContainer::registerService()
*
* @since 20.0.0
*/
public function registerService(string $name, callable $factory, bool $shared = true): void;
/**
* @param string $alias
* @psalm-param string|class-string $alias
* @param string $target
* @psalm-param string|class-string $target
*
* @return void
* @see IContainer::registerAlias()
*
* @since 20.0.0
*/
public function registerServiceAlias(string $alias, string $target): void;
/**
* @param string $name
* @param mixed $value
*
* @return void
* @see IContainer::registerParameter()
*
* @since 20.0.0
*/
public function registerParameter(string $name, $value): void;
/**
* Register a service listener
*
* This is equivalent to calling IEventDispatcher::addServiceListener
*
* @psalm-template T of \OCP\EventDispatcher\Event
* @param string $event preferably the fully-qualified class name of the Event sub class to listen for
* @psalm-param string|class-string<T> $event preferably the fully-qualified class name of the Event sub class to listen for
* @param string $listener fully qualified class name (or ::class notation) of a \OCP\EventDispatcher\IEventListener that can be built by the DI container
* @psalm-param class-string<\OCP\EventDispatcher\IEventListener<T>> $listener fully qualified class name that can be built by the DI container
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*
* @see IEventDispatcher::addServiceListener()
*
* @since 20.0.0
*/
public function registerEventListener(string $event, string $listener, int $priority = 0): void;
/**
* @param string $class
* @param bool $global load this middleware also for requests of other apps? Added in Nextcloud 26
* @psalm-param class-string<\OCP\AppFramework\Middleware> $class
*
* @return void
* @see IAppContainer::registerMiddleWare()
*
* @since 20.0.0
* @since 26.0.0 Added optional argument $global
*/
public function registerMiddleware(string $class, bool $global = false): void;
/**
* Register a search provider for the unified search
*
* It is allowed to register more than one provider per app as the search
* results can go into distinct sections, e.g. "Files" and "Files shared
* with you" in the Files app.
*
* @param string $class
* @psalm-param class-string<\OCP\Search\IProvider> $class
*
* @return void
*
* @since 20.0.0
*/
public function registerSearchProvider(string $class): void;
/**
* Register an alternative login option
*
* It is allowed to register more than one option per app.
*
* @param string $class
* @psalm-param class-string<\OCP\Authentication\IAlternativeLogin> $class
*
* @return void
*
* @since 20.0.0
*/
public function registerAlternativeLogin(string $class): void;
/**
* Register an initialstate provider
*
* It is allowed to register more than one provider per app.
*
* @param string $class
* @psalm-param class-string<\OCP\AppFramework\Services\InitialStateProvider> $class
*
* @return void
*
* @since 21.0.0
*/
public function registerInitialStateProvider(string $class): void;
/**
* Register a well known protocol handler
*
* It is allowed to register more than one handler per app.
*
* @param string $class
* @psalm-param class-string<\OCP\Http\WellKnown\IHandler> $class
*
* @return void
*
* @since 21.0.0
*/
public function registerWellKnownHandler(string $class): void;
/**
* Register a custom SpeechToText provider class that can provide transcription
* of audio through the OCP\SpeechToText APIs
*
* @param string $providerClass
* @psalm-param class-string<ISpeechToTextProvider> $providerClass
* @since 27.0.0
*/
public function registerSpeechToTextProvider(string $providerClass): void;
/**
* Register a custom text processing provider class that provides a promptable language model
* through the OCP\TextProcessing APIs
*
* @param string $providerClass
* @psalm-param class-string<ITextProcessingProvider> $providerClass
* @since 27.1.0
*/
public function registerTextProcessingProvider(string $providerClass): void;
/**
* Register a custom text2image provider class that provides the possibility to generate images
* through the OCP\TextToImage APIs
*
* @param string $providerClass
* @psalm-param class-string<ITextToImageProvider> $providerClass
* @since 28.0.0
*/
public function registerTextToImageProvider(string $providerClass): void;
/**
* Register a custom template provider class that is able to inject custom templates
* in addition to the user defined ones
*
* @param string $providerClass
* @psalm-param class-string<ICustomTemplateProvider> $providerClass
* @since 21.0.0
*/
public function registerTemplateProvider(string $providerClass): void;
/**
* Register a custom translation provider class that can provide translation
* between languages through the OCP\Translation APIs
*
* @param string $providerClass
* @psalm-param class-string<ITranslationProvider> $providerClass
* @since 21.0.0
*/
public function registerTranslationProvider(string $providerClass): void;
/**
* Register an INotifier class
*
* @param string $notifierClass
* @psalm-param class-string<INotifier> $notifierClass
* @since 22.0.0
*/
public function registerNotifierService(string $notifierClass): void;
/**
* Register a two-factor provider
*
* @param string $twoFactorProviderClass
* @psalm-param class-string<IProvider> $twoFactorProviderClass
* @since 22.0.0
*/
public function registerTwoFactorProvider(string $twoFactorProviderClass): void;
/**
* Register a preview provider
*
* It is allowed to register more than one provider per app.
*
* @param string $previewProviderClass
* @param string $mimeTypeRegex
* @psalm-param class-string<IProviderV2> $previewProviderClass
* @since 23.0.0
*/
public function registerPreviewProvider(string $previewProviderClass, string $mimeTypeRegex): void;
/**
* Register a calendar provider
*
* @param string $class
* @psalm-param class-string<ICalendarProvider> $class
* @since 23.0.0
*/
public function registerCalendarProvider(string $class): void;
/**
* Register a reference provider
*
* @param string $class
* @psalm-param class-string<IReferenceProvider> $class
* @since 25.0.0
*/
public function registerReferenceProvider(string $class): void;
/**
* Register an implementation of \OCP\Profile\ILinkAction that
* will handle the implementation of a profile link action
*
* @param string $actionClass
* @psalm-param class-string<\OCP\Profile\ILinkAction> $actionClass
* @return void
* @since 23.0.0
*/
public function registerProfileLinkAction(string $actionClass): void;
/**
* Register the backend of the Talk app
*
* This service must only be used by the Talk app
*
* @param string $backend
* @return void
* @since 24.0.0
*/
public function registerTalkBackend(string $backend): void;
/**
* Register a resource backend for the DAV server
*
* @param string $actionClass
* @psalm-param class-string<\OCP\Calendar\Resource\IBackend> $actionClass
* @return void
* @since 24.0.0
*/
public function registerCalendarResourceBackend(string $class): void;
/**
* Register a room backend for the DAV server
*
* @param string $actionClass
* @psalm-param class-string<\OCP\Calendar\Room\IBackend> $actionClass
* @return void
* @since 24.0.0
*/
public function registerCalendarRoomBackend(string $class): void;
/**
* Register an implementation of \OCP\UserMigration\IMigrator that
* will handle the implementation of a migrator
*
* @param string $migratorClass
* @psalm-param class-string<\OCP\UserMigration\IMigrator> $migratorClass
* @return void
* @since 24.0.0
*/
public function registerUserMigrator(string $migratorClass): void;
/**
* Announce methods of classes that may contain sensitive values, which
* should be obfuscated before being logged.
*
* @param string $class
* @param string[] $methods
* @return void
* @since 25.0.0
*/
public function registerSensitiveMethods(string $class, array $methods): void;
/**
* Register an implementation of IPublicShareTemplateProvider.
*
* @param string $class
* @psalm-param class-string<\OCP\Share\IPublicShareTemplateProvider> $class
* @return void
* @since 26.0.0
*/
public function registerPublicShareTemplateProvider(string $class): void;
/**
* Register an implementation of \OCP\SetupCheck\ISetupCheck that
* will handle the implementation of a setup check
*
* @param class-string<\OCP\SetupCheck\ISetupCheck> $setupCheckClass
* @since 28.0.0
*/
public function registerSetupCheck(string $setupCheckClass): void;
}
@@ -0,0 +1,162 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Donquixote <marjunebatac@gmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
* @author Vincent Petry <vincent@nextcloud.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/>
*
*/
namespace OCP\AppFramework;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
/**
* Base class to inherit your controllers from
* @since 6.0.0
*/
abstract class Controller {
/**
* app name
* @var string
* @since 7.0.0
*/
protected $appName;
/**
* current request
* @var \OCP\IRequest
* @since 6.0.0
*/
protected $request;
/**
* @var array
* @since 7.0.0
*/
private $responders;
/**
* constructor of the controller
* @param string $appName the name of the app
* @param IRequest $request an instance of the request
* @since 6.0.0 - parameter $appName was added in 7.0.0 - parameter $app was removed in 7.0.0
*/
public function __construct($appName,
IRequest $request) {
$this->appName = $appName;
$this->request = $request;
// default responders
$this->responders = [
'json' => function ($data) {
if ($data instanceof DataResponse) {
$response = new JSONResponse(
$data->getData(),
$data->getStatus()
);
$dataHeaders = $data->getHeaders();
$headers = $response->getHeaders();
// do not overwrite Content-Type if it already exists
if (isset($dataHeaders['Content-Type'])) {
unset($headers['Content-Type']);
}
$response->setHeaders(array_merge($dataHeaders, $headers));
if ($data->getETag() !== null) {
$response->setETag($data->getETag());
}
if ($data->getLastModified() !== null) {
$response->setLastModified($data->getLastModified());
}
if ($data->isThrottled()) {
$response->throttle($data->getThrottleMetadata());
}
return $response;
}
return new JSONResponse($data);
}
];
}
/**
* Parses an HTTP accept header and returns the supported responder type
* @param string $acceptHeader
* @param string $default
* @return string the responder type
* @since 7.0.0
* @since 9.1.0 Added default parameter
*/
public function getResponderByHTTPHeader($acceptHeader, $default = 'json') {
$headers = explode(',', $acceptHeader);
// return the first matching responder
foreach ($headers as $header) {
$header = strtolower(trim($header));
$responder = str_replace('application/', '', $header);
if (array_key_exists($responder, $this->responders)) {
return $responder;
}
}
// no matching header return default
return $default;
}
/**
* Registers a formatter for a type
* @param string $format
* @param \Closure $responder
* @since 7.0.0
*/
protected function registerResponder($format, \Closure $responder) {
$this->responders[$format] = $responder;
}
/**
* Serializes and formats a response
* @param mixed $response the value that was returned from a controller and
* is not a Response instance
* @param string $format the format for which a formatter has been registered
* @throws \DomainException if format does not match a registered formatter
* @return Response
* @since 7.0.0
*/
public function buildResponse($response, $format = 'json') {
if (array_key_exists($format, $this->responders)) {
$responder = $this->responders[$format];
return $responder($response);
}
throw new \DomainException('No responder registered for format '.
$format . '!');
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @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/>
*
*/
namespace OCP\AppFramework\Db;
/**
* This is returned or should be returned when a find request does not find an
* entry in the database
* @since 7.0.0
*/
class DoesNotExistException extends \Exception implements IMapperException {
/**
* Constructor
* @param string $msg the error message
* @since 7.0.0
*/
public function __construct($msg) {
parent::__construct($msg);
}
}
@@ -0,0 +1,288 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @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/>
*
*/
namespace OCP\AppFramework\Db;
use function lcfirst;
use function substr;
/**
* @method int getId()
* @method void setId(int $id)
* @since 7.0.0
* @psalm-consistent-constructor
*/
abstract class Entity {
/**
* @var int
*/
public $id;
private array $_updatedFields = [];
private array $_fieldTypes = ['id' => 'integer'];
/**
* Simple alternative constructor for building entities from a request
* @param array $params the array which was obtained via $this->params('key')
* in the controller
* @since 7.0.0
*/
public static function fromParams(array $params): static {
$instance = new static();
foreach ($params as $key => $value) {
$method = 'set' . ucfirst($key);
$instance->$method($value);
}
return $instance;
}
/**
* Maps the keys of the row array to the attributes
* @param array $row the row to map onto the entity
* @since 7.0.0
*/
public static function fromRow(array $row): static {
$instance = new static();
foreach ($row as $key => $value) {
$prop = ucfirst($instance->columnToProperty($key));
$setter = 'set' . $prop;
$instance->$setter($value);
}
$instance->resetUpdatedFields();
return $instance;
}
/**
* @return array with attribute and type
* @since 7.0.0
*/
public function getFieldTypes() {
return $this->_fieldTypes;
}
/**
* Marks the entity as clean needed for setting the id after the insertion
* @since 7.0.0
*/
public function resetUpdatedFields() {
$this->_updatedFields = [];
}
/**
* Generic setter for properties
* @since 7.0.0
*/
protected function setter(string $name, array $args): void {
// setters should only work for existing attributes
if (property_exists($this, $name)) {
if ($this->$name === $args[0]) {
return;
}
$this->markFieldUpdated($name);
// if type definition exists, cast to correct type
if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
$type = $this->_fieldTypes[$name];
if ($type === 'blob') {
// (B)LOB is treated as string when we read from the DB
if (is_resource($args[0])) {
$args[0] = stream_get_contents($args[0]);
}
$type = 'string';
}
if ($type === 'datetime') {
if (!$args[0] instanceof \DateTime) {
$args[0] = new \DateTime($args[0]);
}
} elseif ($type === 'json') {
if (!is_array($args[0])) {
$args[0] = json_decode($args[0], true);
}
} else {
settype($args[0], $type);
}
}
$this->$name = $args[0];
} else {
throw new \BadFunctionCallException($name .
' is not a valid attribute');
}
}
/**
* Generic getter for properties
* @since 7.0.0
*/
protected function getter(string $name): mixed {
// getters should only work for existing attributes
if (property_exists($this, $name)) {
return $this->$name;
} else {
throw new \BadFunctionCallException($name .
' is not a valid attribute');
}
}
/**
* Each time a setter is called, push the part after set
* into an array: for instance setId will save Id in the
* updated fields array so it can be easily used to create the
* getter method
* @since 7.0.0
*/
public function __call(string $methodName, array $args) {
if (str_starts_with($methodName, 'set')) {
$this->setter(lcfirst(substr($methodName, 3)), $args);
} elseif (str_starts_with($methodName, 'get')) {
return $this->getter(lcfirst(substr($methodName, 3)));
} elseif ($this->isGetterForBoolProperty($methodName)) {
return $this->getter(lcfirst(substr($methodName, 2)));
} else {
throw new \BadFunctionCallException($methodName .
' does not exist');
}
}
/**
* @param string $methodName
* @return bool
* @since 18.0.0
*/
protected function isGetterForBoolProperty(string $methodName): bool {
if (str_starts_with($methodName, 'is')) {
$fieldName = lcfirst(substr($methodName, 2));
return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
}
return false;
}
/**
* Mark am attribute as updated
* @param string $attribute the name of the attribute
* @since 7.0.0
*/
protected function markFieldUpdated(string $attribute): void {
$this->_updatedFields[$attribute] = true;
}
/**
* Transform a database columnname to a property
* @param string $columnName the name of the column
* @return string the property name
* @since 7.0.0
*/
public function columnToProperty($columnName) {
$parts = explode('_', $columnName);
$property = null;
foreach ($parts as $part) {
if ($property === null) {
$property = $part;
} else {
$property .= ucfirst($part);
}
}
return $property;
}
/**
* Transform a property to a database column name
* @param string $property the name of the property
* @return string the column name
* @since 7.0.0
*/
public function propertyToColumn($property) {
$parts = preg_split('/(?=[A-Z])/', $property);
$column = null;
foreach ($parts as $part) {
if ($column === null) {
$column = $part;
} else {
$column .= '_' . lcfirst($part);
}
}
return $column;
}
/**
* @return array array of updated fields for update query
* @since 7.0.0
*/
public function getUpdatedFields() {
return $this->_updatedFields;
}
/**
* Adds type information for a field so that its automatically casted to
* that value once its being returned from the database
* @param string $fieldName the name of the attribute
* @param string $type the type which will be used to call settype()
* @since 7.0.0
*/
protected function addType($fieldName, $type) {
$this->_fieldTypes[$fieldName] = $type;
}
/**
* Slugify the value of a given attribute
* Warning: This doesn't result in a unique value
* @param string $attributeName the name of the attribute, which value should be slugified
* @return string slugified value
* @since 7.0.0
* @deprecated 24.0.0
*/
public function slugify($attributeName) {
// toSlug should only work for existing attributes
if (property_exists($this, $attributeName)) {
$value = $this->$attributeName;
// replace everything except alphanumeric with a single '-'
$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
$value = strtolower($value);
// trim '-'
return trim($value, '-');
} else {
throw new \BadFunctionCallException($attributeName .
' is not a valid attribute');
}
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Db;
/**
* @since 16.0.0
*/
interface IMapperException extends \Throwable {
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @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/>
*
*/
namespace OCP\AppFramework\Db;
/**
* This is returned or should be returned when a find request finds more than one
* row
* @since 7.0.0
*/
class MultipleObjectsReturnedException extends \Exception implements IMapperException {
/**
* Constructor
* @param string $msg the error message
* @since 7.0.0
*/
public function __construct($msg) {
parent::__construct($msg);
}
}
@@ -0,0 +1,363 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Anna Larch <anna@nextcloud.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Marius David Wieschollek <git.public@mdns.eu>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Db;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
/**
* Simple parent class for inheriting your data access layer from. This class
* may be subject to change in the future
*
* @since 14.0.0
*
* @template T of Entity
*/
abstract class QBMapper {
/** @var string */
protected $tableName;
/** @var string|class-string<T> */
protected $entityClass;
/** @var IDBConnection */
protected $db;
/**
* @param IDBConnection $db Instance of the Db abstraction layer
* @param string $tableName the name of the table. set this to allow entity
* @param class-string<T>|null $entityClass the name of the entity that the sql should be
* mapped to queries without using sql
* @since 14.0.0
*/
public function __construct(IDBConnection $db, string $tableName, string $entityClass = null) {
$this->db = $db;
$this->tableName = $tableName;
// if not given set the entity name to the class without the mapper part
// cache it here for later use since reflection is slow
if ($entityClass === null) {
$this->entityClass = str_replace('Mapper', '', \get_class($this));
} else {
$this->entityClass = $entityClass;
}
}
/**
* @return string the table name
* @since 14.0.0
*/
public function getTableName(): string {
return $this->tableName;
}
/**
* Deletes an entity from the table
*
* @param Entity $entity the entity that should be deleted
* @psalm-param T $entity the entity that should be deleted
* @return Entity the deleted entity
* @psalm-return T the deleted entity
* @throws Exception
* @since 14.0.0
*/
public function delete(Entity $entity): Entity {
$qb = $this->db->getQueryBuilder();
$idType = $this->getParameterTypeForProperty($entity, 'id');
$qb->delete($this->tableName)
->where(
$qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
);
$qb->executeStatement();
return $entity;
}
/**
* Creates a new entry in the db from an entity
*
* @param Entity $entity the entity that should be created
* @psalm-param T $entity the entity that should be created
* @return Entity the saved entity with the set id
* @psalm-return T the saved entity with the set id
* @throws Exception
* @since 14.0.0
*/
public function insert(Entity $entity): Entity {
// get updated fields to save, fields have to be set using a setter to
// be saved
$properties = $entity->getUpdatedFields();
$qb = $this->db->getQueryBuilder();
$qb->insert($this->tableName);
// build the fields
foreach ($properties as $property => $updated) {
$column = $entity->propertyToColumn($property);
$getter = 'get' . ucfirst($property);
$value = $entity->$getter();
$type = $this->getParameterTypeForProperty($entity, $property);
$qb->setValue($column, $qb->createNamedParameter($value, $type));
}
$qb->executeStatement();
if ($entity->id === null) {
// When autoincrement is used id is always an int
$entity->setId($qb->getLastInsertId());
}
return $entity;
}
/**
* Tries to creates a new entry in the db from an entity and
* updates an existing entry if duplicate keys are detected
* by the database
*
* @param Entity $entity the entity that should be created/updated
* @psalm-param T $entity the entity that should be created/updated
* @return Entity the saved entity with the (new) id
* @psalm-return T the saved entity with the (new) id
* @throws Exception
* @throws \InvalidArgumentException if entity has no id
* @since 15.0.0
*/
public function insertOrUpdate(Entity $entity): Entity {
try {
return $this->insert($entity);
} catch (Exception $ex) {
if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
return $this->update($entity);
}
throw $ex;
}
}
/**
* Updates an entry in the db from an entity
*
* @param Entity $entity the entity that should be created
* @psalm-param T $entity the entity that should be created
* @return Entity the saved entity with the set id
* @psalm-return T the saved entity with the set id
* @throws Exception
* @throws \InvalidArgumentException if entity has no id
* @since 14.0.0
*/
public function update(Entity $entity): Entity {
// if entity wasn't changed it makes no sense to run a db query
$properties = $entity->getUpdatedFields();
if (\count($properties) === 0) {
return $entity;
}
// entity needs an id
$id = $entity->getId();
if ($id === null) {
throw new \InvalidArgumentException(
'Entity which should be updated has no id');
}
// get updated fields to save, fields have to be set using a setter to
// be saved
// do not update the id field
unset($properties['id']);
$qb = $this->db->getQueryBuilder();
$qb->update($this->tableName);
// build the fields
foreach ($properties as $property => $updated) {
$column = $entity->propertyToColumn($property);
$getter = 'get' . ucfirst($property);
$value = $entity->$getter();
$type = $this->getParameterTypeForProperty($entity, $property);
$qb->set($column, $qb->createNamedParameter($value, $type));
}
$idType = $this->getParameterTypeForProperty($entity, 'id');
$qb->where(
$qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
);
$qb->executeStatement();
return $entity;
}
/**
* Returns the type parameter for the QueryBuilder for a specific property
* of the $entity
*
* @param Entity $entity The entity to get the types from
* @psalm-param T $entity
* @param string $property The property of $entity to get the type for
* @return int|string
* @since 16.0.0
*/
protected function getParameterTypeForProperty(Entity $entity, string $property) {
$types = $entity->getFieldTypes();
if (!isset($types[ $property ])) {
return IQueryBuilder::PARAM_STR;
}
switch ($types[ $property ]) {
case 'int':
case 'integer':
return IQueryBuilder::PARAM_INT;
case 'string':
return IQueryBuilder::PARAM_STR;
case 'bool':
case 'boolean':
return IQueryBuilder::PARAM_BOOL;
case 'blob':
return IQueryBuilder::PARAM_LOB;
case 'datetime':
return IQueryBuilder::PARAM_DATE;
case 'json':
return IQueryBuilder::PARAM_JSON;
}
return IQueryBuilder::PARAM_STR;
}
/**
* Returns an db result and throws exceptions when there are more or less
* results
*
* @param IQueryBuilder $query
* @return array the result as row
* @throws Exception
* @throws MultipleObjectsReturnedException if more than one item exist
* @throws DoesNotExistException if the item does not exist
* @see findEntity
*
* @since 14.0.0
*/
protected function findOneQuery(IQueryBuilder $query): array {
$result = $query->executeQuery();
$row = $result->fetch();
if ($row === false) {
$result->closeCursor();
$msg = $this->buildDebugMessage(
'Did expect one result but found none when executing', $query
);
throw new DoesNotExistException($msg);
}
$row2 = $result->fetch();
$result->closeCursor();
if ($row2 !== false) {
$msg = $this->buildDebugMessage(
'Did not expect more than one result when executing', $query
);
throw new MultipleObjectsReturnedException($msg);
}
return $row;
}
/**
* @param string $msg
* @param IQueryBuilder $sql
* @return string
* @since 14.0.0
*/
private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
return $msg .
': query "' . $sql->getSQL() . '"; ';
}
/**
* Creates an entity from a row. Automatically determines the entity class
* from the current mapper name (MyEntityMapper -> MyEntity)
*
* @param array $row the row which should be converted to an entity
* @return Entity the entity
* @psalm-return T the entity
* @since 14.0.0
*/
protected function mapRowToEntity(array $row): Entity {
unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
return \call_user_func($this->entityClass .'::fromRow', $row);
}
/**
* Runs a sql query and returns an array of entities
*
* @param IQueryBuilder $query
* @return Entity[] all fetched entities
* @psalm-return T[] all fetched entities
* @throws Exception
* @since 14.0.0
*/
protected function findEntities(IQueryBuilder $query): array {
$result = $query->executeQuery();
try {
$entities = [];
while ($row = $result->fetch()) {
$entities[] = $this->mapRowToEntity($row);
}
return $entities;
} finally {
$result->closeCursor();
}
}
/**
* Returns an db result and throws exceptions when there are more or less
* results
*
* @param IQueryBuilder $query
* @return Entity the entity
* @psalm-return T the entity
* @throws Exception
* @throws MultipleObjectsReturnedException if more than one item exist
* @throws DoesNotExistException if the item does not exist
* @since 14.0.0
*/
protected function findEntity(IQueryBuilder $query): Entity {
return $this->mapRowToEntity($this->findOneQuery($query));
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
/*
* @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Db;
use OC\DB\Exceptions\DbalException;
use OCP\DB\Exception;
use OCP\IDBConnection;
use Throwable;
use function OCP\Log\logger;
/**
* Helper trait for transactional operations
*
* @since 24.0.0
*/
trait TTransactional {
/**
* Run an atomic database operation
*
* - Commit if no exceptions are thrown, return the callable result
* - Revert otherwise and rethrows the exception
*
* @template T
* @param callable $fn
* @psalm-param callable():T $fn
* @param IDBConnection $db
*
* @return mixed the result of the passed callable
* @psalm-return T
*
* @throws Exception for possible errors of commit or rollback or the custom operations within the closure
* @throws Throwable any other error caused by the closure
*
* @since 24.0.0
* @see https://docs.nextcloud.com/server/latest/developer_manual/basics/storage/database.html#transactions
*/
protected function atomic(callable $fn, IDBConnection $db) {
$db->beginTransaction();
try {
$result = $fn();
$db->commit();
return $result;
} catch (Throwable $e) {
$db->rollBack();
throw $e;
}
}
/**
* Wrapper around atomic() to retry after a retryable exception occurred
*
* Certain transactions might need to be retried. This is especially useful
* in highly concurrent requests where a deadlocks is thrown by the database
* without waiting for the lock to be freed (e.g. due to MySQL/MariaDB deadlock
* detection)
*
* @template T
* @param callable $fn
* @psalm-param callable():T $fn
* @param IDBConnection $db
* @param int $maxRetries
*
* @return mixed the result of the passed callable
* @psalm-return T
*
* @throws Exception for possible errors of commit or rollback or the custom operations within the closure
* @throws Throwable any other error caused by the closure
*
* @since 27.0.0
*/
protected function atomicRetry(callable $fn, IDBConnection $db, int $maxRetries = 3): mixed {
for ($i = 0; $i < $maxRetries; $i++) {
try {
return $this->atomic($fn, $db);
} catch (DbalException $e) {
if (!$e->isRetryable() || $i === ($maxRetries - 1)) {
throw $e;
}
logger('core')->warning('Retrying operation after retryable exception.', [ 'exception' => $e ]);
}
}
}
}
@@ -0,0 +1,91 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
*
* @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/>
*
*/
namespace OCP\AppFramework;
/**
* Base class which contains constants for HTTP status codes
* @since 6.0.0
*/
class Http {
public const STATUS_CONTINUE = 100;
public const STATUS_SWITCHING_PROTOCOLS = 101;
public const STATUS_PROCESSING = 102;
public const STATUS_OK = 200;
public const STATUS_CREATED = 201;
public const STATUS_ACCEPTED = 202;
public const STATUS_NON_AUTHORATIVE_INFORMATION = 203;
public const STATUS_NO_CONTENT = 204;
public const STATUS_RESET_CONTENT = 205;
public const STATUS_PARTIAL_CONTENT = 206;
public const STATUS_MULTI_STATUS = 207;
public const STATUS_ALREADY_REPORTED = 208;
public const STATUS_IM_USED = 226;
public const STATUS_MULTIPLE_CHOICES = 300;
public const STATUS_MOVED_PERMANENTLY = 301;
public const STATUS_FOUND = 302;
public const STATUS_SEE_OTHER = 303;
public const STATUS_NOT_MODIFIED = 304;
public const STATUS_USE_PROXY = 305;
public const STATUS_RESERVED = 306;
public const STATUS_TEMPORARY_REDIRECT = 307;
public const STATUS_BAD_REQUEST = 400;
public const STATUS_UNAUTHORIZED = 401;
public const STATUS_PAYMENT_REQUIRED = 402;
public const STATUS_FORBIDDEN = 403;
public const STATUS_NOT_FOUND = 404;
public const STATUS_METHOD_NOT_ALLOWED = 405;
public const STATUS_NOT_ACCEPTABLE = 406;
public const STATUS_PROXY_AUTHENTICATION_REQUIRED = 407;
public const STATUS_REQUEST_TIMEOUT = 408;
public const STATUS_CONFLICT = 409;
public const STATUS_GONE = 410;
public const STATUS_LENGTH_REQUIRED = 411;
public const STATUS_PRECONDITION_FAILED = 412;
public const STATUS_REQUEST_ENTITY_TOO_LARGE = 413;
public const STATUS_REQUEST_URI_TOO_LONG = 414;
public const STATUS_UNSUPPORTED_MEDIA_TYPE = 415;
public const STATUS_REQUEST_RANGE_NOT_SATISFIABLE = 416;
public const STATUS_EXPECTATION_FAILED = 417;
public const STATUS_IM_A_TEAPOT = 418;
public const STATUS_UNPROCESSABLE_ENTITY = 422;
public const STATUS_LOCKED = 423;
public const STATUS_FAILED_DEPENDENCY = 424;
public const STATUS_UPGRADE_REQUIRED = 426;
public const STATUS_PRECONDITION_REQUIRED = 428;
public const STATUS_TOO_MANY_REQUESTS = 429;
public const STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
public const STATUS_INTERNAL_SERVER_ERROR = 500;
public const STATUS_NOT_IMPLEMENTED = 501;
public const STATUS_BAD_GATEWAY = 502;
public const STATUS_SERVICE_UNAVAILABLE = 503;
public const STATUS_GATEWAY_TIMEOUT = 504;
public const STATUS_HTTP_VERSION_NOT_SUPPORTED = 505;
public const STATUS_VARIANT_ALSO_NEGOTIATES = 506;
public const STATUS_INSUFFICIENT_STORAGE = 507;
public const STATUS_LOOP_DETECTED = 508;
public const STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509;
public const STATUS_NOT_EXTENDED = 510;
public const STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511;
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
/**
* Attribute for controller methods that want to limit the times a logged-in
* user can call the endpoint in a given time period.
*
* @since 27.0.0
*/
abstract class ARateLimit {
/**
* @since 27.0.0
*/
public function __construct(
protected int $limit,
protected int $period,
) {
}
/**
* @since 27.0.0
*/
public function getLimit(): int {
return $this->limit;
}
/**
* @since 27.0.0
*/
public function getPeriod(): int {
return $this->period;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that want to limit the times a not logged-in
* guest can call the endpoint in a given time period.
*
* @since 27.0.0
*/
#[Attribute(Attribute::TARGET_METHOD)]
class AnonRateLimit extends ARateLimit {
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
use OCP\Settings\IDelegatedSettings;
/**
* Attribute for controller methods that should be only accessible with
* full admin or partial admin permissions.
*
* @since 27.0.0
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class AuthorizedAdminSetting {
/**
* @param class-string<IDelegatedSettings> $settings A settings section the user needs to be able to access
* @since 27.0.0
*/
public function __construct(
protected string $settings
) {
}
/**
*
* @return class-string<IDelegatedSettings>
* @since 27.0.0
*/
public function getSettings(): string {
return $this->settings;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that want to protect passwords, keys, tokens
* or other data against brute force
*
* @since 27.0.0
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class BruteForceProtection {
/**
* @since 27.0.0
*/
public function __construct(
protected string $action
) {
}
/**
* @since 27.0.0
*/
public function getAction(): string {
return $this->action;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that can also be accessed by not logged-in user
*
* @since 27.0.0
*/
#[Attribute]
class CORS {
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Kate Döen <kate.doeen@nextcloud.com>
*
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that should be ignored when generating OpenAPI documentation
*
* @since 28.0.0
* @deprecated 28.0.0 Use {@see OpenAPI} with {@see OpenAPI::SCOPE_IGNORE} instead: `#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]`
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class IgnoreOpenAPI {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that can be accessed by any logged-in user
*
* @since 27.0.0
*/
#[Attribute]
class NoAdminRequired {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that are not CSRF protected
*
* @since 27.0.0
*/
#[Attribute]
class NoCSRFRequired {
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* With this attribute a controller or a method can be moved into a different
* scope or tag. Scopes should be seen as API consumers, tags can be used to group
* different routes inside the same scope.
*
* @since 28.0.0
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class OpenAPI {
/**
* APIs used for normal user facing interaction with your app,
* e.g. when you would implement a mobile client or standalone frontend.
*
* @since 28.0.0
*/
public const SCOPE_DEFAULT = 'default';
/**
* APIs used to administrate your app's configuration on an administrative level.
* Will be set automatically when admin permissions are required to access the route.
*
* @since 28.0.0
*/
public const SCOPE_ADMINISTRATION = 'administration';
/**
* APIs used by servers to federate with each other.
*
* @since 28.0.0
*/
public const SCOPE_FEDERATION = 'federation';
/**
* Ignore this controller or method in all generated OpenAPI specifications.
*
* @since 28.0.0
*/
public const SCOPE_IGNORE = 'ignore';
/**
* @param self::SCOPE_*|string $scope Scopes are used to define different clients.
* It is recommended to go with the scopes available as self::SCOPE_* constants,
* but in exotic cases other APIs might need documentation as well,
* then a free string can be provided (but it should be `a-z` only).
* @param ?list<string> $tags Tags can be used to group routes inside a scope
* for easier implementation and reviewing of the API specification.
* It defaults to the controller name in snake_case (should be `a-z` and underscore only).
* @since 28.0.0
*/
public function __construct(
protected string $scope = self::SCOPE_DEFAULT,
protected ?array $tags = null,
) {
}
/**
* @since 28.0.0
*/
public function getScope(): string {
return $this->scope;
}
/**
* @return ?list<string>
* @since 28.0.0
*/
public function getTags(): ?array {
return $this->tags;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that require the password to be confirmed with in the last 30 minutes
*
* @since 27.0.0
*/
#[Attribute]
class PasswordConfirmationRequired {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that can also be accessed by not logged-in user
*
* @since 27.0.0
*/
#[Attribute]
class PublicPage {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that require strict cookies
*
* @since 27.0.0
*/
#[Attribute]
class StrictCookiesRequired {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that can be accessed by sub-admins
*
* @since 27.0.0
*/
#[Attribute]
class SubAdminRequired {
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that need to read/write PHP session data
*
* @since 26.0.0
*/
#[Attribute]
class UseSession {
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http\Attribute;
use Attribute;
/**
* Attribute for controller methods that want to limit the times a logged-in
* user can call the endpoint in a given time period.
*
* @since 27.0.0
*/
#[Attribute(Attribute::TARGET_METHOD)]
class UserRateLimit extends ARateLimit {
}
@@ -0,0 +1,108 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author sualko <klaus@jsxc.org>
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @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/>
*
*/
namespace OCP\AppFramework\Http;
/**
* Class ContentSecurityPolicy is a simple helper which allows applications to
* modify the Content-Security-Policy sent by Nextcloud. Per default only JavaScript,
* stylesheets, images, fonts, media and connections from the same domain
* ('self') are allowed.
*
* Even if a value gets modified above defaults will still get appended. Please
* notice that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* This class allows unsafe-inline of CSS.
*
* @since 8.1.0
*/
class ContentSecurityPolicy extends EmptyContentSecurityPolicy {
/** @var bool Whether inline JS snippets are allowed */
protected $inlineScriptAllowed = false;
/** @var bool Whether eval in JS scripts is allowed */
protected $evalScriptAllowed = false;
/** @var bool Whether WebAssembly compilation is allowed */
protected ?bool $evalWasmAllowed = false;
/** @var bool Whether strict-dynamic should be set */
protected $strictDynamicAllowed = false;
/** @var bool Whether strict-dynamic should be set for 'script-src-elem' */
protected $strictDynamicAllowedOnScripts = true;
/** @var array Domains from which scripts can get loaded */
protected $allowedScriptDomains = [
'\'self\'',
];
/**
* @var bool Whether inline CSS is allowed
* TODO: Disallow per default
* @link https://github.com/owncloud/core/issues/13458
*/
protected $inlineStyleAllowed = true;
/** @var array Domains from which CSS can get loaded */
protected $allowedStyleDomains = [
'\'self\'',
];
/** @var array Domains from which images can get loaded */
protected $allowedImageDomains = [
'\'self\'',
'data:',
'blob:',
];
/** @var array Domains to which connections can be done */
protected $allowedConnectDomains = [
'\'self\'',
];
/** @var array Domains from which media elements can be loaded */
protected $allowedMediaDomains = [
'\'self\'',
];
/** @var array Domains from which object elements can be loaded */
protected $allowedObjectDomains = [];
/** @var array Domains from which iframes can be loaded */
protected $allowedFrameDomains = [];
/** @var array Domains from which fonts can be loaded */
protected $allowedFontDomains = [
'\'self\'',
'data:',
];
/** @var array Domains from which web-workers and nested browsing content can load elements */
protected $allowedChildSrcDomains = [];
/** @var array Domains which can embed this Nextcloud instance */
protected $allowedFrameAncestors = [
'\'self\'',
];
/** @var array Domains from which web-workers can be loaded */
protected $allowedWorkerSrcDomains = [];
/** @var array Domains which can be used as target for forms */
protected $allowedFormActionDomains = [
'\'self\'',
];
/** @var array Locations to report violations to */
protected $reportTo = [];
}
@@ -0,0 +1,90 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Class DataDisplayResponse
*
* @since 8.1.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class DataDisplayResponse extends Response {
/**
* response data
* @var string
*/
protected $data;
/**
* @param string $data the data to display
* @param S $statusCode the Http status code, defaults to 200
* @param H $headers additional key value based headers
* @since 8.1.0
*/
public function __construct(string $data = '', int $statusCode = Http::STATUS_OK, array $headers = []) {
parent::__construct($statusCode, $headers);
$this->data = $data;
$this->addHeader('Content-Disposition', 'inline; filename=""');
}
/**
* Outputs data. No processing is done.
* @return string
* @since 8.1.0
*/
public function render() {
return $this->data;
}
/**
* Sets values in the data
* @param string $data the data to display
* @return DataDisplayResponse Reference to this object
* @since 8.1.0
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* Used to get the set parameters
* @return string the data
* @since 8.1.0
*/
public function getData() {
return $this->data;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Class DataDownloadResponse
*
* @since 8.0.0
* @template S of int
* @template C of string
* @template H of array<string, mixed>
* @template-extends DownloadResponse<int, string, array<string, mixed>>
*/
class DataDownloadResponse extends DownloadResponse {
/**
* @var string
*/
private $data;
/**
* Creates a response that prompts the user to download the text
* @param string $data text to be downloaded
* @param string $filename the name that the downloaded file should have
* @param C $contentType the mimetype that the downloaded file should have
* @param S $status
* @param H $headers
* @since 8.0.0
*/
public function __construct(string $data, string $filename, string $contentType, int $status = Http::STATUS_OK, array $headers = []) {
$this->data = $data;
parent::__construct($filename, $contentType, $status, $headers);
}
/**
* @param string $data
* @since 8.0.0
*/
public function setData($data) {
$this->data = $data;
}
/**
* @return string
* @since 8.0.0
*/
public function render() {
return $this->data;
}
}
@@ -0,0 +1,83 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* A generic DataResponse class that is used to return generic data responses
* for responders to transform
* @since 8.0.0
* @psalm-type DataResponseType = array|int|float|string|bool|object|null|\stdClass|\JsonSerializable
* @template S of int
* @template-covariant T of DataResponseType
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class DataResponse extends Response {
/**
* response data
* @var T
*/
protected $data;
/**
* @param T $data the object or array that should be transformed
* @param S $statusCode the Http status code, defaults to 200
* @param H $headers additional key value based headers
* @since 8.0.0
*/
public function __construct(mixed $data = [], int $statusCode = Http::STATUS_OK, array $headers = []) {
parent::__construct($statusCode, $headers);
$this->data = $data;
}
/**
* Sets values in the data json array
* @psalm-suppress InvalidTemplateParam
* @param T $data an array or object which will be transformed
* @return DataResponse Reference to this object
* @since 8.0.0
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* Used to get the set parameters
* @return T the data
* @since 8.0.0
*/
public function getData() {
return $this->data;
}
}
@@ -0,0 +1,56 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Prompts the user to download the a file
* @since 7.0.0
* @template S of int
* @template C of string
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class DownloadResponse extends Response {
/**
* Creates a response that prompts the user to download the file
* @param string $filename the name that the downloaded file should have
* @param C $contentType the mimetype that the downloaded file should have
* @param S $status
* @param H $headers
* @since 7.0.0
*/
public function __construct(string $filename, string $contentType, int $status = Http::STATUS_OK, array $headers = []) {
parent::__construct($status, $headers);
$filename = strtr($filename, ['"' => '\\"', '\\' => '\\\\']);
$this->addHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
$this->addHeader('Content-Type', $contentType);
}
}
@@ -0,0 +1,568 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Pavel Krasikov <klonishe@gmail.com>
* @author Pierre Rudloff <contact@rudloff.pro>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @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/>
*
*/
namespace OCP\AppFramework\Http;
/**
* Class EmptyContentSecurityPolicy is a simple helper which allows applications
* to modify the Content-Security-Policy sent by Nexcloud. Per default the policy
* is forbidding everything.
*
* As alternative with sane exemptions look at ContentSecurityPolicy
*
* @see \OCP\AppFramework\Http\ContentSecurityPolicy
* @since 9.0.0
*/
class EmptyContentSecurityPolicy {
/** @var string JS nonce to be used */
protected $jsNonce = null;
/** @var bool Whether strict-dynamic should be used */
protected $strictDynamicAllowed = null;
/** @var bool Whether strict-dynamic should be used on script-src-elem */
protected $strictDynamicAllowedOnScripts = null;
/**
* @var bool Whether eval in JS scripts is allowed
* TODO: Disallow per default
* @link https://github.com/owncloud/core/issues/11925
*/
protected $evalScriptAllowed = null;
/** @var bool Whether WebAssembly compilation is allowed */
protected ?bool $evalWasmAllowed = null;
/** @var array Domains from which scripts can get loaded */
protected $allowedScriptDomains = null;
/**
* @var bool Whether inline CSS is allowed
* TODO: Disallow per default
* @link https://github.com/owncloud/core/issues/13458
*/
protected $inlineStyleAllowed = null;
/** @var array Domains from which CSS can get loaded */
protected $allowedStyleDomains = null;
/** @var array Domains from which images can get loaded */
protected $allowedImageDomains = null;
/** @var array Domains to which connections can be done */
protected $allowedConnectDomains = null;
/** @var array Domains from which media elements can be loaded */
protected $allowedMediaDomains = null;
/** @var array Domains from which object elements can be loaded */
protected $allowedObjectDomains = null;
/** @var array Domains from which iframes can be loaded */
protected $allowedFrameDomains = null;
/** @var array Domains from which fonts can be loaded */
protected $allowedFontDomains = null;
/** @var array Domains from which web-workers and nested browsing content can load elements */
protected $allowedChildSrcDomains = null;
/** @var array Domains which can embed this Nextcloud instance */
protected $allowedFrameAncestors = null;
/** @var array Domains from which web-workers can be loaded */
protected $allowedWorkerSrcDomains = null;
/** @var array Domains which can be used as target for forms */
protected $allowedFormActionDomains = null;
/** @var array Locations to report violations to */
protected $reportTo = null;
/**
* @param bool $state
* @return EmptyContentSecurityPolicy
* @since 24.0.0
*/
public function useStrictDynamic(bool $state = false): self {
$this->strictDynamicAllowed = $state;
return $this;
}
/**
* In contrast to `useStrictDynamic` this only sets strict-dynamic on script-src-elem
* Meaning only grants trust to all imports of scripts that were loaded in `<script>` tags, and thus weakens less the CSP.
* @param bool $state
* @return EmptyContentSecurityPolicy
* @since 28.0.0
*/
public function useStrictDynamicOnScripts(bool $state = false): self {
$this->strictDynamicAllowedOnScripts = $state;
return $this;
}
/**
* Use the according JS nonce
* This method is only for CSPMiddleware, custom values are ignored in mergePolicies of ContentSecurityPolicyManager
*
* @param string $nonce
* @return $this
* @since 11.0.0
*/
public function useJsNonce($nonce) {
$this->jsNonce = $nonce;
return $this;
}
/**
* Whether eval in JavaScript is allowed or forbidden
* @param bool $state
* @return $this
* @since 8.1.0
* @deprecated Eval should not be used anymore. Please update your scripts. This function will stop functioning in a future version of Nextcloud.
*/
public function allowEvalScript($state = true) {
$this->evalScriptAllowed = $state;
return $this;
}
/**
* Whether WebAssembly compilation is allowed or forbidden
* @param bool $state
* @return $this
* @since 28.0.0
*/
public function allowEvalWasm(bool $state = true) {
$this->evalWasmAllowed = $state;
return $this;
}
/**
* Allows to execute JavaScript files from a specific domain. Use * to
* allow JavaScript from all domains.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedScriptDomain($domain) {
$this->allowedScriptDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed script domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowScriptDomain($domain) {
$this->allowedScriptDomains = array_diff($this->allowedScriptDomains, [$domain]);
return $this;
}
/**
* Whether inline CSS snippets are allowed or forbidden
* @param bool $state
* @return $this
* @since 8.1.0
*/
public function allowInlineStyle($state = true) {
$this->inlineStyleAllowed = $state;
return $this;
}
/**
* Allows to execute CSS files from a specific domain. Use * to allow
* CSS from all domains.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedStyleDomain($domain) {
$this->allowedStyleDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed style domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowStyleDomain($domain) {
$this->allowedStyleDomains = array_diff($this->allowedStyleDomains, [$domain]);
return $this;
}
/**
* Allows using fonts from a specific domain. Use * to allow
* fonts from all domains.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedFontDomain($domain) {
$this->allowedFontDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed font domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowFontDomain($domain) {
$this->allowedFontDomains = array_diff($this->allowedFontDomains, [$domain]);
return $this;
}
/**
* Allows embedding images from a specific domain. Use * to allow
* images from all domains.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedImageDomain($domain) {
$this->allowedImageDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed image domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowImageDomain($domain) {
$this->allowedImageDomains = array_diff($this->allowedImageDomains, [$domain]);
return $this;
}
/**
* To which remote domains the JS connect to.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedConnectDomain($domain) {
$this->allowedConnectDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed connect domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowConnectDomain($domain) {
$this->allowedConnectDomains = array_diff($this->allowedConnectDomains, [$domain]);
return $this;
}
/**
* From which domains media elements can be embedded.
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedMediaDomain($domain) {
$this->allowedMediaDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed media domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowMediaDomain($domain) {
$this->allowedMediaDomains = array_diff($this->allowedMediaDomains, [$domain]);
return $this;
}
/**
* From which domains objects such as <object>, <embed> or <applet> are executed
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedObjectDomain($domain) {
$this->allowedObjectDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed object domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowObjectDomain($domain) {
$this->allowedObjectDomains = array_diff($this->allowedObjectDomains, [$domain]);
return $this;
}
/**
* Which domains can be embedded in an iframe
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
*/
public function addAllowedFrameDomain($domain) {
$this->allowedFrameDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed frame domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
*/
public function disallowFrameDomain($domain) {
$this->allowedFrameDomains = array_diff($this->allowedFrameDomains, [$domain]);
return $this;
}
/**
* Domains from which web-workers and nested browsing content can load elements
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 8.1.0
* @deprecated 15.0.0 use addAllowedWorkerSrcDomains or addAllowedFrameDomain
*/
public function addAllowedChildSrcDomain($domain) {
$this->allowedChildSrcDomains[] = $domain;
return $this;
}
/**
* Remove the specified allowed child src domain from the allowed domains.
*
* @param string $domain
* @return $this
* @since 8.1.0
* @deprecated 15.0.0 use the WorkerSrcDomains or FrameDomain
*/
public function disallowChildSrcDomain($domain) {
$this->allowedChildSrcDomains = array_diff($this->allowedChildSrcDomains, [$domain]);
return $this;
}
/**
* Domains which can embed an iFrame of the Nextcloud instance
*
* @param string $domain
* @return $this
* @since 13.0.0
*/
public function addAllowedFrameAncestorDomain($domain) {
$this->allowedFrameAncestors[] = $domain;
return $this;
}
/**
* Domains which can embed an iFrame of the Nextcloud instance
*
* @param string $domain
* @return $this
* @since 13.0.0
*/
public function disallowFrameAncestorDomain($domain) {
$this->allowedFrameAncestors = array_diff($this->allowedFrameAncestors, [$domain]);
return $this;
}
/**
* Domain from which workers can be loaded
*
* @param string $domain
* @return $this
* @since 15.0.0
*/
public function addAllowedWorkerSrcDomain(string $domain) {
$this->allowedWorkerSrcDomains[] = $domain;
return $this;
}
/**
* Remove domain from which workers can be loaded
*
* @param string $domain
* @return $this
* @since 15.0.0
*/
public function disallowWorkerSrcDomain(string $domain) {
$this->allowedWorkerSrcDomains = array_diff($this->allowedWorkerSrcDomains, [$domain]);
return $this;
}
/**
* Domain to where forms can submit
*
* @since 17.0.0
*
* @return $this
*/
public function addAllowedFormActionDomain(string $domain) {
$this->allowedFormActionDomains[] = $domain;
return $this;
}
/**
* Remove domain to where forms can submit
*
* @return $this
* @since 17.0.0
*/
public function disallowFormActionDomain(string $domain) {
$this->allowedFormActionDomains = array_diff($this->allowedFormActionDomains, [$domain]);
return $this;
}
/**
* Add location to report CSP violations to
*
* @param string $location
* @return $this
* @since 15.0.0
*/
public function addReportTo(string $location) {
$this->reportTo[] = $location;
return $this;
}
/**
* Get the generated Content-Security-Policy as a string
* @return string
* @since 8.1.0
*/
public function buildPolicy() {
$policy = "default-src 'none';";
$policy .= "base-uri 'none';";
$policy .= "manifest-src 'self';";
if (!empty($this->allowedScriptDomains) || $this->evalScriptAllowed || $this->evalWasmAllowed) {
$policy .= 'script-src ';
$scriptSrc = '';
if (is_string($this->jsNonce)) {
if ($this->strictDynamicAllowed) {
$scriptSrc .= '\'strict-dynamic\' ';
}
$scriptSrc .= '\'nonce-'.base64_encode($this->jsNonce).'\'';
$allowedScriptDomains = array_flip($this->allowedScriptDomains);
unset($allowedScriptDomains['\'self\'']);
$this->allowedScriptDomains = array_flip($allowedScriptDomains);
if (count($allowedScriptDomains) !== 0) {
$scriptSrc .= ' ';
}
}
if (is_array($this->allowedScriptDomains)) {
$scriptSrc .= implode(' ', $this->allowedScriptDomains);
}
if ($this->evalScriptAllowed) {
$scriptSrc .= ' \'unsafe-eval\'';
}
if ($this->evalWasmAllowed) {
$scriptSrc .= ' \'wasm-unsafe-eval\'';
}
$policy .= $scriptSrc . ';';
}
// We only need to set this if 'strictDynamicAllowed' is not set because otherwise we can simply fall back to script-src
if ($this->strictDynamicAllowedOnScripts && is_string($this->jsNonce) && !$this->strictDynamicAllowed) {
$policy .= 'script-src-elem \'strict-dynamic\' ';
$policy .= $scriptSrc ?? '';
$policy .= ';';
}
if (!empty($this->allowedStyleDomains) || $this->inlineStyleAllowed) {
$policy .= 'style-src ';
if (is_array($this->allowedStyleDomains)) {
$policy .= implode(' ', $this->allowedStyleDomains);
}
if ($this->inlineStyleAllowed) {
$policy .= ' \'unsafe-inline\'';
}
$policy .= ';';
}
if (!empty($this->allowedImageDomains)) {
$policy .= 'img-src ' . implode(' ', $this->allowedImageDomains);
$policy .= ';';
}
if (!empty($this->allowedFontDomains)) {
$policy .= 'font-src ' . implode(' ', $this->allowedFontDomains);
$policy .= ';';
}
if (!empty($this->allowedConnectDomains)) {
$policy .= 'connect-src ' . implode(' ', $this->allowedConnectDomains);
$policy .= ';';
}
if (!empty($this->allowedMediaDomains)) {
$policy .= 'media-src ' . implode(' ', $this->allowedMediaDomains);
$policy .= ';';
}
if (!empty($this->allowedObjectDomains)) {
$policy .= 'object-src ' . implode(' ', $this->allowedObjectDomains);
$policy .= ';';
}
if (!empty($this->allowedFrameDomains)) {
$policy .= 'frame-src ';
$policy .= implode(' ', $this->allowedFrameDomains);
$policy .= ';';
}
if (!empty($this->allowedChildSrcDomains)) {
$policy .= 'child-src ' . implode(' ', $this->allowedChildSrcDomains);
$policy .= ';';
}
if (!empty($this->allowedFrameAncestors)) {
$policy .= 'frame-ancestors ' . implode(' ', $this->allowedFrameAncestors);
$policy .= ';';
} else {
$policy .= 'frame-ancestors \'none\';';
}
if (!empty($this->allowedWorkerSrcDomains)) {
$policy .= 'worker-src ' . implode(' ', $this->allowedWorkerSrcDomains);
$policy .= ';';
}
if (!empty($this->allowedFormActionDomains)) {
$policy .= 'form-action ' . implode(' ', $this->allowedFormActionDomains);
$policy .= ';';
}
if (!empty($this->reportTo)) {
$policy .= 'report-uri ' . implode(' ', $this->reportTo);
$policy .= ';';
}
return rtrim($policy, ';');
}
}
@@ -0,0 +1,182 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* Class EmptyFeaturePolicy is a simple helper which allows applications
* to modify the FeaturePolicy sent by Nextcloud. Per default the policy
* is forbidding everything.
*
* As alternative with sane exemptions look at FeaturePolicy
*
* @see \OCP\AppFramework\Http\FeaturePolicy
* @since 17.0.0
*/
class EmptyFeaturePolicy {
/** @var string[] of allowed domains to autoplay media */
protected $autoplayDomains = null;
/** @var string[] of allowed domains that can access the camera */
protected $cameraDomains = null;
/** @var string[] of allowed domains that can use fullscreen */
protected $fullscreenDomains = null;
/** @var string[] of allowed domains that can use the geolocation of the device */
protected $geolocationDomains = null;
/** @var string[] of allowed domains that can use the microphone */
protected $microphoneDomains = null;
/** @var string[] of allowed domains that can use the payment API */
protected $paymentDomains = null;
/**
* Allows to use autoplay from a specific domain. Use * to allow from all domains.
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedAutoplayDomain(string $domain): self {
$this->autoplayDomains[] = $domain;
return $this;
}
/**
* Allows to use the camera on a specific domain. Use * to allow from all domains
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedCameraDomain(string $domain): self {
$this->cameraDomains[] = $domain;
return $this;
}
/**
* Allows the full screen functionality to be used on a specific domain. Use * to allow from all domains
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedFullScreenDomain(string $domain): self {
$this->fullscreenDomains[] = $domain;
return $this;
}
/**
* Allows to use the geolocation on a specific domain. Use * to allow from all domains
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedGeoLocationDomain(string $domain): self {
$this->geolocationDomains[] = $domain;
return $this;
}
/**
* Allows to use the microphone on a specific domain. Use * to allow from all domains
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedMicrophoneDomain(string $domain): self {
$this->microphoneDomains[] = $domain;
return $this;
}
/**
* Allows to use the payment API on a specific domain. Use * to allow from all domains
*
* @param string $domain Domain to whitelist. Any passed value needs to be properly sanitized.
* @return $this
* @since 17.0.0
*/
public function addAllowedPaymentDomain(string $domain): self {
$this->paymentDomains[] = $domain;
return $this;
}
/**
* Get the generated Feature-Policy as a string
*
* @return string
* @since 17.0.0
*/
public function buildPolicy(): string {
$policy = '';
if (empty($this->autoplayDomains)) {
$policy .= "autoplay 'none';";
} else {
$policy .= 'autoplay ' . implode(' ', $this->autoplayDomains);
$policy .= ';';
}
if (empty($this->cameraDomains)) {
$policy .= "camera 'none';";
} else {
$policy .= 'camera ' . implode(' ', $this->cameraDomains);
$policy .= ';';
}
if (empty($this->fullscreenDomains)) {
$policy .= "fullscreen 'none';";
} else {
$policy .= 'fullscreen ' . implode(' ', $this->fullscreenDomains);
$policy .= ';';
}
if (empty($this->geolocationDomains)) {
$policy .= "geolocation 'none';";
} else {
$policy .= 'geolocation ' . implode(' ', $this->geolocationDomains);
$policy .= ';';
}
if (empty($this->microphoneDomains)) {
$policy .= "microphone 'none';";
} else {
$policy .= 'microphone ' . implode(' ', $this->microphoneDomains);
$policy .= ';';
}
if (empty($this->paymentDomains)) {
$policy .= "payment 'none';";
} else {
$policy .= 'payment ' . implode(' ', $this->paymentDomains);
$policy .= ';';
}
return rtrim($policy, ';');
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Events;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\EventDispatcher\Event;
/**
* Emitted before the rendering step of the login TemplateResponse.
*
* @since 28.0.0
*/
class BeforeLoginTemplateRenderedEvent extends Event {
/**
* @since 28.0.0
*/
public function __construct(private TemplateResponse $response) {
parent::__construct();
}
/**
* @since 28.0.0
*/
public function getResponse(): TemplateResponse {
return $this->response;
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Events;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\EventDispatcher\Event;
/**
* Emitted before the rendering step of each TemplateResponse. The event holds a
* flag that specifies if an user is logged in.
*
* @since 20.0.0
*/
class BeforeTemplateRenderedEvent extends Event {
/** @var bool */
private $loggedIn;
/** @var TemplateResponse */
private $response;
/**
* @since 20.0.0
*/
public function __construct(bool $loggedIn, TemplateResponse $response) {
parent::__construct();
$this->loggedIn = $loggedIn;
$this->response = $response;
}
/**
* @since 20.0.0
*/
public function isLoggedIn(): bool {
return $this->loggedIn;
}
/**
* @since 20.0.0
*/
public function getResponse(): TemplateResponse {
return $this->response;
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* Class FeaturePolicy is a simple helper which allows applications to
* modify the Feature-Policy sent by Nextcloud. Per default only autoplay is allowed
* from the same domain and full screen as well from the same domain.
*
* Even if a value gets modified above defaults will still get appended. Please
* notice that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* @since 17.0.0
*/
class FeaturePolicy extends EmptyFeaturePolicy {
protected $autoplayDomains = [
'\'self\'',
];
/** @var string[] of allowed domains that can access the camera */
protected $cameraDomains = [];
protected $fullscreenDomains = [
'\'self\'',
];
/** @var string[] of allowed domains that can use the geolocation of the device */
protected $geolocationDomains = [];
/** @var string[] of allowed domains that can use the microphone */
protected $microphoneDomains = [];
/** @var string[] of allowed domains that can use the payment API */
protected $paymentDomains = [];
}
@@ -0,0 +1,73 @@
<?php
/**
* @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
use OCP\Files\File;
use OCP\Files\SimpleFS\ISimpleFile;
/**
* Class FileDisplayResponse
*
* @since 11.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class FileDisplayResponse extends Response implements ICallbackResponse {
/** @var File|ISimpleFile */
private $file;
/**
* FileDisplayResponse constructor.
*
* @param File|ISimpleFile $file
* @param S $statusCode
* @param H $headers
* @since 11.0.0
*/
public function __construct(File|ISimpleFile $file, int $statusCode = Http::STATUS_OK, array $headers = []) {
parent::__construct($statusCode, $headers);
$this->file = $file;
$this->addHeader('Content-Disposition', 'inline; filename="' . rawurldecode($file->getName()) . '"');
$this->setETag($file->getEtag());
$lastModified = new \DateTime();
$lastModified->setTimestamp($file->getMTime());
$this->setLastModified($lastModified);
}
/**
* @param IOutput $output
* @since 11.0.0
*/
public function callback(IOutput $output) {
if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
$output->setHeader('Content-Length: ' . $this->file->getSize());
$output->setOutput($this->file->getContent());
}
}
}
@@ -0,0 +1,40 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @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/>
*
*/
namespace OCP\AppFramework\Http;
/**
* Interface ICallbackResponse
*
* @since 8.1.0
*/
interface ICallbackResponse {
/**
* Outputs the content that should be printed
*
* @param IOutput $output a small wrapper that handles output
* @since 8.1.0
*/
public function callback(IOutput $output);
}
@@ -0,0 +1,78 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Stefan Weil <sw@weilnetz.de>
*
* @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/>
*
*/
namespace OCP\AppFramework\Http;
/**
* Very thin wrapper class to make output testable
* @since 8.1.0
*/
interface IOutput {
/**
* @param string $out
* @since 8.1.0
*/
public function setOutput($out);
/**
* @param string|resource $path or file handle
*
* @return bool false if an error occurred
* @since 8.1.0
*/
public function setReadfile($path);
/**
* @param string $header
* @since 8.1.0
*/
public function setHeader($header);
/**
* @return int returns the current http response code
* @since 8.1.0
*/
public function getHttpResponseCode();
/**
* @param int $code sets the http status code
* @since 8.1.0
*/
public function setHttpResponseCode($code);
/**
* @param string $name
* @param string $value
* @param int $expire
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httpOnly
* @param string $sameSite (added in 20)
* @since 8.1.0
*/
public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly, $sameSite = 'Lax');
}
@@ -0,0 +1,96 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* A renderer for JSON calls
* @since 6.0.0
* @template S of int
* @template-covariant T of array|object|\stdClass|\JsonSerializable
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class JSONResponse extends Response {
/**
* response data
* @var T
*/
protected $data;
/**
* constructor of JSONResponse
* @param T $data the object or array that should be transformed
* @param S $statusCode the Http status code, defaults to 200
* @param H $headers
* @since 6.0.0
*/
public function __construct(mixed $data = [], int $statusCode = Http::STATUS_OK, array $headers = []) {
parent::__construct($statusCode, $headers);
$this->data = $data;
$this->addHeader('Content-Type', 'application/json; charset=utf-8');
}
/**
* Returns the rendered json
* @return string the rendered json
* @since 6.0.0
* @throws \Exception If data could not get encoded
*/
public function render() {
return json_encode($this->data, JSON_HEX_TAG | JSON_THROW_ON_ERROR);
}
/**
* Sets values in the data json array
* @psalm-suppress InvalidTemplateParam
* @param T $data an array or object which will be transformed
* to JSON
* @return JSONResponse Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* @return T the data
* @since 6.0.0
*/
public function getData() {
return $this->data;
}
}
@@ -0,0 +1,48 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* A generic 404 response showing an 404 error page as well to the end-user
* @since 8.1.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends TemplateResponse<int, array<string, mixed>>
*/
class NotFoundResponse extends TemplateResponse {
/**
* @param S $status
* @param H $headers
* @since 8.1.0
*/
public function __construct(int $status = Http::STATUS_NOT_FOUND, array $headers = []) {
parent::__construct('core', '404', [], 'guest', $status, $headers);
$this->setContentSecurityPolicy(new ContentSecurityPolicy());
}
}
@@ -0,0 +1,63 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author v1r0x <vinzenz.rosenkranz@gmail.com>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Redirects to a different URL
* @since 7.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class RedirectResponse extends Response {
private $redirectURL;
/**
* Creates a response that redirects to a url
* @param string $redirectURL the url to redirect to
* @param S $status
* @param H $headers
* @since 7.0.0
*/
public function __construct(string $redirectURL, int $status = Http::STATUS_SEE_OTHER, array $headers = []) {
parent::__construct($status, $headers);
$this->redirectURL = $redirectURL;
$this->addHeader('Location', $redirectURL);
}
/**
* @return string the url to redirect
* @since 7.0.0
*/
public function getRedirectURL() {
return $this->redirectURL;
}
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
use OCP\IURLGenerator;
/**
* Redirects to the default app
*
* @since 16.0.0
* @deprecated 23.0.0 Use RedirectResponse() with IURLGenerator::linkToDefaultPageUrl() instead
* @template S of int
* @template H of array<string, mixed>
* @template-extends RedirectResponse<int, array<string, mixed>>
*/
class RedirectToDefaultAppResponse extends RedirectResponse {
/**
* Creates a response that redirects to the default app
*
* @param S $status
* @param H $headers
* @since 16.0.0
* @deprecated 23.0.0 Use RedirectResponse() with IURLGenerator::linkToDefaultPageUrl() instead
*/
public function __construct(int $status = Http::STATUS_SEE_OTHER, array $headers = []) {
/** @var IURLGenerator $urlGenerator */
$urlGenerator = \OC::$server->get(IURLGenerator::class);
parent::__construct($urlGenerator->linkToDefaultPageUrl(), $status, $headers);
}
}
@@ -0,0 +1,433 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Clement Wong <git@clement.hk>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
/**
* Base class for responses. Also used to just send headers.
*
* It handles headers, HTTP status code, last modified and ETag.
* @since 6.0.0
* @template S of int
* @template H of array<string, mixed>
*/
class Response {
/**
* Headers
* @var H
*/
private $headers;
/**
* Cookies that will be need to be constructed as header
* @var array
*/
private $cookies = [];
/**
* HTTP status code - defaults to STATUS OK
* @var S
*/
private $status;
/**
* Last modified date
* @var \DateTime
*/
private $lastModified;
/**
* ETag
* @var string
*/
private $ETag;
/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
private $contentSecurityPolicy = null;
/** @var FeaturePolicy */
private $featurePolicy;
/** @var bool */
private $throttled = false;
/** @var array */
private $throttleMetadata = [];
/**
* @param S $status
* @param H $headers
* @since 17.0.0
*/
public function __construct(int $status = Http::STATUS_OK, array $headers = []) {
$this->setStatus($status);
$this->setHeaders($headers);
}
/**
* Caches the response
*
* @param int $cacheSeconds amount of seconds the response is fresh, 0 to disable cache.
* @param bool $public whether the page should be cached by public proxy. Usually should be false, unless this is a static resources.
* @param bool $immutable whether browser should treat the resource as immutable and not ask the server for each page load if the resource changed.
* @return $this
* @since 6.0.0 - return value was added in 7.0.0
*/
public function cacheFor(int $cacheSeconds, bool $public = false, bool $immutable = false) {
if ($cacheSeconds > 0) {
$cacheStore = $public ? 'public' : 'private';
$this->addHeader('Cache-Control', sprintf('%s, max-age=%s, %s', $cacheStore, $cacheSeconds, ($immutable ? 'immutable' : 'must-revalidate')));
// Set expires header
$expires = new \DateTime();
/** @var ITimeFactory $time */
$time = \OCP\Server::get(ITimeFactory::class);
$expires->setTimestamp($time->getTime());
$expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
$this->addHeader('Expires', $expires->format(\DateTimeInterface::RFC2822));
} else {
$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
unset($this->headers['Expires']);
}
return $this;
}
/**
* Adds a new cookie to the response
* @param string $name The name of the cookie
* @param string $value The value of the cookie
* @param \DateTime|null $expireDate Date on that the cookie should expire, if set
* to null cookie will be considered as session
* cookie.
* @param string $sameSite The samesite value of the cookie. Defaults to Lax. Other possibilities are Strict or None
* @return $this
* @since 8.0.0
*/
public function addCookie($name, $value, \DateTime $expireDate = null, $sameSite = 'Lax') {
$this->cookies[$name] = ['value' => $value, 'expireDate' => $expireDate, 'sameSite' => $sameSite];
return $this;
}
/**
* Set the specified cookies
* @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
* @return $this
* @since 8.0.0
*/
public function setCookies(array $cookies) {
$this->cookies = $cookies;
return $this;
}
/**
* Invalidates the specified cookie
* @param string $name
* @return $this
* @since 8.0.0
*/
public function invalidateCookie($name) {
$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
return $this;
}
/**
* Invalidates the specified cookies
* @param array $cookieNames array('foo', 'bar')
* @return $this
* @since 8.0.0
*/
public function invalidateCookies(array $cookieNames) {
foreach ($cookieNames as $cookieName) {
$this->invalidateCookie($cookieName);
}
return $this;
}
/**
* Returns the cookies
* @return array
* @since 8.0.0
*/
public function getCookies() {
return $this->cookies;
}
/**
* Adds a new header to the response that will be called before the render
* function
* @param string $name The name of the HTTP header
* @param string $value The value, null will delete it
* @return $this
* @since 6.0.0 - return value was added in 7.0.0
*/
public function addHeader($name, $value) {
$name = trim($name); // always remove leading and trailing whitespace
// to be able to reliably check for security
// headers
if ($this->status === Http::STATUS_NOT_MODIFIED
&& stripos($name, 'x-') === 0) {
/** @var IConfig $config */
$config = \OC::$server->get(IConfig::class);
if ($config->getSystemValueBool('debug', false)) {
\OC::$server->get(LoggerInterface::class)->error('Setting custom header on a 204 or 304 is not supported (Header: {header})', [
'header' => $name,
]);
}
}
if (is_null($value)) {
unset($this->headers[$name]);
} else {
$this->headers[$name] = $value;
}
return $this;
}
/**
* Set the headers
* @template NewH as array<string, mixed>
* @param NewH $headers value header pairs
* @psalm-this-out static<S, NewH>
* @return static
* @since 8.0.0
*/
public function setHeaders(array $headers): static {
/** @psalm-suppress InvalidPropertyAssignmentValue Expected due to @psalm-this-out */
$this->headers = $headers;
return $this;
}
/**
* Returns the set headers
* @return array{X-Request-Id: string, Cache-Control: string, Content-Security-Policy: string, Feature-Policy: string, X-Robots-Tag: string, Last-Modified?: string, ETag?: string, ...H} the headers
* @since 6.0.0
*/
public function getHeaders() {
/** @var IRequest $request */
/**
* @psalm-suppress UndefinedClass
*/
$request = \OC::$server->get(IRequest::class);
$mergeWith = [
'X-Request-Id' => $request->getId(),
'Cache-Control' => 'no-cache, no-store, must-revalidate',
'Content-Security-Policy' => $this->getContentSecurityPolicy()->buildPolicy(),
'Feature-Policy' => $this->getFeaturePolicy()->buildPolicy(),
'X-Robots-Tag' => 'noindex, nofollow',
];
if ($this->lastModified) {
$mergeWith['Last-Modified'] = $this->lastModified->format(\DateTimeInterface::RFC2822);
}
if ($this->ETag) {
$mergeWith['ETag'] = '"' . $this->ETag . '"';
}
return array_merge($mergeWith, $this->headers);
}
/**
* By default renders no output
* @return string
* @since 6.0.0
*/
public function render() {
return '';
}
/**
* Set response status
* @template NewS as int
* @param NewS $status a HTTP status code, see also the STATUS constants
* @psalm-this-out static<NewS, H>
* @return static
* @since 6.0.0 - return value was added in 7.0.0
*/
public function setStatus($status): static {
/** @psalm-suppress InvalidPropertyAssignmentValue Expected due to @psalm-this-out */
$this->status = $status;
return $this;
}
/**
* Set a Content-Security-Policy
* @param EmptyContentSecurityPolicy $csp Policy to set for the response object
* @return $this
* @since 8.1.0
*/
public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
$this->contentSecurityPolicy = $csp;
return $this;
}
/**
* Get the currently used Content-Security-Policy
* @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
* none specified.
* @since 8.1.0
*/
public function getContentSecurityPolicy() {
if ($this->contentSecurityPolicy === null) {
$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
}
return $this->contentSecurityPolicy;
}
/**
* @since 17.0.0
*/
public function getFeaturePolicy(): EmptyFeaturePolicy {
if ($this->featurePolicy === null) {
$this->setFeaturePolicy(new EmptyFeaturePolicy());
}
return $this->featurePolicy;
}
/**
* @since 17.0.0
*/
public function setFeaturePolicy(EmptyFeaturePolicy $featurePolicy): self {
$this->featurePolicy = $featurePolicy;
return $this;
}
/**
* Get response status
* @since 6.0.0
* @return S
*/
public function getStatus() {
return $this->status;
}
/**
* Get the ETag
* @return string the etag
* @since 6.0.0
*/
public function getETag() {
return $this->ETag;
}
/**
* Get "last modified" date
* @return \DateTime RFC2822 formatted last modified date
* @since 6.0.0
*/
public function getLastModified() {
return $this->lastModified;
}
/**
* Set the ETag
* @param string $ETag
* @return Response Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public function setETag($ETag) {
$this->ETag = $ETag;
return $this;
}
/**
* Set "last modified" date
* @param \DateTime $lastModified
* @return Response Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public function setLastModified($lastModified) {
$this->lastModified = $lastModified;
return $this;
}
/**
* Marks the response as to throttle. Will be throttled when the
* @BruteForceProtection annotation is added.
*
* @param array $metadata
* @since 12.0.0
*/
public function throttle(array $metadata = []) {
$this->throttled = true;
$this->throttleMetadata = $metadata;
}
/**
* Returns the throttle metadata, defaults to empty array
*
* @return array
* @since 13.0.0
*/
public function getThrottleMetadata() {
return $this->throttleMetadata;
}
/**
* Whether the current response is throttled.
*
* @since 12.0.0
*/
public function isThrottled() {
return $this->throttled;
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* A template response that does not emit the loadAdditionalScripts events.
*
* This is useful for pages that are authenticated but do not yet show the
* full nextcloud UI. Like the 2FA page, or the grant page in the login flow.
*
* @since 16.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends TemplateResponse<int, array<string, mixed>>
*/
class StandaloneTemplateResponse extends TemplateResponse {
}
@@ -0,0 +1,73 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Class StreamResponse
*
* @since 8.1.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class StreamResponse extends Response implements ICallbackResponse {
/** @var string */
private $filePath;
/**
* @param string|resource $filePath the path to the file or a file handle which should be streamed
* @param S $status
* @param H $headers
* @since 8.1.0
*/
public function __construct(mixed $filePath, int $status = Http::STATUS_OK, array $headers = []) {
parent::__construct($status, $headers);
$this->filePath = $filePath;
}
/**
* Streams the file using readfile
*
* @param IOutput $output a small wrapper that handles output
* @since 8.1.0
*/
public function callback(IOutput $output) {
// handle caching
if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
} elseif ($output->setReadfile($this->filePath) === false) {
$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
}
}
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* Class StrictContentSecurityPolicy is a simple helper which allows applications to
* modify the Content-Security-Policy sent by Nextcloud. Per default only JavaScript,
* stylesheets, images, fonts, media and connections from the same domain
* ('self') are allowed.
*
* Even if a value gets modified above defaults will still get appended. Please
* note that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* This class represents out strictest defaults. They may get change from release
* to release if more strict CSP directives become available.
*
* @since 14.0.0
* @deprecated 17.0.0
*/
class StrictContentSecurityPolicy extends EmptyContentSecurityPolicy {
/** @var bool Whether inline JS snippets are allowed */
protected $inlineScriptAllowed = false;
/** @var bool Whether eval in JS scripts is allowed */
protected $evalScriptAllowed = false;
/** @var bool Whether WebAssembly compilation is allowed */
protected ?bool $evalWasmAllowed = false;
/** @var array Domains from which scripts can get loaded */
protected $allowedScriptDomains = [
'\'self\'',
];
/** @var bool Whether inline CSS is allowed */
protected $inlineStyleAllowed = false;
/** @var array Domains from which CSS can get loaded */
protected $allowedStyleDomains = [
'\'self\'',
];
/** @var array Domains from which images can get loaded */
protected $allowedImageDomains = [
'\'self\'',
'data:',
'blob:',
];
/** @var array Domains to which connections can be done */
protected $allowedConnectDomains = [
'\'self\'',
];
/** @var array Domains from which media elements can be loaded */
protected $allowedMediaDomains = [
'\'self\'',
];
/** @var array Domains from which object elements can be loaded */
protected $allowedObjectDomains = [];
/** @var array Domains from which iframes can be loaded */
protected $allowedFrameDomains = [];
/** @var array Domains from which fonts can be loaded */
protected $allowedFontDomains = [
'\'self\'',
];
/** @var array Domains from which web-workers and nested browsing content can load elements */
protected $allowedChildSrcDomains = [];
/** @var array Domains which can embed this Nextcloud instance */
protected $allowedFrameAncestors = [];
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* Class StrictEvalContentSecurityPolicy is a simple helper which allows applications to
* modify the Content-Security-Policy sent by Nextcloud. Per default only JavaScript,
* stylesheets, images, fonts, media and connections from the same domain
* ('self') are allowed.
*
* Even if a value gets modified above defaults will still get appended. Please
* note that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* This is a temp helper class from the default ContentSecurityPolicy to allow slow
* migration to a stricter CSP. This does not allow unsafe eval.
*
* @since 14.0.0
* @deprecated 17.0.0
*/
class StrictEvalContentSecurityPolicy extends ContentSecurityPolicy {
/**
* @since 14.0.0
*/
public function __construct() {
$this->evalScriptAllowed = false;
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
/**
* Class StrictInlineContentSecurityPolicy is a simple helper which allows applications to
* modify the Content-Security-Policy sent by Nextcloud. Per default only JavaScript,
* stylesheets, images, fonts, media and connections from the same domain
* ('self') are allowed.
*
* Even if a value gets modified above defaults will still get appended. Please
* note that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* This is a temp helper class from the default ContentSecurityPolicy to allow slow
* migration to a stricter CSP. This does not allow inline styles.
*
* @since 14.0.0
* @deprecated 17.0.0
*/
class StrictInlineContentSecurityPolicy extends ContentSecurityPolicy {
/**
* @since 14.0.0
*/
public function __construct() {
$this->inlineStyleAllowed = false;
}
}
@@ -0,0 +1,78 @@
<?php
/**
* @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
*
* @author Daniel Calviño Sánchez <danxuliu@gmail.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Template;
use OCP\Util;
/**
* Class LinkMenuAction
*
* @since 14.0.0
*/
class ExternalShareMenuAction extends SimpleMenuAction {
/** @var string */
private $owner;
/** @var string */
private $displayname;
/** @var string */
private $shareName;
/**
* ExternalShareMenuAction constructor.
*
* @param string $label
* @param string $icon
* @param string $owner
* @param string $displayname
* @param string $shareName
* @since 14.0.0
*/
public function __construct(string $label, string $icon, string $owner, string $displayname, string $shareName) {
parent::__construct('save', $label, $icon);
$this->owner = $owner;
$this->displayname = $displayname;
$this->shareName = $shareName;
}
/**
* @since 14.0.0
*/
public function render(): string {
return '<li>' .
' <button id="save-external-share" class="icon ' . Util::sanitizeHTML($this->getIcon()) . '" data-protected="false" data-owner-display-name="' . Util::sanitizeHTML($this->displayname) . '" data-owner="' . Util::sanitizeHTML($this->owner) . '" data-name="' . Util::sanitizeHTML($this->shareName) . '">' . Util::sanitizeHTML($this->getLabel()) . '</button>' .
'</li>' .
'<li id="external-share-menu-item" class="hidden">' .
' <span class="menuitem">' .
' <form class="save-form" action="#">' .
' <input type="text" id="remote_address" placeholder="user@yourNextcloud.org">' .
' <input type="submit" value=" " id="save-button-confirm" class="icon-confirm" disabled="disabled"></button>' .
' </form>' .
' </span>' .
'</li>';
}
}
@@ -0,0 +1,61 @@
<?php
/**
* @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Template;
/**
* Interface IMenuAction
*
* @since 14.0
*/
interface IMenuAction {
/**
* @since 14.0.0
* @return string
*/
public function getId(): string;
/**
* @since 14.0.0
* @return string
*/
public function getLabel(): string;
/**
* @since 14.0.0
* @return string
*/
public function getLink(): string;
/**
* @since 14.0.0
* @return int
*/
public function getPriority(): int;
/**
* @since 14.0.0
* @return string
*/
public function render(): string;
}
@@ -0,0 +1,63 @@
<?php
/**
* @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Template;
use OCP\Util;
/**
* Class LinkMenuAction
*
* @since 14.0.0
*/
class LinkMenuAction extends SimpleMenuAction {
/**
* LinkMenuAction constructor.
*
* @param string $label
* @param string $icon
* @param string $link
* @since 14.0.0
*/
public function __construct(string $label, string $icon, string $link) {
parent::__construct('directLink-container', $label, $icon, $link);
}
/**
* @return string
* @since 14.0.0
*/
public function render(): string {
return '<li>' .
'<a id="directLink-container">' .
'<span class="icon ' . Util::sanitizeHTML($this->getIcon()) . '"></span>' .
'<label for="directLink">' . Util::sanitizeHTML($this->getLabel()) . '</label>' .
'</a>' .
'</li>' .
'<li>' .
'<span class="menuitem">' .
'<input id="directLink" type="text" readonly="" value="' . Util::sanitizeHTML($this->getLink()) . '">' .
'</span>' .
'</li>';
}
}
@@ -0,0 +1,163 @@
<?php
/**
* @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Template;
use InvalidArgumentException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\TemplateResponse;
/**
* Class PublicTemplateResponse
*
* @since 14.0.0
* @template H of array<string, mixed>
* @template S of int
* @template-extends TemplateResponse<int, array<string, mixed>>
*/
class PublicTemplateResponse extends TemplateResponse {
private $headerTitle = '';
private $headerDetails = '';
private $headerActions = [];
private $footerVisible = true;
/**
* PublicTemplateResponse constructor.
*
* @param string $appName
* @param string $templateName
* @param array $params
* @param S $status
* @param H $headers
* @since 14.0.0
*/
public function __construct(string $appName, string $templateName, array $params = [], $status = Http::STATUS_OK, array $headers = []) {
parent::__construct($appName, $templateName, $params, 'public', $status, $headers);
\OC_Util::addScript('core', 'public/publicpage');
}
/**
* @param string $title
* @since 14.0.0
*/
public function setHeaderTitle(string $title) {
$this->headerTitle = $title;
}
/**
* @return string
* @since 14.0.0
*/
public function getHeaderTitle(): string {
return $this->headerTitle;
}
/**
* @param string $details
* @since 14.0.0
*/
public function setHeaderDetails(string $details) {
$this->headerDetails = $details;
}
/**
* @return string
* @since 14.0.0
*/
public function getHeaderDetails(): string {
return $this->headerDetails;
}
/**
* @param array $actions
* @since 14.0.0
* @throws InvalidArgumentException
*/
public function setHeaderActions(array $actions) {
foreach ($actions as $action) {
if ($actions instanceof IMenuAction) {
throw new InvalidArgumentException('Actions must be of type IMenuAction');
}
$this->headerActions[] = $action;
}
usort($this->headerActions, function (IMenuAction $a, IMenuAction $b) {
return $a->getPriority() <=> $b->getPriority();
});
}
/**
* @return IMenuAction
* @since 14.0.0
* @throws \Exception
*/
public function getPrimaryAction(): IMenuAction {
if ($this->getActionCount() > 0) {
return $this->headerActions[0];
}
throw new \Exception('No header actions have been set');
}
/**
* @return int
* @since 14.0.0
*/
public function getActionCount(): int {
return count($this->headerActions);
}
/**
* @return IMenuAction[]
* @since 14.0.0
*/
public function getOtherActions(): array {
return array_slice($this->headerActions, 1);
}
/**
* @since 14.0.0
*/
public function setFooterVisible(bool $visible = false) {
$this->footerVisible = $visible;
}
/**
* @since 14.0.0
*/
public function getFooterVisible(): bool {
return $this->footerVisible;
}
/**
* @return string
* @since 14.0.0
*/
public function render(): string {
$params = array_merge($this->getParams(), [
'template' => $this,
]);
$this->setParams($params);
return parent::render();
}
}
@@ -0,0 +1,123 @@
<?php
/**
* @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http\Template;
use OCP\Util;
/**
* Class SimpleMenuAction
*
* @since 14.0.0
*/
class SimpleMenuAction implements IMenuAction {
/** @var string */
private $id;
/** @var string */
private $label;
/** @var string */
private $icon;
/** @var string */
private $link;
/** @var int */
private $priority;
/** @var string */
private $detail;
/**
* SimpleMenuAction constructor.
*
* @param string $id
* @param string $label
* @param string $icon
* @param string $link
* @param int $priority
* @param string $detail
* @since 14.0.0
*/
public function __construct(string $id, string $label, string $icon, string $link = '', int $priority = 100, string $detail = '') {
$this->id = $id;
$this->label = $label;
$this->icon = $icon;
$this->link = $link;
$this->priority = $priority;
$this->detail = $detail;
}
/**
* @return string
* @since 14.0.0
*/
public function getId(): string {
return $this->id;
}
/**
* @return string
* @since 14.0.0
*/
public function getLabel(): string {
return $this->label;
}
/**
* @return string
* @since 14.0.0
*/
public function getIcon(): string {
return $this->icon;
}
/**
* @return string
* @since 14.0.0
*/
public function getLink(): string {
return $this->link;
}
/**
* @return int
* @since 14.0.0
*/
public function getPriority(): int {
return $this->priority;
}
/**
* @return string
* @since 14.0.0
*/
public function render(): string {
$detailContent = ($this->detail !== '') ? '&nbsp;<span class="download-size">(' . Util::sanitizeHTML($this->detail) . ')</span>' : '';
return sprintf(
'<li id="%s"><a href="%s"><span class="icon %s"></span>%s %s</a></li>',
Util::sanitizeHTML($this->id), Util::sanitizeHTML($this->link), Util::sanitizeHTML($this->icon), Util::sanitizeHTML($this->label), $detailContent
);
}
}
@@ -0,0 +1,213 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
* @author Kate Döen <kate.doeen@nextcloud.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/>
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* Response for a normal template
* @since 6.0.0
*
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class TemplateResponse extends Response {
/**
* @since 20.0.0
*/
public const RENDER_AS_GUEST = 'guest';
/**
* @since 20.0.0
*/
public const RENDER_AS_BLANK = '';
/**
* @since 20.0.0
*/
public const RENDER_AS_BASE = 'base';
/**
* @since 20.0.0
*/
public const RENDER_AS_USER = 'user';
/**
* @since 20.0.0
*/
public const RENDER_AS_ERROR = 'error';
/**
* @since 20.0.0
*/
public const RENDER_AS_PUBLIC = 'public';
/**
* name of the template
* @var string
*/
protected $templateName;
/**
* parameters
* @var array
*/
protected $params;
/**
* rendering type (admin, user, blank)
* @var string
*/
protected $renderAs;
/**
* app name
* @var string
*/
protected $appName;
/**
* constructor of TemplateResponse
* @param string $appName the name of the app to load the template from
* @param string $templateName the name of the template
* @param array $params an array of parameters which should be passed to the
* template
* @param string $renderAs how the page should be rendered, defaults to user
* @param S $status
* @param H $headers
* @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
*/
public function __construct(string $appName, string $templateName, array $params = [], string $renderAs = self::RENDER_AS_USER, int $status = Http::STATUS_OK, array $headers = []) {
parent::__construct($status, $headers);
$this->templateName = $templateName;
$this->appName = $appName;
$this->params = $params;
$this->renderAs = $renderAs;
$this->setContentSecurityPolicy(new ContentSecurityPolicy());
$this->setFeaturePolicy(new FeaturePolicy());
}
/**
* Sets template parameters
* @param array $params an array with key => value structure which sets template
* variables
* @return TemplateResponse Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public function setParams(array $params) {
$this->params = $params;
return $this;
}
/**
* Used for accessing the set parameters
* @return array the params
* @since 6.0.0
*/
public function getParams() {
return $this->params;
}
/**
* @return string the app id of the used template
* @since 25.0.0
*/
public function getApp(): string {
return $this->appName;
}
/**
* Used for accessing the name of the set template
* @return string the name of the used template
* @since 6.0.0
*/
public function getTemplateName() {
return $this->templateName;
}
/**
* Sets the template page
* @param string $renderAs admin, user or blank. Admin also prints the admin
* settings header and footer, user renders the normal
* normal page including footer and header and blank
* just renders the plain template
* @return TemplateResponse Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public function renderAs($renderAs) {
$this->renderAs = $renderAs;
return $this;
}
/**
* Returns the set renderAs
* @return string the renderAs value
* @since 6.0.0
*/
public function getRenderAs() {
return $this->renderAs;
}
/**
* Returns the rendered html
* @return string the rendered html
* @since 6.0.0
*/
public function render() {
$renderAs = self::RENDER_AS_USER;
if ($this->renderAs === 'blank') {
// Legacy fallback as \OCP\Template needs an empty string instead of 'blank' for an unwrapped response
$renderAs = self::RENDER_AS_BLANK;
} elseif (in_array($this->renderAs, [
self::RENDER_AS_GUEST,
self::RENDER_AS_BLANK,
self::RENDER_AS_BASE,
self::RENDER_AS_ERROR,
self::RENDER_AS_PUBLIC,
self::RENDER_AS_USER], true)) {
$renderAs = $this->renderAs;
}
$template = new \OCP\Template($this->appName, $this->templateName, $renderAs);
foreach ($this->params as $key => $value) {
$template->assign($key, $value);
}
return $template->fetchPage($this->params);
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* @copyright 2021 Lukas Reschke <lukas@statuscode.ch>
*
* @author 2021 Lukas Reschke <lukas@statuscode.ch>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
/**
* A renderer for text responses
* @since 22.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class TextPlainResponse extends Response {
/** @var string */
private $text = '';
/**
* constructor of TextPlainResponse
* @param string $text The text body
* @param S $statusCode the Http status code, defaults to 200
* @param H $headers
* @since 22.0.0
*/
public function __construct(string $text = '', int $statusCode = Http::STATUS_OK, array $headers = []) {
parent::__construct($statusCode, $headers);
$this->text = $text;
$this->addHeader('Content-Type', 'text/plain');
}
/**
* Returns the text
* @return string
* @since 22.0.0
* @throws \Exception If data could not get encoded
*/
public function render() : string {
return $this->text;
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
use OCP\Template;
/**
* A generic 429 response showing an 404 error page as well to the end-user
* @since 19.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class TooManyRequestsResponse extends Response {
/**
* @param S $status
* @param H $headers
* @since 19.0.0
*/
public function __construct(int $status = Http::STATUS_TOO_MANY_REQUESTS, array $headers = []) {
parent::__construct($status, $headers);
$this->setContentSecurityPolicy(new ContentSecurityPolicy());
}
/**
* @return string
* @since 19.0.0
*/
public function render() {
$template = new Template('core', '429', 'blank');
return $template->fetchPage();
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Jakob Sack <mail@jakobsack.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Http;
use OC\Streamer;
use OCP\AppFramework\Http;
use OCP\IRequest;
/**
* Public library to send several files in one zip archive.
*
* @since 15.0.0
* @template S of int
* @template H of array<string, mixed>
* @template-extends Response<int, array<string, mixed>>
*/
class ZipResponse extends Response implements ICallbackResponse {
/** @var array{internalName: string, resource: resource, size: int, time: int}[] Files to be added to the zip response */
private array $resources = [];
/** @var string Filename that the zip file should have */
private string $name;
private IRequest $request;
/**
* @param S $status
* @param H $headers
* @since 15.0.0
*/
public function __construct(IRequest $request, string $name = 'output', int $status = Http::STATUS_OK, array $headers = []) {
parent::__construct($status, $headers);
$this->name = $name;
$this->request = $request;
}
/**
* @since 15.0.0
*/
public function addResource($r, string $internalName, int $size, int $time = -1) {
if (!\is_resource($r)) {
throw new \InvalidArgumentException('No resource provided');
}
$this->resources[] = [
'resource' => $r,
'internalName' => $internalName,
'size' => $size,
'time' => $time,
];
}
/**
* @since 15.0.0
*/
public function callback(IOutput $output) {
$size = 0;
$files = count($this->resources);
foreach ($this->resources as $resource) {
$size += $resource['size'];
}
$zip = new Streamer($this->request, $size, $files);
$zip->sendHeaders($this->name);
foreach ($this->resources as $resource) {
$zip->addFileFromStream($resource['resource'], $resource['internalName'], $resource['size'], $resource['time']);
}
$zip->finalize();
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use OCP\IContainer;
use Psr\Container\ContainerInterface;
/**
* This is a tagging interface for a container that belongs to an app
*
* The interface currently extends IContainer, but this interface is deprecated as of Nextcloud 20,
* thus this interface won't extend it anymore once that was removed. So migrate to the ContainerInterface
* only.
*
* @deprecated 20.0.0
* @since 6.0.0
*/
interface IAppContainer extends ContainerInterface, IContainer {
/**
* used to return the appname of the set application
* @return string the name of your application
* @since 6.0.0
* @deprecated 20.0.0
*/
public function getAppName();
/**
* @return \OCP\IServerContainer
* @since 6.0.0
* @deprecated 20.0.0
*/
public function getServer();
/**
* @param string $middleWare
* @return boolean
* @since 6.0.0
* @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerMiddleware
*/
public function registerMiddleWare($middleWare);
/**
* Register a capability
*
* @param string $serviceName e.g. 'OCA\Files\Capabilities'
* @since 8.2.0
* @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerCapability
*/
public function registerCapability($serviceName);
}
@@ -0,0 +1,103 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Stefan Weil <sw@weilnetz.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use Exception;
use OCP\AppFramework\Http\Response;
/**
* Middleware is used to provide hooks before or after controller methods and
* deal with possible exceptions raised in the controller methods.
* They're modeled after Django's middleware system:
* https://docs.djangoproject.com/en/dev/topics/http/middleware/
* @since 6.0.0
*/
abstract class Middleware {
/**
* This is being run in normal order before the controller is being
* called which allows several modifications and checks
*
* @param Controller $controller the controller that is being called
* @param string $methodName the name of the method that will be called on
* the controller
* @return void
* @since 6.0.0
*/
public function beforeController(Controller $controller, string $methodName) {
}
/**
* This is being run when either the beforeController method or the
* controller method itself is throwing an exception. The middleware is
* asked in reverse order to handle the exception and to return a response.
* If the response is null, it is assumed that the exception could not be
* handled and the error will be thrown again
*
* @param Controller $controller the controller that is being called
* @param string $methodName the name of the method that will be called on
* the controller
* @param Exception $exception the thrown exception
* @throws Exception the passed in exception if it can't handle it
* @return Response a Response object in case that the exception was handled
* @since 6.0.0
*/
public function afterException(Controller $controller, string $methodName, Exception $exception) {
throw $exception;
}
/**
* This is being run after a successful controllermethod call and allows
* the manipulation of a Response object. The middleware is run in reverse order
*
* @param Controller $controller the controller that is being called
* @param string $methodName the name of the method that will be called on
* the controller
* @param Response $response the generated response from the controller
* @return Response a Response object
* @since 6.0.0
*/
public function afterController(Controller $controller, string $methodName, Response $response) {
return $response;
}
/**
* This is being run after the response object has been rendered and
* allows the manipulation of the output. The middleware is run in reverse order
*
* @param Controller $controller the controller that is being called
* @param string $methodName the name of the method that will be called on
* the controller
* @param string $output the generated output from a response
* @return string the output that should be printed
* @since 6.0.0
*/
public function beforeOutput(Controller $controller, string $methodName, string $output) {
return $output;
}
}
@@ -0,0 +1,44 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\OCS;
use Exception;
use OCP\AppFramework\Http;
/**
* Class OCSBadRequestException
*
* @since 9.1.0
*/
class OCSBadRequestException extends OCSException {
/**
* OCSBadRequestException constructor.
*
* @param string $message
* @param Exception|null $previous
* @since 9.1.0
*/
public function __construct($message = '', Exception $previous = null) {
parent::__construct($message, Http::STATUS_BAD_REQUEST, $previous);
}
}
@@ -0,0 +1,34 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\OCS;
use Exception;
/**
* Class OCSException
*
* @since 9.1.0
*/
class OCSException extends Exception {
}
@@ -0,0 +1,44 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\OCS;
use Exception;
use OCP\AppFramework\Http;
/**
* Class OCSForbiddenException
*
* @since 9.1.0
*/
class OCSForbiddenException extends OCSException {
/**
* OCSForbiddenException constructor.
*
* @param string $message
* @param Exception|null $previous
* @since 9.1.0
*/
public function __construct($message = '', Exception $previous = null) {
parent::__construct($message, Http::STATUS_FORBIDDEN, $previous);
}
}
@@ -0,0 +1,44 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\OCS;
use Exception;
use OCP\AppFramework\Http;
/**
* Class OCSNotFoundException
*
* @since 9.1.0
*/
class OCSNotFoundException extends OCSException {
/**
* OCSNotFoundException constructor.
*
* @param string $message
* @param Exception|null $previous
* @since 9.1.0
*/
public function __construct($message = '', Exception $previous = null) {
parent::__construct($message, Http::STATUS_NOT_FOUND, $previous);
}
}
@@ -0,0 +1,44 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\OCS;
use Exception;
use OCP\AppFramework\Http;
/**
* Class OCSPreconditionFailedException
*
* @since 28.0.0
*/
class OCSPreconditionFailedException extends OCSException {
/**
* OCSPreconditionFailedException constructor.
*
* @param string $message
* @param Exception|null $previous
* @since 9.1.0
*/
public function __construct($message = '', Exception $previous = null) {
parent::__construct($message, Http::STATUS_PRECONDITION_FAILED, $previous);
}
}
@@ -0,0 +1,112 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Donquixote <marjunebatac@gmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Stefan Weil <sw@weilnetz.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
/**
* Base class to inherit your controllers from that are used for RESTful APIs
* @since 8.1.0
*/
abstract class OCSController extends ApiController {
public const RESPOND_UNAUTHORISED = 997;
public const RESPOND_SERVER_ERROR = 996;
public const RESPOND_NOT_FOUND = 998;
public const RESPOND_UNKNOWN_ERROR = 999;
/** @var int */
private $ocsVersion;
/**
* constructor of the controller
* @param string $appName the name of the app
* @param IRequest $request an instance of the request
* @param string $corsMethods comma separated string of HTTP verbs which
* should be allowed for websites or webapps when calling your API, defaults to
* 'PUT, POST, GET, DELETE, PATCH'
* @param string $corsAllowedHeaders comma separated string of HTTP headers
* which should be allowed for websites or webapps when calling your API,
* defaults to 'Authorization, Content-Type, Accept'
* @param int $corsMaxAge number in seconds how long a preflighted OPTIONS
* request should be cached, defaults to 1728000 seconds
* @since 8.1.0
*/
public function __construct($appName,
IRequest $request,
$corsMethods = 'PUT, POST, GET, DELETE, PATCH',
$corsAllowedHeaders = 'Authorization, Content-Type, Accept, OCS-APIRequest',
$corsMaxAge = 1728000) {
parent::__construct($appName, $request, $corsMethods,
$corsAllowedHeaders, $corsMaxAge);
$this->registerResponder('json', function ($data) {
return $this->buildOCSResponse('json', $data);
});
$this->registerResponder('xml', function ($data) {
return $this->buildOCSResponse('xml', $data);
});
}
/**
* @param int $version
* @since 11.0.0
* @internal
*/
public function setOCSVersion($version) {
$this->ocsVersion = $version;
}
/**
* Since the OCS endpoints default to XML we need to find out the format
* again
* @param mixed $response the value that was returned from a controller and
* is not a Response instance
* @param string $format the format for which a formatter has been registered
* @throws \DomainException if format does not match a registered formatter
* @return Response
* @since 9.1.0
*/
public function buildResponse($response, $format = 'xml') {
return parent::buildResponse($response, $format);
}
/**
* Unwrap data and build ocs response
* @param string $format json or xml
* @param DataResponse $data the data which should be transformed
* @since 8.1.0
* @return \OC\AppFramework\OCS\BaseResponse
*/
private function buildOCSResponse($format, DataResponse $data) {
if ($this->ocsVersion === 1) {
return new \OC\AppFramework\OCS\V1Response($data, $format);
}
return new \OC\AppFramework\OCS\V2Response($data, $format);
}
}
@@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework;
use OCP\IRequest;
use OCP\ISession;
/**
* Base controller for public shares
*
* It will verify if the user is properly authenticated to the share. If not a 404
* is thrown by the PublicShareMiddleware.
*
* Use this for example for a controller that is not to be called via a webbrowser
* directly. For example a PublicPreviewController. As this is not meant to be
* called by a user directly.
*
* To show an auth page extend the AuthPublicShareController
*
* @since 14.0.0
*/
abstract class PublicShareController extends Controller {
/** @var ISession */
protected $session;
/** @var string */
private $token;
/**
* @since 14.0.0
*/
public function __construct(string $appName,
IRequest $request,
ISession $session) {
parent::__construct($appName, $request);
$this->session = $session;
}
/**
* Middleware set the token for the request
*
* @since 14.0.0
*/
final public function setToken(string $token) {
$this->token = $token;
}
/**
* Get the token for this request
*
* @since 14.0.0
*/
final public function getToken(): string {
return $this->token;
}
/**
* Get a hash of the password for this share
*
* To ensure access is blocked when the password to a share is changed we store
* a hash of the password for this token.
*
* @since 14.0.0
*/
abstract protected function getPasswordHash(): string;
/**
* Is the provided token a valid token
*
* This function is already called from the middleware directly after setting the token.
*
* @since 14.0.0
*/
abstract public function isValidToken(): bool;
/**
* Is a share with this token password protected
*
* @since 14.0.0
*/
abstract protected function isPasswordProtected(): bool;
/**
* Check if a share is authenticated or not
*
* @since 14.0.0
*/
public function isAuthenticated(): bool {
// Always authenticated against non password protected shares
if (!$this->isPasswordProtected()) {
return true;
}
// If we are authenticated properly
if ($this->session->get('public_link_authenticated_token') === $this->getToken() &&
$this->session->get('public_link_authenticated_password_hash') === $this->getPasswordHash()) {
return true;
}
// Fail by default if nothing matches
return false;
}
/**
* Function called if the share is not found.
*
* You can use this to do some logging for example
*
* @since 14.0.0
*/
public function shareNotFound() {
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @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/>
*
*/
namespace OCP\AppFramework;
use Exception;
use Psr\Container\ContainerExceptionInterface;
/**
* Class QueryException
*
* The class extends `ContainerExceptionInterface` since 20.0.0
*
* @since 8.1.0
* @deprecated 20.0.0 catch \Psr\Container\ContainerExceptionInterface
*/
class QueryException extends Exception implements ContainerExceptionInterface {
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Services;
/**
* Wrapper for AppConfig for the AppFramework
*
* @since 20.0.0
*/
interface IAppConfig {
/**
* Get all keys stored for this app
*
* @return string[] the keys stored for the app
* @since 20.0.0
*/
public function getAppKeys(): array ;
/**
* Writes a new app wide value
*
* @param string $key the key of the value, under which will be saved
* @param string $value the value that should be stored
* @return void
* @since 20.0.0
*/
public function setAppValue(string $key, string $value): void;
/**
* Looks up an app wide defined value
*
* @param string $key the key of the value, under which it was saved
* @param string $default the default value to be returned if the value isn't set
* @return string the saved value
* @since 20.0.0
*/
public function getAppValue(string $key, string $default = ''): string;
/**
* Delete an app wide defined value
*
* @param string $key the key of the value, under which it was saved
* @return void
* @since 20.0.0
*/
public function deleteAppValue(string $key): void;
/**
* Removes all keys in appconfig belonging to the app
*
* @return void
* @since 20.0.0
*/
public function deleteAppValues(): void;
/**
* Set a user defined value
*
* @param string $userId the userId of the user that we want to store the value under
* @param string $key the key under which the value is being stored
* @param string $value the value that you want to store
* @param string $preCondition only update if the config value was previously the value passed as $preCondition
* @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
* @throws \UnexpectedValueException when trying to store an unexpected value
* @since 20.0.0
*/
public function setUserValue(string $userId, string $key, string $value, ?string $preCondition = null): void;
/**
* Shortcut for getting a user defined value
*
* @param string $userId the userId of the user that we want to store the value under
* @param string $key the key under which the value is being stored
* @param mixed $default the default value to be returned if the value isn't set
* @return string
* @since 20.0.0
*/
public function getUserValue(string $userId, string $key, string $default = ''): string;
/**
* Delete a user value
*
* @param string $userId the userId of the user that we want to store the value under
* @param string $key the key under which the value is being stored
* @since 20.0.0
*/
public function deleteUserValue(string $userId, string $key): void;
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Services;
use Closure;
/**
* @since 20.0.0
*/
interface IInitialState {
/**
* Allows an app to provide its initial state to the template system.
* Use this if you know your initial state sill be used for example if
* you are in the render function of you controller.
*
* @since 20.0.0
*
* @param string $key
* @param bool|int|float|string|array|\JsonSerializable $data
*/
public function provideInitialState(string $key, $data): void;
/**
* Allows an app to provide its initial state via a lazy method.
* This will call the closure when the template is being generated.
* Use this if your app is injected into pages. Since then the render method
* is not called explicitly. But we do not want to load the state on webdav
* requests for example.
*
* @since 20.0.0
*
* @param string $key
* @param Closure $closure returns a primitive or an object that implements JsonSerializable
* @psalm-param Closure():bool|Closure():int|Closure():float|Closure():string|Closure():\JsonSerializable $closure
*/
public function provideLazyInitialState(string $key, Closure $closure): void;
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\AppFramework\Services;
/**
* @since 21.0.0
*/
abstract class InitialStateProvider implements \JsonSerializable {
/**
* @since 21.0.0
*/
abstract public function getKey(): string;
/**
* @since 21.0.0
*/
abstract public function getData();
/**
* @since 21.0.0
* @return mixed
*/
#[\ReturnTypeWillChange]
final public function jsonSerialize() {
return $this->getData();
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Olivier Paroz <github@oparoz.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @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/>
*
*/
namespace OCP\AppFramework\Utility;
/**
* Interface ControllerMethodReflector
*
* Reads and parses annotations from doc comments
*
* @since 8.0.0
* @deprecated 22.0.0 will be obsolete with native attributes in PHP8
* @see https://help.nextcloud.com/t/how-should-we-use-php8-attributes/104278
*/
interface IControllerMethodReflector {
/**
* @param object $object an object or classname
* @param string $method the method which we want to inspect
* @return void
* @since 8.0.0
* @deprecated 17.0.0 Reflect should not be called multiple times and only be used internally. This will be removed in Nextcloud 18
*/
public function reflect($object, string $method);
/**
* Inspects the PHPDoc parameters for types
*
* @param string $parameter the parameter whose type comments should be
* parsed
* @return string|null type in the type parameters (@param int $something)
* would return int or null if not existing
* @since 8.0.0
* @deprecated 22.0.0 this method is only used internally
*/
public function getType(string $parameter);
/**
* @return array the arguments of the method with key => default value
* @since 8.0.0
* @deprecated 22.0.0 this method is only used internally
*/
public function getParameters(): array;
/**
* Check if a method contains an annotation
*
* @param string $name the name of the annotation
* @return bool true if the annotation is found
* @since 8.0.0
* @deprecated 22.0.0 will be obsolete with native attributes in PHP8
* @see https://help.nextcloud.com/t/how-should-we-use-php8-attributes/104278
*/
public function hasAnnotation(string $name): bool;
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022, Joas Schilling <coding@schilljs.com>
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @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/>
*
*/
namespace OCP\AppFramework\Utility;
use Psr\Clock\ClockInterface;
/**
* Use this to get a timestamp or DateTime object in code to remain testable
*
* @since 8.0.0
* @since 27.0.0 Extends the \Psr\Clock\ClockInterface interface
* @ref https://www.php-fig.org/psr/psr-20/#21-clockinterface
*/
interface ITimeFactory extends ClockInterface {
/**
* @return int the result of a call to time()
* @since 8.0.0
*/
public function getTime(): int;
/**
* @param string $time
* @param \DateTimeZone|null $timezone
* @return \DateTime
* @since 15.0.0
*/
public function getDateTime(string $time = 'now', \DateTimeZone $timezone = null): \DateTime;
/**
* @param \DateTimeZone $timezone
* @return static
* @since 26.0.0
*/
public function withTimeZone(\DateTimeZone $timezone): static;
}