base.php 38 KB

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