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.

1005 lines
33 KiB

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