DIContainer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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@owncloud.com>
  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\Security\CORSMiddleware;
  41. use OC\AppFramework\Middleware\OCSMiddleware;
  42. use OC\AppFramework\Middleware\Security\RateLimitingMiddleware;
  43. use OC\AppFramework\Middleware\Security\SecurityMiddleware;
  44. use OC\AppFramework\Middleware\SessionMiddleware;
  45. use OC\AppFramework\Utility\SimpleContainer;
  46. use OC\Core\Middleware\TwoFactorMiddleware;
  47. use OC\ServerContainer;
  48. use OCP\AppFramework\Http\IOutput;
  49. use OCP\AppFramework\IAppContainer;
  50. use OCP\AppFramework\QueryException;
  51. use OCP\AppFramework\Utility\IControllerMethodReflector;
  52. use OCP\AppFramework\Utility\ITimeFactory;
  53. use OCP\Files\Folder;
  54. use OCP\Files\IAppData;
  55. use OCP\GlobalScale\IConfig;
  56. use OCP\IL10N;
  57. use OCP\ILogger;
  58. use OCP\INavigationManager;
  59. use OCP\IRequest;
  60. use OCP\IServerContainer;
  61. use OCP\ISession;
  62. use OCP\IURLGenerator;
  63. use OCP\IUserSession;
  64. use OCA\WorkflowEngine\Manager;
  65. class DIContainer extends SimpleContainer implements IAppContainer {
  66. /**
  67. * @var array
  68. */
  69. private $middleWares = [];
  70. /** @var ServerContainer */
  71. private $server;
  72. /**
  73. * Put your class dependencies in here
  74. * @param string $appName the name of the app
  75. * @param array $urlParams
  76. * @param ServerContainer|null $server
  77. */
  78. public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
  79. parent::__construct();
  80. $this['AppName'] = $appName;
  81. $this['urlParams'] = $urlParams;
  82. $this->registerAlias('Request', IRequest::class);
  83. /** @var \OC\ServerContainer $server */
  84. if ($server === null) {
  85. $server = \OC::$server;
  86. }
  87. $this->server = $server;
  88. $this->server->registerAppContainer($appName, $this);
  89. // aliases
  90. $this->registerAlias('appName', 'AppName');
  91. $this->registerAlias('webRoot', 'WebRoot');
  92. $this->registerAlias('userId', 'UserId');
  93. /**
  94. * Core services
  95. */
  96. $this->registerService(IOutput::class, function(){
  97. return new Output($this->getServer()->getWebRoot());
  98. });
  99. $this->registerService(Folder::class, function() {
  100. return $this->getServer()->getUserFolder();
  101. });
  102. $this->registerService(IAppData::class, function (SimpleContainer $c) {
  103. return $this->getServer()->getAppDataDir($c->query('AppName'));
  104. });
  105. $this->registerService(IL10N::class, function($c) {
  106. return $this->getServer()->getL10N($c->query('AppName'));
  107. });
  108. // Log wrapper
  109. $this->registerService(ILogger::class, function ($c) {
  110. return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('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 ($c) {
  117. return $c->query(Manager::class);
  118. });
  119. $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
  120. return $c;
  121. });
  122. // commonly used attributes
  123. $this->registerService('UserId', function ($c) {
  124. return $c->query(IUserSession::class)->getSession()->get('user_id');
  125. });
  126. $this->registerService('WebRoot', function ($c) {
  127. return $c->query('ServerContainer')->getWebRoot();
  128. });
  129. $this->registerService('OC_Defaults', function ($c) {
  130. return $c->getServer()->getThemingDefaults();
  131. });
  132. $this->registerService(IConfig::class, function ($c) {
  133. return $c->query(OC\GlobalScale\Config::class);
  134. });
  135. $this->registerService('Protocol', function($c){
  136. /** @var \OC\Server $server */
  137. $server = $c->query('ServerContainer');
  138. $protocol = $server->getRequest()->getHttpProtocol();
  139. return new Http($_SERVER, $protocol);
  140. });
  141. $this->registerService('Dispatcher', function($c) {
  142. return new Dispatcher(
  143. $c['Protocol'],
  144. $c['MiddlewareDispatcher'],
  145. $c->query(IControllerMethodReflector::class),
  146. $c['Request']
  147. );
  148. });
  149. /**
  150. * App Framework default arguments
  151. */
  152. $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
  153. $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
  154. $this->registerParameter('corsMaxAge', 1728000);
  155. /**
  156. * Middleware
  157. */
  158. $this->registerService('MiddlewareDispatcher', function(SimpleContainer $c) {
  159. $server = $this->getServer();
  160. $dispatcher = new MiddlewareDispatcher();
  161. $dispatcher->registerMiddleware(
  162. new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
  163. $c->query(IRequest::class),
  164. $c->query(IControllerMethodReflector::class)
  165. )
  166. );
  167. $dispatcher->registerMiddleware(
  168. new CORSMiddleware(
  169. $c->query(IRequest::class),
  170. $c->query(IControllerMethodReflector::class),
  171. $c->query(IUserSession::class),
  172. $c->query(OC\Security\Bruteforce\Throttler::class)
  173. )
  174. );
  175. $dispatcher->registerMiddleware(
  176. new OCSMiddleware(
  177. $c->query(IRequest::class)
  178. )
  179. );
  180. $securityMiddleware = new SecurityMiddleware(
  181. $c->query(IRequest::class),
  182. $c->query(IControllerMethodReflector::class),
  183. $c->query(INavigationManager::class),
  184. $c->query(IURLGenerator::class),
  185. $server->getLogger(),
  186. $c['AppName'],
  187. $server->getUserSession()->isLoggedIn(),
  188. $server->getGroupManager()->isAdmin($this->getUserId()),
  189. $server->getContentSecurityPolicyManager(),
  190. $server->getCsrfTokenManager(),
  191. $server->getContentSecurityPolicyNonceManager(),
  192. $server->getAppManager(),
  193. $server->getL10N('lib')
  194. );
  195. $dispatcher->registerMiddleware($securityMiddleware);
  196. $dispatcher->registerMiddleware(
  197. new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
  198. $c->query(IControllerMethodReflector::class),
  199. $c->query(ISession::class),
  200. $c->query(IUserSession::class),
  201. $c->query(ITimeFactory::class)
  202. )
  203. );
  204. $dispatcher->registerMiddleware(
  205. new TwoFactorMiddleware(
  206. $c->query(OC\Authentication\TwoFactorAuth\Manager::class),
  207. $c->query(IUserSession::class),
  208. $c->query(ISession::class),
  209. $c->query(IURLGenerator::class),
  210. $c->query(IControllerMethodReflector::class),
  211. $c->query(IRequest::class)
  212. )
  213. );
  214. $dispatcher->registerMiddleware(
  215. new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
  216. $c->query(IControllerMethodReflector::class),
  217. $c->query(OC\Security\Bruteforce\Throttler::class),
  218. $c->query(IRequest::class)
  219. )
  220. );
  221. $dispatcher->registerMiddleware(
  222. new RateLimitingMiddleware(
  223. $c->query(IRequest::class),
  224. $c->query(IUserSession::class),
  225. $c->query(IControllerMethodReflector::class),
  226. $c->query(OC\Security\RateLimiting\Limiter::class)
  227. )
  228. );
  229. $dispatcher->registerMiddleware(
  230. new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
  231. $c->query(IRequest::class),
  232. $c->query(ISession::class),
  233. $c->query(\OCP\IConfig::class)
  234. )
  235. );
  236. $dispatcher->registerMiddleware(
  237. $c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
  238. );
  239. foreach($this->middleWares as $middleWare) {
  240. $dispatcher->registerMiddleware($c[$middleWare]);
  241. }
  242. $dispatcher->registerMiddleware(
  243. new SessionMiddleware(
  244. $c->query(IRequest::class),
  245. $c->query(IControllerMethodReflector::class),
  246. $c->query(ISession::class)
  247. )
  248. );
  249. return $dispatcher;
  250. });
  251. }
  252. /**
  253. * @return \OCP\IServerContainer
  254. */
  255. public function getServer()
  256. {
  257. return $this->server;
  258. }
  259. /**
  260. * @param string $middleWare
  261. * @return boolean|null
  262. */
  263. public function registerMiddleWare($middleWare) {
  264. $this->middleWares[] = $middleWare;
  265. }
  266. /**
  267. * used to return the appname of the set application
  268. * @return string the name of your application
  269. */
  270. public function getAppName() {
  271. return $this->query('AppName');
  272. }
  273. /**
  274. * @deprecated use IUserSession->isLoggedIn()
  275. * @return boolean
  276. */
  277. public function isLoggedIn() {
  278. return \OC::$server->getUserSession()->isLoggedIn();
  279. }
  280. /**
  281. * @deprecated use IGroupManager->isAdmin($userId)
  282. * @return boolean
  283. */
  284. public function isAdminUser() {
  285. $uid = $this->getUserId();
  286. return \OC_User::isAdminUser($uid);
  287. }
  288. private function getUserId() {
  289. return $this->getServer()->getSession()->get('user_id');
  290. }
  291. /**
  292. * @deprecated use the ILogger instead
  293. * @param string $message
  294. * @param string $level
  295. * @return mixed
  296. */
  297. public function log($message, $level) {
  298. switch($level){
  299. case 'debug':
  300. $level = ILogger::DEBUG;
  301. break;
  302. case 'info':
  303. $level = ILogger::INFO;
  304. break;
  305. case 'warn':
  306. $level = ILogger::WARN;
  307. break;
  308. case 'fatal':
  309. $level = ILogger::FATAL;
  310. break;
  311. default:
  312. $level = ILogger::ERROR;
  313. break;
  314. }
  315. \OCP\Util::writeLog($this->getAppName(), $message, $level);
  316. }
  317. /**
  318. * Register a capability
  319. *
  320. * @param string $serviceName e.g. 'OCA\Files\Capabilities'
  321. */
  322. public function registerCapability($serviceName) {
  323. $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
  324. return $this->query($serviceName);
  325. });
  326. }
  327. /**
  328. * @param string $name
  329. * @return mixed
  330. * @throws QueryException if the query could not be resolved
  331. */
  332. public function query($name) {
  333. try {
  334. return $this->queryNoFallback($name);
  335. } catch (QueryException $firstException) {
  336. try {
  337. return $this->getServer()->query($name);
  338. } catch (QueryException $secondException) {
  339. if ($firstException->getCode() === 1) {
  340. throw $secondException;
  341. }
  342. throw $firstException;
  343. }
  344. }
  345. }
  346. /**
  347. * @param string $name
  348. * @return mixed
  349. * @throws QueryException if the query could not be resolved
  350. */
  351. public function queryNoFallback($name) {
  352. $name = $this->sanitizeName($name);
  353. if ($this->offsetExists($name)) {
  354. return parent::query($name);
  355. } else {
  356. if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
  357. return parent::query($name);
  358. } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
  359. return parent::query($name);
  360. } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
  361. return parent::query($name);
  362. }
  363. }
  364. throw new QueryException('Could not resolve ' . $name . '!' .
  365. ' Class can not be instantiated', 1);
  366. }
  367. }