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.

1485 lines
48 KiB

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