OC_Util.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. use bantu\IniGetWrapper\IniGetWrapper;
  8. use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager;
  9. use OC\Files\SetupManager;
  10. use OCP\Files\Template\ITemplateManager;
  11. use OCP\Http\Client\IClientService;
  12. use OCP\IConfig;
  13. use OCP\IGroupManager;
  14. use OCP\IURLGenerator;
  15. use OCP\IUser;
  16. use OCP\L10N\IFactory;
  17. use OCP\Security\ISecureRandom;
  18. use OCP\Share\IManager;
  19. use Psr\Log\LoggerInterface;
  20. class OC_Util {
  21. public static $scripts = [];
  22. public static $styles = [];
  23. public static $headers = [];
  24. /** @var array Local cache of version.php */
  25. private static $versionCache = null;
  26. protected static function getAppManager() {
  27. return \OC::$server->getAppManager();
  28. }
  29. /**
  30. * Setup the file system
  31. *
  32. * @param string|null $user
  33. * @return boolean
  34. * @description configure the initial filesystem based on the configuration
  35. * @suppress PhanDeprecatedFunction
  36. * @suppress PhanAccessMethodInternal
  37. */
  38. public static function setupFS(?string $user = '') {
  39. // If we are not forced to load a specific user we load the one that is logged in
  40. if ($user === '') {
  41. $userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
  42. } else {
  43. $userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
  44. }
  45. /** @var SetupManager $setupManager */
  46. $setupManager = \OC::$server->get(SetupManager::class);
  47. if ($userObject) {
  48. $setupManager->setupForUser($userObject);
  49. } else {
  50. $setupManager->setupRoot();
  51. }
  52. return true;
  53. }
  54. /**
  55. * Check if a password is required for each public link
  56. *
  57. * @param bool $checkGroupMembership Check group membership exclusion
  58. * @return boolean
  59. * @suppress PhanDeprecatedFunction
  60. */
  61. public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) {
  62. /** @var IManager $shareManager */
  63. $shareManager = \OC::$server->get(IManager::class);
  64. return $shareManager->shareApiLinkEnforcePassword($checkGroupMembership);
  65. }
  66. /**
  67. * check if sharing is disabled for the current user
  68. * @param IConfig $config
  69. * @param IGroupManager $groupManager
  70. * @param IUser|null $user
  71. * @return bool
  72. */
  73. public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
  74. /** @var IManager $shareManager */
  75. $shareManager = \OC::$server->get(IManager::class);
  76. $userId = $user ? $user->getUID() : null;
  77. return $shareManager->sharingDisabledForUser($userId);
  78. }
  79. /**
  80. * check if share API enforces a default expire date
  81. *
  82. * @return bool
  83. * @suppress PhanDeprecatedFunction
  84. */
  85. public static function isDefaultExpireDateEnforced() {
  86. /** @var IManager $shareManager */
  87. $shareManager = \OC::$server->get(IManager::class);
  88. return $shareManager->shareApiLinkDefaultExpireDateEnforced();
  89. }
  90. /**
  91. * Get the quota of a user
  92. *
  93. * @param IUser|null $user
  94. * @return int|\OCP\Files\FileInfo::SPACE_UNLIMITED|false|float Quota bytes
  95. */
  96. public static function getUserQuota(?IUser $user) {
  97. if (is_null($user)) {
  98. return \OCP\Files\FileInfo::SPACE_UNLIMITED;
  99. }
  100. $userQuota = $user->getQuota();
  101. if ($userQuota === 'none') {
  102. return \OCP\Files\FileInfo::SPACE_UNLIMITED;
  103. }
  104. return OC_Helper::computerFileSize($userQuota);
  105. }
  106. /**
  107. * copies the skeleton to the users /files
  108. *
  109. * @param string $userId
  110. * @param \OCP\Files\Folder $userDirectory
  111. * @throws \OCP\Files\NotFoundException
  112. * @throws \OCP\Files\NotPermittedException
  113. * @suppress PhanDeprecatedFunction
  114. */
  115. public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
  116. /** @var LoggerInterface $logger */
  117. $logger = \OC::$server->get(LoggerInterface::class);
  118. $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
  119. $userLang = \OC::$server->get(IFactory::class)->findLanguage();
  120. $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
  121. if (!file_exists($skeletonDirectory)) {
  122. $dialectStart = strpos($userLang, '_');
  123. if ($dialectStart !== false) {
  124. $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
  125. }
  126. if ($dialectStart === false || !file_exists($skeletonDirectory)) {
  127. $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
  128. }
  129. if (!file_exists($skeletonDirectory)) {
  130. $skeletonDirectory = '';
  131. }
  132. }
  133. $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
  134. if ($instanceId === null) {
  135. throw new \RuntimeException('no instance id!');
  136. }
  137. $appdata = 'appdata_' . $instanceId;
  138. if ($userId === $appdata) {
  139. throw new \RuntimeException('username is reserved name: ' . $appdata);
  140. }
  141. if (!empty($skeletonDirectory)) {
  142. $logger->debug('copying skeleton for ' . $userId . ' from ' . $skeletonDirectory . ' to ' . $userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
  143. self::copyr($skeletonDirectory, $userDirectory);
  144. // update the file cache
  145. $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
  146. /** @var ITemplateManager $templateManager */
  147. $templateManager = \OC::$server->get(ITemplateManager::class);
  148. $templateManager->initializeTemplateDirectory(null, $userId);
  149. }
  150. }
  151. /**
  152. * copies a directory recursively by using streams
  153. *
  154. * @param string $source
  155. * @param \OCP\Files\Folder $target
  156. * @return void
  157. */
  158. public static function copyr($source, \OCP\Files\Folder $target) {
  159. $logger = \OCP\Server::get(LoggerInterface::class);
  160. // Verify if folder exists
  161. $dir = opendir($source);
  162. if ($dir === false) {
  163. $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
  164. return;
  165. }
  166. // Copy the files
  167. while (false !== ($file = readdir($dir))) {
  168. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  169. if (is_dir($source . '/' . $file)) {
  170. $child = $target->newFolder($file);
  171. self::copyr($source . '/' . $file, $child);
  172. } else {
  173. $child = $target->newFile($file);
  174. $sourceStream = fopen($source . '/' . $file, 'r');
  175. if ($sourceStream === false) {
  176. $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
  177. closedir($dir);
  178. return;
  179. }
  180. $child->putContent($sourceStream);
  181. }
  182. }
  183. }
  184. closedir($dir);
  185. }
  186. /**
  187. * @return void
  188. * @suppress PhanUndeclaredMethod
  189. */
  190. public static function tearDownFS() {
  191. /** @var SetupManager $setupManager */
  192. $setupManager = \OC::$server->get(SetupManager::class);
  193. $setupManager->tearDown();
  194. }
  195. /**
  196. * generates a path for JS/CSS files. If no application is provided it will create the path for core.
  197. *
  198. * @param string $application application to get the files from
  199. * @param string $directory directory within this application (css, js, vendor, etc)
  200. * @param string $file the file inside of the above folder
  201. * @return string the path
  202. */
  203. private static function generatePath($application, $directory, $file) {
  204. if (is_null($file)) {
  205. $file = $application;
  206. $application = '';
  207. }
  208. if (!empty($application)) {
  209. return "$application/$directory/$file";
  210. } else {
  211. return "$directory/$file";
  212. }
  213. }
  214. /**
  215. * add a javascript file
  216. *
  217. * @deprecated 24.0.0 - Use \OCP\Util::addScript
  218. *
  219. * @param string $application application id
  220. * @param string|null $file filename
  221. * @param bool $prepend prepend the Script to the beginning of the list
  222. * @return void
  223. */
  224. public static function addScript($application, $file = null, $prepend = false) {
  225. $path = OC_Util::generatePath($application, 'js', $file);
  226. // core js files need separate handling
  227. if ($application !== 'core' && $file !== null) {
  228. self::addTranslations($application);
  229. }
  230. self::addExternalResource($application, $prepend, $path, 'script');
  231. }
  232. /**
  233. * add a javascript file from the vendor sub folder
  234. *
  235. * @param string $application application id
  236. * @param string|null $file filename
  237. * @param bool $prepend prepend the Script to the beginning of the list
  238. * @return void
  239. */
  240. public static function addVendorScript($application, $file = null, $prepend = false) {
  241. $path = OC_Util::generatePath($application, 'vendor', $file);
  242. self::addExternalResource($application, $prepend, $path, 'script');
  243. }
  244. /**
  245. * add a translation JS file
  246. *
  247. * @deprecated 24.0.0
  248. *
  249. * @param string $application application id
  250. * @param string|null $languageCode language code, defaults to the current language
  251. * @param bool|null $prepend prepend the Script to the beginning of the list
  252. */
  253. public static function addTranslations($application, $languageCode = null, $prepend = false) {
  254. if (is_null($languageCode)) {
  255. $languageCode = \OC::$server->get(IFactory::class)->findLanguage($application);
  256. }
  257. if (!empty($application)) {
  258. $path = "$application/l10n/$languageCode";
  259. } else {
  260. $path = "l10n/$languageCode";
  261. }
  262. self::addExternalResource($application, $prepend, $path, 'script');
  263. }
  264. /**
  265. * add a css file
  266. *
  267. * @param string $application application id
  268. * @param string|null $file filename
  269. * @param bool $prepend prepend the Style to the beginning of the list
  270. * @return void
  271. */
  272. public static function addStyle($application, $file = null, $prepend = false) {
  273. $path = OC_Util::generatePath($application, 'css', $file);
  274. self::addExternalResource($application, $prepend, $path, 'style');
  275. }
  276. /**
  277. * add a css file from the vendor sub folder
  278. *
  279. * @param string $application application id
  280. * @param string|null $file filename
  281. * @param bool $prepend prepend the Style to the beginning of the list
  282. * @return void
  283. */
  284. public static function addVendorStyle($application, $file = null, $prepend = false) {
  285. $path = OC_Util::generatePath($application, 'vendor', $file);
  286. self::addExternalResource($application, $prepend, $path, 'style');
  287. }
  288. /**
  289. * add an external resource css/js file
  290. *
  291. * @param string $application application id
  292. * @param bool $prepend prepend the file to the beginning of the list
  293. * @param string $path
  294. * @param string $type (script or style)
  295. * @return void
  296. */
  297. private static function addExternalResource($application, $prepend, $path, $type = 'script') {
  298. if ($type === 'style') {
  299. if (!in_array($path, self::$styles)) {
  300. if ($prepend === true) {
  301. array_unshift(self::$styles, $path);
  302. } else {
  303. self::$styles[] = $path;
  304. }
  305. }
  306. } elseif ($type === 'script') {
  307. if (!in_array($path, self::$scripts)) {
  308. if ($prepend === true) {
  309. array_unshift(self::$scripts, $path);
  310. } else {
  311. self::$scripts [] = $path;
  312. }
  313. }
  314. }
  315. }
  316. /**
  317. * Add a custom element to the header
  318. * If $text is null then the element will be written as empty element.
  319. * So use "" to get a closing tag.
  320. * @param string $tag tag name of the element
  321. * @param array $attributes array of attributes for the element
  322. * @param string $text the text content for the element
  323. * @param bool $prepend prepend the header to the beginning of the list
  324. */
  325. public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
  326. $header = [
  327. 'tag' => $tag,
  328. 'attributes' => $attributes,
  329. 'text' => $text
  330. ];
  331. if ($prepend === true) {
  332. array_unshift(self::$headers, $header);
  333. } else {
  334. self::$headers[] = $header;
  335. }
  336. }
  337. /**
  338. * check if the current server configuration is suitable for ownCloud
  339. *
  340. * @param \OC\SystemConfig $config
  341. * @return array arrays with error messages and hints
  342. */
  343. public static function checkServer(\OC\SystemConfig $config) {
  344. $l = \OC::$server->getL10N('lib');
  345. $errors = [];
  346. $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
  347. if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
  348. // this check needs to be done every time
  349. $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
  350. }
  351. // Assume that if checkServer() succeeded before in this session, then all is fine.
  352. if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
  353. return $errors;
  354. }
  355. $webServerRestart = false;
  356. $setup = \OCP\Server::get(\OC\Setup::class);
  357. $urlGenerator = \OC::$server->getURLGenerator();
  358. $availableDatabases = $setup->getSupportedDatabases();
  359. if (empty($availableDatabases)) {
  360. $errors[] = [
  361. 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
  362. 'hint' => '' //TODO: sane hint
  363. ];
  364. $webServerRestart = true;
  365. }
  366. // Check if config folder is writable.
  367. if (!OC_Helper::isReadOnlyConfigEnabled()) {
  368. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  369. $errors[] = [
  370. 'error' => $l->t('Cannot write into "config" directory.'),
  371. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
  372. [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
  373. . $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',
  374. [ $urlGenerator->linkToDocs('admin-config') ])
  375. ];
  376. }
  377. }
  378. // Check if there is a writable install folder.
  379. if ($config->getValue('appstoreenabled', true)) {
  380. if (OC_App::getInstallPath() === null
  381. || !is_writable(OC_App::getInstallPath())
  382. || !is_readable(OC_App::getInstallPath())
  383. ) {
  384. $errors[] = [
  385. 'error' => $l->t('Cannot write into "apps" directory.'),
  386. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
  387. . ' or disabling the App Store in the config file.')
  388. ];
  389. }
  390. }
  391. // Create root dir.
  392. if ($config->getValue('installed', false)) {
  393. if (!is_dir($CONFIG_DATADIRECTORY)) {
  394. $success = @mkdir($CONFIG_DATADIRECTORY);
  395. if ($success) {
  396. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  397. } else {
  398. $errors[] = [
  399. 'error' => $l->t('Cannot create "data" directory.'),
  400. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
  401. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  402. ];
  403. }
  404. } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  405. // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
  406. $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
  407. $handle = fopen($testFile, 'w');
  408. if (!$handle || fwrite($handle, 'Test write operation') === false) {
  409. $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
  410. [$urlGenerator->linkToDocs('admin-dir_permissions')]);
  411. $errors[] = [
  412. 'error' => $l->t('Your data directory is not writable.'),
  413. 'hint' => $permissionsHint
  414. ];
  415. } else {
  416. fclose($handle);
  417. unlink($testFile);
  418. }
  419. } else {
  420. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  421. }
  422. }
  423. if (!OC_Util::isSetLocaleWorking()) {
  424. $errors[] = [
  425. 'error' => $l->t('Setting locale to %s failed.',
  426. ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  427. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
  428. 'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
  429. ];
  430. }
  431. // Contains the dependencies that should be checked against
  432. // classes = class_exists
  433. // functions = function_exists
  434. // defined = defined
  435. // ini = ini_get
  436. // If the dependency is not found the missing module name is shown to the EndUser
  437. // When adding new checks always verify that they pass on CI as well
  438. $dependencies = [
  439. 'classes' => [
  440. 'ZipArchive' => 'zip',
  441. 'DOMDocument' => 'dom',
  442. 'XMLWriter' => 'XMLWriter',
  443. 'XMLReader' => 'XMLReader',
  444. ],
  445. 'functions' => [
  446. 'xml_parser_create' => 'libxml',
  447. 'mb_strcut' => 'mbstring',
  448. 'ctype_digit' => 'ctype',
  449. 'json_encode' => 'JSON',
  450. 'gd_info' => 'GD',
  451. 'gzencode' => 'zlib',
  452. 'simplexml_load_string' => 'SimpleXML',
  453. 'hash' => 'HASH Message Digest Framework',
  454. 'curl_init' => 'cURL',
  455. 'openssl_verify' => 'OpenSSL',
  456. ],
  457. 'defined' => [
  458. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  459. ],
  460. 'ini' => [
  461. 'default_charset' => 'UTF-8',
  462. ],
  463. ];
  464. $missingDependencies = [];
  465. $invalidIniSettings = [];
  466. $iniWrapper = \OC::$server->get(IniGetWrapper::class);
  467. foreach ($dependencies['classes'] as $class => $module) {
  468. if (!class_exists($class)) {
  469. $missingDependencies[] = $module;
  470. }
  471. }
  472. foreach ($dependencies['functions'] as $function => $module) {
  473. if (!function_exists($function)) {
  474. $missingDependencies[] = $module;
  475. }
  476. }
  477. foreach ($dependencies['defined'] as $defined => $module) {
  478. if (!defined($defined)) {
  479. $missingDependencies[] = $module;
  480. }
  481. }
  482. foreach ($dependencies['ini'] as $setting => $expected) {
  483. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  484. $invalidIniSettings[] = [$setting, $expected];
  485. }
  486. }
  487. foreach ($missingDependencies as $missingDependency) {
  488. $errors[] = [
  489. 'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
  490. 'hint' => $l->t('Please ask your server administrator to install the module.'),
  491. ];
  492. $webServerRestart = true;
  493. }
  494. foreach ($invalidIniSettings as $setting) {
  495. $errors[] = [
  496. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  497. 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
  498. ];
  499. $webServerRestart = true;
  500. }
  501. /**
  502. * The mbstring.func_overload check can only be performed if the mbstring
  503. * module is installed as it will return null if the checking setting is
  504. * not available and thus a check on the boolean value fails.
  505. *
  506. * TODO: Should probably be implemented in the above generic dependency
  507. * check somehow in the long-term.
  508. */
  509. if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
  510. $iniWrapper->getBool('mbstring.func_overload') === true) {
  511. $errors[] = [
  512. 'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
  513. 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
  514. ];
  515. }
  516. if (!self::isAnnotationsWorking()) {
  517. $errors[] = [
  518. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  519. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  520. ];
  521. }
  522. if (!\OC::$CLI && $webServerRestart) {
  523. $errors[] = [
  524. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  525. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  526. ];
  527. }
  528. foreach (['secret', 'instanceid', 'passwordsalt'] as $requiredConfig) {
  529. if ($config->getValue($requiredConfig, '') === '' && !\OC::$CLI && $config->getValue('installed', false)) {
  530. $errors[] = [
  531. 'error' => $l->t('The required %s config variable is not configured in the config.php file.', [$requiredConfig]),
  532. 'hint' => $l->t('Please ask your server administrator to check the Nextcloud configuration.')
  533. ];
  534. }
  535. }
  536. // Cache the result of this function
  537. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  538. return $errors;
  539. }
  540. /**
  541. * Check for correct file permissions of data directory
  542. *
  543. * @param string $dataDirectory
  544. * @return array arrays with error messages and hints
  545. */
  546. public static function checkDataDirectoryPermissions($dataDirectory) {
  547. if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
  548. return [];
  549. }
  550. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  551. if (substr($perms, -1) !== '0') {
  552. chmod($dataDirectory, 0770);
  553. clearstatcache();
  554. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  555. if ($perms[2] !== '0') {
  556. $l = \OC::$server->getL10N('lib');
  557. return [[
  558. 'error' => $l->t('Your data directory is readable by other people.'),
  559. 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other people.'),
  560. ]];
  561. }
  562. }
  563. return [];
  564. }
  565. /**
  566. * Check that the data directory exists and is valid by
  567. * checking the existence of the ".ncdata" file.
  568. *
  569. * @param string $dataDirectory data directory path
  570. * @return array errors found
  571. */
  572. public static function checkDataDirectoryValidity($dataDirectory) {
  573. $l = \OC::$server->getL10N('lib');
  574. $errors = [];
  575. if ($dataDirectory[0] !== '/') {
  576. $errors[] = [
  577. 'error' => $l->t('Your data directory must be an absolute path.'),
  578. 'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
  579. ];
  580. }
  581. if (!file_exists($dataDirectory . '/.ncdata')) {
  582. $errors[] = [
  583. 'error' => $l->t('Your data directory is invalid.'),
  584. 'hint' => $l->t('Ensure there is a file called "%1$s" in the root of the data directory. It should have the content: "%2$s"', ['.ncdata', '# Nextcloud data directory']),
  585. ];
  586. }
  587. return $errors;
  588. }
  589. /**
  590. * Check if the user is logged in, redirects to home if not. With
  591. * redirect URL parameter to the request URI.
  592. *
  593. * @return void
  594. */
  595. public static function checkLoggedIn() {
  596. // Check if we are a user
  597. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  598. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  599. 'core.login.showLoginForm',
  600. [
  601. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  602. ]
  603. )
  604. );
  605. exit();
  606. }
  607. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  608. if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  609. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  610. exit();
  611. }
  612. }
  613. /**
  614. * Check if the user is a admin, redirects to home if not
  615. *
  616. * @return void
  617. */
  618. public static function checkAdminUser() {
  619. OC_Util::checkLoggedIn();
  620. if (!OC_User::isAdminUser(OC_User::getUser())) {
  621. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  622. exit();
  623. }
  624. }
  625. /**
  626. * Returns the URL of the default page
  627. * based on the system configuration and
  628. * the apps visible for the current user
  629. *
  630. * @return string URL
  631. * @suppress PhanDeprecatedFunction
  632. */
  633. public static function getDefaultPageUrl() {
  634. /** @var IURLGenerator $urlGenerator */
  635. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  636. return $urlGenerator->linkToDefaultPageUrl();
  637. }
  638. /**
  639. * Redirect to the user default page
  640. *
  641. * @return void
  642. */
  643. public static function redirectToDefaultPage() {
  644. $location = self::getDefaultPageUrl();
  645. header('Location: ' . $location);
  646. exit();
  647. }
  648. /**
  649. * get an id unique for this instance
  650. *
  651. * @return string
  652. */
  653. public static function getInstanceId() {
  654. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  655. if (is_null($id)) {
  656. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  657. $id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
  658. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  659. }
  660. return $id;
  661. }
  662. /**
  663. * Public function to sanitize HTML
  664. *
  665. * This function is used to sanitize HTML and should be applied on any
  666. * string or array of strings before displaying it on a web page.
  667. *
  668. * @param string|string[] $value
  669. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  670. */
  671. public static function sanitizeHTML($value) {
  672. if (is_array($value)) {
  673. /** @var string[] $value */
  674. $value = array_map(function ($value) {
  675. return self::sanitizeHTML($value);
  676. }, $value);
  677. } else {
  678. // Specify encoding for PHP<5.4
  679. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  680. }
  681. return $value;
  682. }
  683. /**
  684. * Public function to encode url parameters
  685. *
  686. * This function is used to encode path to file before output.
  687. * Encoding is done according to RFC 3986 with one exception:
  688. * Character '/' is preserved as is.
  689. *
  690. * @param string $component part of URI to encode
  691. * @return string
  692. */
  693. public static function encodePath($component) {
  694. $encoded = rawurlencode($component);
  695. $encoded = str_replace('%2F', '/', $encoded);
  696. return $encoded;
  697. }
  698. public function createHtaccessTestFile(\OCP\IConfig $config) {
  699. // php dev server does not support htaccess
  700. if (php_sapi_name() === 'cli-server') {
  701. return false;
  702. }
  703. // testdata
  704. $fileName = '/htaccesstest.txt';
  705. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  706. // creating a test file
  707. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  708. if (file_exists($testFile)) {// already running this test, possible recursive call
  709. return false;
  710. }
  711. $fp = @fopen($testFile, 'w');
  712. if (!$fp) {
  713. throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
  714. 'Make sure it is possible for the web server to write to ' . $testFile);
  715. }
  716. fwrite($fp, $testContent);
  717. fclose($fp);
  718. return $testContent;
  719. }
  720. /**
  721. * Check if the .htaccess file is working
  722. *
  723. * @param \OCP\IConfig $config
  724. * @return bool
  725. * @throws Exception
  726. * @throws \OCP\HintException If the test file can't get written.
  727. */
  728. public function isHtaccessWorking(\OCP\IConfig $config) {
  729. if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
  730. return true;
  731. }
  732. $testContent = $this->createHtaccessTestFile($config);
  733. if ($testContent === false) {
  734. return false;
  735. }
  736. $fileName = '/htaccesstest.txt';
  737. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  738. // accessing the file via http
  739. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  740. try {
  741. $content = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  742. } catch (\Exception $e) {
  743. $content = false;
  744. }
  745. if (str_starts_with($url, 'https:')) {
  746. $url = 'http:' . substr($url, 6);
  747. } else {
  748. $url = 'https:' . substr($url, 5);
  749. }
  750. try {
  751. $fallbackContent = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  752. } catch (\Exception $e) {
  753. $fallbackContent = false;
  754. }
  755. // cleanup
  756. @unlink($testFile);
  757. /*
  758. * If the content is not equal to test content our .htaccess
  759. * is working as required
  760. */
  761. return $content !== $testContent && $fallbackContent !== $testContent;
  762. }
  763. /**
  764. * Check if current locale is non-UTF8
  765. *
  766. * @return bool
  767. */
  768. private static function isNonUTF8Locale() {
  769. if (function_exists('escapeshellcmd')) {
  770. return escapeshellcmd('§') === '';
  771. } elseif (function_exists('escapeshellarg')) {
  772. return escapeshellarg('§') === '\'\'';
  773. } else {
  774. return preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0)) === 0;
  775. }
  776. }
  777. /**
  778. * Check if the setlocale call does not work. This can happen if the right
  779. * local packages are not available on the server.
  780. *
  781. * @return bool
  782. */
  783. public static function isSetLocaleWorking() {
  784. if (self::isNonUTF8Locale()) {
  785. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  786. setlocale(LC_ALL, 'C.UTF-8', 'C');
  787. 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');
  788. // Check again
  789. if (self::isNonUTF8Locale()) {
  790. return false;
  791. }
  792. }
  793. return true;
  794. }
  795. /**
  796. * Check if it's possible to get the inline annotations
  797. *
  798. * @return bool
  799. */
  800. public static function isAnnotationsWorking() {
  801. if (PHP_VERSION_ID >= 80300) {
  802. /** @psalm-suppress UndefinedMethod */
  803. $reflection = \ReflectionMethod::createFromMethodName(__METHOD__);
  804. } else {
  805. $reflection = new \ReflectionMethod(__METHOD__);
  806. }
  807. $docs = $reflection->getDocComment();
  808. return (is_string($docs) && strlen($docs) > 50);
  809. }
  810. /**
  811. * Check if the PHP module fileinfo is loaded.
  812. *
  813. * @return bool
  814. */
  815. public static function fileInfoLoaded() {
  816. return function_exists('finfo_open');
  817. }
  818. /**
  819. * clear all levels of output buffering
  820. *
  821. * @return void
  822. */
  823. public static function obEnd() {
  824. while (ob_get_level()) {
  825. ob_end_clean();
  826. }
  827. }
  828. /**
  829. * Checks whether the server is running on Mac OS X
  830. *
  831. * @return bool true if running on Mac OS X, false otherwise
  832. */
  833. public static function runningOnMac() {
  834. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  835. }
  836. /**
  837. * Handles the case that there may not be a theme, then check if a "default"
  838. * theme exists and take that one
  839. *
  840. * @return string the theme
  841. */
  842. public static function getTheme() {
  843. $theme = \OC::$server->getSystemConfig()->getValue('theme', '');
  844. if ($theme === '') {
  845. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  846. $theme = 'default';
  847. }
  848. }
  849. return $theme;
  850. }
  851. /**
  852. * Normalize a unicode string
  853. *
  854. * @param string $value a not normalized string
  855. * @return bool|string
  856. */
  857. public static function normalizeUnicode($value) {
  858. if (Normalizer::isNormalized($value)) {
  859. return $value;
  860. }
  861. $normalizedValue = Normalizer::normalize($value);
  862. if ($normalizedValue === null || $normalizedValue === false) {
  863. \OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  864. return $value;
  865. }
  866. return $normalizedValue;
  867. }
  868. /**
  869. * Check whether the instance needs to perform an upgrade,
  870. * either when the core version is higher or any app requires
  871. * an upgrade.
  872. *
  873. * @param \OC\SystemConfig $config
  874. * @return bool whether the core or any app needs an upgrade
  875. * @throws \OCP\HintException When the upgrade from the given version is not allowed
  876. */
  877. public static function needUpgrade(\OC\SystemConfig $config) {
  878. if ($config->getValue('installed', false)) {
  879. $installedVersion = $config->getValue('version', '0.0.0');
  880. $currentVersion = implode('.', \OCP\Util::getVersion());
  881. $versionDiff = version_compare($currentVersion, $installedVersion);
  882. if ($versionDiff > 0) {
  883. return true;
  884. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  885. // downgrade with debug
  886. $installedMajor = explode('.', $installedVersion);
  887. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  888. $currentMajor = explode('.', $currentVersion);
  889. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  890. if ($installedMajor === $currentMajor) {
  891. // Same major, allow downgrade for developers
  892. return true;
  893. } else {
  894. // downgrade attempt, throw exception
  895. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  896. }
  897. } elseif ($versionDiff < 0) {
  898. // downgrade attempt, throw exception
  899. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  900. }
  901. // also check for upgrades for apps (independently from the user)
  902. $apps = \OC_App::getEnabledApps(false, true);
  903. $shouldUpgrade = false;
  904. foreach ($apps as $app) {
  905. if (\OC_App::shouldUpgrade($app)) {
  906. $shouldUpgrade = true;
  907. break;
  908. }
  909. }
  910. return $shouldUpgrade;
  911. } else {
  912. return false;
  913. }
  914. }
  915. }