1
0

DIContainer.php 13 KB

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