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\IInitialStateService;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  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 Psr\Container\ContainerInterface;
  49. use Psr\Log\LoggerInterface;
  50. /**
  51. * @deprecated 20.0.0
  52. */
  53. class DIContainer extends SimpleContainer implements IAppContainer {
  54. private string $appName;
  55. /**
  56. * @var array
  57. */
  58. private $middleWares = [];
  59. /** @var ServerContainer */
  60. private $server;
  61. /**
  62. * Put your class dependencies in here
  63. * @param string $appName the name of the app
  64. * @param array $urlParams
  65. * @param ServerContainer|null $server
  66. */
  67. public function __construct(string $appName, array $urlParams = [], ?ServerContainer $server = null) {
  68. parent::__construct();
  69. $this->appName = $appName;
  70. $this['appName'] = $appName;
  71. $this['urlParams'] = $urlParams;
  72. $this->registerAlias('Request', IRequest::class);
  73. /** @var \OC\ServerContainer $server */
  74. if ($server === null) {
  75. $server = \OC::$server;
  76. }
  77. $this->server = $server;
  78. $this->server->registerAppContainer($appName, $this);
  79. // aliases
  80. /** @deprecated inject $appName */
  81. $this->registerAlias('AppName', 'appName');
  82. /** @deprecated inject $webRoot*/
  83. $this->registerAlias('WebRoot', 'webRoot');
  84. /** @deprecated inject $userId */
  85. $this->registerAlias('UserId', 'userId');
  86. /**
  87. * Core services
  88. */
  89. $this->registerService(IOutput::class, function () {
  90. return new Output($this->getServer()->getWebRoot());
  91. });
  92. $this->registerService(Folder::class, function () {
  93. return $this->getServer()->getUserFolder();
  94. });
  95. $this->registerService(IAppData::class, function (ContainerInterface $c) {
  96. return $this->getServer()->getAppDataDir($c->get('AppName'));
  97. });
  98. $this->registerService(IL10N::class, function (ContainerInterface $c) {
  99. return $this->getServer()->getL10N($c->get('AppName'));
  100. });
  101. // Log wrappers
  102. $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
  103. return new ScopedPsrLogger(
  104. $c->get(PsrLoggerAdapter::class),
  105. $c->get('AppName')
  106. );
  107. });
  108. $this->registerService(ILogger::class, function (ContainerInterface $c) {
  109. return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
  110. });
  111. $this->registerService(IServerContainer::class, function () {
  112. return $this->getServer();
  113. });
  114. $this->registerAlias('ServerContainer', IServerContainer::class);
  115. $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
  116. return $c->get(Manager::class);
  117. });
  118. $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
  119. return $c;
  120. });
  121. $this->registerAlias(IAppContainer::class, ContainerInterface::class);
  122. // commonly used attributes
  123. $this->registerService('userId', function (ContainerInterface $c) {
  124. return $c->get(IUserSession::class)->getSession()->get('user_id');
  125. });
  126. $this->registerService('webRoot', function (ContainerInterface $c) {
  127. return $c->get(IServerContainer::class)->getWebRoot();
  128. });
  129. $this->registerService('OC_Defaults', function (ContainerInterface $c) {
  130. return $c->get(IServerContainer::class)->get('ThemingDefaults');
  131. });
  132. $this->registerService('Protocol', function (ContainerInterface $c) {
  133. /** @var \OC\Server $server */
  134. $server = $c->get(IServerContainer::class);
  135. $protocol = $server->getRequest()->getHttpProtocol();
  136. return new Http($_SERVER, $protocol);
  137. });
  138. $this->registerService('Dispatcher', function (ContainerInterface $c) {
  139. return new Dispatcher(
  140. $c->get('Protocol'),
  141. $c->get(MiddlewareDispatcher::class),
  142. $c->get(IControllerMethodReflector::class),
  143. $c->get(IRequest::class),
  144. $c->get(IConfig::class),
  145. $c->get(IDBConnection::class),
  146. $c->get(LoggerInterface::class),
  147. $c->get(EventLogger::class),
  148. $c,
  149. );
  150. });
  151. /**
  152. * App Framework default arguments
  153. */
  154. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  155. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  156. $this->registerParameter('corsMaxAge', 1728000);
  157. /**
  158. * Middleware
  159. */
  160. $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
  161. $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
  162. $server = $this->getServer();
  163. $dispatcher = new MiddlewareDispatcher();
  164. $dispatcher->registerMiddleware(
  165. $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
  166. );
  167. $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
  168. $dispatcher->registerMiddleware(
  169. $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
  170. );
  171. $dispatcher->registerMiddleware(
  172. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  173. $c->get(IRequest::class),
  174. $c->get(IControllerMethodReflector::class)
  175. )
  176. );
  177. $dispatcher->registerMiddleware(
  178. new CORSMiddleware(
  179. $c->get(IRequest::class),
  180. $c->get(IControllerMethodReflector::class),
  181. $c->get(IUserSession::class),
  182. $c->get(IThrottler::class)
  183. )
  184. );
  185. $dispatcher->registerMiddleware(
  186. new OCSMiddleware(
  187. $c->get(IRequest::class)
  188. )
  189. );
  190. $securityMiddleware = new SecurityMiddleware(
  191. $c->get(IRequest::class),
  192. $c->get(IControllerMethodReflector::class),
  193. $c->get(INavigationManager::class),
  194. $c->get(IURLGenerator::class),
  195. $server->get(LoggerInterface::class),
  196. $c->get('AppName'),
  197. $server->getUserSession()->isLoggedIn(),
  198. $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
  199. $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
  200. $server->getAppManager(),
  201. $server->getL10N('lib'),
  202. $c->get(AuthorizedGroupMapper::class),
  203. $server->get(IUserSession::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. $server->query(OC\Security\CSRF\CsrfTokenManager::class)
  211. )
  212. );
  213. $dispatcher->registerMiddleware(
  214. $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
  215. );
  216. $dispatcher->registerMiddleware(
  217. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  218. $c->get(IControllerMethodReflector::class),
  219. $c->get(ISession::class),
  220. $c->get(IUserSession::class),
  221. $c->get(ITimeFactory::class),
  222. $c->get(\OC\Authentication\Token\IProvider::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(\OCP\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 use IUserSession->isLoggedIn()
  325. * @return boolean
  326. */
  327. public function isLoggedIn() {
  328. return \OC::$server->getUserSession()->isLoggedIn();
  329. }
  330. /**
  331. * @deprecated 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. }