DIContainer.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 Psr\Container\ContainerInterface;
  75. use Psr\Log\LoggerInterface;
  76. /**
  77. * @deprecated 20.0.0
  78. */
  79. class DIContainer extends SimpleContainer implements IAppContainer {
  80. private string $appName;
  81. /**
  82. * @var array
  83. */
  84. private $middleWares = [];
  85. /** @var ServerContainer */
  86. private $server;
  87. /**
  88. * Put your class dependencies in here
  89. * @param string $appName the name of the app
  90. * @param array $urlParams
  91. * @param ServerContainer|null $server
  92. */
  93. public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
  94. parent::__construct();
  95. $this->appName = $appName;
  96. $this['appName'] = $appName;
  97. $this['urlParams'] = $urlParams;
  98. $this->registerAlias('Request', IRequest::class);
  99. /** @var \OC\ServerContainer $server */
  100. if ($server === null) {
  101. $server = \OC::$server;
  102. }
  103. $this->server = $server;
  104. $this->server->registerAppContainer($appName, $this);
  105. // aliases
  106. /** @deprecated inject $appName */
  107. $this->registerAlias('AppName', 'appName');
  108. /** @deprecated inject $webRoot*/
  109. $this->registerAlias('WebRoot', 'webRoot');
  110. /** @deprecated inject $userId */
  111. $this->registerAlias('UserId', 'userId');
  112. /**
  113. * Core services
  114. */
  115. $this->registerService(IOutput::class, function () {
  116. return new Output($this->getServer()->getWebRoot());
  117. });
  118. $this->registerService(Folder::class, function () {
  119. return $this->getServer()->getUserFolder();
  120. });
  121. $this->registerService(IAppData::class, function (ContainerInterface $c) {
  122. return $this->getServer()->getAppDataDir($c->get('AppName'));
  123. });
  124. $this->registerService(IL10N::class, function (ContainerInterface $c) {
  125. return $this->getServer()->getL10N($c->get('AppName'));
  126. });
  127. // Log wrappers
  128. $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
  129. return new ScopedPsrLogger(
  130. $c->get(PsrLoggerAdapter::class),
  131. $c->get('AppName')
  132. );
  133. });
  134. $this->registerService(ILogger::class, function (ContainerInterface $c) {
  135. return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
  136. });
  137. $this->registerService(IServerContainer::class, function () {
  138. return $this->getServer();
  139. });
  140. $this->registerAlias('ServerContainer', IServerContainer::class);
  141. $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
  142. return $c->get(Manager::class);
  143. });
  144. $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
  145. return $c;
  146. });
  147. $this->registerAlias(IAppContainer::class, ContainerInterface::class);
  148. // commonly used attributes
  149. $this->registerService('userId', function (ContainerInterface $c) {
  150. return $c->get(IUserSession::class)->getSession()->get('user_id');
  151. });
  152. $this->registerService('webRoot', function (ContainerInterface $c) {
  153. return $c->get(IServerContainer::class)->getWebRoot();
  154. });
  155. $this->registerService('OC_Defaults', function (ContainerInterface $c) {
  156. return $c->get(IServerContainer::class)->getThemingDefaults();
  157. });
  158. $this->registerService('Protocol', function (ContainerInterface $c) {
  159. /** @var \OC\Server $server */
  160. $server = $c->get(IServerContainer::class);
  161. $protocol = $server->getRequest()->getHttpProtocol();
  162. return new Http($_SERVER, $protocol);
  163. });
  164. $this->registerService('Dispatcher', function (ContainerInterface $c) {
  165. return new Dispatcher(
  166. $c->get('Protocol'),
  167. $c->get(MiddlewareDispatcher::class),
  168. $c->get(IControllerMethodReflector::class),
  169. $c->get(IRequest::class),
  170. $c->get(IConfig::class),
  171. $c->get(IDBConnection::class),
  172. $c->get(LoggerInterface::class),
  173. $c->get(EventLogger::class),
  174. $c,
  175. );
  176. });
  177. /**
  178. * App Framework default arguments
  179. */
  180. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  181. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  182. $this->registerParameter('corsMaxAge', 1728000);
  183. /**
  184. * Middleware
  185. */
  186. $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
  187. $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
  188. $server = $this->getServer();
  189. $dispatcher = new MiddlewareDispatcher();
  190. $dispatcher->registerMiddleware(
  191. $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
  192. );
  193. $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
  194. $dispatcher->registerMiddleware(
  195. $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
  196. );
  197. $dispatcher->registerMiddleware(
  198. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  199. $c->get(IRequest::class),
  200. $c->get(IControllerMethodReflector::class)
  201. )
  202. );
  203. $dispatcher->registerMiddleware(
  204. new CORSMiddleware(
  205. $c->get(IRequest::class),
  206. $c->get(IControllerMethodReflector::class),
  207. $c->get(IUserSession::class),
  208. $c->get(OC\Security\Bruteforce\Throttler::class)
  209. )
  210. );
  211. $dispatcher->registerMiddleware(
  212. new OCSMiddleware(
  213. $c->get(IRequest::class)
  214. )
  215. );
  216. $securityMiddleware = new SecurityMiddleware(
  217. $c->get(IRequest::class),
  218. $c->get(IControllerMethodReflector::class),
  219. $c->get(INavigationManager::class),
  220. $c->get(IURLGenerator::class),
  221. $server->get(LoggerInterface::class),
  222. $c->get('AppName'),
  223. $server->getUserSession()->isLoggedIn(),
  224. $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
  225. $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
  226. $server->getAppManager(),
  227. $server->getL10N('lib'),
  228. $c->get(AuthorizedGroupMapper::class),
  229. $server->get(IUserSession::class)
  230. );
  231. $dispatcher->registerMiddleware($securityMiddleware);
  232. $dispatcher->registerMiddleware(
  233. new OC\AppFramework\Middleware\Security\CSPMiddleware(
  234. $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
  235. $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
  236. $server->query(OC\Security\CSRF\CsrfTokenManager::class)
  237. )
  238. );
  239. $dispatcher->registerMiddleware(
  240. $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
  241. );
  242. $dispatcher->registerMiddleware(
  243. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  244. $c->get(IControllerMethodReflector::class),
  245. $c->get(ISession::class),
  246. $c->get(IUserSession::class),
  247. $c->get(ITimeFactory::class)
  248. )
  249. );
  250. $dispatcher->registerMiddleware(
  251. new TwoFactorMiddleware(
  252. $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
  253. $c->get(IUserSession::class),
  254. $c->get(ISession::class),
  255. $c->get(IURLGenerator::class),
  256. $c->get(IControllerMethodReflector::class),
  257. $c->get(IRequest::class)
  258. )
  259. );
  260. $dispatcher->registerMiddleware(
  261. new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
  262. $c->get(IControllerMethodReflector::class),
  263. $c->get(OC\Security\Bruteforce\Throttler::class),
  264. $c->get(IRequest::class),
  265. $c->get(LoggerInterface::class)
  266. )
  267. );
  268. $dispatcher->registerMiddleware(
  269. new RateLimitingMiddleware(
  270. $c->get(IRequest::class),
  271. $c->get(IUserSession::class),
  272. $c->get(IControllerMethodReflector::class),
  273. $c->get(OC\Security\RateLimiting\Limiter::class)
  274. )
  275. );
  276. $dispatcher->registerMiddleware(
  277. new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
  278. $c->get(IRequest::class),
  279. $c->get(ISession::class),
  280. $c->get(\OCP\IConfig::class),
  281. $c->get(OC\Security\Bruteforce\Throttler::class)
  282. )
  283. );
  284. $dispatcher->registerMiddleware(
  285. $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
  286. );
  287. /** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
  288. $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
  289. $registrationContext = $coordinator->getRegistrationContext();
  290. if ($registrationContext !== null) {
  291. $appId = $this->getAppName();
  292. foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
  293. if ($middlewareRegistration->getAppId() === $appId
  294. || $middlewareRegistration->isGlobal()) {
  295. $dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
  296. }
  297. }
  298. }
  299. foreach ($this->middleWares as $middleWare) {
  300. $dispatcher->registerMiddleware($c->get($middleWare));
  301. }
  302. $dispatcher->registerMiddleware(
  303. new SessionMiddleware(
  304. $c->get(IControllerMethodReflector::class),
  305. $c->get(ISession::class)
  306. )
  307. );
  308. return $dispatcher;
  309. });
  310. $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
  311. return new OC\AppFramework\Services\AppConfig(
  312. $c->get(IConfig::class),
  313. $c->get('AppName')
  314. );
  315. });
  316. $this->registerService(IInitialState::class, function (ContainerInterface $c) {
  317. return new OC\AppFramework\Services\InitialState(
  318. $c->get(IInitialStateService::class),
  319. $c->get('AppName')
  320. );
  321. });
  322. }
  323. /**
  324. * @return \OCP\IServerContainer
  325. */
  326. public function getServer() {
  327. return $this->server;
  328. }
  329. /**
  330. * @param string $middleWare
  331. * @return boolean|null
  332. */
  333. public function registerMiddleWare($middleWare) {
  334. if (in_array($middleWare, $this->middleWares, true) !== false) {
  335. return false;
  336. }
  337. $this->middleWares[] = $middleWare;
  338. }
  339. /**
  340. * used to return the appname of the set application
  341. * @return string the name of your application
  342. */
  343. public function getAppName() {
  344. return $this->query('AppName');
  345. }
  346. /**
  347. * @deprecated use IUserSession->isLoggedIn()
  348. * @return boolean
  349. */
  350. public function isLoggedIn() {
  351. return \OC::$server->getUserSession()->isLoggedIn();
  352. }
  353. /**
  354. * @deprecated use IGroupManager->isAdmin($userId)
  355. * @return boolean
  356. */
  357. public function isAdminUser() {
  358. $uid = $this->getUserId();
  359. return \OC_User::isAdminUser($uid);
  360. }
  361. private function getUserId() {
  362. return $this->getServer()->getSession()->get('user_id');
  363. }
  364. /**
  365. * @deprecated use the ILogger instead
  366. * @param string $message
  367. * @param string $level
  368. * @return mixed
  369. */
  370. public function log($message, $level) {
  371. switch ($level) {
  372. case 'debug':
  373. $level = ILogger::DEBUG;
  374. break;
  375. case 'info':
  376. $level = ILogger::INFO;
  377. break;
  378. case 'warn':
  379. $level = ILogger::WARN;
  380. break;
  381. case 'fatal':
  382. $level = ILogger::FATAL;
  383. break;
  384. default:
  385. $level = ILogger::ERROR;
  386. break;
  387. }
  388. \OCP\Util::writeLog($this->getAppName(), $message, $level);
  389. }
  390. /**
  391. * Register a capability
  392. *
  393. * @param string $serviceName e.g. 'OCA\Files\Capabilities'
  394. */
  395. public function registerCapability($serviceName) {
  396. $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
  397. return $this->query($serviceName);
  398. });
  399. }
  400. public function has($id): bool {
  401. if (parent::has($id)) {
  402. return true;
  403. }
  404. if ($this->server->has($id, true)) {
  405. return true;
  406. }
  407. return false;
  408. }
  409. public function query(string $name, bool $autoload = true) {
  410. if ($name === 'AppName' || $name === 'appName') {
  411. return $this->appName;
  412. }
  413. $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
  414. if ($isServerClass && !$this->has($name)) {
  415. return $this->getServer()->query($name, $autoload);
  416. }
  417. try {
  418. return $this->queryNoFallback($name);
  419. } catch (QueryException $firstException) {
  420. try {
  421. return $this->getServer()->query($name, $autoload);
  422. } catch (QueryException $secondException) {
  423. if ($firstException->getCode() === 1) {
  424. throw $secondException;
  425. }
  426. throw $firstException;
  427. }
  428. }
  429. }
  430. /**
  431. * @param string $name
  432. * @return mixed
  433. * @throws QueryException if the query could not be resolved
  434. */
  435. public function queryNoFallback($name) {
  436. $name = $this->sanitizeName($name);
  437. if ($this->offsetExists($name)) {
  438. return parent::query($name);
  439. } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
  440. return parent::query($name);
  441. } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
  442. return parent::query($name);
  443. } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
  444. return parent::query($name);
  445. }
  446. throw new QueryException('Could not resolve ' . $name . '!' .
  447. ' Class can not be instantiated', 1);
  448. }
  449. }