DIContainer.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\AppFramework\DependencyInjection;
  8. use OC;
  9. use OC\AppFramework\Http;
  10. use OC\AppFramework\Http\Dispatcher;
  11. use OC\AppFramework\Http\Output;
  12. use OC\AppFramework\Middleware\MiddlewareDispatcher;
  13. use OC\AppFramework\Middleware\OCSMiddleware;
  14. use OC\AppFramework\Middleware\Security\CORSMiddleware;
  15. use OC\AppFramework\Middleware\Security\RateLimitingMiddleware;
  16. use OC\AppFramework\Middleware\Security\SecurityMiddleware;
  17. use OC\AppFramework\Middleware\SessionMiddleware;
  18. use OC\AppFramework\ScopedPsrLogger;
  19. use OC\AppFramework\Utility\SimpleContainer;
  20. use OC\Core\Middleware\TwoFactorMiddleware;
  21. use OC\Diagnostics\EventLogger;
  22. use OC\Log\PsrLoggerAdapter;
  23. use OC\ServerContainer;
  24. use OC\Settings\AuthorizedGroupMapper;
  25. use OCA\WorkflowEngine\Manager;
  26. use OCP\AppFramework\Http\IOutput;
  27. use OCP\AppFramework\IAppContainer;
  28. use OCP\AppFramework\QueryException;
  29. use OCP\AppFramework\Services\IAppConfig;
  30. use OCP\AppFramework\Services\IInitialState;
  31. use OCP\AppFramework\Utility\IControllerMethodReflector;
  32. use OCP\AppFramework\Utility\ITimeFactory;
  33. use OCP\Files\Folder;
  34. use OCP\Files\IAppData;
  35. use OCP\Group\ISubAdmin;
  36. use OCP\IConfig;
  37. use OCP\IDBConnection;
  38. use OCP\IGroupManager;
  39. use OCP\IInitialStateService;
  40. use OCP\IL10N;
  41. use OCP\INavigationManager;
  42. use OCP\IRequest;
  43. use OCP\IServerContainer;
  44. use OCP\ISession;
  45. use OCP\IURLGenerator;
  46. use OCP\IUserSession;
  47. use OCP\Security\Bruteforce\IThrottler;
  48. use OCP\Security\Ip\IRemoteAddress;
  49. use Psr\Container\ContainerInterface;
  50. use Psr\Log\LoggerInterface;
  51. /**
  52. * @deprecated 20.0.0
  53. */
  54. class DIContainer extends SimpleContainer implements IAppContainer {
  55. private string $appName;
  56. /**
  57. * @var array
  58. */
  59. private $middleWares = [];
  60. /** @var ServerContainer */
  61. private $server;
  62. /**
  63. * Put your class dependencies in here
  64. * @param string $appName the name of the app
  65. * @param array $urlParams
  66. * @param ServerContainer|null $server
  67. */
  68. public function __construct(string $appName, array $urlParams = [], ?ServerContainer $server = null) {
  69. parent::__construct();
  70. $this->appName = $appName;
  71. $this['appName'] = $appName;
  72. $this['urlParams'] = $urlParams;
  73. $this->registerAlias('Request', IRequest::class);
  74. /** @var \OC\ServerContainer $server */
  75. if ($server === null) {
  76. $server = \OC::$server;
  77. }
  78. $this->server = $server;
  79. $this->server->registerAppContainer($appName, $this);
  80. // aliases
  81. /** @deprecated 26.0.0 inject $appName */
  82. $this->registerAlias('AppName', 'appName');
  83. /** @deprecated 26.0.0 inject $webRoot*/
  84. $this->registerAlias('WebRoot', 'webRoot');
  85. /** @deprecated 26.0.0 inject $userId */
  86. $this->registerAlias('UserId', 'userId');
  87. /**
  88. * Core services
  89. */
  90. $this->registerService(IOutput::class, function () {
  91. return new Output($this->getServer()->getWebRoot());
  92. });
  93. $this->registerService(Folder::class, function () {
  94. return $this->getServer()->getUserFolder();
  95. });
  96. $this->registerService(IAppData::class, function (ContainerInterface $c) {
  97. return $this->getServer()->getAppDataDir($c->get('AppName'));
  98. });
  99. $this->registerService(IL10N::class, function (ContainerInterface $c) {
  100. return $this->getServer()->getL10N($c->get('AppName'));
  101. });
  102. // Log wrappers
  103. $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
  104. return new ScopedPsrLogger(
  105. $c->get(PsrLoggerAdapter::class),
  106. $c->get('AppName')
  107. );
  108. });
  109. $this->registerService(IServerContainer::class, function () {
  110. return $this->getServer();
  111. });
  112. $this->registerAlias('ServerContainer', IServerContainer::class);
  113. $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
  114. return $c->get(Manager::class);
  115. });
  116. $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
  117. return $c;
  118. });
  119. $this->registerAlias(IAppContainer::class, ContainerInterface::class);
  120. // commonly used attributes
  121. $this->registerService('userId', function (ContainerInterface $c) {
  122. return $c->get(IUserSession::class)->getSession()->get('user_id');
  123. });
  124. $this->registerService('webRoot', function (ContainerInterface $c) {
  125. return $c->get(IServerContainer::class)->getWebRoot();
  126. });
  127. $this->registerService('OC_Defaults', function (ContainerInterface $c) {
  128. return $c->get(IServerContainer::class)->get('ThemingDefaults');
  129. });
  130. $this->registerService('Protocol', function (ContainerInterface $c) {
  131. /** @var \OC\Server $server */
  132. $server = $c->get(IServerContainer::class);
  133. $protocol = $server->getRequest()->getHttpProtocol();
  134. return new Http($_SERVER, $protocol);
  135. });
  136. $this->registerService('Dispatcher', function (ContainerInterface $c) {
  137. return new Dispatcher(
  138. $c->get('Protocol'),
  139. $c->get(MiddlewareDispatcher::class),
  140. $c->get(IControllerMethodReflector::class),
  141. $c->get(IRequest::class),
  142. $c->get(IConfig::class),
  143. $c->get(IDBConnection::class),
  144. $c->get(LoggerInterface::class),
  145. $c->get(EventLogger::class),
  146. $c,
  147. );
  148. });
  149. /**
  150. * App Framework default arguments
  151. */
  152. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  153. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  154. $this->registerParameter('corsMaxAge', 1728000);
  155. /**
  156. * Middleware
  157. */
  158. $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
  159. $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
  160. $server = $this->getServer();
  161. $dispatcher = new MiddlewareDispatcher();
  162. $dispatcher->registerMiddleware(
  163. $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
  164. );
  165. $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
  166. $dispatcher->registerMiddleware(
  167. $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
  168. );
  169. $dispatcher->registerMiddleware(
  170. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  171. $c->get(IRequest::class),
  172. $c->get(IControllerMethodReflector::class)
  173. )
  174. );
  175. $dispatcher->registerMiddleware(
  176. new CORSMiddleware(
  177. $c->get(IRequest::class),
  178. $c->get(IControllerMethodReflector::class),
  179. $c->get(IUserSession::class),
  180. $c->get(IThrottler::class),
  181. $c->get(LoggerInterface::class)
  182. )
  183. );
  184. $dispatcher->registerMiddleware(
  185. new OCSMiddleware(
  186. $c->get(IRequest::class)
  187. )
  188. );
  189. $securityMiddleware = new SecurityMiddleware(
  190. $c->get(IRequest::class),
  191. $c->get(IControllerMethodReflector::class),
  192. $c->get(INavigationManager::class),
  193. $c->get(IURLGenerator::class),
  194. $server->get(LoggerInterface::class),
  195. $c->get('AppName'),
  196. $server->getUserSession()->isLoggedIn(),
  197. $c->get(IGroupManager::class),
  198. $c->get(ISubAdmin::class),
  199. $server->getAppManager(),
  200. $server->getL10N('lib'),
  201. $c->get(AuthorizedGroupMapper::class),
  202. $server->get(IUserSession::class),
  203. $c->get(IRemoteAddress::class),
  204. );
  205. $dispatcher->registerMiddleware($securityMiddleware);
  206. $dispatcher->registerMiddleware(
  207. new OC\AppFramework\Middleware\Security\CSPMiddleware(
  208. $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
  209. $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
  210. )
  211. );
  212. $dispatcher->registerMiddleware(
  213. $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
  214. );
  215. $dispatcher->registerMiddleware(
  216. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  217. $c->get(IControllerMethodReflector::class),
  218. $c->get(ISession::class),
  219. $c->get(IUserSession::class),
  220. $c->get(ITimeFactory::class),
  221. $c->get(\OC\Authentication\Token\IProvider::class),
  222. $c->get(LoggerInterface::class),
  223. )
  224. );
  225. $dispatcher->registerMiddleware(
  226. new TwoFactorMiddleware(
  227. $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
  228. $c->get(IUserSession::class),
  229. $c->get(ISession::class),
  230. $c->get(IURLGenerator::class),
  231. $c->get(IControllerMethodReflector::class),
  232. $c->get(IRequest::class)
  233. )
  234. );
  235. $dispatcher->registerMiddleware(
  236. new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
  237. $c->get(IControllerMethodReflector::class),
  238. $c->get(IThrottler::class),
  239. $c->get(IRequest::class),
  240. $c->get(LoggerInterface::class)
  241. )
  242. );
  243. $dispatcher->registerMiddleware(
  244. new RateLimitingMiddleware(
  245. $c->get(IRequest::class),
  246. $c->get(IUserSession::class),
  247. $c->get(IControllerMethodReflector::class),
  248. $c->get(OC\Security\RateLimiting\Limiter::class),
  249. $c->get(ISession::class)
  250. )
  251. );
  252. $dispatcher->registerMiddleware(
  253. new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
  254. $c->get(IRequest::class),
  255. $c->get(ISession::class),
  256. $c->get(IConfig::class),
  257. $c->get(IThrottler::class)
  258. )
  259. );
  260. $dispatcher->registerMiddleware(
  261. $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
  262. );
  263. /** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
  264. $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
  265. $registrationContext = $coordinator->getRegistrationContext();
  266. if ($registrationContext !== null) {
  267. $appId = $this->getAppName();
  268. foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
  269. if ($middlewareRegistration->getAppId() === $appId
  270. || $middlewareRegistration->isGlobal()) {
  271. $dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
  272. }
  273. }
  274. }
  275. foreach ($this->middleWares as $middleWare) {
  276. $dispatcher->registerMiddleware($c->get($middleWare));
  277. }
  278. $dispatcher->registerMiddleware(
  279. new SessionMiddleware(
  280. $c->get(IControllerMethodReflector::class),
  281. $c->get(ISession::class)
  282. )
  283. );
  284. return $dispatcher;
  285. });
  286. $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
  287. return new OC\AppFramework\Services\AppConfig(
  288. $c->get(IConfig::class),
  289. $c->get(\OCP\IAppConfig::class),
  290. $c->get('AppName')
  291. );
  292. });
  293. $this->registerService(IInitialState::class, function (ContainerInterface $c) {
  294. return new OC\AppFramework\Services\InitialState(
  295. $c->get(IInitialStateService::class),
  296. $c->get('AppName')
  297. );
  298. });
  299. }
  300. /**
  301. * @return \OCP\IServerContainer
  302. */
  303. public function getServer() {
  304. return $this->server;
  305. }
  306. /**
  307. * @param string $middleWare
  308. * @return boolean|null
  309. */
  310. public function registerMiddleWare($middleWare) {
  311. if (in_array($middleWare, $this->middleWares, true) !== false) {
  312. return false;
  313. }
  314. $this->middleWares[] = $middleWare;
  315. }
  316. /**
  317. * used to return the appname of the set application
  318. * @return string the name of your application
  319. */
  320. public function getAppName() {
  321. return $this->query('AppName');
  322. }
  323. /**
  324. * @deprecated 12.0.0 use IUserSession->isLoggedIn()
  325. * @return boolean
  326. */
  327. public function isLoggedIn() {
  328. return \OC::$server->getUserSession()->isLoggedIn();
  329. }
  330. /**
  331. * @deprecated 12.0.0 use IGroupManager->isAdmin($userId)
  332. * @return boolean
  333. */
  334. public function isAdminUser() {
  335. $uid = $this->getUserId();
  336. return \OC_User::isAdminUser($uid);
  337. }
  338. private function getUserId() {
  339. return $this->getServer()->getSession()->get('user_id');
  340. }
  341. /**
  342. * Register a capability
  343. *
  344. * @param string $serviceName e.g. 'OCA\Files\Capabilities'
  345. */
  346. public function registerCapability($serviceName) {
  347. $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
  348. return $this->query($serviceName);
  349. });
  350. }
  351. public function has($id): bool {
  352. if (parent::has($id)) {
  353. return true;
  354. }
  355. if ($this->server->has($id, true)) {
  356. return true;
  357. }
  358. return false;
  359. }
  360. public function query(string $name, bool $autoload = true) {
  361. if ($name === 'AppName' || $name === 'appName') {
  362. return $this->appName;
  363. }
  364. $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
  365. if ($isServerClass && !$this->has($name)) {
  366. return $this->getServer()->query($name, $autoload);
  367. }
  368. try {
  369. return $this->queryNoFallback($name);
  370. } catch (QueryException $firstException) {
  371. try {
  372. return $this->getServer()->query($name, $autoload);
  373. } catch (QueryException $secondException) {
  374. if ($firstException->getCode() === 1) {
  375. throw $secondException;
  376. }
  377. throw $firstException;
  378. }
  379. }
  380. }
  381. /**
  382. * @param string $name
  383. * @return mixed
  384. * @throws QueryException if the query could not be resolved
  385. */
  386. public function queryNoFallback($name) {
  387. $name = $this->sanitizeName($name);
  388. if ($this->offsetExists($name)) {
  389. return parent::query($name);
  390. } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
  391. return parent::query($name);
  392. } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
  393. return parent::query($name);
  394. } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
  395. return parent::query($name);
  396. }
  397. throw new QueryException('Could not resolve ' . $name . '!' .
  398. ' Class can not be instantiated', 1);
  399. }
  400. }