DIContainer.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 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 inject $appName */
  82. $this->registerAlias('AppName', 'appName');
  83. /** @deprecated inject $webRoot*/
  84. $this->registerAlias('WebRoot', 'webRoot');
  85. /** @deprecated 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(ILogger::class, function (ContainerInterface $c) {
  110. return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
  111. });
  112. $this->registerService(IServerContainer::class, function () {
  113. return $this->getServer();
  114. });
  115. $this->registerAlias('ServerContainer', IServerContainer::class);
  116. $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
  117. return $c->get(Manager::class);
  118. });
  119. $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
  120. return $c;
  121. });
  122. $this->registerAlias(IAppContainer::class, ContainerInterface::class);
  123. // commonly used attributes
  124. $this->registerService('userId', function (ContainerInterface $c) {
  125. return $c->get(IUserSession::class)->getSession()->get('user_id');
  126. });
  127. $this->registerService('webRoot', function (ContainerInterface $c) {
  128. return $c->get(IServerContainer::class)->getWebRoot();
  129. });
  130. $this->registerService('OC_Defaults', function (ContainerInterface $c) {
  131. return $c->get(IServerContainer::class)->get('ThemingDefaults');
  132. });
  133. $this->registerService('Protocol', function (ContainerInterface $c) {
  134. /** @var \OC\Server $server */
  135. $server = $c->get(IServerContainer::class);
  136. $protocol = $server->getRequest()->getHttpProtocol();
  137. return new Http($_SERVER, $protocol);
  138. });
  139. $this->registerService('Dispatcher', function (ContainerInterface $c) {
  140. return new Dispatcher(
  141. $c->get('Protocol'),
  142. $c->get(MiddlewareDispatcher::class),
  143. $c->get(IControllerMethodReflector::class),
  144. $c->get(IRequest::class),
  145. $c->get(IConfig::class),
  146. $c->get(IDBConnection::class),
  147. $c->get(LoggerInterface::class),
  148. $c->get(EventLogger::class),
  149. $c,
  150. );
  151. });
  152. /**
  153. * App Framework default arguments
  154. */
  155. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  156. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  157. $this->registerParameter('corsMaxAge', 1728000);
  158. /**
  159. * Middleware
  160. */
  161. $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
  162. $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
  163. $server = $this->getServer();
  164. $dispatcher = new MiddlewareDispatcher();
  165. $dispatcher->registerMiddleware(
  166. $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
  167. );
  168. $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
  169. $dispatcher->registerMiddleware(
  170. $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
  171. );
  172. $dispatcher->registerMiddleware(
  173. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  174. $c->get(IRequest::class),
  175. $c->get(IControllerMethodReflector::class)
  176. )
  177. );
  178. $dispatcher->registerMiddleware(
  179. new CORSMiddleware(
  180. $c->get(IRequest::class),
  181. $c->get(IControllerMethodReflector::class),
  182. $c->get(IUserSession::class),
  183. $c->get(IThrottler::class),
  184. $c->get(LoggerInterface::class)
  185. )
  186. );
  187. $dispatcher->registerMiddleware(
  188. new OCSMiddleware(
  189. $c->get(IRequest::class)
  190. )
  191. );
  192. $securityMiddleware = new SecurityMiddleware(
  193. $c->get(IRequest::class),
  194. $c->get(IControllerMethodReflector::class),
  195. $c->get(INavigationManager::class),
  196. $c->get(IURLGenerator::class),
  197. $server->get(LoggerInterface::class),
  198. $c->get('AppName'),
  199. $server->getUserSession()->isLoggedIn(),
  200. $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
  201. $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
  202. $server->getAppManager(),
  203. $server->getL10N('lib'),
  204. $c->get(AuthorizedGroupMapper::class),
  205. $server->get(IUserSession::class),
  206. $c->get(IRemoteAddress::class),
  207. );
  208. $dispatcher->registerMiddleware($securityMiddleware);
  209. $dispatcher->registerMiddleware(
  210. new OC\AppFramework\Middleware\Security\CSPMiddleware(
  211. $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
  212. $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
  213. $server->query(OC\Security\CSRF\CsrfTokenManager::class)
  214. )
  215. );
  216. $dispatcher->registerMiddleware(
  217. $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
  218. );
  219. $dispatcher->registerMiddleware(
  220. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  221. $c->get(IControllerMethodReflector::class),
  222. $c->get(ISession::class),
  223. $c->get(IUserSession::class),
  224. $c->get(ITimeFactory::class),
  225. $c->get(\OC\Authentication\Token\IProvider::class),
  226. $c->get(LoggerInterface::class),
  227. )
  228. );
  229. $dispatcher->registerMiddleware(
  230. new TwoFactorMiddleware(
  231. $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
  232. $c->get(IUserSession::class),
  233. $c->get(ISession::class),
  234. $c->get(IURLGenerator::class),
  235. $c->get(IControllerMethodReflector::class),
  236. $c->get(IRequest::class)
  237. )
  238. );
  239. $dispatcher->registerMiddleware(
  240. new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
  241. $c->get(IControllerMethodReflector::class),
  242. $c->get(IThrottler::class),
  243. $c->get(IRequest::class),
  244. $c->get(LoggerInterface::class)
  245. )
  246. );
  247. $dispatcher->registerMiddleware(
  248. new RateLimitingMiddleware(
  249. $c->get(IRequest::class),
  250. $c->get(IUserSession::class),
  251. $c->get(IControllerMethodReflector::class),
  252. $c->get(OC\Security\RateLimiting\Limiter::class),
  253. $c->get(ISession::class)
  254. )
  255. );
  256. $dispatcher->registerMiddleware(
  257. new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
  258. $c->get(IRequest::class),
  259. $c->get(ISession::class),
  260. $c->get(\OCP\IConfig::class),
  261. $c->get(IThrottler::class)
  262. )
  263. );
  264. $dispatcher->registerMiddleware(
  265. $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
  266. );
  267. /** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
  268. $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
  269. $registrationContext = $coordinator->getRegistrationContext();
  270. if ($registrationContext !== null) {
  271. $appId = $this->getAppName();
  272. foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
  273. if ($middlewareRegistration->getAppId() === $appId
  274. || $middlewareRegistration->isGlobal()) {
  275. $dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
  276. }
  277. }
  278. }
  279. foreach ($this->middleWares as $middleWare) {
  280. $dispatcher->registerMiddleware($c->get($middleWare));
  281. }
  282. $dispatcher->registerMiddleware(
  283. new SessionMiddleware(
  284. $c->get(IControllerMethodReflector::class),
  285. $c->get(ISession::class)
  286. )
  287. );
  288. return $dispatcher;
  289. });
  290. $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
  291. return new OC\AppFramework\Services\AppConfig(
  292. $c->get(IConfig::class),
  293. $c->get(\OCP\IAppConfig::class),
  294. $c->get('AppName')
  295. );
  296. });
  297. $this->registerService(IInitialState::class, function (ContainerInterface $c) {
  298. return new OC\AppFramework\Services\InitialState(
  299. $c->get(IInitialStateService::class),
  300. $c->get('AppName')
  301. );
  302. });
  303. }
  304. /**
  305. * @return \OCP\IServerContainer
  306. */
  307. public function getServer() {
  308. return $this->server;
  309. }
  310. /**
  311. * @param string $middleWare
  312. * @return boolean|null
  313. */
  314. public function registerMiddleWare($middleWare) {
  315. if (in_array($middleWare, $this->middleWares, true) !== false) {
  316. return false;
  317. }
  318. $this->middleWares[] = $middleWare;
  319. }
  320. /**
  321. * used to return the appname of the set application
  322. * @return string the name of your application
  323. */
  324. public function getAppName() {
  325. return $this->query('AppName');
  326. }
  327. /**
  328. * @deprecated use IUserSession->isLoggedIn()
  329. * @return boolean
  330. */
  331. public function isLoggedIn() {
  332. return \OC::$server->getUserSession()->isLoggedIn();
  333. }
  334. /**
  335. * @deprecated use IGroupManager->isAdmin($userId)
  336. * @return boolean
  337. */
  338. public function isAdminUser() {
  339. $uid = $this->getUserId();
  340. return \OC_User::isAdminUser($uid);
  341. }
  342. private function getUserId() {
  343. return $this->getServer()->getSession()->get('user_id');
  344. }
  345. /**
  346. * Register a capability
  347. *
  348. * @param string $serviceName e.g. 'OCA\Files\Capabilities'
  349. */
  350. public function registerCapability($serviceName) {
  351. $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
  352. return $this->query($serviceName);
  353. });
  354. }
  355. public function has($id): bool {
  356. if (parent::has($id)) {
  357. return true;
  358. }
  359. if ($this->server->has($id, true)) {
  360. return true;
  361. }
  362. return false;
  363. }
  364. public function query(string $name, bool $autoload = true) {
  365. if ($name === 'AppName' || $name === 'appName') {
  366. return $this->appName;
  367. }
  368. $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
  369. if ($isServerClass && !$this->has($name)) {
  370. return $this->getServer()->query($name, $autoload);
  371. }
  372. try {
  373. return $this->queryNoFallback($name);
  374. } catch (QueryException $firstException) {
  375. try {
  376. return $this->getServer()->query($name, $autoload);
  377. } catch (QueryException $secondException) {
  378. if ($firstException->getCode() === 1) {
  379. throw $secondException;
  380. }
  381. throw $firstException;
  382. }
  383. }
  384. }
  385. /**
  386. * @param string $name
  387. * @return mixed
  388. * @throws QueryException if the query could not be resolved
  389. */
  390. public function queryNoFallback($name) {
  391. $name = $this->sanitizeName($name);
  392. if ($this->offsetExists($name)) {
  393. return parent::query($name);
  394. } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
  395. return parent::query($name);
  396. } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
  397. return parent::query($name);
  398. } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
  399. return parent::query($name);
  400. }
  401. throw new QueryException('Could not resolve ' . $name . '!' .
  402. ' Class can not be instantiated', 1);
  403. }
  404. }