You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OC_Util.php 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Birk Borkason <daniel.niccoli@gmail.com>
  9. * @author Bjoern Schiessle <bjoern@schiessle.org>
  10. * @author Björn Schießle <bjoern@schiessle.org>
  11. * @author Brice Maron <brice@bmaron.net>
  12. * @author Christopher Schäpers <kondou@ts.unde.re>
  13. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  14. * @author Clark Tomlinson <fallen013@gmail.com>
  15. * @author cmeh <cmeh@users.noreply.github.com>
  16. * @author Eric Masseran <rico.masseran@gmail.com>
  17. * @author Felix Epp <work@felixepp.de>
  18. * @author Florin Peter <github@florin-peter.de>
  19. * @author Frank Karlitschek <frank@karlitschek.de>
  20. * @author Georg Ehrke <oc.list@georgehrke.com>
  21. * @author helix84 <helix84@centrum.sk>
  22. * @author Ilja Neumann <ineumann@owncloud.com>
  23. * @author Individual IT Services <info@individual-it.net>
  24. * @author Jakob Sack <mail@jakobsack.de>
  25. * @author Joas Schilling <coding@schilljs.com>
  26. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  27. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  28. * @author Julius Härtl <jus@bitgrid.net>
  29. * @author Kawohl <john@owncloud.com>
  30. * @author Lukas Reschke <lukas@statuscode.ch>
  31. * @author Markus Goetz <markus@woboq.com>
  32. * @author Martin Mattel <martin.mattel@diemattels.at>
  33. * @author Marvin Thomas Rabe <mrabe@marvinrabe.de>
  34. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  35. * @author Morris Jobke <hey@morrisjobke.de>
  36. * @author rakekniven <mark.ziegler@rakekniven.de>
  37. * @author Robert Dailey <rcdailey@gmail.com>
  38. * @author Robin Appelman <robin@icewind.nl>
  39. * @author Robin McCorkell <robin@mccorkell.me.uk>
  40. * @author Roeland Jago Douma <roeland@famdouma.nl>
  41. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  42. * @author Stefan Rado <owncloud@sradonia.net>
  43. * @author Stefan Weil <sw@weilnetz.de>
  44. * @author Thomas Müller <thomas.mueller@tmit.eu>
  45. * @author Thomas Tanghus <thomas@tanghus.net>
  46. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  47. * @author Vincent Petry <vincent@nextcloud.com>
  48. * @author Volkan Gezer <volkangezer@gmail.com>
  49. *
  50. * @license AGPL-3.0
  51. *
  52. * This code is free software: you can redistribute it and/or modify
  53. * it under the terms of the GNU Affero General Public License, version 3,
  54. * as published by the Free Software Foundation.
  55. *
  56. * This program is distributed in the hope that it will be useful,
  57. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  58. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  59. * GNU Affero General Public License for more details.
  60. *
  61. * You should have received a copy of the GNU Affero General Public License, version 3,
  62. * along with this program. If not, see <http://www.gnu.org/licenses/>
  63. *
  64. */
  65. use bantu\IniGetWrapper\IniGetWrapper;
  66. use OC\AppFramework\Http\Request;
  67. use OC\Files\Storage\LocalRootStorage;
  68. use OCP\Files\Template\ITemplateManager;
  69. use OCP\IConfig;
  70. use OCP\IGroupManager;
  71. use OCP\ILogger;
  72. use OCP\IUser;
  73. use OCP\IUserSession;
  74. use Psr\Log\LoggerInterface;
  75. class OC_Util {
  76. public static $scripts = [];
  77. public static $styles = [];
  78. public static $headers = [];
  79. private static $rootMounted = false;
  80. private static $fsSetup = false;
  81. /** @var array Local cache of version.php */
  82. private static $versionCache = null;
  83. protected static function getAppManager() {
  84. return \OC::$server->getAppManager();
  85. }
  86. private static function initLocalStorageRootFS() {
  87. // mount local file backend as root
  88. $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
  89. //first set up the local "root" storage
  90. \OC\Files\Filesystem::initMountManager();
  91. if (!self::$rootMounted) {
  92. \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
  93. self::$rootMounted = true;
  94. }
  95. }
  96. /**
  97. * mounting an object storage as the root fs will in essence remove the
  98. * necessity of a data folder being present.
  99. * TODO make home storage aware of this and use the object storage instead of local disk access
  100. *
  101. * @param array $config containing 'class' and optional 'arguments'
  102. * @suppress PhanDeprecatedFunction
  103. */
  104. private static function initObjectStoreRootFS($config) {
  105. // check misconfiguration
  106. if (empty($config['class'])) {
  107. \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
  108. }
  109. if (!isset($config['arguments'])) {
  110. $config['arguments'] = [];
  111. }
  112. // instantiate object store implementation
  113. $name = $config['class'];
  114. if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
  115. $segments = explode('\\', $name);
  116. OC_App::loadApp(strtolower($segments[1]));
  117. }
  118. $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
  119. // mount with plain / root object store implementation
  120. $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
  121. // mount object storage as root
  122. \OC\Files\Filesystem::initMountManager();
  123. if (!self::$rootMounted) {
  124. \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
  125. self::$rootMounted = true;
  126. }
  127. }
  128. /**
  129. * mounting an object storage as the root fs will in essence remove the
  130. * necessity of a data folder being present.
  131. *
  132. * @param array $config containing 'class' and optional 'arguments'
  133. * @suppress PhanDeprecatedFunction
  134. */
  135. private static function initObjectStoreMultibucketRootFS($config) {
  136. // check misconfiguration
  137. if (empty($config['class'])) {
  138. \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
  139. }
  140. if (!isset($config['arguments'])) {
  141. $config['arguments'] = [];
  142. }
  143. // instantiate object store implementation
  144. $name = $config['class'];
  145. if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
  146. $segments = explode('\\', $name);
  147. OC_App::loadApp(strtolower($segments[1]));
  148. }
  149. if (!isset($config['arguments']['bucket'])) {
  150. $config['arguments']['bucket'] = '';
  151. }
  152. // put the root FS always in first bucket for multibucket configuration
  153. $config['arguments']['bucket'] .= '0';
  154. $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
  155. // mount with plain / root object store implementation
  156. $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
  157. // mount object storage as root
  158. \OC\Files\Filesystem::initMountManager();
  159. if (!self::$rootMounted) {
  160. \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
  161. self::$rootMounted = true;
  162. }
  163. }
  164. /**
  165. * Can be set up
  166. *
  167. * @param string $user
  168. * @return boolean
  169. * @description configure the initial filesystem based on the configuration
  170. * @suppress PhanDeprecatedFunction
  171. * @suppress PhanAccessMethodInternal
  172. */
  173. public static function setupFS($user = '') {
  174. //setting up the filesystem twice can only lead to trouble
  175. if (self::$fsSetup) {
  176. return false;
  177. }
  178. \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
  179. // If we are not forced to load a specific user we load the one that is logged in
  180. if ($user === null) {
  181. $user = '';
  182. } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
  183. $user = OC_User::getUser();
  184. }
  185. // load all filesystem apps before, so no setup-hook gets lost
  186. OC_App::loadApps(['filesystem']);
  187. // the filesystem will finish when $user is not empty,
  188. // mark fs setup here to avoid doing the setup from loading
  189. // OC_Filesystem
  190. if ($user != '') {
  191. self::$fsSetup = true;
  192. }
  193. \OC\Files\Filesystem::initMountManager();
  194. $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
  195. \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  196. if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
  197. /** @var \OC\Files\Storage\Common $storage */
  198. $storage->setMountOptions($mount->getOptions());
  199. }
  200. return $storage;
  201. });
  202. \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  203. if (!$mount->getOption('enable_sharing', true)) {
  204. return new \OC\Files\Storage\Wrapper\PermissionsMask([
  205. 'storage' => $storage,
  206. 'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
  207. ]);
  208. }
  209. return $storage;
  210. });
  211. // install storage availability wrapper, before most other wrappers
  212. \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
  213. if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
  214. return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
  215. }
  216. return $storage;
  217. });
  218. \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  219. if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
  220. return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
  221. }
  222. return $storage;
  223. });
  224. \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
  225. // set up quota for home storages, even for other users
  226. // which can happen when using sharing
  227. /**
  228. * @var \OC\Files\Storage\Storage $storage
  229. */
  230. if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
  231. || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
  232. ) {
  233. /** @var \OC\Files\Storage\Home $storage */
  234. if (is_object($storage->getUser())) {
  235. $quota = OC_Util::getUserQuota($storage->getUser());
  236. if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  237. return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
  238. }
  239. }
  240. }
  241. return $storage;
  242. });
  243. \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  244. /*
  245. * Do not allow any operations that modify the storage
  246. */
  247. if ($mount->getOption('readonly', false)) {
  248. return new \OC\Files\Storage\Wrapper\PermissionsMask([
  249. 'storage' => $storage,
  250. 'mask' => \OCP\Constants::PERMISSION_ALL & ~(
  251. \OCP\Constants::PERMISSION_UPDATE |
  252. \OCP\Constants::PERMISSION_CREATE |
  253. \OCP\Constants::PERMISSION_DELETE
  254. ),
  255. ]);
  256. }
  257. return $storage;
  258. });
  259. OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
  260. \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
  261. //check if we are using an object storage
  262. $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
  263. $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
  264. // use the same order as in ObjectHomeMountProvider
  265. if (isset($objectStoreMultibucket)) {
  266. self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
  267. } elseif (isset($objectStore)) {
  268. self::initObjectStoreRootFS($objectStore);
  269. } else {
  270. self::initLocalStorageRootFS();
  271. }
  272. /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
  273. $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
  274. $rootMountProviders = $mountProviderCollection->getRootMounts();
  275. /** @var \OC\Files\Mount\Manager $mountManager */
  276. $mountManager = \OC\Files\Filesystem::getMountManager();
  277. foreach ($rootMountProviders as $rootMountProvider) {
  278. $mountManager->addMount($rootMountProvider);
  279. }
  280. if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
  281. \OC::$server->getEventLogger()->end('setup_fs');
  282. return false;
  283. }
  284. //if we aren't logged in, there is no use to set up the filesystem
  285. if ($user != "") {
  286. $userDir = '/' . $user . '/files';
  287. //jail the user into his "home" directory
  288. \OC\Files\Filesystem::init($user, $userDir);
  289. OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
  290. }
  291. \OC::$server->getEventLogger()->end('setup_fs');
  292. return true;
  293. }
  294. /**
  295. * check if a password is required for each public link
  296. *
  297. * @return boolean
  298. * @suppress PhanDeprecatedFunction
  299. */
  300. public static function isPublicLinkPasswordRequired() {
  301. $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
  302. return $enforcePassword === 'yes';
  303. }
  304. /**
  305. * check if sharing is disabled for the current user
  306. * @param IConfig $config
  307. * @param IGroupManager $groupManager
  308. * @param IUser|null $user
  309. * @return bool
  310. */
  311. public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
  312. if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
  313. $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  314. $excludedGroups = json_decode($groupsList);
  315. if (is_null($excludedGroups)) {
  316. $excludedGroups = explode(',', $groupsList);
  317. $newValue = json_encode($excludedGroups);
  318. $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
  319. }
  320. $usersGroups = $groupManager->getUserGroupIds($user);
  321. if (!empty($usersGroups)) {
  322. $remainingGroups = array_diff($usersGroups, $excludedGroups);
  323. // if the user is only in groups which are disabled for sharing then
  324. // sharing is also disabled for the user
  325. if (empty($remainingGroups)) {
  326. return true;
  327. }
  328. }
  329. }
  330. return false;
  331. }
  332. /**
  333. * check if share API enforces a default expire date
  334. *
  335. * @return boolean
  336. * @suppress PhanDeprecatedFunction
  337. */
  338. public static function isDefaultExpireDateEnforced() {
  339. $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
  340. $enforceDefaultExpireDate = false;
  341. if ($isDefaultExpireDateEnabled === 'yes') {
  342. $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
  343. $enforceDefaultExpireDate = $value === 'yes';
  344. }
  345. return $enforceDefaultExpireDate;
  346. }
  347. /**
  348. * Get the quota of a user
  349. *
  350. * @param IUser|null $user
  351. * @return float Quota bytes
  352. */
  353. public static function getUserQuota(?IUser $user) {
  354. if (is_null($user)) {
  355. return \OCP\Files\FileInfo::SPACE_UNLIMITED;
  356. }
  357. $userQuota = $user->getQuota();
  358. if ($userQuota === 'none') {
  359. return \OCP\Files\FileInfo::SPACE_UNLIMITED;
  360. }
  361. return OC_Helper::computerFileSize($userQuota);
  362. }
  363. /**
  364. * copies the skeleton to the users /files
  365. *
  366. * @param string $userId
  367. * @param \OCP\Files\Folder $userDirectory
  368. * @throws \OCP\Files\NotFoundException
  369. * @throws \OCP\Files\NotPermittedException
  370. * @suppress PhanDeprecatedFunction
  371. */
  372. public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
  373. /** @var LoggerInterface $logger */
  374. $logger = \OC::$server->get(LoggerInterface::class);
  375. $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
  376. $userLang = \OC::$server->getL10NFactory()->findLanguage();
  377. $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
  378. if (!file_exists($skeletonDirectory)) {
  379. $dialectStart = strpos($userLang, '_');
  380. if ($dialectStart !== false) {
  381. $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
  382. }
  383. if ($dialectStart === false || !file_exists($skeletonDirectory)) {
  384. $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
  385. }
  386. if (!file_exists($skeletonDirectory)) {
  387. $skeletonDirectory = '';
  388. }
  389. }
  390. $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
  391. if ($instanceId === null) {
  392. throw new \RuntimeException('no instance id!');
  393. }
  394. $appdata = 'appdata_' . $instanceId;
  395. if ($userId === $appdata) {
  396. throw new \RuntimeException('username is reserved name: ' . $appdata);
  397. }
  398. if (!empty($skeletonDirectory)) {
  399. $logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
  400. self::copyr($skeletonDirectory, $userDirectory);
  401. // update the file cache
  402. $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
  403. /** @var ITemplateManager $templateManaer */
  404. $templateManaer = \OC::$server->get(ITemplateManager::class);
  405. $templateManaer->initializeTemplateDirectory(null, $userId);
  406. }
  407. }
  408. /**
  409. * copies a directory recursively by using streams
  410. *
  411. * @param string $source
  412. * @param \OCP\Files\Folder $target
  413. * @return void
  414. */
  415. public static function copyr($source, \OCP\Files\Folder $target) {
  416. $logger = \OC::$server->getLogger();
  417. // Verify if folder exists
  418. $dir = opendir($source);
  419. if ($dir === false) {
  420. $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
  421. return;
  422. }
  423. // Copy the files
  424. while (false !== ($file = readdir($dir))) {
  425. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  426. if (is_dir($source . '/' . $file)) {
  427. $child = $target->newFolder($file);
  428. self::copyr($source . '/' . $file, $child);
  429. } else {
  430. $child = $target->newFile($file);
  431. $sourceStream = fopen($source . '/' . $file, 'r');
  432. if ($sourceStream === false) {
  433. $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
  434. closedir($dir);
  435. return;
  436. }
  437. stream_copy_to_stream($sourceStream, $child->fopen('w'));
  438. }
  439. }
  440. }
  441. closedir($dir);
  442. }
  443. /**
  444. * @return void
  445. * @suppress PhanUndeclaredMethod
  446. */
  447. public static function tearDownFS() {
  448. \OC\Files\Filesystem::tearDown();
  449. \OC::$server->getRootFolder()->clearCache();
  450. self::$fsSetup = false;
  451. self::$rootMounted = false;
  452. }
  453. /**
  454. * get the current installed version of ownCloud
  455. *
  456. * @return array
  457. */
  458. public static function getVersion() {
  459. OC_Util::loadVersion();
  460. return self::$versionCache['OC_Version'];
  461. }
  462. /**
  463. * get the current installed version string of ownCloud
  464. *
  465. * @return string
  466. */
  467. public static function getVersionString() {
  468. OC_Util::loadVersion();
  469. return self::$versionCache['OC_VersionString'];
  470. }
  471. /**
  472. * @deprecated the value is of no use anymore
  473. * @return string
  474. */
  475. public static function getEditionString() {
  476. return '';
  477. }
  478. /**
  479. * @description get the update channel of the current installed of ownCloud.
  480. * @return string
  481. */
  482. public static function getChannel() {
  483. OC_Util::loadVersion();
  484. return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
  485. }
  486. /**
  487. * @description get the build number of the current installed of ownCloud.
  488. * @return string
  489. */
  490. public static function getBuild() {
  491. OC_Util::loadVersion();
  492. return self::$versionCache['OC_Build'];
  493. }
  494. /**
  495. * @description load the version.php into the session as cache
  496. * @suppress PhanUndeclaredVariable
  497. */
  498. private static function loadVersion() {
  499. if (self::$versionCache !== null) {
  500. return;
  501. }
  502. $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
  503. require OC::$SERVERROOT . '/version.php';
  504. /** @var int $timestamp */
  505. self::$versionCache['OC_Version_Timestamp'] = $timestamp;
  506. /** @var string $OC_Version */
  507. self::$versionCache['OC_Version'] = $OC_Version;
  508. /** @var string $OC_VersionString */
  509. self::$versionCache['OC_VersionString'] = $OC_VersionString;
  510. /** @var string $OC_Build */
  511. self::$versionCache['OC_Build'] = $OC_Build;
  512. /** @var string $OC_Channel */
  513. self::$versionCache['OC_Channel'] = $OC_Channel;
  514. }
  515. /**
  516. * generates a path for JS/CSS files. If no application is provided it will create the path for core.
  517. *
  518. * @param string $application application to get the files from
  519. * @param string $directory directory within this application (css, js, vendor, etc)
  520. * @param string $file the file inside of the above folder
  521. * @return string the path
  522. */
  523. private static function generatePath($application, $directory, $file) {
  524. if (is_null($file)) {
  525. $file = $application;
  526. $application = "";
  527. }
  528. if (!empty($application)) {
  529. return "$application/$directory/$file";
  530. } else {
  531. return "$directory/$file";
  532. }
  533. }
  534. /**
  535. * add a javascript file
  536. *
  537. * @param string $application application id
  538. * @param string|null $file filename
  539. * @param bool $prepend prepend the Script to the beginning of the list
  540. * @return void
  541. */
  542. public static function addScript($application, $file = null, $prepend = false) {
  543. $path = OC_Util::generatePath($application, 'js', $file);
  544. // core js files need separate handling
  545. if ($application !== 'core' && $file !== null) {
  546. self::addTranslations($application);
  547. }
  548. self::addExternalResource($application, $prepend, $path, "script");
  549. }
  550. /**
  551. * add a javascript file from the vendor sub folder
  552. *
  553. * @param string $application application id
  554. * @param string|null $file filename
  555. * @param bool $prepend prepend the Script to the beginning of the list
  556. * @return void
  557. */
  558. public static function addVendorScript($application, $file = null, $prepend = false) {
  559. $path = OC_Util::generatePath($application, 'vendor', $file);
  560. self::addExternalResource($application, $prepend, $path, "script");
  561. }
  562. /**
  563. * add a translation JS file
  564. *
  565. * @param string $application application id
  566. * @param string|null $languageCode language code, defaults to the current language
  567. * @param bool|null $prepend prepend the Script to the beginning of the list
  568. */
  569. public static function addTranslations($application, $languageCode = null, $prepend = false) {
  570. if (is_null($languageCode)) {
  571. $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
  572. }
  573. if (!empty($application)) {
  574. $path = "$application/l10n/$languageCode";
  575. } else {
  576. $path = "l10n/$languageCode";
  577. }
  578. self::addExternalResource($application, $prepend, $path, "script");
  579. }
  580. /**
  581. * add a css file
  582. *
  583. * @param string $application application id
  584. * @param string|null $file filename
  585. * @param bool $prepend prepend the Style to the beginning of the list
  586. * @return void
  587. */
  588. public static function addStyle($application, $file = null, $prepend = false) {
  589. $path = OC_Util::generatePath($application, 'css', $file);
  590. self::addExternalResource($application, $prepend, $path, "style");
  591. }
  592. /**
  593. * add a css file from the vendor sub folder
  594. *
  595. * @param string $application application id
  596. * @param string|null $file filename
  597. * @param bool $prepend prepend the Style to the beginning of the list
  598. * @return void
  599. */
  600. public static function addVendorStyle($application, $file = null, $prepend = false) {
  601. $path = OC_Util::generatePath($application, 'vendor', $file);
  602. self::addExternalResource($application, $prepend, $path, "style");
  603. }
  604. /**
  605. * add an external resource css/js file
  606. *
  607. * @param string $application application id
  608. * @param bool $prepend prepend the file to the beginning of the list
  609. * @param string $path
  610. * @param string $type (script or style)
  611. * @return void
  612. */
  613. private static function addExternalResource($application, $prepend, $path, $type = "script") {
  614. if ($type === "style") {
  615. if (!in_array($path, self::$styles)) {
  616. if ($prepend === true) {
  617. array_unshift(self::$styles, $path);
  618. } else {
  619. self::$styles[] = $path;
  620. }
  621. }
  622. } elseif ($type === "script") {
  623. if (!in_array($path, self::$scripts)) {
  624. if ($prepend === true) {
  625. array_unshift(self::$scripts, $path);
  626. } else {
  627. self::$scripts [] = $path;
  628. }
  629. }
  630. }
  631. }
  632. /**
  633. * Add a custom element to the header
  634. * If $text is null then the element will be written as empty element.
  635. * So use "" to get a closing tag.
  636. * @param string $tag tag name of the element
  637. * @param array $attributes array of attributes for the element
  638. * @param string $text the text content for the element
  639. * @param bool $prepend prepend the header to the beginning of the list
  640. */
  641. public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
  642. $header = [
  643. 'tag' => $tag,
  644. 'attributes' => $attributes,
  645. 'text' => $text
  646. ];
  647. if ($prepend === true) {
  648. array_unshift(self::$headers, $header);
  649. } else {
  650. self::$headers[] = $header;
  651. }
  652. }
  653. /**
  654. * check if the current server configuration is suitable for ownCloud
  655. *
  656. * @param \OC\SystemConfig $config
  657. * @return array arrays with error messages and hints
  658. */
  659. public static function checkServer(\OC\SystemConfig $config) {
  660. $l = \OC::$server->getL10N('lib');
  661. $errors = [];
  662. $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
  663. if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
  664. // this check needs to be done every time
  665. $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
  666. }
  667. // Assume that if checkServer() succeeded before in this session, then all is fine.
  668. if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
  669. return $errors;
  670. }
  671. $webServerRestart = false;
  672. $setup = new \OC\Setup(
  673. $config,
  674. \OC::$server->get(IniGetWrapper::class),
  675. \OC::$server->getL10N('lib'),
  676. \OC::$server->query(\OCP\Defaults::class),
  677. \OC::$server->getLogger(),
  678. \OC::$server->getSecureRandom(),
  679. \OC::$server->query(\OC\Installer::class)
  680. );
  681. $urlGenerator = \OC::$server->getURLGenerator();
  682. $availableDatabases = $setup->getSupportedDatabases();
  683. if (empty($availableDatabases)) {
  684. $errors[] = [
  685. 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
  686. 'hint' => '' //TODO: sane hint
  687. ];
  688. $webServerRestart = true;
  689. }
  690. // Check if config folder is writable.
  691. if (!OC_Helper::isReadOnlyConfigEnabled()) {
  692. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  693. $errors[] = [
  694. 'error' => $l->t('Cannot write into "config" directory'),
  695. 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
  696. [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
  697. . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
  698. [ $urlGenerator->linkToDocs('admin-config') ])
  699. ];
  700. }
  701. }
  702. // Check if there is a writable install folder.
  703. if ($config->getValue('appstoreenabled', true)) {
  704. if (OC_App::getInstallPath() === null
  705. || !is_writable(OC_App::getInstallPath())
  706. || !is_readable(OC_App::getInstallPath())
  707. ) {
  708. $errors[] = [
  709. 'error' => $l->t('Cannot write into "apps" directory'),
  710. 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
  711. . ' or disabling the appstore in the config file.')
  712. ];
  713. }
  714. }
  715. // Create root dir.
  716. if ($config->getValue('installed', false)) {
  717. if (!is_dir($CONFIG_DATADIRECTORY)) {
  718. $success = @mkdir($CONFIG_DATADIRECTORY);
  719. if ($success) {
  720. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  721. } else {
  722. $errors[] = [
  723. 'error' => $l->t('Cannot create "data" directory'),
  724. 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
  725. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  726. ];
  727. }
  728. } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  729. // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
  730. $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
  731. $handle = fopen($testFile, 'w');
  732. if (!$handle || fwrite($handle, 'Test write operation') === false) {
  733. $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
  734. [$urlGenerator->linkToDocs('admin-dir_permissions')]);
  735. $errors[] = [
  736. 'error' => 'Your data directory is not writable',
  737. 'hint' => $permissionsHint
  738. ];
  739. } else {
  740. fclose($handle);
  741. unlink($testFile);
  742. }
  743. } else {
  744. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  745. }
  746. }
  747. if (!OC_Util::isSetLocaleWorking()) {
  748. $errors[] = [
  749. 'error' => $l->t('Setting locale to %s failed',
  750. ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  751. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
  752. 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
  753. ];
  754. }
  755. // Contains the dependencies that should be checked against
  756. // classes = class_exists
  757. // functions = function_exists
  758. // defined = defined
  759. // ini = ini_get
  760. // If the dependency is not found the missing module name is shown to the EndUser
  761. // When adding new checks always verify that they pass on Travis as well
  762. // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
  763. $dependencies = [
  764. 'classes' => [
  765. 'ZipArchive' => 'zip',
  766. 'DOMDocument' => 'dom',
  767. 'XMLWriter' => 'XMLWriter',
  768. 'XMLReader' => 'XMLReader',
  769. ],
  770. 'functions' => [
  771. 'xml_parser_create' => 'libxml',
  772. 'mb_strcut' => 'mbstring',
  773. 'ctype_digit' => 'ctype',
  774. 'json_encode' => 'JSON',
  775. 'gd_info' => 'GD',
  776. 'gzencode' => 'zlib',
  777. 'iconv' => 'iconv',
  778. 'simplexml_load_string' => 'SimpleXML',
  779. 'hash' => 'HASH Message Digest Framework',
  780. 'curl_init' => 'cURL',
  781. 'openssl_verify' => 'OpenSSL',
  782. ],
  783. 'defined' => [
  784. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  785. ],
  786. 'ini' => [
  787. 'default_charset' => 'UTF-8',
  788. ],
  789. ];
  790. $missingDependencies = [];
  791. $invalidIniSettings = [];
  792. $iniWrapper = \OC::$server->get(IniGetWrapper::class);
  793. foreach ($dependencies['classes'] as $class => $module) {
  794. if (!class_exists($class)) {
  795. $missingDependencies[] = $module;
  796. }
  797. }
  798. foreach ($dependencies['functions'] as $function => $module) {
  799. if (!function_exists($function)) {
  800. $missingDependencies[] = $module;
  801. }
  802. }
  803. foreach ($dependencies['defined'] as $defined => $module) {
  804. if (!defined($defined)) {
  805. $missingDependencies[] = $module;
  806. }
  807. }
  808. foreach ($dependencies['ini'] as $setting => $expected) {
  809. if (is_bool($expected)) {
  810. if ($iniWrapper->getBool($setting) !== $expected) {
  811. $invalidIniSettings[] = [$setting, $expected];
  812. }
  813. }
  814. if (is_int($expected)) {
  815. if ($iniWrapper->getNumeric($setting) !== $expected) {
  816. $invalidIniSettings[] = [$setting, $expected];
  817. }
  818. }
  819. if (is_string($expected)) {
  820. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  821. $invalidIniSettings[] = [$setting, $expected];
  822. }
  823. }
  824. }
  825. foreach ($missingDependencies as $missingDependency) {
  826. $errors[] = [
  827. 'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
  828. 'hint' => $l->t('Please ask your server administrator to install the module.'),
  829. ];
  830. $webServerRestart = true;
  831. }
  832. foreach ($invalidIniSettings as $setting) {
  833. if (is_bool($setting[1])) {
  834. $setting[1] = $setting[1] ? 'on' : 'off';
  835. }
  836. $errors[] = [
  837. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  838. 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
  839. ];
  840. $webServerRestart = true;
  841. }
  842. /**
  843. * The mbstring.func_overload check can only be performed if the mbstring
  844. * module is installed as it will return null if the checking setting is
  845. * not available and thus a check on the boolean value fails.
  846. *
  847. * TODO: Should probably be implemented in the above generic dependency
  848. * check somehow in the long-term.
  849. */
  850. if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
  851. $iniWrapper->getBool('mbstring.func_overload') === true) {
  852. $errors[] = [
  853. 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
  854. 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
  855. ];
  856. }
  857. if (function_exists('xml_parser_create') &&
  858. LIBXML_LOADED_VERSION < 20700) {
  859. $version = LIBXML_LOADED_VERSION;
  860. $major = floor($version / 10000);
  861. $version -= ($major * 10000);
  862. $minor = floor($version / 100);
  863. $version -= ($minor * 100);
  864. $patch = $version;
  865. $errors[] = [
  866. 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
  867. 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
  868. ];
  869. }
  870. if (!self::isAnnotationsWorking()) {
  871. $errors[] = [
  872. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  873. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  874. ];
  875. }
  876. if (!\OC::$CLI && $webServerRestart) {
  877. $errors[] = [
  878. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  879. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  880. ];
  881. }
  882. $errors = array_merge($errors, self::checkDatabaseVersion());
  883. // Cache the result of this function
  884. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  885. return $errors;
  886. }
  887. /**
  888. * Check the database version
  889. *
  890. * @return array errors array
  891. */
  892. public static function checkDatabaseVersion() {
  893. $l = \OC::$server->getL10N('lib');
  894. $errors = [];
  895. $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
  896. if ($dbType === 'pgsql') {
  897. // check PostgreSQL version
  898. try {
  899. $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
  900. $data = $result->fetchRow();
  901. $result->closeCursor();
  902. if (isset($data['server_version'])) {
  903. $version = $data['server_version'];
  904. if (version_compare($version, '9.0.0', '<')) {
  905. $errors[] = [
  906. 'error' => $l->t('PostgreSQL >= 9 required'),
  907. 'hint' => $l->t('Please upgrade your database version')
  908. ];
  909. }
  910. }
  911. } catch (\Doctrine\DBAL\Exception $e) {
  912. $logger = \OC::$server->getLogger();
  913. $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
  914. $logger->logException($e);
  915. }
  916. }
  917. return $errors;
  918. }
  919. /**
  920. * Check for correct file permissions of data directory
  921. *
  922. * @param string $dataDirectory
  923. * @return array arrays with error messages and hints
  924. */
  925. public static function checkDataDirectoryPermissions($dataDirectory) {
  926. if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
  927. return [];
  928. }
  929. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  930. if (substr($perms, -1) !== '0') {
  931. chmod($dataDirectory, 0770);
  932. clearstatcache();
  933. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  934. if ($perms[2] !== '0') {
  935. $l = \OC::$server->getL10N('lib');
  936. return [[
  937. 'error' => $l->t('Your data directory is readable by other users'),
  938. 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
  939. ]];
  940. }
  941. }
  942. return [];
  943. }
  944. /**
  945. * Check that the data directory exists and is valid by
  946. * checking the existence of the ".ocdata" file.
  947. *
  948. * @param string $dataDirectory data directory path
  949. * @return array errors found
  950. */
  951. public static function checkDataDirectoryValidity($dataDirectory) {
  952. $l = \OC::$server->getL10N('lib');
  953. $errors = [];
  954. if ($dataDirectory[0] !== '/') {
  955. $errors[] = [
  956. 'error' => $l->t('Your data directory must be an absolute path'),
  957. 'hint' => $l->t('Check the value of "datadirectory" in your configuration')
  958. ];
  959. }
  960. if (!file_exists($dataDirectory . '/.ocdata')) {
  961. $errors[] = [
  962. 'error' => $l->t('Your data directory is invalid'),
  963. 'hint' => $l->t('Ensure there is a file called ".ocdata"' .
  964. ' in the root of the data directory.')
  965. ];
  966. }
  967. return $errors;
  968. }
  969. /**
  970. * Check if the user is logged in, redirects to home if not. With
  971. * redirect URL parameter to the request URI.
  972. *
  973. * @return void
  974. */
  975. public static function checkLoggedIn() {
  976. // Check if we are a user
  977. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  978. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  979. 'core.login.showLoginForm',
  980. [
  981. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  982. ]
  983. )
  984. );
  985. exit();
  986. }
  987. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  988. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  989. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  990. exit();
  991. }
  992. }
  993. /**
  994. * Check if the user is a admin, redirects to home if not
  995. *
  996. * @return void
  997. */
  998. public static function checkAdminUser() {
  999. OC_Util::checkLoggedIn();
  1000. if (!OC_User::isAdminUser(OC_User::getUser())) {
  1001. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  1002. exit();
  1003. }
  1004. }
  1005. /**
  1006. * Returns the URL of the default page
  1007. * based on the system configuration and
  1008. * the apps visible for the current user
  1009. *
  1010. * @return string URL
  1011. * @suppress PhanDeprecatedFunction
  1012. */
  1013. public static function getDefaultPageUrl() {
  1014. /** @var IConfig $config */
  1015. $config = \OC::$server->get(IConfig::class);
  1016. $urlGenerator = \OC::$server->getURLGenerator();
  1017. // Deny the redirect if the URL contains a @
  1018. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  1019. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  1020. $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  1021. } else {
  1022. $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
  1023. if ($defaultPage) {
  1024. $location = $urlGenerator->getAbsoluteURL($defaultPage);
  1025. } else {
  1026. $appId = 'files';
  1027. $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
  1028. /** @var IUserSession $userSession */
  1029. $userSession = \OC::$server->get(IUserSession::class);
  1030. $user = $userSession->getUser();
  1031. if ($user) {
  1032. $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
  1033. $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
  1034. }
  1035. // find the first app that is enabled for the current user
  1036. foreach ($defaultApps as $defaultApp) {
  1037. $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
  1038. if (static::getAppManager()->isEnabledForUser($defaultApp)) {
  1039. $appId = $defaultApp;
  1040. break;
  1041. }
  1042. }
  1043. if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
  1044. $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
  1045. } else {
  1046. $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  1047. }
  1048. }
  1049. }
  1050. return $location;
  1051. }
  1052. /**
  1053. * Redirect to the user default page
  1054. *
  1055. * @return void
  1056. */
  1057. public static function redirectToDefaultPage() {
  1058. $location = self::getDefaultPageUrl();
  1059. header('Location: ' . $location);
  1060. exit();
  1061. }
  1062. /**
  1063. * get an id unique for this instance
  1064. *
  1065. * @return string
  1066. */
  1067. public static function getInstanceId() {
  1068. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  1069. if (is_null($id)) {
  1070. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  1071. $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  1072. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  1073. }
  1074. return $id;
  1075. }
  1076. /**
  1077. * Public function to sanitize HTML
  1078. *
  1079. * This function is used to sanitize HTML and should be applied on any
  1080. * string or array of strings before displaying it on a web page.
  1081. *
  1082. * @param string|array $value
  1083. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  1084. */
  1085. public static function sanitizeHTML($value) {
  1086. if (is_array($value)) {
  1087. $value = array_map(function ($value) {
  1088. return self::sanitizeHTML($value);
  1089. }, $value);
  1090. } else {
  1091. // Specify encoding for PHP<5.4
  1092. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  1093. }
  1094. return $value;
  1095. }
  1096. /**
  1097. * Public function to encode url parameters
  1098. *
  1099. * This function is used to encode path to file before output.
  1100. * Encoding is done according to RFC 3986 with one exception:
  1101. * Character '/' is preserved as is.
  1102. *
  1103. * @param string $component part of URI to encode
  1104. * @return string
  1105. */
  1106. public static function encodePath($component) {
  1107. $encoded = rawurlencode($component);
  1108. $encoded = str_replace('%2F', '/', $encoded);
  1109. return $encoded;
  1110. }
  1111. public function createHtaccessTestFile(\OCP\IConfig $config) {
  1112. // php dev server does not support htaccess
  1113. if (php_sapi_name() === 'cli-server') {
  1114. return false;
  1115. }
  1116. // testdata
  1117. $fileName = '/htaccesstest.txt';
  1118. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  1119. // creating a test file
  1120. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1121. if (file_exists($testFile)) {// already running this test, possible recursive call
  1122. return false;
  1123. }
  1124. $fp = @fopen($testFile, 'w');
  1125. if (!$fp) {
  1126. throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
  1127. 'Make sure it is possible for the webserver to write to ' . $testFile);
  1128. }
  1129. fwrite($fp, $testContent);
  1130. fclose($fp);
  1131. return $testContent;
  1132. }
  1133. /**
  1134. * Check if the .htaccess file is working
  1135. * @param \OCP\IConfig $config
  1136. * @return bool
  1137. * @throws Exception
  1138. * @throws \OC\HintException If the test file can't get written.
  1139. */
  1140. public function isHtaccessWorking(\OCP\IConfig $config) {
  1141. if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
  1142. return true;
  1143. }
  1144. $testContent = $this->createHtaccessTestFile($config);
  1145. if ($testContent === false) {
  1146. return false;
  1147. }
  1148. $fileName = '/htaccesstest.txt';
  1149. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1150. // accessing the file via http
  1151. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  1152. try {
  1153. $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  1154. } catch (\Exception $e) {
  1155. $content = false;
  1156. }
  1157. if (strpos($url, 'https:') === 0) {
  1158. $url = 'http:' . substr($url, 6);
  1159. } else {
  1160. $url = 'https:' . substr($url, 5);
  1161. }
  1162. try {
  1163. $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  1164. } catch (\Exception $e) {
  1165. $fallbackContent = false;
  1166. }
  1167. // cleanup
  1168. @unlink($testFile);
  1169. /*
  1170. * If the content is not equal to test content our .htaccess
  1171. * is working as required
  1172. */
  1173. return $content !== $testContent && $fallbackContent !== $testContent;
  1174. }
  1175. /**
  1176. * Check if the setlocal call does not work. This can happen if the right
  1177. * local packages are not available on the server.
  1178. *
  1179. * @return bool
  1180. */
  1181. public static function isSetLocaleWorking() {
  1182. if ('' === basename('§')) {
  1183. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  1184. setlocale(LC_ALL, 'C.UTF-8', 'C');
  1185. setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
  1186. }
  1187. // Check again
  1188. if ('' === basename('§')) {
  1189. return false;
  1190. }
  1191. return true;
  1192. }
  1193. /**
  1194. * Check if it's possible to get the inline annotations
  1195. *
  1196. * @return bool
  1197. */
  1198. public static function isAnnotationsWorking() {
  1199. $reflection = new \ReflectionMethod(__METHOD__);
  1200. $docs = $reflection->getDocComment();
  1201. return (is_string($docs) && strlen($docs) > 50);
  1202. }
  1203. /**
  1204. * Check if the PHP module fileinfo is loaded.
  1205. *
  1206. * @return bool
  1207. */
  1208. public static function fileInfoLoaded() {
  1209. return function_exists('finfo_open');
  1210. }
  1211. /**
  1212. * clear all levels of output buffering
  1213. *
  1214. * @return void
  1215. */
  1216. public static function obEnd() {
  1217. while (ob_get_level()) {
  1218. ob_end_clean();
  1219. }
  1220. }
  1221. /**
  1222. * Checks whether the server is running on Mac OS X
  1223. *
  1224. * @return bool true if running on Mac OS X, false otherwise
  1225. */
  1226. public static function runningOnMac() {
  1227. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  1228. }
  1229. /**
  1230. * Handles the case that there may not be a theme, then check if a "default"
  1231. * theme exists and take that one
  1232. *
  1233. * @return string the theme
  1234. */
  1235. public static function getTheme() {
  1236. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  1237. if ($theme === '') {
  1238. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1239. $theme = 'default';
  1240. }
  1241. }
  1242. return $theme;
  1243. }
  1244. /**
  1245. * Normalize a unicode string
  1246. *
  1247. * @param string $value a not normalized string
  1248. * @return bool|string
  1249. */
  1250. public static function normalizeUnicode($value) {
  1251. if (Normalizer::isNormalized($value)) {
  1252. return $value;
  1253. }
  1254. $normalizedValue = Normalizer::normalize($value);
  1255. if ($normalizedValue === null || $normalizedValue === false) {
  1256. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  1257. return $value;
  1258. }
  1259. return $normalizedValue;
  1260. }
  1261. /**
  1262. * A human readable string is generated based on version and build number
  1263. *
  1264. * @return string
  1265. */
  1266. public static function getHumanVersion() {
  1267. $version = OC_Util::getVersionString();
  1268. $build = OC_Util::getBuild();
  1269. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1270. $version .= ' Build:' . $build;
  1271. }
  1272. return $version;
  1273. }
  1274. /**
  1275. * Returns whether the given file name is valid
  1276. *
  1277. * @param string $file file name to check
  1278. * @return bool true if the file name is valid, false otherwise
  1279. * @deprecated use \OC\Files\View::verifyPath()
  1280. */
  1281. public static function isValidFileName($file) {
  1282. $trimmed = trim($file);
  1283. if ($trimmed === '') {
  1284. return false;
  1285. }
  1286. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  1287. return false;
  1288. }
  1289. // detect part files
  1290. if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
  1291. return false;
  1292. }
  1293. foreach (str_split($trimmed) as $char) {
  1294. if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
  1295. return false;
  1296. }
  1297. }
  1298. return true;
  1299. }
  1300. /**
  1301. * Check whether the instance needs to perform an upgrade,
  1302. * either when the core version is higher or any app requires
  1303. * an upgrade.
  1304. *
  1305. * @param \OC\SystemConfig $config
  1306. * @return bool whether the core or any app needs an upgrade
  1307. * @throws \OC\HintException When the upgrade from the given version is not allowed
  1308. */
  1309. public static function needUpgrade(\OC\SystemConfig $config) {
  1310. if ($config->getValue('installed', false)) {
  1311. $installedVersion = $config->getValue('version', '0.0.0');
  1312. $currentVersion = implode('.', \OCP\Util::getVersion());
  1313. $versionDiff = version_compare($currentVersion, $installedVersion);
  1314. if ($versionDiff > 0) {
  1315. return true;
  1316. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  1317. // downgrade with debug
  1318. $installedMajor = explode('.', $installedVersion);
  1319. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  1320. $currentMajor = explode('.', $currentVersion);
  1321. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  1322. if ($installedMajor === $currentMajor) {
  1323. // Same major, allow downgrade for developers
  1324. return true;
  1325. } else {
  1326. // downgrade attempt, throw exception
  1327. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1328. }
  1329. } elseif ($versionDiff < 0) {
  1330. // downgrade attempt, throw exception
  1331. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1332. }
  1333. // also check for upgrades for apps (independently from the user)
  1334. $apps = \OC_App::getEnabledApps(false, true);
  1335. $shouldUpgrade = false;
  1336. foreach ($apps as $app) {
  1337. if (\OC_App::shouldUpgrade($app)) {
  1338. $shouldUpgrade = true;
  1339. break;
  1340. }
  1341. }
  1342. return $shouldUpgrade;
  1343. } else {
  1344. return false;
  1345. }
  1346. }
  1347. /**
  1348. * is this Internet explorer ?
  1349. *
  1350. * @return boolean
  1351. */
  1352. public static function isIe() {
  1353. if (!isset($_SERVER['HTTP_USER_AGENT'])) {
  1354. return false;
  1355. }
  1356. return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
  1357. }
  1358. }