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.

1102 lines
37 KiB

10 years ago
15 years ago
10 years ago
15 years ago
15 years ago
15 years ago
15 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
11 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
Squashed commit of the following: commit ae1f68ac54cf2878d265b2bbce13bd600d2d0719 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Thu Aug 22 11:45:27 2013 +0200 fixing undefined variable commit 982f327ca10eea0a2222eae3e74210648591fd8a Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 12:00:14 2013 +0200 adding login.php as alternative for index.php/login commit da0d7e1d096fb80789524b01f0f96fe08d147943 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 11:36:12 2013 +0200 adding a route for web login commit 8e2a01160485cf7e9a2eb8bf46f06fae73956e8e Author: Karl Beecher <karl@endocode.com> Date: Tue Aug 6 17:00:28 2013 +0200 Login attempt returns true instead of exiting immediately commit fd89d55de9e71e986e03a0de9aad9407b632e22f Author: Karl Beecher <karl@endocode.com> Date: Mon Aug 5 15:31:30 2013 +0200 Further abstraction. This change introduces the ApacheBackend interface for backends that depend on Apache authentication and session management. There are no longer references to specific backends in OC_User. commit 469cfd98aea5a37985722cf5f9e00ece0ce38178 Author: Karl Beecher <karl@endocode.com> Date: Thu Aug 1 15:46:36 2013 +0200 Make login attempt function protected. commit d803515f19ff086e2028fcaa51afae579685e596 Author: Karl Beecher <karl@endocode.com> Date: Wed Jul 31 16:00:22 2013 +0200 Amends the login link When using a Shibboleth login, clicking logout displays a message to the user instead of ending the session. commit aa8c1fcea05c8268f26a10b21c4e0bc547c3414f Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 13:15:59 2013 +0200 Abstract Shibboleth authentication into an Apache authentication method commit 69082f2ebcab267f6e8eceb1a252f84c52236546 Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 11:22:26 2013 +0200 Convert spaces -> tabs commit 5a80861d86855eec5906fd5e235ac4ff12efb0f2 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:40:48 2013 +0200 Separate the authentication methods SABRE authentication and base authentication have slightly different workings right now. They should be refactored into a common method later, but time pressure requires us to reinvent the wheel slightly. commit dc20a9f8764b103b7d8c5b713f2bcdae18708b65 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:07:07 2013 +0200 Authenicate calls to WebDAV against Shibboleth. When using WebDAV, the OC_Connector_Sabre_Auth::authenticate method is normally called without trying the Shibboleth authentication... thus the session is not established. The method now tries Shib authentication, setting up a session if the user has already authenticated. commit 091e4861b2246c4084c9b30e232289fde4ba1abf Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 14:04:54 2013 +0200 Sets up the Shibboleth login attempt. commit bae710ec0579ef99b23022cc12f6876c5fe6b0d5 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 12:36:44 2013 +0200 Add a method for attempting shibboleth login. If the PHP_AUTH_USER and EPPN environment variables are set, attempt a Shibboleth (passwordless) login. commit 667d0710a7854e58fb109201d9cee6ec064e793a Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:38:04 2013 +0200 Revert "Adds the apps2 folder with user_shibboleth backend." This reverts commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef. commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:28:06 2013 +0200 Adds the apps2 folder with user_shibboleth backend. Conflicts: core/templates/layout.user.php lib/base.php
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
Squashed commit of the following: commit ae1f68ac54cf2878d265b2bbce13bd600d2d0719 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Thu Aug 22 11:45:27 2013 +0200 fixing undefined variable commit 982f327ca10eea0a2222eae3e74210648591fd8a Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 12:00:14 2013 +0200 adding login.php as alternative for index.php/login commit da0d7e1d096fb80789524b01f0f96fe08d147943 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 11:36:12 2013 +0200 adding a route for web login commit 8e2a01160485cf7e9a2eb8bf46f06fae73956e8e Author: Karl Beecher <karl@endocode.com> Date: Tue Aug 6 17:00:28 2013 +0200 Login attempt returns true instead of exiting immediately commit fd89d55de9e71e986e03a0de9aad9407b632e22f Author: Karl Beecher <karl@endocode.com> Date: Mon Aug 5 15:31:30 2013 +0200 Further abstraction. This change introduces the ApacheBackend interface for backends that depend on Apache authentication and session management. There are no longer references to specific backends in OC_User. commit 469cfd98aea5a37985722cf5f9e00ece0ce38178 Author: Karl Beecher <karl@endocode.com> Date: Thu Aug 1 15:46:36 2013 +0200 Make login attempt function protected. commit d803515f19ff086e2028fcaa51afae579685e596 Author: Karl Beecher <karl@endocode.com> Date: Wed Jul 31 16:00:22 2013 +0200 Amends the login link When using a Shibboleth login, clicking logout displays a message to the user instead of ending the session. commit aa8c1fcea05c8268f26a10b21c4e0bc547c3414f Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 13:15:59 2013 +0200 Abstract Shibboleth authentication into an Apache authentication method commit 69082f2ebcab267f6e8eceb1a252f84c52236546 Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 11:22:26 2013 +0200 Convert spaces -> tabs commit 5a80861d86855eec5906fd5e235ac4ff12efb0f2 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:40:48 2013 +0200 Separate the authentication methods SABRE authentication and base authentication have slightly different workings right now. They should be refactored into a common method later, but time pressure requires us to reinvent the wheel slightly. commit dc20a9f8764b103b7d8c5b713f2bcdae18708b65 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:07:07 2013 +0200 Authenicate calls to WebDAV against Shibboleth. When using WebDAV, the OC_Connector_Sabre_Auth::authenticate method is normally called without trying the Shibboleth authentication... thus the session is not established. The method now tries Shib authentication, setting up a session if the user has already authenticated. commit 091e4861b2246c4084c9b30e232289fde4ba1abf Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 14:04:54 2013 +0200 Sets up the Shibboleth login attempt. commit bae710ec0579ef99b23022cc12f6876c5fe6b0d5 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 12:36:44 2013 +0200 Add a method for attempting shibboleth login. If the PHP_AUTH_USER and EPPN environment variables are set, attempt a Shibboleth (passwordless) login. commit 667d0710a7854e58fb109201d9cee6ec064e793a Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:38:04 2013 +0200 Revert "Adds the apps2 folder with user_shibboleth backend." This reverts commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef. commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:28:06 2013 +0200 Adds the apps2 folder with user_shibboleth backend. Conflicts: core/templates/layout.user.php lib/base.php
12 years ago
Squashed commit of the following: commit ae1f68ac54cf2878d265b2bbce13bd600d2d0719 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Thu Aug 22 11:45:27 2013 +0200 fixing undefined variable commit 982f327ca10eea0a2222eae3e74210648591fd8a Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 12:00:14 2013 +0200 adding login.php as alternative for index.php/login commit da0d7e1d096fb80789524b01f0f96fe08d147943 Author: Thomas Müller <thomas.mueller@tmit.eu> Date: Wed Aug 7 11:36:12 2013 +0200 adding a route for web login commit 8e2a01160485cf7e9a2eb8bf46f06fae73956e8e Author: Karl Beecher <karl@endocode.com> Date: Tue Aug 6 17:00:28 2013 +0200 Login attempt returns true instead of exiting immediately commit fd89d55de9e71e986e03a0de9aad9407b632e22f Author: Karl Beecher <karl@endocode.com> Date: Mon Aug 5 15:31:30 2013 +0200 Further abstraction. This change introduces the ApacheBackend interface for backends that depend on Apache authentication and session management. There are no longer references to specific backends in OC_User. commit 469cfd98aea5a37985722cf5f9e00ece0ce38178 Author: Karl Beecher <karl@endocode.com> Date: Thu Aug 1 15:46:36 2013 +0200 Make login attempt function protected. commit d803515f19ff086e2028fcaa51afae579685e596 Author: Karl Beecher <karl@endocode.com> Date: Wed Jul 31 16:00:22 2013 +0200 Amends the login link When using a Shibboleth login, clicking logout displays a message to the user instead of ending the session. commit aa8c1fcea05c8268f26a10b21c4e0bc547c3414f Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 13:15:59 2013 +0200 Abstract Shibboleth authentication into an Apache authentication method commit 69082f2ebcab267f6e8eceb1a252f84c52236546 Author: Karl Beecher <karl@endocode.com> Date: Tue Jul 30 11:22:26 2013 +0200 Convert spaces -> tabs commit 5a80861d86855eec5906fd5e235ac4ff12efb0f2 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:40:48 2013 +0200 Separate the authentication methods SABRE authentication and base authentication have slightly different workings right now. They should be refactored into a common method later, but time pressure requires us to reinvent the wheel slightly. commit dc20a9f8764b103b7d8c5b713f2bcdae18708b65 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 17:07:07 2013 +0200 Authenicate calls to WebDAV against Shibboleth. When using WebDAV, the OC_Connector_Sabre_Auth::authenticate method is normally called without trying the Shibboleth authentication... thus the session is not established. The method now tries Shib authentication, setting up a session if the user has already authenticated. commit 091e4861b2246c4084c9b30e232289fde4ba1abf Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 14:04:54 2013 +0200 Sets up the Shibboleth login attempt. commit bae710ec0579ef99b23022cc12f6876c5fe6b0d5 Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 12:36:44 2013 +0200 Add a method for attempting shibboleth login. If the PHP_AUTH_USER and EPPN environment variables are set, attempt a Shibboleth (passwordless) login. commit 667d0710a7854e58fb109201d9cee6ec064e793a Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:38:04 2013 +0200 Revert "Adds the apps2 folder with user_shibboleth backend." This reverts commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef. commit 7abbdb64676d667b0c69aca37becdc47e56dc7ef Author: Karl Beecher <karl@endocode.com> Date: Mon Jul 29 11:28:06 2013 +0200 Adds the apps2 folder with user_shibboleth backend. Conflicts: core/templates/layout.user.php lib/base.php
12 years ago
13 years ago
13 years ago
11 years ago
13 years ago
13 years ago
12 years ago
13 years ago
11 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. <?php
  2. /**
  3. * @author Adam Williamson <awilliam@redhat.com>
  4. * @author Andreas Fischer <bantu@owncloud.com>
  5. * @author Arthur Schiwon <blizzz@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Björn Schießle <schiessle@owncloud.com>
  9. * @author Christopher Schäpers <kondou@ts.unde.re>
  10. * @author davidgumberg <davidnoizgumberg@gmail.com>
  11. * @author Florian Scholz <FlorianScholz@bgstyle.de>
  12. * @author Florin Peter <github@florin-peter.de>
  13. * @author Frank Karlitschek <frank@owncloud.org>
  14. * @author Georg Ehrke <georg@owncloud.com>
  15. * @author Hugo Gonzalez Labrador <hglavra@gmail.com>
  16. * @author Individual IT Services <info@individual-it.net>
  17. * @author Jakob Sack <mail@jakobsack.de>
  18. * @author Joachim Bauch <bauch@struktur.de>
  19. * @author Joas Schilling <nickvergessen@owncloud.com>
  20. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  21. * @author Lukas Reschke <lukas@owncloud.com>
  22. * @author marc0s <marcos@tenak.net>
  23. * @author Martin Mattel <martin.mattel@diemattels.at>
  24. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  25. * @author Morris Jobke <hey@morrisjobke.de>
  26. * @author Owen Winkler <a_github@midnightcircus.com>
  27. * @author Phil Davis <phil.davis@inf.org>
  28. * @author Ramiro Aparicio <rapariciog@gmail.com>
  29. * @author Robin Appelman <icewind@owncloud.com>
  30. * @author Robin McCorkell <robin@mccorkell.me.uk>
  31. * @author Roeland Jago Douma <rullzer@owncloud.com>
  32. * @author scolebrook <scolebrook@mac.com>
  33. * @author Thomas Müller <thomas.mueller@tmit.eu>
  34. * @author Thomas Tanghus <thomas@tanghus.net>
  35. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  36. * @author Vincent Petry <pvince81@owncloud.com>
  37. * @author Volkan Gezer <volkangezer@gmail.com>
  38. *
  39. * @copyright Copyright (c) 2016, ownCloud, Inc.
  40. * @license AGPL-3.0
  41. *
  42. * This code is free software: you can redistribute it and/or modify
  43. * it under the terms of the GNU Affero General Public License, version 3,
  44. * as published by the Free Software Foundation.
  45. *
  46. * This program is distributed in the hope that it will be useful,
  47. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  48. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  49. * GNU Affero General Public License for more details.
  50. *
  51. * You should have received a copy of the GNU Affero General Public License, version 3,
  52. * along with this program. If not, see <http://www.gnu.org/licenses/>
  53. *
  54. */
  55. require_once 'public/constants.php';
  56. /**
  57. * Class that is a namespace for all global OC variables
  58. * No, we can not put this class in its own file because it is used by
  59. * OC_autoload!
  60. */
  61. class OC {
  62. /**
  63. * Associative array for autoloading. classname => filename
  64. */
  65. public static $CLASSPATH = array();
  66. /**
  67. * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
  68. */
  69. public static $SERVERROOT = '';
  70. /**
  71. * the current request path relative to the owncloud root (e.g. files/index.php)
  72. */
  73. private static $SUBURI = '';
  74. /**
  75. * the owncloud root path for http requests (e.g. owncloud/)
  76. */
  77. public static $WEBROOT = '';
  78. /**
  79. * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
  80. */
  81. public static $THIRDPARTYROOT = '';
  82. /**
  83. * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
  84. */
  85. public static $THIRDPARTYWEBROOT = '';
  86. /**
  87. * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
  88. * web path in 'url'
  89. */
  90. public static $APPSROOTS = array();
  91. public static $configDir;
  92. /**
  93. * requested app
  94. */
  95. public static $REQUESTEDAPP = '';
  96. /**
  97. * check if ownCloud runs in cli mode
  98. */
  99. public static $CLI = false;
  100. /**
  101. * @var \OC\Autoloader $loader
  102. */
  103. public static $loader = null;
  104. /**
  105. * @var \OC\Server
  106. */
  107. public static $server = null;
  108. /**
  109. * @var \OC\Config
  110. */
  111. private static $config = null;
  112. /**
  113. * @throws \RuntimeException when the 3rdparty directory is missing or
  114. * the app path list is empty or contains an invalid path
  115. */
  116. public static function initPaths() {
  117. if(defined('PHPUNIT_CONFIG_DIR')) {
  118. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  119. } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  120. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  121. } else {
  122. self::$configDir = OC::$SERVERROOT . '/config/';
  123. }
  124. self::$config = new \OC\Config(self::$configDir);
  125. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  126. /**
  127. * FIXME: The following lines are required because we can't yet instantiiate
  128. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  129. */
  130. $params = [
  131. 'server' => [
  132. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  133. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  134. ],
  135. ];
  136. $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
  137. $scriptName = $fakeRequest->getScriptName();
  138. if (substr($scriptName, -1) == '/') {
  139. $scriptName .= 'index.php';
  140. //make sure suburi follows the same rules as scriptName
  141. if (substr(OC::$SUBURI, -9) != 'index.php') {
  142. if (substr(OC::$SUBURI, -1) != '/') {
  143. OC::$SUBURI = OC::$SUBURI . '/';
  144. }
  145. OC::$SUBURI = OC::$SUBURI . 'index.php';
  146. }
  147. }
  148. if (OC::$CLI) {
  149. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  150. } else {
  151. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  152. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  153. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  154. OC::$WEBROOT = '/' . OC::$WEBROOT;
  155. }
  156. } else {
  157. // The scriptName is not ending with OC::$SUBURI
  158. // This most likely means that we are calling from CLI.
  159. // However some cron jobs still need to generate
  160. // a web URL, so we use overwritewebroot as a fallback.
  161. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  162. }
  163. // Resolve /owncloud to /owncloud/ to ensure to always have a trailing
  164. // slash which is required by URL generation.
  165. if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  166. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  167. header('Location: '.\OC::$WEBROOT.'/');
  168. exit();
  169. }
  170. }
  171. // search the 3rdparty folder
  172. OC::$THIRDPARTYROOT = self::$config->getValue('3rdpartyroot', null);
  173. OC::$THIRDPARTYWEBROOT = self::$config->getValue('3rdpartyurl', null);
  174. if (empty(OC::$THIRDPARTYROOT) && empty(OC::$THIRDPARTYWEBROOT)) {
  175. if (file_exists(OC::$SERVERROOT . '/3rdparty')) {
  176. OC::$THIRDPARTYROOT = OC::$SERVERROOT;
  177. OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
  178. } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
  179. OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
  180. OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
  181. }
  182. }
  183. if (empty(OC::$THIRDPARTYROOT) || !file_exists(OC::$THIRDPARTYROOT)) {
  184. throw new \RuntimeException('3rdparty directory not found! Please put the ownCloud 3rdparty'
  185. . ' folder in the ownCloud folder or the folder above.'
  186. . ' You can also configure the location in the config.php file.');
  187. }
  188. // search the apps folder
  189. $config_paths = self::$config->getValue('apps_paths', array());
  190. if (!empty($config_paths)) {
  191. foreach ($config_paths as $paths) {
  192. if (isset($paths['url']) && isset($paths['path'])) {
  193. $paths['url'] = rtrim($paths['url'], '/');
  194. $paths['path'] = rtrim($paths['path'], '/');
  195. OC::$APPSROOTS[] = $paths;
  196. }
  197. }
  198. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  199. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  200. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  201. OC::$APPSROOTS[] = array(
  202. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  203. 'url' => '/apps',
  204. 'writable' => true
  205. );
  206. }
  207. if (empty(OC::$APPSROOTS)) {
  208. throw new \RuntimeException('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
  209. . ' or the folder above. You can also configure the location in the config.php file.');
  210. }
  211. $paths = array();
  212. foreach (OC::$APPSROOTS as $path) {
  213. $paths[] = $path['path'];
  214. if (!is_dir($path['path'])) {
  215. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the ownCloud apps folder in the'
  216. . ' ownCloud folder or the folder above. You can also configure the location in the'
  217. . ' config.php file.', $path['path']));
  218. }
  219. }
  220. // set the right include path
  221. set_include_path(
  222. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  223. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  224. OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
  225. implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
  226. get_include_path() . PATH_SEPARATOR .
  227. OC::$SERVERROOT
  228. );
  229. }
  230. public static function checkConfig() {
  231. $l = \OC::$server->getL10N('lib');
  232. // Create config if it does not already exist
  233. $configFilePath = self::$configDir .'/config.php';
  234. if(!file_exists($configFilePath)) {
  235. @touch($configFilePath);
  236. }
  237. // Check if config is writable
  238. $configFileWritable = is_writable($configFilePath);
  239. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  240. || !$configFileWritable && self::checkUpgrade(false)) {
  241. $urlGenerator = \OC::$server->getURLGenerator();
  242. if (self::$CLI) {
  243. echo $l->t('Cannot write into "config" directory!')."\n";
  244. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  245. echo "\n";
  246. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
  247. exit;
  248. } else {
  249. OC_Template::printErrorPage(
  250. $l->t('Cannot write into "config" directory!'),
  251. $l->t('This can usually be fixed by '
  252. . '%sgiving the webserver write access to the config directory%s.',
  253. array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
  254. );
  255. }
  256. }
  257. }
  258. public static function checkInstalled() {
  259. if (defined('OC_CONSOLE')) {
  260. return;
  261. }
  262. // Redirect to installer if not installed
  263. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
  264. if (OC::$CLI) {
  265. throw new Exception('Not installed');
  266. } else {
  267. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  268. header('Location: ' . $url);
  269. }
  270. exit();
  271. }
  272. }
  273. public static function checkMaintenanceMode() {
  274. // Allow ajax update script to execute without being stopped
  275. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  276. // send http status 503
  277. header('HTTP/1.1 503 Service Temporarily Unavailable');
  278. header('Status: 503 Service Temporarily Unavailable');
  279. header('Retry-After: 120');
  280. // render error page
  281. $template = new OC_Template('', 'update.user', 'guest');
  282. OC_Util::addscript('maintenance-check');
  283. $template->printPage();
  284. die();
  285. }
  286. }
  287. public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
  288. if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
  289. return;
  290. }
  291. $user = OC_User::getUserSession()->getUser();
  292. if ($user) {
  293. $group = \OC::$server->getGroupManager()->get('admin');
  294. if ($group->inGroup($user)) {
  295. return;
  296. }
  297. } else {
  298. if(!$lockIfNoUserLoggedIn) {
  299. return;
  300. }
  301. }
  302. // send http status 503
  303. header('HTTP/1.1 503 Service Temporarily Unavailable');
  304. header('Status: 503 Service Temporarily Unavailable');
  305. header('Retry-After: 120');
  306. // render error page
  307. $template = new OC_Template('', 'singleuser.user', 'guest');
  308. $template->printPage();
  309. die();
  310. }
  311. /**
  312. * Checks if the version requires an update and shows
  313. * @param bool $showTemplate Whether an update screen should get shown
  314. * @return bool|void
  315. */
  316. public static function checkUpgrade($showTemplate = true) {
  317. if (\OCP\Util::needUpgrade()) {
  318. $systemConfig = \OC::$server->getSystemConfig();
  319. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  320. self::printUpgradePage();
  321. exit();
  322. } else {
  323. return true;
  324. }
  325. }
  326. return false;
  327. }
  328. /**
  329. * Prints the upgrade page
  330. */
  331. private static function printUpgradePage() {
  332. $systemConfig = \OC::$server->getSystemConfig();
  333. $oldTheme = $systemConfig->getValue('theme');
  334. $systemConfig->setValue('theme', '');
  335. \OCP\Util::addScript('config'); // needed for web root
  336. \OCP\Util::addScript('update');
  337. // check whether this is a core update or apps update
  338. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  339. $currentVersion = implode('.', \OCP\Util::getVersion());
  340. $appManager = \OC::$server->getAppManager();
  341. $tmpl = new OC_Template('', 'update.admin', 'guest');
  342. $tmpl->assign('version', OC_Util::getVersionString());
  343. // if not a core upgrade, then it's apps upgrade
  344. if (version_compare($currentVersion, $installedVersion, '=')) {
  345. $tmpl->assign('isAppsOnlyUpgrade', true);
  346. } else {
  347. $tmpl->assign('isAppsOnlyUpgrade', false);
  348. }
  349. // get third party apps
  350. $ocVersion = \OCP\Util::getVersion();
  351. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  352. $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
  353. $tmpl->assign('productName', 'ownCloud'); // for now
  354. $tmpl->assign('oldTheme', $oldTheme);
  355. $tmpl->printPage();
  356. }
  357. public static function initSession() {
  358. // prevents javascript from accessing php session cookies
  359. ini_set('session.cookie_httponly', true);
  360. // set the cookie path to the ownCloud directory
  361. $cookie_path = OC::$WEBROOT ? : '/';
  362. ini_set('session.cookie_path', $cookie_path);
  363. // Let the session name be changed in the initSession Hook
  364. $sessionName = OC_Util::getInstanceId();
  365. try {
  366. // Allow session apps to create a custom session object
  367. $useCustomSession = false;
  368. $session = self::$server->getSession();
  369. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  370. if (!$useCustomSession) {
  371. // set the session name to the instance id - which is unique
  372. $session = new \OC\Session\Internal($sessionName);
  373. }
  374. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  375. $session = $cryptoWrapper->wrapSession($session);
  376. self::$server->setSession($session);
  377. // if session cant be started break with http 500 error
  378. } catch (Exception $e) {
  379. \OCP\Util::logException('base', $e);
  380. //show the user a detailed error page
  381. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  382. OC_Template::printExceptionErrorPage($e);
  383. die();
  384. }
  385. $sessionLifeTime = self::getSessionLifeTime();
  386. // session timeout
  387. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  388. if (isset($_COOKIE[session_name()])) {
  389. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  390. }
  391. $session->clear();
  392. }
  393. $session->set('LAST_ACTIVITY', time());
  394. }
  395. /**
  396. * @return string
  397. */
  398. private static function getSessionLifeTime() {
  399. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  400. }
  401. public static function loadAppClassPaths() {
  402. foreach (OC_APP::getEnabledApps() as $app) {
  403. $appPath = OC_App::getAppPath($app);
  404. if ($appPath === false) {
  405. continue;
  406. }
  407. $file = $appPath . '/appinfo/classpath.php';
  408. if (file_exists($file)) {
  409. require_once $file;
  410. }
  411. }
  412. }
  413. /**
  414. * Try to set some values to the required ownCloud default
  415. */
  416. public static function setRequiredIniValues() {
  417. @ini_set('default_charset', 'UTF-8');
  418. @ini_set('gd.jpeg_ignore_warning', 1);
  419. }
  420. public static function init() {
  421. // calculate the root directories
  422. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  423. // register autoloader
  424. $loaderStart = microtime(true);
  425. require_once __DIR__ . '/autoloader.php';
  426. self::$loader = new \OC\Autoloader([
  427. OC::$SERVERROOT . '/lib',
  428. OC::$SERVERROOT . '/core',
  429. OC::$SERVERROOT . '/settings',
  430. OC::$SERVERROOT . '/ocs',
  431. OC::$SERVERROOT . '/ocs-provider',
  432. ]);
  433. if (defined('PHPUNIT_RUN')) {
  434. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  435. }
  436. spl_autoload_register(array(self::$loader, 'load'));
  437. $loaderEnd = microtime(true);
  438. self::$CLI = (php_sapi_name() == 'cli');
  439. try {
  440. self::initPaths();
  441. // setup 3rdparty autoloader
  442. $vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
  443. if (!file_exists($vendorAutoLoad)) {
  444. throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
  445. }
  446. require_once $vendorAutoLoad;
  447. } catch (\RuntimeException $e) {
  448. if (!self::$CLI) {
  449. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  450. }
  451. // we can't use the template error page here, because this needs the
  452. // DI container which isn't available yet
  453. print($e->getMessage());
  454. exit();
  455. }
  456. // Add default composer PSR-4 autoloader
  457. require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  458. // setup the basic server
  459. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  460. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  461. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  462. // Don't display errors and log them
  463. error_reporting(E_ALL | E_STRICT);
  464. @ini_set('display_errors', 0);
  465. @ini_set('log_errors', 1);
  466. date_default_timezone_set('UTC');
  467. //try to configure php to enable big file uploads.
  468. //this doesn´t work always depending on the webserver and php configuration.
  469. //Let´s try to overwrite some defaults anyway
  470. //try to set the maximum execution time to 60min
  471. @set_time_limit(3600);
  472. @ini_set('max_execution_time', 3600);
  473. @ini_set('max_input_time', 3600);
  474. //try to set the maximum filesize to 10G
  475. @ini_set('upload_max_filesize', '10G');
  476. @ini_set('post_max_size', '10G');
  477. @ini_set('file_uploads', '50');
  478. self::setRequiredIniValues();
  479. self::handleAuthHeaders();
  480. self::registerAutoloaderCache();
  481. // initialize intl fallback is necessary
  482. \Patchwork\Utf8\Bootup::initIntl();
  483. OC_Util::isSetLocaleWorking();
  484. if (!defined('PHPUNIT_RUN')) {
  485. $logger = \OC::$server->getLogger();
  486. OC\Log\ErrorHandler::setLogger($logger);
  487. if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
  488. OC\Log\ErrorHandler::register(true);
  489. set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
  490. } else {
  491. OC\Log\ErrorHandler::register();
  492. }
  493. }
  494. // register the stream wrappers
  495. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  496. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  497. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  498. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  499. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  500. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  501. OC_App::loadApps(array('session'));
  502. if (!self::$CLI) {
  503. self::initSession();
  504. }
  505. \OC::$server->getEventLogger()->end('init_session');
  506. self::checkConfig();
  507. self::checkInstalled();
  508. OC_Response::addSecurityHeaders();
  509. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  510. ini_set('session.cookie_secure', true);
  511. }
  512. if (!defined('OC_CONSOLE')) {
  513. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  514. if (count($errors) > 0) {
  515. if (self::$CLI) {
  516. // Convert l10n string into regular string for usage in database
  517. $staticErrors = [];
  518. foreach ($errors as $error) {
  519. echo $error['error'] . "\n";
  520. echo $error['hint'] . "\n\n";
  521. $staticErrors[] = [
  522. 'error' => (string)$error['error'],
  523. 'hint' => (string)$error['hint'],
  524. ];
  525. }
  526. try {
  527. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  528. } catch (\Exception $e) {
  529. echo('Writing to database failed');
  530. }
  531. exit(1);
  532. } else {
  533. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  534. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  535. exit;
  536. }
  537. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  538. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  539. }
  540. }
  541. //try to set the session lifetime
  542. $sessionLifeTime = self::getSessionLifeTime();
  543. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  544. $systemConfig = \OC::$server->getSystemConfig();
  545. // User and Groups
  546. if (!$systemConfig->getValue("installed", false)) {
  547. self::$server->getSession()->set('user_id', '');
  548. }
  549. OC_User::useBackend(new OC_User_Database());
  550. OC_Group::useBackend(new OC_Group_Database());
  551. // Subscribe to the hook
  552. \OCP\Util::connectHook(
  553. '\OCA\Files_Sharing\API\Server2Server',
  554. 'preLoginNameUsedAsUserName',
  555. '\OC_User_Database',
  556. 'preLoginNameUsedAsUserName'
  557. );
  558. //setup extra user backends
  559. if (!self::checkUpgrade(false)) {
  560. OC_User::setupBackends();
  561. }
  562. self::registerCacheHooks();
  563. self::registerFilesystemHooks();
  564. if ($systemConfig->getValue('enable_previews', true)) {
  565. self::registerPreviewHooks();
  566. }
  567. self::registerShareHooks();
  568. self::registerLogRotate();
  569. self::registerEncryptionWrapper();
  570. self::registerEncryptionHooks();
  571. //make sure temporary files are cleaned up
  572. $tmpManager = \OC::$server->getTempManager();
  573. register_shutdown_function(array($tmpManager, 'clean'));
  574. $lockProvider = \OC::$server->getLockingProvider();
  575. register_shutdown_function(array($lockProvider, 'releaseAll'));
  576. // Check whether the sample configuration has been copied
  577. if($systemConfig->getValue('copied_sample_config', false)) {
  578. $l = \OC::$server->getL10N('lib');
  579. header('HTTP/1.1 503 Service Temporarily Unavailable');
  580. header('Status: 503 Service Temporarily Unavailable');
  581. OC_Template::printErrorPage(
  582. $l->t('Sample configuration detected'),
  583. $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
  584. );
  585. return;
  586. }
  587. $request = \OC::$server->getRequest();
  588. $host = $request->getInsecureServerHost();
  589. /**
  590. * if the host passed in headers isn't trusted
  591. * FIXME: Should not be in here at all :see_no_evil:
  592. */
  593. if (!OC::$CLI
  594. // overwritehost is always trusted, workaround to not have to make
  595. // \OC\AppFramework\Http\Request::getOverwriteHost public
  596. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  597. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  598. && self::$server->getConfig()->getSystemValue('installed', false)
  599. ) {
  600. header('HTTP/1.1 400 Bad Request');
  601. header('Status: 400 Bad Request');
  602. \OC::$server->getLogger()->warning(
  603. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  604. [
  605. 'app' => 'core',
  606. 'remoteAddress' => $request->getRemoteAddress(),
  607. 'host' => $host,
  608. ]
  609. );
  610. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  611. $tmpl->assign('domain', $host);
  612. $tmpl->printPage();
  613. exit();
  614. }
  615. \OC::$server->getEventLogger()->end('boot');
  616. }
  617. /**
  618. * register hooks for the cache
  619. */
  620. public static function registerCacheHooks() {
  621. //don't try to do this before we are properly setup
  622. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  623. // NOTE: This will be replaced to use OCP
  624. $userSession = self::$server->getUserSession();
  625. $userSession->listen('\OC\User', 'postLogin', function () {
  626. try {
  627. $cache = new \OC\Cache\File();
  628. $cache->gc();
  629. } catch (\OC\ServerNotAvailableException $e) {
  630. // not a GC exception, pass it on
  631. throw $e;
  632. } catch (\Exception $e) {
  633. // a GC exception should not prevent users from using OC,
  634. // so log the exception
  635. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  636. }
  637. });
  638. }
  639. }
  640. private static function registerEncryptionWrapper() {
  641. $manager = self::$server->getEncryptionManager();
  642. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  643. }
  644. private static function registerEncryptionHooks() {
  645. $enabled = self::$server->getEncryptionManager()->isEnabled();
  646. if ($enabled) {
  647. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  648. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  649. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  650. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  651. }
  652. }
  653. /**
  654. * register hooks for the cache
  655. */
  656. public static function registerLogRotate() {
  657. $systemConfig = \OC::$server->getSystemConfig();
  658. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  659. //don't try to do this before we are properly setup
  660. //use custom logfile path if defined, otherwise use default of owncloud.log in data directory
  661. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
  662. }
  663. }
  664. /**
  665. * register hooks for the filesystem
  666. */
  667. public static function registerFilesystemHooks() {
  668. // Check for blacklisted files
  669. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  670. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  671. }
  672. /**
  673. * register hooks for previews
  674. */
  675. public static function registerPreviewHooks() {
  676. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  677. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  678. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  679. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  680. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  681. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  682. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  683. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  684. }
  685. /**
  686. * register hooks for sharing
  687. */
  688. public static function registerShareHooks() {
  689. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  690. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
  691. OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
  692. OC_Hook::connect('OC_Group', 'pre_addToGroup', 'OC\Share\Hooks', 'pre_addToGroup');
  693. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
  694. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
  695. }
  696. }
  697. protected static function registerAutoloaderCache() {
  698. // The class loader takes an optional low-latency cache, which MUST be
  699. // namespaced. The instanceid is used for namespacing, but might be
  700. // unavailable at this point. Futhermore, it might not be possible to
  701. // generate an instanceid via \OC_Util::getInstanceId() because the
  702. // config file may not be writable. As such, we only register a class
  703. // loader cache if instanceid is available without trying to create one.
  704. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  705. if ($instanceId) {
  706. try {
  707. $memcacheFactory = \OC::$server->getMemCacheFactory();
  708. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  709. } catch (\Exception $ex) {
  710. }
  711. }
  712. }
  713. /**
  714. * Handle the request
  715. */
  716. public static function handleRequest() {
  717. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  718. $systemConfig = \OC::$server->getSystemConfig();
  719. // load all the classpaths from the enabled apps so they are available
  720. // in the routing files of each app
  721. OC::loadAppClassPaths();
  722. // Check if ownCloud is installed or in maintenance (update) mode
  723. if (!$systemConfig->getValue('installed', false)) {
  724. \OC::$server->getSession()->clear();
  725. $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  726. \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
  727. \OC::$server->getSecureRandom());
  728. $controller = new OC\Core\Controller\SetupController($setupHelper);
  729. $controller->run($_POST);
  730. exit();
  731. }
  732. $request = \OC::$server->getRequest();
  733. $requestPath = $request->getRawPathInfo();
  734. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  735. self::checkMaintenanceMode();
  736. self::checkUpgrade();
  737. }
  738. // emergency app disabling
  739. if ($requestPath === '/disableapp'
  740. && $request->getMethod() === 'POST'
  741. && ((string)$request->getParam('appid')) !== ''
  742. ) {
  743. \OCP\JSON::callCheck();
  744. \OCP\JSON::checkAdminUser();
  745. $appId = (string)$request->getParam('appid');
  746. $appId = \OC_App::cleanAppId($appId);
  747. \OC_App::disable($appId);
  748. \OC_JSON::success();
  749. exit();
  750. }
  751. // Always load authentication apps
  752. OC_App::loadApps(['authentication']);
  753. // Load minimum set of apps
  754. if (!self::checkUpgrade(false)
  755. && !$systemConfig->getValue('maintenance', false)) {
  756. // For logged-in users: Load everything
  757. if(OC_User::isLoggedIn()) {
  758. OC_App::loadApps();
  759. } else {
  760. // For guests: Load only filesystem and logging
  761. OC_App::loadApps(array('filesystem', 'logging'));
  762. \OC_User::tryBasicAuthLogin();
  763. }
  764. }
  765. if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
  766. try {
  767. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  768. OC_App::loadApps(array('filesystem', 'logging'));
  769. OC_App::loadApps();
  770. }
  771. self::checkSingleUserMode();
  772. OC_Util::setupFS();
  773. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  774. return;
  775. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  776. //header('HTTP/1.0 404 Not Found');
  777. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  778. OC_Response::setStatus(405);
  779. return;
  780. }
  781. }
  782. // Handle redirect URL for logged in users
  783. if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
  784. $location = \OC::$server->getURLGenerator()->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  785. // Deny the redirect if the URL contains a @
  786. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  787. if (strpos($location, '@') === false) {
  788. header('Location: ' . $location);
  789. return;
  790. }
  791. }
  792. // Handle WebDAV
  793. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  794. // not allowed any more to prevent people
  795. // mounting this root directly.
  796. // Users need to mount remote.php/webdav instead.
  797. header('HTTP/1.1 405 Method Not Allowed');
  798. header('Status: 405 Method Not Allowed');
  799. return;
  800. }
  801. // Redirect to index if the logout link is accessed without valid session
  802. // this is needed to prevent "Token expired" messages while login if a session is expired
  803. // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
  804. if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
  805. header("Location: " . \OC::$server->getURLGenerator()->getAbsoluteURL('/'));
  806. return;
  807. }
  808. // Someone is logged in
  809. if (OC_User::isLoggedIn()) {
  810. OC_App::loadApps();
  811. OC_User::setupBackends();
  812. OC_Util::setupFS();
  813. if (isset($_GET["logout"]) and ($_GET["logout"])) {
  814. OC_JSON::callCheck();
  815. if (isset($_COOKIE['oc_token'])) {
  816. \OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
  817. }
  818. OC_User::logout();
  819. // redirect to webroot and add slash if webroot is empty
  820. header("Location: " . \OC::$server->getURLGenerator()->getAbsoluteURL('/'));
  821. } else {
  822. // Redirect to default application
  823. OC_Util::redirectToDefaultPage();
  824. }
  825. } else {
  826. // Not handled and not logged in
  827. self::handleLogin();
  828. }
  829. }
  830. protected static function handleAuthHeaders() {
  831. //copy http auth headers for apache+php-fcgid work around
  832. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  833. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  834. }
  835. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  836. $vars = array(
  837. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  838. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  839. );
  840. foreach ($vars as $var) {
  841. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  842. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  843. $_SERVER['PHP_AUTH_USER'] = $name;
  844. $_SERVER['PHP_AUTH_PW'] = $password;
  845. break;
  846. }
  847. }
  848. }
  849. protected static function handleLogin() {
  850. OC_App::loadApps(array('prelogin'));
  851. $error = array();
  852. $messages = [];
  853. try {
  854. // auth possible via apache module?
  855. if (OC::tryApacheAuth()) {
  856. $error[] = 'apacheauthfailed';
  857. } // remember was checked after last login
  858. elseif (OC::tryRememberLogin()) {
  859. $error[] = 'invalidcookie';
  860. } // logon via web form
  861. elseif (OC::tryFormLogin()) {
  862. $error[] = 'invalidpassword';
  863. }
  864. } catch (\OC\User\LoginException $e) {
  865. $messages[] = $e->getMessage();
  866. } catch (\Exception $ex) {
  867. \OCP\Util::logException('handleLogin', $ex);
  868. // do not disclose information. show generic error
  869. $error[] = 'internalexception';
  870. }
  871. OC_Util::displayLoginPage(array_unique($error), $messages);
  872. }
  873. /**
  874. * Remove outdated and therefore invalid tokens for a user
  875. * @param string $user
  876. */
  877. protected static function cleanupLoginTokens($user) {
  878. $config = \OC::$server->getConfig();
  879. $cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  880. $tokens = $config->getUserKeys($user, 'login_token');
  881. foreach ($tokens as $token) {
  882. $time = $config->getUserValue($user, 'login_token', $token);
  883. if ($time < $cutoff) {
  884. $config->deleteUserValue($user, 'login_token', $token);
  885. }
  886. }
  887. }
  888. /**
  889. * Try to login a user via HTTP authentication
  890. * @return bool|void
  891. */
  892. protected static function tryApacheAuth() {
  893. $return = OC_User::handleApacheAuth();
  894. // if return is true we are logged in -> redirect to the default page
  895. if ($return === true) {
  896. $_REQUEST['redirect_url'] = \OC::$server->getRequest()->getRequestUri();
  897. OC_Util::redirectToDefaultPage();
  898. exit;
  899. }
  900. // in case $return is null apache based auth is not enabled
  901. return is_null($return) ? false : true;
  902. }
  903. /**
  904. * Try to login a user using the remember me cookie.
  905. * @return bool Whether the provided cookie was valid
  906. */
  907. protected static function tryRememberLogin() {
  908. if (!isset($_COOKIE["oc_remember_login"])
  909. || !isset($_COOKIE["oc_token"])
  910. || !isset($_COOKIE["oc_username"])
  911. || !$_COOKIE["oc_remember_login"]
  912. || !OC_Util::rememberLoginAllowed()
  913. ) {
  914. return false;
  915. }
  916. if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
  917. \OCP\Util::writeLog('core', 'Trying to login from cookie', \OCP\Util::DEBUG);
  918. }
  919. if(OC_User::userExists($_COOKIE['oc_username'])) {
  920. self::cleanupLoginTokens($_COOKIE['oc_username']);
  921. // verify whether the supplied "remember me" token was valid
  922. $granted = OC_User::loginWithCookie(
  923. $_COOKIE['oc_username'], $_COOKIE['oc_token']);
  924. if($granted === true) {
  925. OC_Util::redirectToDefaultPage();
  926. // doesn't return
  927. }
  928. \OCP\Util::writeLog('core', 'Authentication cookie rejected for user ' .
  929. $_COOKIE['oc_username'], \OCP\Util::WARN);
  930. // if you reach this point you have changed your password
  931. // or you are an attacker
  932. // we can not delete tokens here because users may reach
  933. // this point multiple times after a password change
  934. }
  935. OC_User::unsetMagicInCookie();
  936. return true;
  937. }
  938. /**
  939. * Tries to login a user using the form based authentication
  940. * @return bool|void
  941. */
  942. protected static function tryFormLogin() {
  943. if (!isset($_POST["user"]) || !isset($_POST['password'])) {
  944. return false;
  945. }
  946. if(!(\OC::$server->getRequest()->passesCSRFCheck())) {
  947. return false;
  948. }
  949. OC_App::loadApps();
  950. //setup extra user backends
  951. OC_User::setupBackends();
  952. if (OC_User::login((string)$_POST["user"], (string)$_POST["password"])) {
  953. $userId = OC_User::getUser();
  954. // setting up the time zone
  955. if (isset($_POST['timezone-offset'])) {
  956. self::$server->getSession()->set('timezone', (string)$_POST['timezone-offset']);
  957. self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string)$_POST['timezone']);
  958. }
  959. self::cleanupLoginTokens($userId);
  960. if (!empty($_POST["remember_login"])) {
  961. $config = self::$server->getConfig();
  962. if ($config->getSystemValue('debug', false)) {
  963. self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
  964. }
  965. $token = \OC::$server->getSecureRandom()->generate(32);
  966. $config->setUserValue($userId, 'login_token', $token, time());
  967. OC_User::setMagicInCookie($userId, $token);
  968. } else {
  969. OC_User::unsetMagicInCookie();
  970. }
  971. OC_Util::redirectToDefaultPage();
  972. exit();
  973. }
  974. return true;
  975. }
  976. }
  977. OC::init();