base.php 37 KB

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