You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1767 lines
51 KiB

9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
Add code integrity check This PR implements the base foundation of the code signing and integrity check. In this PR implemented is the signing and verification logic, as well as commands to sign single apps or the core repository. Furthermore, there is a basic implementation to display problems with the code integrity on the update screen. Code signing basically happens the following way: - There is a ownCloud Root Certificate authority stored `resources/codesigning/root.crt` (in this PR I also ship the private key which we obviously need to change before a release :wink:). This certificate is not intended to be used for signing directly and only is used to sign new certificates. - Using the `integrity:sign-core` and `integrity:sign-app` commands developers can sign either the core release or a single app. The core release needs to be signed with a certificate that has a CN of `core`, apps need to be signed with a certificate that either has a CN of `core` (shipped apps!) or the AppID. - The command generates a signature.json file of the following format: ```json { "hashes": { "/filename.php": "2401fed2eea6f2c1027c482a633e8e25cd46701f811e2d2c10dc213fd95fa60e350bccbbebdccc73a042b1a2799f673fbabadc783284cc288e4f1a1eacb74e3d", "/lib/base.php": "55548cc16b457cd74241990cc9d3b72b6335f2e5f45eee95171da024087d114fcbc2effc3d5818a6d5d55f2ae960ab39fd0414d0c542b72a3b9e08eb21206dd9" }, "certificate": "-----BEGIN CERTIFICATE-----MIIBvTCCASagAwIBAgIUPvawyqJwCwYazcv7iz16TWxfeUMwDQYJKoZIhvcNAQEF\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTAx\nNDEzMTcxMFoXDTE2MTAxNDEzMTcxMFowEzERMA8GA1UEAwwIY29udGFjdHMwgZ8w\nDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANoQesGdCW0L2L+a2xITYipixkScrIpB\nkX5Snu3fs45MscDb61xByjBSlFgR4QI6McoCipPw4SUr28EaExVvgPSvqUjYLGps\nfiv0Cvgquzbx/X3mUcdk9LcFo1uWGtrTfkuXSKX41PnJGTr6RQWGIBd1V52q1qbC\nJKkfzyeMeuQfAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAvF/KIhRMQ3tYTmgHWsiM\nwDMgIDb7iaHF0fS+/Nvo4PzoTO/trev6tMyjLbJ7hgdCpz/1sNzE11Cibf6V6dsz\njCE9invP368Xv0bTRObRqeSNsGogGl5ceAvR0c9BG+NRIKHcly3At3gLkS2791bC\niG+UxI/MNcWV0uJg9S63LF8=\n-----END CERTIFICATE-----", "signature": "U29tZVNpZ25lZERhdGFFeGFtcGxl" } ``` `hashes` is an array of all files in the folder with their corresponding SHA512 hashes (this is actually quite cheap to calculate), the `certificate` is the certificate used for signing. It has to be issued by the ownCloud Root Authority and it's CN needs to be permitted to perform the required action. The `signature` is then a signature of the `hashes` which can be verified using the `certificate`. Steps to do in other PRs, this is already a quite huge one: - Add nag screen in case the code check fails to ensure that administrators are aware of this. - Add code verification also to OCC upgrade and unify display code more. - Add enforced code verification to apps shipped from the appstore with a level of "official" - Add enfocrced code verification to apps shipped from the appstore that were already signed in a previous release - Add some developer documentation on how devs can request their own certificate - Check when installing ownCloud - Add support for CRLs to allow revoking certificates **Note:** The upgrade checks are only run when the instance has a defined release channel of `stable` (defined in `version.php`). If you want to test this, you need to change the channel thus and then generate the core signature: ``` ➜ master git:(add-integrity-checker) ✗ ./occ integrity:sign-core --privateKey=resources/codesigning/core.key --certificate=resources/codesigning/core.crt Successfully signed "core" ``` Then increase the version and you should see something like the following: ![2015-11-04_12-02-57](https://cloud.githubusercontent.com/assets/878997/10936336/6adb1d14-82ec-11e5-8f06-9a74801c9abf.png) As you can see a failed code check will not prevent the further update. It will instead just be a notice to the admin. In a next step we will add some nag screen. For packaging stable releases this requires the following additional steps as a last action before zipping: 1. Run `./occ integrity:sign-core` once 2. Run `./occ integrity:sign-app` _for each_ app. However, this can be simply automated using a simple foreach on the apps folder.
10 years ago
10 years ago
11 years ago
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
10 years ago
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
10 years ago
10 years ago
10 years ago
Add code integrity check This PR implements the base foundation of the code signing and integrity check. In this PR implemented is the signing and verification logic, as well as commands to sign single apps or the core repository. Furthermore, there is a basic implementation to display problems with the code integrity on the update screen. Code signing basically happens the following way: - There is a ownCloud Root Certificate authority stored `resources/codesigning/root.crt` (in this PR I also ship the private key which we obviously need to change before a release :wink:). This certificate is not intended to be used for signing directly and only is used to sign new certificates. - Using the `integrity:sign-core` and `integrity:sign-app` commands developers can sign either the core release or a single app. The core release needs to be signed with a certificate that has a CN of `core`, apps need to be signed with a certificate that either has a CN of `core` (shipped apps!) or the AppID. - The command generates a signature.json file of the following format: ```json { "hashes": { "/filename.php": "2401fed2eea6f2c1027c482a633e8e25cd46701f811e2d2c10dc213fd95fa60e350bccbbebdccc73a042b1a2799f673fbabadc783284cc288e4f1a1eacb74e3d", "/lib/base.php": "55548cc16b457cd74241990cc9d3b72b6335f2e5f45eee95171da024087d114fcbc2effc3d5818a6d5d55f2ae960ab39fd0414d0c542b72a3b9e08eb21206dd9" }, "certificate": "-----BEGIN CERTIFICATE-----MIIBvTCCASagAwIBAgIUPvawyqJwCwYazcv7iz16TWxfeUMwDQYJKoZIhvcNAQEF\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTAx\nNDEzMTcxMFoXDTE2MTAxNDEzMTcxMFowEzERMA8GA1UEAwwIY29udGFjdHMwgZ8w\nDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANoQesGdCW0L2L+a2xITYipixkScrIpB\nkX5Snu3fs45MscDb61xByjBSlFgR4QI6McoCipPw4SUr28EaExVvgPSvqUjYLGps\nfiv0Cvgquzbx/X3mUcdk9LcFo1uWGtrTfkuXSKX41PnJGTr6RQWGIBd1V52q1qbC\nJKkfzyeMeuQfAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAvF/KIhRMQ3tYTmgHWsiM\nwDMgIDb7iaHF0fS+/Nvo4PzoTO/trev6tMyjLbJ7hgdCpz/1sNzE11Cibf6V6dsz\njCE9invP368Xv0bTRObRqeSNsGogGl5ceAvR0c9BG+NRIKHcly3At3gLkS2791bC\niG+UxI/MNcWV0uJg9S63LF8=\n-----END CERTIFICATE-----", "signature": "U29tZVNpZ25lZERhdGFFeGFtcGxl" } ``` `hashes` is an array of all files in the folder with their corresponding SHA512 hashes (this is actually quite cheap to calculate), the `certificate` is the certificate used for signing. It has to be issued by the ownCloud Root Authority and it's CN needs to be permitted to perform the required action. The `signature` is then a signature of the `hashes` which can be verified using the `certificate`. Steps to do in other PRs, this is already a quite huge one: - Add nag screen in case the code check fails to ensure that administrators are aware of this. - Add code verification also to OCC upgrade and unify display code more. - Add enforced code verification to apps shipped from the appstore with a level of "official" - Add enfocrced code verification to apps shipped from the appstore that were already signed in a previous release - Add some developer documentation on how devs can request their own certificate - Check when installing ownCloud - Add support for CRLs to allow revoking certificates **Note:** The upgrade checks are only run when the instance has a defined release channel of `stable` (defined in `version.php`). If you want to test this, you need to change the channel thus and then generate the core signature: ``` ➜ master git:(add-integrity-checker) ✗ ./occ integrity:sign-core --privateKey=resources/codesigning/core.key --certificate=resources/codesigning/core.crt Successfully signed "core" ``` Then increase the version and you should see something like the following: ![2015-11-04_12-02-57](https://cloud.githubusercontent.com/assets/878997/10936336/6adb1d14-82ec-11e5-8f06-9a74801c9abf.png) As you can see a failed code check will not prevent the further update. It will instead just be a notice to the admin. In a next step we will add some nag screen. For packaging stable releases this requires the following additional steps as a last action before zipping: 1. Run `./occ integrity:sign-core` once 2. Run `./occ integrity:sign-app` _for each_ app. However, this can be simply automated using a simple foreach on the apps folder.
10 years ago
Add code integrity check This PR implements the base foundation of the code signing and integrity check. In this PR implemented is the signing and verification logic, as well as commands to sign single apps or the core repository. Furthermore, there is a basic implementation to display problems with the code integrity on the update screen. Code signing basically happens the following way: - There is a ownCloud Root Certificate authority stored `resources/codesigning/root.crt` (in this PR I also ship the private key which we obviously need to change before a release :wink:). This certificate is not intended to be used for signing directly and only is used to sign new certificates. - Using the `integrity:sign-core` and `integrity:sign-app` commands developers can sign either the core release or a single app. The core release needs to be signed with a certificate that has a CN of `core`, apps need to be signed with a certificate that either has a CN of `core` (shipped apps!) or the AppID. - The command generates a signature.json file of the following format: ```json { "hashes": { "/filename.php": "2401fed2eea6f2c1027c482a633e8e25cd46701f811e2d2c10dc213fd95fa60e350bccbbebdccc73a042b1a2799f673fbabadc783284cc288e4f1a1eacb74e3d", "/lib/base.php": "55548cc16b457cd74241990cc9d3b72b6335f2e5f45eee95171da024087d114fcbc2effc3d5818a6d5d55f2ae960ab39fd0414d0c542b72a3b9e08eb21206dd9" }, "certificate": "-----BEGIN CERTIFICATE-----MIIBvTCCASagAwIBAgIUPvawyqJwCwYazcv7iz16TWxfeUMwDQYJKoZIhvcNAQEF\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTAx\nNDEzMTcxMFoXDTE2MTAxNDEzMTcxMFowEzERMA8GA1UEAwwIY29udGFjdHMwgZ8w\nDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANoQesGdCW0L2L+a2xITYipixkScrIpB\nkX5Snu3fs45MscDb61xByjBSlFgR4QI6McoCipPw4SUr28EaExVvgPSvqUjYLGps\nfiv0Cvgquzbx/X3mUcdk9LcFo1uWGtrTfkuXSKX41PnJGTr6RQWGIBd1V52q1qbC\nJKkfzyeMeuQfAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAvF/KIhRMQ3tYTmgHWsiM\nwDMgIDb7iaHF0fS+/Nvo4PzoTO/trev6tMyjLbJ7hgdCpz/1sNzE11Cibf6V6dsz\njCE9invP368Xv0bTRObRqeSNsGogGl5ceAvR0c9BG+NRIKHcly3At3gLkS2791bC\niG+UxI/MNcWV0uJg9S63LF8=\n-----END CERTIFICATE-----", "signature": "U29tZVNpZ25lZERhdGFFeGFtcGxl" } ``` `hashes` is an array of all files in the folder with their corresponding SHA512 hashes (this is actually quite cheap to calculate), the `certificate` is the certificate used for signing. It has to be issued by the ownCloud Root Authority and it's CN needs to be permitted to perform the required action. The `signature` is then a signature of the `hashes` which can be verified using the `certificate`. Steps to do in other PRs, this is already a quite huge one: - Add nag screen in case the code check fails to ensure that administrators are aware of this. - Add code verification also to OCC upgrade and unify display code more. - Add enforced code verification to apps shipped from the appstore with a level of "official" - Add enfocrced code verification to apps shipped from the appstore that were already signed in a previous release - Add some developer documentation on how devs can request their own certificate - Check when installing ownCloud - Add support for CRLs to allow revoking certificates **Note:** The upgrade checks are only run when the instance has a defined release channel of `stable` (defined in `version.php`). If you want to test this, you need to change the channel thus and then generate the core signature: ``` ➜ master git:(add-integrity-checker) ✗ ./occ integrity:sign-core --privateKey=resources/codesigning/core.key --certificate=resources/codesigning/core.crt Successfully signed "core" ``` Then increase the version and you should see something like the following: ![2015-11-04_12-02-57](https://cloud.githubusercontent.com/assets/878997/10936336/6adb1d14-82ec-11e5-8f06-9a74801c9abf.png) As you can see a failed code check will not prevent the further update. It will instead just be a notice to the admin. In a next step we will add some nag screen. For packaging stable releases this requires the following additional steps as a last action before zipping: 1. Run `./occ integrity:sign-core` once 2. Run `./occ integrity:sign-app` _for each_ app. However, this can be simply automated using a simple foreach on the apps folder.
10 years ago
10 years ago
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
Add code integrity check This PR implements the base foundation of the code signing and integrity check. In this PR implemented is the signing and verification logic, as well as commands to sign single apps or the core repository. Furthermore, there is a basic implementation to display problems with the code integrity on the update screen. Code signing basically happens the following way: - There is a ownCloud Root Certificate authority stored `resources/codesigning/root.crt` (in this PR I also ship the private key which we obviously need to change before a release :wink:). This certificate is not intended to be used for signing directly and only is used to sign new certificates. - Using the `integrity:sign-core` and `integrity:sign-app` commands developers can sign either the core release or a single app. The core release needs to be signed with a certificate that has a CN of `core`, apps need to be signed with a certificate that either has a CN of `core` (shipped apps!) or the AppID. - The command generates a signature.json file of the following format: ```json { "hashes": { "/filename.php": "2401fed2eea6f2c1027c482a633e8e25cd46701f811e2d2c10dc213fd95fa60e350bccbbebdccc73a042b1a2799f673fbabadc783284cc288e4f1a1eacb74e3d", "/lib/base.php": "55548cc16b457cd74241990cc9d3b72b6335f2e5f45eee95171da024087d114fcbc2effc3d5818a6d5d55f2ae960ab39fd0414d0c542b72a3b9e08eb21206dd9" }, "certificate": "-----BEGIN CERTIFICATE-----MIIBvTCCASagAwIBAgIUPvawyqJwCwYazcv7iz16TWxfeUMwDQYJKoZIhvcNAQEF\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTAx\nNDEzMTcxMFoXDTE2MTAxNDEzMTcxMFowEzERMA8GA1UEAwwIY29udGFjdHMwgZ8w\nDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANoQesGdCW0L2L+a2xITYipixkScrIpB\nkX5Snu3fs45MscDb61xByjBSlFgR4QI6McoCipPw4SUr28EaExVvgPSvqUjYLGps\nfiv0Cvgquzbx/X3mUcdk9LcFo1uWGtrTfkuXSKX41PnJGTr6RQWGIBd1V52q1qbC\nJKkfzyeMeuQfAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAvF/KIhRMQ3tYTmgHWsiM\nwDMgIDb7iaHF0fS+/Nvo4PzoTO/trev6tMyjLbJ7hgdCpz/1sNzE11Cibf6V6dsz\njCE9invP368Xv0bTRObRqeSNsGogGl5ceAvR0c9BG+NRIKHcly3At3gLkS2791bC\niG+UxI/MNcWV0uJg9S63LF8=\n-----END CERTIFICATE-----", "signature": "U29tZVNpZ25lZERhdGFFeGFtcGxl" } ``` `hashes` is an array of all files in the folder with their corresponding SHA512 hashes (this is actually quite cheap to calculate), the `certificate` is the certificate used for signing. It has to be issued by the ownCloud Root Authority and it's CN needs to be permitted to perform the required action. The `signature` is then a signature of the `hashes` which can be verified using the `certificate`. Steps to do in other PRs, this is already a quite huge one: - Add nag screen in case the code check fails to ensure that administrators are aware of this. - Add code verification also to OCC upgrade and unify display code more. - Add enforced code verification to apps shipped from the appstore with a level of "official" - Add enfocrced code verification to apps shipped from the appstore that were already signed in a previous release - Add some developer documentation on how devs can request their own certificate - Check when installing ownCloud - Add support for CRLs to allow revoking certificates **Note:** The upgrade checks are only run when the instance has a defined release channel of `stable` (defined in `version.php`). If you want to test this, you need to change the channel thus and then generate the core signature: ``` ➜ master git:(add-integrity-checker) ✗ ./occ integrity:sign-core --privateKey=resources/codesigning/core.key --certificate=resources/codesigning/core.crt Successfully signed "core" ``` Then increase the version and you should see something like the following: ![2015-11-04_12-02-57](https://cloud.githubusercontent.com/assets/878997/10936336/6adb1d14-82ec-11e5-8f06-9a74801c9abf.png) As you can see a failed code check will not prevent the further update. It will instead just be a notice to the admin. In a next step we will add some nag screen. For packaging stable releases this requires the following additional steps as a last action before zipping: 1. Run `./occ integrity:sign-core` once 2. Run `./occ integrity:sign-app` _for each_ app. However, this can be simply automated using a simple foreach on the apps folder.
10 years ago
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
10 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Bernhard Reiter <ockham@raz.or.at>
  10. * @author Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Björn Schießle <bjoern@schiessle.org>
  12. * @author Christopher Schäpers <kondou@ts.unde.re>
  13. * @author Christoph Wurst <christoph@owncloud.com>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Robin McCorkell <robin@mccorkell.me.uk>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Sander <brantje@gmail.com>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Thomas Tanghus <thomas@tanghus.net>
  24. * @author Vincent Petry <pvince81@owncloud.com>
  25. * @author Roger Szabo <roger.szabo@web.de>
  26. *
  27. * @license AGPL-3.0
  28. *
  29. * This code is free software: you can redistribute it and/or modify
  30. * it under the terms of the GNU Affero General Public License, version 3,
  31. * as published by the Free Software Foundation.
  32. *
  33. * This program is distributed in the hope that it will be useful,
  34. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  35. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  36. * GNU Affero General Public License for more details.
  37. *
  38. * You should have received a copy of the GNU Affero General Public License, version 3,
  39. * along with this program. If not, see <http://www.gnu.org/licenses/>
  40. *
  41. */
  42. namespace OC;
  43. use bantu\IniGetWrapper\IniGetWrapper;
  44. use OC\App\AppManager;
  45. use OC\App\AppStore\Bundles\BundleFetcher;
  46. use OC\App\AppStore\Fetcher\AppFetcher;
  47. use OC\App\AppStore\Fetcher\CategoryFetcher;
  48. use OC\AppFramework\Http\Request;
  49. use OC\AppFramework\Utility\SimpleContainer;
  50. use OC\AppFramework\Utility\TimeFactory;
  51. use OC\Authentication\LoginCredentials\Store;
  52. use OC\Command\AsyncBus;
  53. use OC\Contacts\ContactsMenu\ActionFactory;
  54. use OC\Diagnostics\EventLogger;
  55. use OC\Diagnostics\NullEventLogger;
  56. use OC\Diagnostics\NullQueryLogger;
  57. use OC\Diagnostics\QueryLogger;
  58. use OC\Federation\CloudIdManager;
  59. use OC\Files\Config\UserMountCache;
  60. use OC\Files\Config\UserMountCacheListener;
  61. use OC\Files\Mount\CacheMountProvider;
  62. use OC\Files\Mount\LocalHomeMountProvider;
  63. use OC\Files\Mount\ObjectHomeMountProvider;
  64. use OC\Files\Node\HookConnector;
  65. use OC\Files\Node\LazyRoot;
  66. use OC\Files\Node\Root;
  67. use OC\Files\View;
  68. use OC\Http\Client\ClientService;
  69. use OC\IntegrityCheck\Checker;
  70. use OC\IntegrityCheck\Helpers\AppLocator;
  71. use OC\IntegrityCheck\Helpers\EnvironmentHelper;
  72. use OC\IntegrityCheck\Helpers\FileAccessHelper;
  73. use OC\Lock\DBLockingProvider;
  74. use OC\Lock\MemcacheLockingProvider;
  75. use OC\Lock\NoopLockingProvider;
  76. use OC\Lockdown\LockdownManager;
  77. use OC\Mail\Mailer;
  78. use OC\Memcache\ArrayCache;
  79. use OC\Memcache\Factory;
  80. use OC\Notification\Manager;
  81. use OC\OCS\DiscoveryService;
  82. use OC\Repair\NC11\CleanPreviewsBackgroundJob;
  83. use OC\RichObjectStrings\Validator;
  84. use OC\Security\Bruteforce\Throttler;
  85. use OC\Security\CertificateManager;
  86. use OC\Security\CSP\ContentSecurityPolicyManager;
  87. use OC\Security\Crypto;
  88. use OC\Security\CSP\ContentSecurityPolicyNonceManager;
  89. use OC\Security\CSRF\CsrfTokenGenerator;
  90. use OC\Security\CSRF\CsrfTokenManager;
  91. use OC\Security\CSRF\TokenStorage\SessionStorage;
  92. use OC\Security\Hasher;
  93. use OC\Security\CredentialsManager;
  94. use OC\Security\SecureRandom;
  95. use OC\Security\TrustedDomainHelper;
  96. use OC\Session\CryptoWrapper;
  97. use OC\Share20\ShareHelper;
  98. use OC\Tagging\TagMapper;
  99. use OC\Template\SCSSCacher;
  100. use OCA\Theming\ThemingDefaults;
  101. use OCP\App\IAppManager;
  102. use OCP\Defaults;
  103. use OCA\Theming\Util;
  104. use OCP\Federation\ICloudIdManager;
  105. use OCP\Authentication\LoginCredentials\IStore;
  106. use OCP\ICacheFactory;
  107. use OCP\IDBConnection;
  108. use OCP\IL10N;
  109. use OCP\IServerContainer;
  110. use OCP\ITempManager;
  111. use OCP\Contacts\ContactsMenu\IActionFactory;
  112. use OCP\IURLGenerator;
  113. use OCP\RichObjectStrings\IValidator;
  114. use OCP\Security\IContentSecurityPolicyManager;
  115. use OCP\Share\IShareHelper;
  116. use Symfony\Component\EventDispatcher\EventDispatcher;
  117. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  118. /**
  119. * Class Server
  120. *
  121. * @package OC
  122. *
  123. * TODO: hookup all manager classes
  124. */
  125. class Server extends ServerContainer implements IServerContainer {
  126. /** @var string */
  127. private $webRoot;
  128. /**
  129. * @param string $webRoot
  130. * @param \OC\Config $config
  131. */
  132. public function __construct($webRoot, \OC\Config $config) {
  133. parent::__construct();
  134. $this->webRoot = $webRoot;
  135. $this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
  136. return $c;
  137. });
  138. $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
  139. $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
  140. $this->registerAlias(IActionFactory::class, ActionFactory::class);
  141. $this->registerService(\OCP\IPreview::class, function (Server $c) {
  142. return new PreviewManager(
  143. $c->getConfig(),
  144. $c->getRootFolder(),
  145. $c->getAppDataDir('preview'),
  146. $c->getEventDispatcher(),
  147. $c->getSession()->get('user_id')
  148. );
  149. });
  150. $this->registerAlias('PreviewManager', \OCP\IPreview::class);
  151. $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
  152. return new \OC\Preview\Watcher(
  153. $c->getAppDataDir('preview')
  154. );
  155. });
  156. $this->registerService('EncryptionManager', function (Server $c) {
  157. $view = new View();
  158. $util = new Encryption\Util(
  159. $view,
  160. $c->getUserManager(),
  161. $c->getGroupManager(),
  162. $c->getConfig()
  163. );
  164. return new Encryption\Manager(
  165. $c->getConfig(),
  166. $c->getLogger(),
  167. $c->getL10N('core'),
  168. new View(),
  169. $util,
  170. new ArrayCache()
  171. );
  172. });
  173. $this->registerService('EncryptionFileHelper', function (Server $c) {
  174. $util = new Encryption\Util(
  175. new View(),
  176. $c->getUserManager(),
  177. $c->getGroupManager(),
  178. $c->getConfig()
  179. );
  180. return new Encryption\File(
  181. $util,
  182. $c->getRootFolder(),
  183. $c->getShareManager()
  184. );
  185. });
  186. $this->registerService('EncryptionKeyStorage', function (Server $c) {
  187. $view = new View();
  188. $util = new Encryption\Util(
  189. $view,
  190. $c->getUserManager(),
  191. $c->getGroupManager(),
  192. $c->getConfig()
  193. );
  194. return new Encryption\Keys\Storage($view, $util);
  195. });
  196. $this->registerService('TagMapper', function (Server $c) {
  197. return new TagMapper($c->getDatabaseConnection());
  198. });
  199. $this->registerService(\OCP\ITagManager::class, function (Server $c) {
  200. $tagMapper = $c->query('TagMapper');
  201. return new TagManager($tagMapper, $c->getUserSession());
  202. });
  203. $this->registerAlias('TagManager', \OCP\ITagManager::class);
  204. $this->registerService('SystemTagManagerFactory', function (Server $c) {
  205. $config = $c->getConfig();
  206. $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
  207. /** @var \OC\SystemTag\ManagerFactory $factory */
  208. $factory = new $factoryClass($this);
  209. return $factory;
  210. });
  211. $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
  212. return $c->query('SystemTagManagerFactory')->getManager();
  213. });
  214. $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
  215. $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
  216. return $c->query('SystemTagManagerFactory')->getObjectMapper();
  217. });
  218. $this->registerService('RootFolder', function (Server $c) {
  219. $manager = \OC\Files\Filesystem::getMountManager(null);
  220. $view = new View();
  221. $root = new Root(
  222. $manager,
  223. $view,
  224. null,
  225. $c->getUserMountCache(),
  226. $this->getLogger(),
  227. $this->getUserManager()
  228. );
  229. $connector = new HookConnector($root, $view);
  230. $connector->viewToNode();
  231. $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
  232. $previewConnector->connectWatcher();
  233. return $root;
  234. });
  235. $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
  236. $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
  237. return new LazyRoot(function() use ($c) {
  238. return $c->query('RootFolder');
  239. });
  240. });
  241. $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
  242. $this->registerService(\OCP\IUserManager::class, function (Server $c) {
  243. $config = $c->getConfig();
  244. return new \OC\User\Manager($config);
  245. });
  246. $this->registerAlias('UserManager', \OCP\IUserManager::class);
  247. $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
  248. $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
  249. $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
  250. \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
  251. });
  252. $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
  253. \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
  254. });
  255. $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
  256. \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
  257. });
  258. $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
  259. \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
  260. });
  261. $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
  262. \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
  263. });
  264. $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
  265. \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
  266. //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
  267. \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
  268. });
  269. return $groupManager;
  270. });
  271. $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
  272. $this->registerService(Store::class, function(Server $c) {
  273. $session = $c->getSession();
  274. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  275. $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
  276. } else {
  277. $tokenProvider = null;
  278. }
  279. $logger = $c->getLogger();
  280. return new Store($session, $logger, $tokenProvider);
  281. });
  282. $this->registerAlias(IStore::class, Store::class);
  283. $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
  284. $dbConnection = $c->getDatabaseConnection();
  285. return new Authentication\Token\DefaultTokenMapper($dbConnection);
  286. });
  287. $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
  288. $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
  289. $crypto = $c->getCrypto();
  290. $config = $c->getConfig();
  291. $logger = $c->getLogger();
  292. $timeFactory = new TimeFactory();
  293. return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
  294. });
  295. $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
  296. $this->registerService(\OCP\IUserSession::class, function (Server $c) {
  297. $manager = $c->getUserManager();
  298. $session = new \OC\Session\Memory('');
  299. $timeFactory = new TimeFactory();
  300. // Token providers might require a working database. This code
  301. // might however be called when ownCloud is not yet setup.
  302. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  303. $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
  304. } else {
  305. $defaultTokenProvider = null;
  306. }
  307. $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
  308. $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
  309. \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
  310. });
  311. $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
  312. /** @var $user \OC\User\User */
  313. \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
  314. });
  315. $userSession->listen('\OC\User', 'preDelete', function ($user) {
  316. /** @var $user \OC\User\User */
  317. \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
  318. });
  319. $userSession->listen('\OC\User', 'postDelete', function ($user) {
  320. /** @var $user \OC\User\User */
  321. \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
  322. });
  323. $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
  324. /** @var $user \OC\User\User */
  325. \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
  326. });
  327. $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
  328. /** @var $user \OC\User\User */
  329. \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
  330. });
  331. $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
  332. \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
  333. });
  334. $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
  335. /** @var $user \OC\User\User */
  336. \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
  337. });
  338. $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
  339. /** @var $user \OC\User\User */
  340. \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
  341. });
  342. $userSession->listen('\OC\User', 'logout', function () {
  343. \OC_Hook::emit('OC_User', 'logout', array());
  344. });
  345. $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
  346. /** @var $user \OC\User\User */
  347. \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
  348. });
  349. return $userSession;
  350. });
  351. $this->registerAlias('UserSession', \OCP\IUserSession::class);
  352. $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
  353. return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
  354. });
  355. $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
  356. $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
  357. $this->registerService(\OC\AllConfig::class, function (Server $c) {
  358. return new \OC\AllConfig(
  359. $c->getSystemConfig()
  360. );
  361. });
  362. $this->registerAlias('AllConfig', \OC\AllConfig::class);
  363. $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
  364. $this->registerService('SystemConfig', function ($c) use ($config) {
  365. return new \OC\SystemConfig($config);
  366. });
  367. $this->registerService(\OC\AppConfig::class, function (Server $c) {
  368. return new \OC\AppConfig($c->getDatabaseConnection());
  369. });
  370. $this->registerAlias('AppConfig', \OC\AppConfig::class);
  371. $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
  372. $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
  373. return new \OC\L10N\Factory(
  374. $c->getConfig(),
  375. $c->getRequest(),
  376. $c->getUserSession(),
  377. \OC::$SERVERROOT
  378. );
  379. });
  380. $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
  381. $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
  382. $config = $c->getConfig();
  383. $cacheFactory = $c->getMemCacheFactory();
  384. return new \OC\URLGenerator(
  385. $config,
  386. $cacheFactory
  387. );
  388. });
  389. $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
  390. $this->registerService('AppHelper', function ($c) {
  391. return new \OC\AppHelper();
  392. });
  393. $this->registerAlias('AppFetcher', AppFetcher::class);
  394. $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
  395. $this->registerService(\OCP\ICache::class, function ($c) {
  396. return new Cache\File();
  397. });
  398. $this->registerAlias('UserCache', \OCP\ICache::class);
  399. $this->registerService(Factory::class, function (Server $c) {
  400. $config = $c->getConfig();
  401. if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
  402. $v = \OC_App::getAppVersions();
  403. $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
  404. $version = implode(',', $v);
  405. $instanceId = \OC_Util::getInstanceId();
  406. $path = \OC::$SERVERROOT;
  407. $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
  408. return new \OC\Memcache\Factory($prefix, $c->getLogger(),
  409. $config->getSystemValue('memcache.local', null),
  410. $config->getSystemValue('memcache.distributed', null),
  411. $config->getSystemValue('memcache.locking', null)
  412. );
  413. }
  414. return new \OC\Memcache\Factory('', $c->getLogger(),
  415. '\\OC\\Memcache\\ArrayCache',
  416. '\\OC\\Memcache\\ArrayCache',
  417. '\\OC\\Memcache\\ArrayCache'
  418. );
  419. });
  420. $this->registerAlias('MemCacheFactory', Factory::class);
  421. $this->registerAlias(ICacheFactory::class, Factory::class);
  422. $this->registerService('RedisFactory', function (Server $c) {
  423. $systemConfig = $c->getSystemConfig();
  424. return new RedisFactory($systemConfig);
  425. });
  426. $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
  427. return new \OC\Activity\Manager(
  428. $c->getRequest(),
  429. $c->getUserSession(),
  430. $c->getConfig(),
  431. $c->query(IValidator::class)
  432. );
  433. });
  434. $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
  435. $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
  436. return new \OC\Activity\EventMerger(
  437. $c->getL10N('lib')
  438. );
  439. });
  440. $this->registerAlias(IValidator::class, Validator::class);
  441. $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
  442. return new AvatarManager(
  443. $c->getUserManager(),
  444. $c->getAppDataDir('avatar'),
  445. $c->getL10N('lib'),
  446. $c->getLogger(),
  447. $c->getConfig()
  448. );
  449. });
  450. $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
  451. $this->registerService(\OCP\ILogger::class, function (Server $c) {
  452. $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
  453. $logger = Log::getLogClass($logType);
  454. call_user_func(array($logger, 'init'));
  455. return new Log($logger);
  456. });
  457. $this->registerAlias('Logger', \OCP\ILogger::class);
  458. $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
  459. $config = $c->getConfig();
  460. return new \OC\BackgroundJob\JobList(
  461. $c->getDatabaseConnection(),
  462. $config,
  463. new TimeFactory()
  464. );
  465. });
  466. $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
  467. $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
  468. $cacheFactory = $c->getMemCacheFactory();
  469. $logger = $c->getLogger();
  470. if ($cacheFactory->isAvailable()) {
  471. $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
  472. } else {
  473. $router = new \OC\Route\Router($logger);
  474. }
  475. return $router;
  476. });
  477. $this->registerAlias('Router', \OCP\Route\IRouter::class);
  478. $this->registerService(\OCP\ISearch::class, function ($c) {
  479. return new Search();
  480. });
  481. $this->registerAlias('Search', \OCP\ISearch::class);
  482. $this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
  483. return new \OC\Security\RateLimiting\Limiter(
  484. $this->getUserSession(),
  485. $this->getRequest(),
  486. new \OC\AppFramework\Utility\TimeFactory(),
  487. $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
  488. );
  489. });
  490. $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
  491. return new \OC\Security\RateLimiting\Backend\MemoryCache(
  492. $this->getMemCacheFactory(),
  493. new \OC\AppFramework\Utility\TimeFactory()
  494. );
  495. });
  496. $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
  497. return new SecureRandom();
  498. });
  499. $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
  500. $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
  501. return new Crypto($c->getConfig(), $c->getSecureRandom());
  502. });
  503. $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
  504. $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
  505. return new Hasher($c->getConfig());
  506. });
  507. $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
  508. $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
  509. return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
  510. });
  511. $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
  512. $this->registerService(IDBConnection::class, function (Server $c) {
  513. $systemConfig = $c->getSystemConfig();
  514. $factory = new \OC\DB\ConnectionFactory($systemConfig);
  515. $type = $systemConfig->getValue('dbtype', 'sqlite');
  516. if (!$factory->isValidType($type)) {
  517. throw new \OC\DatabaseException('Invalid database type');
  518. }
  519. $connectionParams = $factory->createConnectionParams();
  520. $connection = $factory->getConnection($type, $connectionParams);
  521. $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
  522. return $connection;
  523. });
  524. $this->registerAlias('DatabaseConnection', IDBConnection::class);
  525. $this->registerService('HTTPHelper', function (Server $c) {
  526. $config = $c->getConfig();
  527. return new HTTPHelper(
  528. $config,
  529. $c->getHTTPClientService()
  530. );
  531. });
  532. $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
  533. $user = \OC_User::getUser();
  534. $uid = $user ? $user : null;
  535. return new ClientService(
  536. $c->getConfig(),
  537. new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
  538. );
  539. });
  540. $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
  541. $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
  542. $eventLogger = new EventLogger();
  543. if ($c->getSystemConfig()->getValue('debug', false)) {
  544. // In debug mode, module is being activated by default
  545. $eventLogger->activate();
  546. }
  547. return $eventLogger;
  548. });
  549. $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
  550. $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
  551. $queryLogger = new QueryLogger();
  552. if ($c->getSystemConfig()->getValue('debug', false)) {
  553. // In debug mode, module is being activated by default
  554. $queryLogger->activate();
  555. }
  556. return $queryLogger;
  557. });
  558. $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
  559. $this->registerService(TempManager::class, function (Server $c) {
  560. return new TempManager(
  561. $c->getLogger(),
  562. $c->getConfig()
  563. );
  564. });
  565. $this->registerAlias('TempManager', TempManager::class);
  566. $this->registerAlias(ITempManager::class, TempManager::class);
  567. $this->registerService(AppManager::class, function (Server $c) {
  568. return new \OC\App\AppManager(
  569. $c->getUserSession(),
  570. $c->getAppConfig(),
  571. $c->getGroupManager(),
  572. $c->getMemCacheFactory(),
  573. $c->getEventDispatcher()
  574. );
  575. });
  576. $this->registerAlias('AppManager', AppManager::class);
  577. $this->registerAlias(IAppManager::class, AppManager::class);
  578. $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
  579. return new DateTimeZone(
  580. $c->getConfig(),
  581. $c->getSession()
  582. );
  583. });
  584. $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
  585. $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
  586. $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
  587. return new DateTimeFormatter(
  588. $c->getDateTimeZone()->getTimeZone(),
  589. $c->getL10N('lib', $language)
  590. );
  591. });
  592. $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
  593. $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
  594. $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
  595. $listener = new UserMountCacheListener($mountCache);
  596. $listener->listen($c->getUserManager());
  597. return $mountCache;
  598. });
  599. $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
  600. $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
  601. $loader = \OC\Files\Filesystem::getLoader();
  602. $mountCache = $c->query('UserMountCache');
  603. $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
  604. // builtin providers
  605. $config = $c->getConfig();
  606. $manager->registerProvider(new CacheMountProvider($config));
  607. $manager->registerHomeProvider(new LocalHomeMountProvider());
  608. $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
  609. return $manager;
  610. });
  611. $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
  612. $this->registerService('IniWrapper', function ($c) {
  613. return new IniGetWrapper();
  614. });
  615. $this->registerService('AsyncCommandBus', function (Server $c) {
  616. $jobList = $c->getJobList();
  617. return new AsyncBus($jobList);
  618. });
  619. $this->registerService('TrustedDomainHelper', function ($c) {
  620. return new TrustedDomainHelper($this->getConfig());
  621. });
  622. $this->registerService('Throttler', function(Server $c) {
  623. return new Throttler(
  624. $c->getDatabaseConnection(),
  625. new TimeFactory(),
  626. $c->getLogger(),
  627. $c->getConfig()
  628. );
  629. });
  630. $this->registerService('IntegrityCodeChecker', function (Server $c) {
  631. // IConfig and IAppManager requires a working database. This code
  632. // might however be called when ownCloud is not yet setup.
  633. if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
  634. $config = $c->getConfig();
  635. $appManager = $c->getAppManager();
  636. } else {
  637. $config = null;
  638. $appManager = null;
  639. }
  640. return new Checker(
  641. new EnvironmentHelper(),
  642. new FileAccessHelper(),
  643. new AppLocator(),
  644. $config,
  645. $c->getMemCacheFactory(),
  646. $appManager,
  647. $c->getTempManager()
  648. );
  649. });
  650. $this->registerService(\OCP\IRequest::class, function ($c) {
  651. if (isset($this['urlParams'])) {
  652. $urlParams = $this['urlParams'];
  653. } else {
  654. $urlParams = [];
  655. }
  656. if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
  657. && in_array('fakeinput', stream_get_wrappers())
  658. ) {
  659. $stream = 'fakeinput://data';
  660. } else {
  661. $stream = 'php://input';
  662. }
  663. return new Request(
  664. [
  665. 'get' => $_GET,
  666. 'post' => $_POST,
  667. 'files' => $_FILES,
  668. 'server' => $_SERVER,
  669. 'env' => $_ENV,
  670. 'cookies' => $_COOKIE,
  671. 'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
  672. ? $_SERVER['REQUEST_METHOD']
  673. : null,
  674. 'urlParams' => $urlParams,
  675. ],
  676. $this->getSecureRandom(),
  677. $this->getConfig(),
  678. $this->getCsrfTokenManager(),
  679. $stream
  680. );
  681. });
  682. $this->registerAlias('Request', \OCP\IRequest::class);
  683. $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
  684. return new Mailer(
  685. $c->getConfig(),
  686. $c->getLogger(),
  687. $c->query(Defaults::class),
  688. $c->getURLGenerator(),
  689. $c->getL10N('lib')
  690. );
  691. });
  692. $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
  693. $this->registerService('LDAPProvider', function(Server $c) {
  694. $config = $c->getConfig();
  695. $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
  696. if(is_null($factoryClass)) {
  697. throw new \Exception('ldapProviderFactory not set');
  698. }
  699. /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
  700. $factory = new $factoryClass($this);
  701. return $factory->getLDAPProvider();
  702. });
  703. $this->registerService('LockingProvider', function (Server $c) {
  704. $ini = $c->getIniWrapper();
  705. $config = $c->getConfig();
  706. $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
  707. if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
  708. /** @var \OC\Memcache\Factory $memcacheFactory */
  709. $memcacheFactory = $c->getMemCacheFactory();
  710. $memcache = $memcacheFactory->createLocking('lock');
  711. if (!($memcache instanceof \OC\Memcache\NullCache)) {
  712. return new MemcacheLockingProvider($memcache, $ttl);
  713. }
  714. return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
  715. }
  716. return new NoopLockingProvider();
  717. });
  718. $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
  719. return new \OC\Files\Mount\Manager();
  720. });
  721. $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
  722. $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
  723. return new \OC\Files\Type\Detection(
  724. $c->getURLGenerator(),
  725. \OC::$configDir,
  726. \OC::$SERVERROOT . '/resources/config/'
  727. );
  728. });
  729. $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
  730. $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
  731. return new \OC\Files\Type\Loader(
  732. $c->getDatabaseConnection()
  733. );
  734. });
  735. $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
  736. $this->registerService(BundleFetcher::class, function () {
  737. return new BundleFetcher($this->getL10N('lib'));
  738. });
  739. $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
  740. return new Manager(
  741. $c->query(IValidator::class)
  742. );
  743. });
  744. $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
  745. $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
  746. $manager = new \OC\CapabilitiesManager($c->getLogger());
  747. $manager->registerCapability(function () use ($c) {
  748. return new \OC\OCS\CoreCapabilities($c->getConfig());
  749. });
  750. return $manager;
  751. });
  752. $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
  753. $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
  754. $config = $c->getConfig();
  755. $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
  756. /** @var \OCP\Comments\ICommentsManagerFactory $factory */
  757. $factory = new $factoryClass($this);
  758. return $factory->getManager();
  759. });
  760. $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
  761. $this->registerService('ThemingDefaults', function(Server $c) {
  762. /*
  763. * Dark magic for autoloader.
  764. * If we do a class_exists it will try to load the class which will
  765. * make composer cache the result. Resulting in errors when enabling
  766. * the theming app.
  767. */
  768. $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
  769. if (isset($prefixes['OCA\\Theming\\'])) {
  770. $classExists = true;
  771. } else {
  772. $classExists = false;
  773. }
  774. if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
  775. return new ThemingDefaults(
  776. $c->getConfig(),
  777. $c->getL10N('theming'),
  778. $c->getURLGenerator(),
  779. $c->getAppDataDir('theming'),
  780. $c->getMemCacheFactory(),
  781. new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming'))
  782. );
  783. }
  784. return new \OC_Defaults();
  785. });
  786. $this->registerService(SCSSCacher::class, function(Server $c) {
  787. /** @var Factory $cacheFactory */
  788. $cacheFactory = $c->query(Factory::class);
  789. return new SCSSCacher(
  790. $c->getLogger(),
  791. $c->query(\OC\Files\AppData\Factory::class),
  792. $c->getURLGenerator(),
  793. $c->getConfig(),
  794. $c->getThemingDefaults(),
  795. \OC::$SERVERROOT,
  796. $cacheFactory->create('SCSS')
  797. );
  798. });
  799. $this->registerService(EventDispatcher::class, function () {
  800. return new EventDispatcher();
  801. });
  802. $this->registerAlias('EventDispatcher', EventDispatcher::class);
  803. $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
  804. $this->registerService('CryptoWrapper', function (Server $c) {
  805. // FIXME: Instantiiated here due to cyclic dependency
  806. $request = new Request(
  807. [
  808. 'get' => $_GET,
  809. 'post' => $_POST,
  810. 'files' => $_FILES,
  811. 'server' => $_SERVER,
  812. 'env' => $_ENV,
  813. 'cookies' => $_COOKIE,
  814. 'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
  815. ? $_SERVER['REQUEST_METHOD']
  816. : null,
  817. ],
  818. $c->getSecureRandom(),
  819. $c->getConfig()
  820. );
  821. return new CryptoWrapper(
  822. $c->getConfig(),
  823. $c->getCrypto(),
  824. $c->getSecureRandom(),
  825. $request
  826. );
  827. });
  828. $this->registerService('CsrfTokenManager', function (Server $c) {
  829. $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
  830. return new CsrfTokenManager(
  831. $tokenGenerator,
  832. $c->query(SessionStorage::class)
  833. );
  834. });
  835. $this->registerService(SessionStorage::class, function (Server $c) {
  836. return new SessionStorage($c->getSession());
  837. });
  838. $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
  839. return new ContentSecurityPolicyManager();
  840. });
  841. $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
  842. $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
  843. return new ContentSecurityPolicyNonceManager(
  844. $c->getCsrfTokenManager(),
  845. $c->getRequest()
  846. );
  847. });
  848. $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
  849. $config = $c->getConfig();
  850. $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
  851. /** @var \OCP\Share\IProviderFactory $factory */
  852. $factory = new $factoryClass($this);
  853. $manager = new \OC\Share20\Manager(
  854. $c->getLogger(),
  855. $c->getConfig(),
  856. $c->getSecureRandom(),
  857. $c->getHasher(),
  858. $c->getMountManager(),
  859. $c->getGroupManager(),
  860. $c->getL10N('core'),
  861. $factory,
  862. $c->getUserManager(),
  863. $c->getLazyRootFolder(),
  864. $c->getEventDispatcher()
  865. );
  866. return $manager;
  867. });
  868. $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
  869. $this->registerService('SettingsManager', function(Server $c) {
  870. $manager = new \OC\Settings\Manager(
  871. $c->getLogger(),
  872. $c->getDatabaseConnection(),
  873. $c->getL10N('lib'),
  874. $c->getConfig(),
  875. $c->getEncryptionManager(),
  876. $c->getUserManager(),
  877. $c->getLockingProvider(),
  878. $c->getRequest(),
  879. new \OC\Settings\Mapper($c->getDatabaseConnection()),
  880. $c->getURLGenerator()
  881. );
  882. return $manager;
  883. });
  884. $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
  885. return new \OC\Files\AppData\Factory(
  886. $c->getRootFolder(),
  887. $c->getSystemConfig()
  888. );
  889. });
  890. $this->registerService('LockdownManager', function (Server $c) {
  891. return new LockdownManager(function() use ($c) {
  892. return $c->getSession();
  893. });
  894. });
  895. $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
  896. return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
  897. });
  898. $this->registerService(ICloudIdManager::class, function (Server $c) {
  899. return new CloudIdManager();
  900. });
  901. /* To trick DI since we don't extend the DIContainer here */
  902. $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
  903. return new CleanPreviewsBackgroundJob(
  904. $c->getRootFolder(),
  905. $c->getLogger(),
  906. $c->getJobList(),
  907. new TimeFactory()
  908. );
  909. });
  910. $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
  911. $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
  912. $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
  913. $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
  914. $this->registerService(Defaults::class, function (Server $c) {
  915. return new Defaults(
  916. $c->getThemingDefaults()
  917. );
  918. });
  919. $this->registerAlias('Defaults', \OCP\Defaults::class);
  920. $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
  921. return $c->query(\OCP\IUserSession::class)->getSession();
  922. });
  923. $this->registerService(IShareHelper::class, function(Server $c) {
  924. return new ShareHelper(
  925. $c->query(\OCP\Share\IManager::class)
  926. );
  927. });
  928. }
  929. /**
  930. * @return \OCP\Contacts\IManager
  931. */
  932. public function getContactsManager() {
  933. return $this->query('ContactsManager');
  934. }
  935. /**
  936. * @return \OC\Encryption\Manager
  937. */
  938. public function getEncryptionManager() {
  939. return $this->query('EncryptionManager');
  940. }
  941. /**
  942. * @return \OC\Encryption\File
  943. */
  944. public function getEncryptionFilesHelper() {
  945. return $this->query('EncryptionFileHelper');
  946. }
  947. /**
  948. * @return \OCP\Encryption\Keys\IStorage
  949. */
  950. public function getEncryptionKeyStorage() {
  951. return $this->query('EncryptionKeyStorage');
  952. }
  953. /**
  954. * The current request object holding all information about the request
  955. * currently being processed is returned from this method.
  956. * In case the current execution was not initiated by a web request null is returned
  957. *
  958. * @return \OCP\IRequest
  959. */
  960. public function getRequest() {
  961. return $this->query('Request');
  962. }
  963. /**
  964. * Returns the preview manager which can create preview images for a given file
  965. *
  966. * @return \OCP\IPreview
  967. */
  968. public function getPreviewManager() {
  969. return $this->query('PreviewManager');
  970. }
  971. /**
  972. * Returns the tag manager which can get and set tags for different object types
  973. *
  974. * @see \OCP\ITagManager::load()
  975. * @return \OCP\ITagManager
  976. */
  977. public function getTagManager() {
  978. return $this->query('TagManager');
  979. }
  980. /**
  981. * Returns the system-tag manager
  982. *
  983. * @return \OCP\SystemTag\ISystemTagManager
  984. *
  985. * @since 9.0.0
  986. */
  987. public function getSystemTagManager() {
  988. return $this->query('SystemTagManager');
  989. }
  990. /**
  991. * Returns the system-tag object mapper
  992. *
  993. * @return \OCP\SystemTag\ISystemTagObjectMapper
  994. *
  995. * @since 9.0.0
  996. */
  997. public function getSystemTagObjectMapper() {
  998. return $this->query('SystemTagObjectMapper');
  999. }
  1000. /**
  1001. * Returns the avatar manager, used for avatar functionality
  1002. *
  1003. * @return \OCP\IAvatarManager
  1004. */
  1005. public function getAvatarManager() {
  1006. return $this->query('AvatarManager');
  1007. }
  1008. /**
  1009. * Returns the root folder of ownCloud's data directory
  1010. *
  1011. * @return \OCP\Files\IRootFolder
  1012. */
  1013. public function getRootFolder() {
  1014. return $this->query('LazyRootFolder');
  1015. }
  1016. /**
  1017. * Returns the root folder of ownCloud's data directory
  1018. * This is the lazy variant so this gets only initialized once it
  1019. * is actually used.
  1020. *
  1021. * @return \OCP\Files\IRootFolder
  1022. */
  1023. public function getLazyRootFolder() {
  1024. return $this->query('LazyRootFolder');
  1025. }
  1026. /**
  1027. * Returns a view to ownCloud's files folder
  1028. *
  1029. * @param string $userId user ID
  1030. * @return \OCP\Files\Folder|null
  1031. */
  1032. public function getUserFolder($userId = null) {
  1033. if ($userId === null) {
  1034. $user = $this->getUserSession()->getUser();
  1035. if (!$user) {
  1036. return null;
  1037. }
  1038. $userId = $user->getUID();
  1039. }
  1040. $root = $this->getRootFolder();
  1041. return $root->getUserFolder($userId);
  1042. }
  1043. /**
  1044. * Returns an app-specific view in ownClouds data directory
  1045. *
  1046. * @return \OCP\Files\Folder
  1047. * @deprecated since 9.2.0 use IAppData
  1048. */
  1049. public function getAppFolder() {
  1050. $dir = '/' . \OC_App::getCurrentApp();
  1051. $root = $this->getRootFolder();
  1052. if (!$root->nodeExists($dir)) {
  1053. $folder = $root->newFolder($dir);
  1054. } else {
  1055. $folder = $root->get($dir);
  1056. }
  1057. return $folder;
  1058. }
  1059. /**
  1060. * @return \OC\User\Manager
  1061. */
  1062. public function getUserManager() {
  1063. return $this->query('UserManager');
  1064. }
  1065. /**
  1066. * @return \OC\Group\Manager
  1067. */
  1068. public function getGroupManager() {
  1069. return $this->query('GroupManager');
  1070. }
  1071. /**
  1072. * @return \OC\User\Session
  1073. */
  1074. public function getUserSession() {
  1075. return $this->query('UserSession');
  1076. }
  1077. /**
  1078. * @return \OCP\ISession
  1079. */
  1080. public function getSession() {
  1081. return $this->query('UserSession')->getSession();
  1082. }
  1083. /**
  1084. * @param \OCP\ISession $session
  1085. */
  1086. public function setSession(\OCP\ISession $session) {
  1087. $this->query(SessionStorage::class)->setSession($session);
  1088. $this->query('UserSession')->setSession($session);
  1089. $this->query(Store::class)->setSession($session);
  1090. }
  1091. /**
  1092. * @return \OC\Authentication\TwoFactorAuth\Manager
  1093. */
  1094. public function getTwoFactorAuthManager() {
  1095. return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
  1096. }
  1097. /**
  1098. * @return \OC\NavigationManager
  1099. */
  1100. public function getNavigationManager() {
  1101. return $this->query('NavigationManager');
  1102. }
  1103. /**
  1104. * @return \OCP\IConfig
  1105. */
  1106. public function getConfig() {
  1107. return $this->query('AllConfig');
  1108. }
  1109. /**
  1110. * @internal For internal use only
  1111. * @return \OC\SystemConfig
  1112. */
  1113. public function getSystemConfig() {
  1114. return $this->query('SystemConfig');
  1115. }
  1116. /**
  1117. * Returns the app config manager
  1118. *
  1119. * @return \OCP\IAppConfig
  1120. */
  1121. public function getAppConfig() {
  1122. return $this->query('AppConfig');
  1123. }
  1124. /**
  1125. * @return \OCP\L10N\IFactory
  1126. */
  1127. public function getL10NFactory() {
  1128. return $this->query('L10NFactory');
  1129. }
  1130. /**
  1131. * get an L10N instance
  1132. *
  1133. * @param string $app appid
  1134. * @param string $lang
  1135. * @return IL10N
  1136. */
  1137. public function getL10N($app, $lang = null) {
  1138. return $this->getL10NFactory()->get($app, $lang);
  1139. }
  1140. /**
  1141. * @return \OCP\IURLGenerator
  1142. */
  1143. public function getURLGenerator() {
  1144. return $this->query('URLGenerator');
  1145. }
  1146. /**
  1147. * @return \OCP\IHelper
  1148. */
  1149. public function getHelper() {
  1150. return $this->query('AppHelper');
  1151. }
  1152. /**
  1153. * @return AppFetcher
  1154. */
  1155. public function getAppFetcher() {
  1156. return $this->query(AppFetcher::class);
  1157. }
  1158. /**
  1159. * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
  1160. * getMemCacheFactory() instead.
  1161. *
  1162. * @return \OCP\ICache
  1163. * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
  1164. */
  1165. public function getCache() {
  1166. return $this->query('UserCache');
  1167. }
  1168. /**
  1169. * Returns an \OCP\CacheFactory instance
  1170. *
  1171. * @return \OCP\ICacheFactory
  1172. */
  1173. public function getMemCacheFactory() {
  1174. return $this->query('MemCacheFactory');
  1175. }
  1176. /**
  1177. * Returns an \OC\RedisFactory instance
  1178. *
  1179. * @return \OC\RedisFactory
  1180. */
  1181. public function getGetRedisFactory() {
  1182. return $this->query('RedisFactory');
  1183. }
  1184. /**
  1185. * Returns the current session
  1186. *
  1187. * @return \OCP\IDBConnection
  1188. */
  1189. public function getDatabaseConnection() {
  1190. return $this->query('DatabaseConnection');
  1191. }
  1192. /**
  1193. * Returns the activity manager
  1194. *
  1195. * @return \OCP\Activity\IManager
  1196. */
  1197. public function getActivityManager() {
  1198. return $this->query('ActivityManager');
  1199. }
  1200. /**
  1201. * Returns an job list for controlling background jobs
  1202. *
  1203. * @return \OCP\BackgroundJob\IJobList
  1204. */
  1205. public function getJobList() {
  1206. return $this->query('JobList');
  1207. }
  1208. /**
  1209. * Returns a logger instance
  1210. *
  1211. * @return \OCP\ILogger
  1212. */
  1213. public function getLogger() {
  1214. return $this->query('Logger');
  1215. }
  1216. /**
  1217. * Returns a router for generating and matching urls
  1218. *
  1219. * @return \OCP\Route\IRouter
  1220. */
  1221. public function getRouter() {
  1222. return $this->query('Router');
  1223. }
  1224. /**
  1225. * Returns a search instance
  1226. *
  1227. * @return \OCP\ISearch
  1228. */
  1229. public function getSearch() {
  1230. return $this->query('Search');
  1231. }
  1232. /**
  1233. * Returns a SecureRandom instance
  1234. *
  1235. * @return \OCP\Security\ISecureRandom
  1236. */
  1237. public function getSecureRandom() {
  1238. return $this->query('SecureRandom');
  1239. }
  1240. /**
  1241. * Returns a Crypto instance
  1242. *
  1243. * @return \OCP\Security\ICrypto
  1244. */
  1245. public function getCrypto() {
  1246. return $this->query('Crypto');
  1247. }
  1248. /**
  1249. * Returns a Hasher instance
  1250. *
  1251. * @return \OCP\Security\IHasher
  1252. */
  1253. public function getHasher() {
  1254. return $this->query('Hasher');
  1255. }
  1256. /**
  1257. * Returns a CredentialsManager instance
  1258. *
  1259. * @return \OCP\Security\ICredentialsManager
  1260. */
  1261. public function getCredentialsManager() {
  1262. return $this->query('CredentialsManager');
  1263. }
  1264. /**
  1265. * Returns an instance of the HTTP helper class
  1266. *
  1267. * @deprecated Use getHTTPClientService()
  1268. * @return \OC\HTTPHelper
  1269. */
  1270. public function getHTTPHelper() {
  1271. return $this->query('HTTPHelper');
  1272. }
  1273. /**
  1274. * Get the certificate manager for the user
  1275. *
  1276. * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
  1277. * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
  1278. */
  1279. public function getCertificateManager($userId = '') {
  1280. if ($userId === '') {
  1281. $userSession = $this->getUserSession();
  1282. $user = $userSession->getUser();
  1283. if (is_null($user)) {
  1284. return null;
  1285. }
  1286. $userId = $user->getUID();
  1287. }
  1288. return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
  1289. }
  1290. /**
  1291. * Returns an instance of the HTTP client service
  1292. *
  1293. * @return \OCP\Http\Client\IClientService
  1294. */
  1295. public function getHTTPClientService() {
  1296. return $this->query('HttpClientService');
  1297. }
  1298. /**
  1299. * Create a new event source
  1300. *
  1301. * @return \OCP\IEventSource
  1302. */
  1303. public function createEventSource() {
  1304. return new \OC_EventSource();
  1305. }
  1306. /**
  1307. * Get the active event logger
  1308. *
  1309. * The returned logger only logs data when debug mode is enabled
  1310. *
  1311. * @return \OCP\Diagnostics\IEventLogger
  1312. */
  1313. public function getEventLogger() {
  1314. return $this->query('EventLogger');
  1315. }
  1316. /**
  1317. * Get the active query logger
  1318. *
  1319. * The returned logger only logs data when debug mode is enabled
  1320. *
  1321. * @return \OCP\Diagnostics\IQueryLogger
  1322. */
  1323. public function getQueryLogger() {
  1324. return $this->query('QueryLogger');
  1325. }
  1326. /**
  1327. * Get the manager for temporary files and folders
  1328. *
  1329. * @return \OCP\ITempManager
  1330. */
  1331. public function getTempManager() {
  1332. return $this->query('TempManager');
  1333. }
  1334. /**
  1335. * Get the app manager
  1336. *
  1337. * @return \OCP\App\IAppManager
  1338. */
  1339. public function getAppManager() {
  1340. return $this->query('AppManager');
  1341. }
  1342. /**
  1343. * Creates a new mailer
  1344. *
  1345. * @return \OCP\Mail\IMailer
  1346. */
  1347. public function getMailer() {
  1348. return $this->query('Mailer');
  1349. }
  1350. /**
  1351. * Get the webroot
  1352. *
  1353. * @return string
  1354. */
  1355. public function getWebRoot() {
  1356. return $this->webRoot;
  1357. }
  1358. /**
  1359. * @return \OC\OCSClient
  1360. */
  1361. public function getOcsClient() {
  1362. return $this->query('OcsClient');
  1363. }
  1364. /**
  1365. * @return \OCP\IDateTimeZone
  1366. */
  1367. public function getDateTimeZone() {
  1368. return $this->query('DateTimeZone');
  1369. }
  1370. /**
  1371. * @return \OCP\IDateTimeFormatter
  1372. */
  1373. public function getDateTimeFormatter() {
  1374. return $this->query('DateTimeFormatter');
  1375. }
  1376. /**
  1377. * @return \OCP\Files\Config\IMountProviderCollection
  1378. */
  1379. public function getMountProviderCollection() {
  1380. return $this->query('MountConfigManager');
  1381. }
  1382. /**
  1383. * Get the IniWrapper
  1384. *
  1385. * @return IniGetWrapper
  1386. */
  1387. public function getIniWrapper() {
  1388. return $this->query('IniWrapper');
  1389. }
  1390. /**
  1391. * @return \OCP\Command\IBus
  1392. */
  1393. public function getCommandBus() {
  1394. return $this->query('AsyncCommandBus');
  1395. }
  1396. /**
  1397. * Get the trusted domain helper
  1398. *
  1399. * @return TrustedDomainHelper
  1400. */
  1401. public function getTrustedDomainHelper() {
  1402. return $this->query('TrustedDomainHelper');
  1403. }
  1404. /**
  1405. * Get the locking provider
  1406. *
  1407. * @return \OCP\Lock\ILockingProvider
  1408. * @since 8.1.0
  1409. */
  1410. public function getLockingProvider() {
  1411. return $this->query('LockingProvider');
  1412. }
  1413. /**
  1414. * @return \OCP\Files\Mount\IMountManager
  1415. **/
  1416. function getMountManager() {
  1417. return $this->query('MountManager');
  1418. }
  1419. /** @return \OCP\Files\Config\IUserMountCache */
  1420. function getUserMountCache() {
  1421. return $this->query('UserMountCache');
  1422. }
  1423. /**
  1424. * Get the MimeTypeDetector
  1425. *
  1426. * @return \OCP\Files\IMimeTypeDetector
  1427. */
  1428. public function getMimeTypeDetector() {
  1429. return $this->query('MimeTypeDetector');
  1430. }
  1431. /**
  1432. * Get the MimeTypeLoader
  1433. *
  1434. * @return \OCP\Files\IMimeTypeLoader
  1435. */
  1436. public function getMimeTypeLoader() {
  1437. return $this->query('MimeTypeLoader');
  1438. }
  1439. /**
  1440. * Get the manager of all the capabilities
  1441. *
  1442. * @return \OC\CapabilitiesManager
  1443. */
  1444. public function getCapabilitiesManager() {
  1445. return $this->query('CapabilitiesManager');
  1446. }
  1447. /**
  1448. * Get the EventDispatcher
  1449. *
  1450. * @return EventDispatcherInterface
  1451. * @since 8.2.0
  1452. */
  1453. public function getEventDispatcher() {
  1454. return $this->query('EventDispatcher');
  1455. }
  1456. /**
  1457. * Get the Notification Manager
  1458. *
  1459. * @return \OCP\Notification\IManager
  1460. * @since 8.2.0
  1461. */
  1462. public function getNotificationManager() {
  1463. return $this->query('NotificationManager');
  1464. }
  1465. /**
  1466. * @return \OCP\Comments\ICommentsManager
  1467. */
  1468. public function getCommentsManager() {
  1469. return $this->query('CommentsManager');
  1470. }
  1471. /**
  1472. * @return \OCA\Theming\ThemingDefaults
  1473. */
  1474. public function getThemingDefaults() {
  1475. return $this->query('ThemingDefaults');
  1476. }
  1477. /**
  1478. * @return \OC\IntegrityCheck\Checker
  1479. */
  1480. public function getIntegrityCodeChecker() {
  1481. return $this->query('IntegrityCodeChecker');
  1482. }
  1483. /**
  1484. * @return \OC\Session\CryptoWrapper
  1485. */
  1486. public function getSessionCryptoWrapper() {
  1487. return $this->query('CryptoWrapper');
  1488. }
  1489. /**
  1490. * @return CsrfTokenManager
  1491. */
  1492. public function getCsrfTokenManager() {
  1493. return $this->query('CsrfTokenManager');
  1494. }
  1495. /**
  1496. * @return Throttler
  1497. */
  1498. public function getBruteForceThrottler() {
  1499. return $this->query('Throttler');
  1500. }
  1501. /**
  1502. * @return IContentSecurityPolicyManager
  1503. */
  1504. public function getContentSecurityPolicyManager() {
  1505. return $this->query('ContentSecurityPolicyManager');
  1506. }
  1507. /**
  1508. * @return ContentSecurityPolicyNonceManager
  1509. */
  1510. public function getContentSecurityPolicyNonceManager() {
  1511. return $this->query('ContentSecurityPolicyNonceManager');
  1512. }
  1513. /**
  1514. * Not a public API as of 8.2, wait for 9.0
  1515. *
  1516. * @return \OCA\Files_External\Service\BackendService
  1517. */
  1518. public function getStoragesBackendService() {
  1519. return $this->query('OCA\\Files_External\\Service\\BackendService');
  1520. }
  1521. /**
  1522. * Not a public API as of 8.2, wait for 9.0
  1523. *
  1524. * @return \OCA\Files_External\Service\GlobalStoragesService
  1525. */
  1526. public function getGlobalStoragesService() {
  1527. return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
  1528. }
  1529. /**
  1530. * Not a public API as of 8.2, wait for 9.0
  1531. *
  1532. * @return \OCA\Files_External\Service\UserGlobalStoragesService
  1533. */
  1534. public function getUserGlobalStoragesService() {
  1535. return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
  1536. }
  1537. /**
  1538. * Not a public API as of 8.2, wait for 9.0
  1539. *
  1540. * @return \OCA\Files_External\Service\UserStoragesService
  1541. */
  1542. public function getUserStoragesService() {
  1543. return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
  1544. }
  1545. /**
  1546. * @return \OCP\Share\IManager
  1547. */
  1548. public function getShareManager() {
  1549. return $this->query('ShareManager');
  1550. }
  1551. /**
  1552. * Returns the LDAP Provider
  1553. *
  1554. * @return \OCP\LDAP\ILDAPProvider
  1555. */
  1556. public function getLDAPProvider() {
  1557. return $this->query('LDAPProvider');
  1558. }
  1559. /**
  1560. * @return \OCP\Settings\IManager
  1561. */
  1562. public function getSettingsManager() {
  1563. return $this->query('SettingsManager');
  1564. }
  1565. /**
  1566. * @return \OCP\Files\IAppData
  1567. */
  1568. public function getAppDataDir($app) {
  1569. /** @var \OC\Files\AppData\Factory $factory */
  1570. $factory = $this->query(\OC\Files\AppData\Factory::class);
  1571. return $factory->get($app);
  1572. }
  1573. /**
  1574. * @return \OCP\Lockdown\ILockdownManager
  1575. */
  1576. public function getLockdownManager() {
  1577. return $this->query('LockdownManager');
  1578. }
  1579. /**
  1580. * @return \OCP\Federation\ICloudIdManager
  1581. */
  1582. public function getCloudIdManager() {
  1583. return $this->query(ICloudIdManager::class);
  1584. }
  1585. }