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.

1145 lines
39 KiB

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