DIContainer.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin McCorkell <robin@mccorkell.me.uk>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Thomas Tanghus <thomas@tanghus.net>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\AppFramework\DependencyInjection;
  35. use OC;
  36. use OC\AppFramework\Http;
  37. use OC\AppFramework\Http\Dispatcher;
  38. use OC\AppFramework\Http\Output;
  39. use OC\AppFramework\Middleware\MiddlewareDispatcher;
  40. use OC\AppFramework\Middleware\OCSMiddleware;
  41. use OC\AppFramework\Middleware\Security\CORSMiddleware;
  42. use OC\AppFramework\Middleware\Security\RateLimitingMiddleware;
  43. use OC\AppFramework\Middleware\Security\SecurityMiddleware;
  44. use OC\AppFramework\Middleware\SessionMiddleware;
  45. use OC\AppFramework\ScopedPsrLogger;
  46. use OC\AppFramework\Utility\SimpleContainer;
  47. use OC\Core\Middleware\TwoFactorMiddleware;
  48. use OC\Diagnostics\EventLogger;
  49. use OC\Log\PsrLoggerAdapter;
  50. use OC\ServerContainer;
  51. use OC\Settings\AuthorizedGroupMapper;
  52. use OCA\WorkflowEngine\Manager;
  53. use OCP\AppFramework\Http\IOutput;
  54. use OCP\AppFramework\IAppContainer;
  55. use OCP\AppFramework\QueryException;
  56. use OCP\AppFramework\Services\IAppConfig;
  57. use OCP\AppFramework\Services\IInitialState;
  58. use OCP\AppFramework\Utility\IControllerMethodReflector;
  59. use OCP\AppFramework\Utility\ITimeFactory;
  60. use OCP\Files\Folder;
  61. use OCP\Files\IAppData;
  62. use OCP\Group\ISubAdmin;
  63. use OCP\IConfig;
  64. use OCP\IDBConnection;
  65. use OCP\IInitialStateService;
  66. use OCP\IL10N;
  67. use OCP\ILogger;
  68. use OCP\INavigationManager;
  69. use OCP\IRequest;
  70. use OCP\IServerContainer;
  71. use OCP\ISession;
  72. use OCP\IURLGenerator;
  73. use OCP\IUserSession;
  74. use OCP\Security\Bruteforce\IThrottler;
  75. use Psr\Container\ContainerInterface;
  76. use Psr\Log\LoggerInterface;
  77. /**
  78. * @deprecated 20.0.0
  79. */
  80. class DIContainer extends SimpleContainer implements IAppContainer {
  81. private string $appName;
  82. /**
  83. * @var array
  84. */
  85. private $middleWares = [];
  86. /** @var ServerContainer */
  87. private $server;
  88. /**
  89. * Put your class dependencies in here
  90. * @param string $appName the name of the app
  91. * @param array $urlParams
  92. * @param ServerContainer|null $server
  93. */
  94. public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
  95. parent::__construct();
  96. $this->appName = $appName;
  97. $this['appName'] = $appName;
  98. $this['urlParams'] = $urlParams;
  99. $this->registerAlias('Request', IRequest::class);
  100. /** @var \OC\ServerContainer $server */
  101. if ($server === null) {
  102. $server = \OC::$server;
  103. }
  104. $this->server = $server;
  105. $this->server->registerAppContainer($appName, $this);
  106. // aliases
  107. /** @deprecated inject $appName */
  108. $this->registerAlias('AppName', 'appName');
  109. /** @deprecated inject $webRoot*/
  110. $this->registerAlias('WebRoot', 'webRoot');
  111. /** @deprecated inject $userId */
  112. $this->registerAlias('UserId', 'userId');
  113. /**
  114. * Core services
  115. */
  116. $this->registerService(IOutput::class, function () {
  117. return new Output($this->getServer()->getWebRoot());
  118. });
  119. $this->registerService(Folder::class, function () {
  120. return $this->getServer()->getUserFolder();
  121. });
  122. $this->registerService(IAppData::class, function (ContainerInterface $c) {
  123. return $this->getServer()->getAppDataDir($c->get('AppName'));
  124. });
  125. $this->registerService(IL10N::class, function (ContainerInterface $c) {
  126. return $this->getServer()->getL10N($c->get('AppName'));
  127. });
  128. // Log wrappers
  129. $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
  130. return new ScopedPsrLogger(
  131. $c->get(PsrLoggerAdapter::class),
  132. $c->get('AppName')
  133. );
  134. });
  135. $this->registerService(ILogger::class, function (ContainerInterface $c) {
  136. return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
  137. });
  138. $this->registerService(IServerContainer::class, function () {
  139. return $this->getServer();
  140. });
  141. $this->registerAlias('ServerContainer', IServerContainer::class);
  142. $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
  143. return $c->get(Manager::class);
  144. });
  145. $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
  146. return $c;
  147. });
  148. $this->registerAlias(IAppContainer::class, ContainerInterface::class);
  149. // commonly used attributes
  150. $this->registerService('userId', function (ContainerInterface $c) {
  151. return $c->get(IUserSession::class)->getSession()->get('user_id');
  152. });
  153. $this->registerService('webRoot', function (ContainerInterface $c) {
  154. return $c->get(IServerContainer::class)->getWebRoot();
  155. });
  156. $this->registerService('OC_Defaults', function (ContainerInterface $c) {
  157. return $c->get(IServerContainer::class)->get('ThemingDefaults');
  158. });
  159. $this->registerService('Protocol', function (ContainerInterface $c) {
  160. /** @var \OC\Server $server */
  161. $server = $c->get(IServerContainer::class);
  162. $protocol = $server->getRequest()->getHttpProtocol();
  163. return new Http($_SERVER, $protocol);
  164. });
  165. $this->registerService('Dispatcher', function (ContainerInterface $c) {
  166. return new Dispatcher(
  167. $c->get('Protocol'),
  168. $c->get(MiddlewareDispatcher::class),
  169. $c->get(IControllerMethodReflector::class),
  170. $c->get(IRequest::class),
  171. $c->get(IConfig::class),
  172. $c->get(IDBConnection::class),
  173. $c->get(LoggerInterface::class),
  174. $c->get(EventLogger::class),
  175. $c,
  176. );
  177. });
  178. /**
  179. * App Framework default arguments
  180. */
  181. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  182. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  183. $this->registerParameter('corsMaxAge', 1728000);
  184. /**
  185. * Middleware
  186. */
  187. $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
  188. $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
  189. $server = $this->getServer();
  190. $dispatcher = new MiddlewareDispatcher();
  191. $dispatcher->registerMiddleware(
  192. $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
  193. );
  194. $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
  195. $dispatcher->registerMiddleware(
  196. $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
  197. );
  198. $dispatcher->registerMiddleware(
  199. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  200. $c->get(IRequest::class),
  201. $c->get(IControllerMethodReflector::class)
  202. )
  203. );
  204. $dispatcher->registerMiddleware(
  205. new CORSMiddleware(
  206. $c->get(IRequest::class),
  207. $c->get(IControllerMethodReflector::class),
  208. $c->get(IUserSession::class),
  209. $c->get(IThrottler::class)
  210. )
  211. );
  212. $dispatcher->registerMiddleware(
  213. new OCSMiddleware(
  214. $c->get(IRequest::class)
  215. )
  216. );
  217. $securityMiddleware = new SecurityMiddleware(
  218. $c->get(IRequest::class),
  219. $c->get(IControllerMethodReflector::class),
  220. $c->get(INavigationManager::class),
  221. $c->get(IURLGenerator::class),
  222. $server->get(LoggerInterface::class),
  223. $c->get('AppName'),
  224. $server->getUserSession()->isLoggedIn(),
  225. $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
  226. $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
  227. $server->getAppManager(),
  228. $server->getL10N('lib'),
  229. $c->get(AuthorizedGroupMapper::class),
  230. $server->get(IUserSession::class)
  231. );
  232. $dispatcher->registerMiddleware($securityMiddleware);
  233. $dispatcher->registerMiddleware(
  234. new OC\AppFramework\Middleware\Security\CSPMiddleware(
  235. $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
  236. $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
  237. $server->query(OC\Security\CSRF\CsrfTokenManager::class)
  238. )
  239. );
  240. $dispatcher->registerMiddleware(
  241. $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
  242. );
  243. $dispatcher->registerMiddleware(
  244. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  245. $c->get(IControllerMethodReflector::class),
  246. $c->get(ISession::class),
  247. $c->get(IUserSession::class),
  248. $c->get(ITimeFactory::class)
  249. )
  250. );
  251. $dispatcher->registerMiddleware(
  252. new TwoFactorMiddleware(
  253. $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
  254. $c->get(IUserSession::class),
  255. $c->get(ISession::class),
  256. $c->get(IURLGenerator::class),
  257. $c->get(IControllerMethodReflector::class),
  258. $c->get(IRequest::class)
  259. )
  260. );
  261. $dispatcher->registerMiddleware(
  262. new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
  263. $c->get(IControllerMethodReflector::class),
  264. $c->get(IThrottler::class),
  265. $c->get(IRequest::class),
  266. $c->get(LoggerInterface::class)
  267. )
  268. );
  269. $dispatcher->registerMiddleware(
  270. new RateLimitingMiddleware(
  271. $c->get(IRequest::class),
  272. $c->get(IUserSession::class),
  273. $c->get(IControllerMethodReflector::class),
  274. $c->get(OC\Security\RateLimiting\Limiter::class),
  275. $c->get(ISession::class)
  276. )
  277. );
  278. $dispatcher->registerMiddleware(
  279. new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
  280. $c->get(IRequest::class),
  281. $c->get(ISession::class),
  282. $c->get(\OCP\IConfig::class),
  283. $c->get(IThrottler::class)
  284. )
  285. );
  286. $dispatcher->registerMiddleware(
  287. $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
  288. );
  289. /** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
  290. $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
  291. $registrationContext = $coordinator->getRegistrationContext();
  292. if ($registrationContext !== null) {
  293. $appId = $this->getAppName();
  294. foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
  295. if ($middlewareRegistration->getAppId() === $appId
  296. || $middlewareRegistration->isGlobal()) {
  297. $dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
  298. }
  299. }
  300. }
  301. foreach ($this->middleWares as $middleWare) {
  302. $dispatcher->registerMiddleware($c->get($middleWare));
  303. }
  304. $dispatcher->registerMiddleware(
  305. new SessionMiddleware(
  306. $c->get(IControllerMethodReflector::class),
  307. $c->get(ISession::class)
  308. )
  309. );
  310. return $dispatcher;
  311. });
  312. $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
  313. return new OC\AppFramework\Services\AppConfig(
  314. $c->get(IConfig::class),
  315. $c->get(\OCP\IAppConfig::class),
  316. $c->get('AppName')
  317. );
  318. });
  319. $this->registerService(IInitialState::class, function (ContainerInterface $c) {
  320. return new OC\AppFramework\Services\InitialState(
  321. $c->get(IInitialStateService::class),
  322. $c->get('AppName')
  323. );
  324. });
  325. }
  326. /**
  327. * @return \OCP\IServerContainer
  328. */
  329. public function getServer() {
  330. return $this->server;
  331. }
  332. /**
  333. * @param string $middleWare
  334. * @return boolean|null
  335. */
  336. public function registerMiddleWare($middleWare) {
  337. if (in_array($middleWare, $this->middleWares, true) !== false) {
  338. return false;
  339. }
  340. $this->middleWares[] = $middleWare;
  341. }
  342. /**
  343. * used to return the appname of the set application
  344. * @return string the name of your application
  345. */
  346. public function getAppName() {
  347. return $this->query('AppName');
  348. }
  349. /**
  350. * @deprecated use IUserSession->isLoggedIn()
  351. * @return boolean
  352. */
  353. public function isLoggedIn() {
  354. return \OC::$server->getUserSession()->isLoggedIn();
  355. }
  356. /**
  357. * @deprecated use IGroupManager->isAdmin($userId)
  358. * @return boolean
  359. */
  360. public function isAdminUser() {
  361. $uid = $this->getUserId();
  362. return \OC_User::isAdminUser($uid);
  363. }
  364. private function getUserId() {
  365. return $this->getServer()->getSession()->get('user_id');
  366. }
  367. /**
  368. * Register a capability
  369. *
  370. * @param string $serviceName e.g. 'OCA\Files\Capabilities'
  371. */
  372. public function registerCapability($serviceName) {
  373. $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
  374. return $this->query($serviceName);
  375. });
  376. }
  377. public function has($id): bool {
  378. if (parent::has($id)) {
  379. return true;
  380. }
  381. if ($this->server->has($id, true)) {
  382. return true;
  383. }
  384. return false;
  385. }
  386. public function query(string $name, bool $autoload = true) {
  387. if ($name === 'AppName' || $name === 'appName') {
  388. return $this->appName;
  389. }
  390. $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
  391. if ($isServerClass && !$this->has($name)) {
  392. return $this->getServer()->query($name, $autoload);
  393. }
  394. try {
  395. return $this->queryNoFallback($name);
  396. } catch (QueryException $firstException) {
  397. try {
  398. return $this->getServer()->query($name, $autoload);
  399. } catch (QueryException $secondException) {
  400. if ($firstException->getCode() === 1) {
  401. throw $secondException;
  402. }
  403. throw $firstException;
  404. }
  405. }
  406. }
  407. /**
  408. * @param string $name
  409. * @return mixed
  410. * @throws QueryException if the query could not be resolved
  411. */
  412. public function queryNoFallback($name) {
  413. $name = $this->sanitizeName($name);
  414. if ($this->offsetExists($name)) {
  415. return parent::query($name);
  416. } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
  417. return parent::query($name);
  418. } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
  419. return parent::query($name);
  420. } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
  421. return parent::query($name);
  422. }
  423. throw new QueryException('Could not resolve ' . $name . '!' .
  424. ' Class can not be instantiated', 1);
  425. }
  426. }