OC_Util.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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 = \OC::$server->getLogger();
  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. * get the current installed version of ownCloud
  197. *
  198. * @return array
  199. */
  200. public static function getVersion() {
  201. OC_Util::loadVersion();
  202. return self::$versionCache['OC_Version'];
  203. }
  204. /**
  205. * get the current installed version string of ownCloud
  206. *
  207. * @return string
  208. */
  209. public static function getVersionString() {
  210. OC_Util::loadVersion();
  211. return self::$versionCache['OC_VersionString'];
  212. }
  213. /**
  214. * @deprecated the value is of no use anymore
  215. * @return string
  216. */
  217. public static function getEditionString() {
  218. return '';
  219. }
  220. /**
  221. * @description get the update channel of the current installed of ownCloud.
  222. * @return string
  223. */
  224. public static function getChannel() {
  225. OC_Util::loadVersion();
  226. return \OC::$server->getConfig()->getSystemValueString('updater.release.channel', self::$versionCache['OC_Channel']);
  227. }
  228. /**
  229. * @description get the build number of the current installed of ownCloud.
  230. * @return string
  231. */
  232. public static function getBuild() {
  233. OC_Util::loadVersion();
  234. return self::$versionCache['OC_Build'];
  235. }
  236. /**
  237. * @description load the version.php into the session as cache
  238. * @suppress PhanUndeclaredVariable
  239. */
  240. private static function loadVersion() {
  241. if (self::$versionCache !== null) {
  242. return;
  243. }
  244. $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
  245. require OC::$SERVERROOT . '/version.php';
  246. /** @var int $timestamp */
  247. self::$versionCache['OC_Version_Timestamp'] = $timestamp;
  248. /** @var string $OC_Version */
  249. self::$versionCache['OC_Version'] = $OC_Version;
  250. /** @var string $OC_VersionString */
  251. self::$versionCache['OC_VersionString'] = $OC_VersionString;
  252. /** @var string $OC_Build */
  253. self::$versionCache['OC_Build'] = $OC_Build;
  254. /** @var string $OC_Channel */
  255. self::$versionCache['OC_Channel'] = $OC_Channel;
  256. }
  257. /**
  258. * generates a path for JS/CSS files. If no application is provided it will create the path for core.
  259. *
  260. * @param string $application application to get the files from
  261. * @param string $directory directory within this application (css, js, vendor, etc)
  262. * @param string $file the file inside of the above folder
  263. * @return string the path
  264. */
  265. private static function generatePath($application, $directory, $file) {
  266. if (is_null($file)) {
  267. $file = $application;
  268. $application = "";
  269. }
  270. if (!empty($application)) {
  271. return "$application/$directory/$file";
  272. } else {
  273. return "$directory/$file";
  274. }
  275. }
  276. /**
  277. * add a javascript file
  278. *
  279. * @deprecated 24.0.0 - Use \OCP\Util::addScript
  280. *
  281. * @param string $application application id
  282. * @param string|null $file filename
  283. * @param bool $prepend prepend the Script to the beginning of the list
  284. * @return void
  285. */
  286. public static function addScript($application, $file = null, $prepend = false) {
  287. $path = OC_Util::generatePath($application, 'js', $file);
  288. // core js files need separate handling
  289. if ($application !== 'core' && $file !== null) {
  290. self::addTranslations($application);
  291. }
  292. self::addExternalResource($application, $prepend, $path, "script");
  293. }
  294. /**
  295. * add a javascript file from the vendor sub folder
  296. *
  297. * @param string $application application id
  298. * @param string|null $file filename
  299. * @param bool $prepend prepend the Script to the beginning of the list
  300. * @return void
  301. */
  302. public static function addVendorScript($application, $file = null, $prepend = false) {
  303. $path = OC_Util::generatePath($application, 'vendor', $file);
  304. self::addExternalResource($application, $prepend, $path, "script");
  305. }
  306. /**
  307. * add a translation JS file
  308. *
  309. * @deprecated 24.0.0
  310. *
  311. * @param string $application application id
  312. * @param string|null $languageCode language code, defaults to the current language
  313. * @param bool|null $prepend prepend the Script to the beginning of the list
  314. */
  315. public static function addTranslations($application, $languageCode = null, $prepend = false) {
  316. if (is_null($languageCode)) {
  317. $languageCode = \OC::$server->get(IFactory::class)->findLanguage($application);
  318. }
  319. if (!empty($application)) {
  320. $path = "$application/l10n/$languageCode";
  321. } else {
  322. $path = "l10n/$languageCode";
  323. }
  324. self::addExternalResource($application, $prepend, $path, "script");
  325. }
  326. /**
  327. * add a css file
  328. *
  329. * @param string $application application id
  330. * @param string|null $file filename
  331. * @param bool $prepend prepend the Style to the beginning of the list
  332. * @return void
  333. */
  334. public static function addStyle($application, $file = null, $prepend = false) {
  335. $path = OC_Util::generatePath($application, 'css', $file);
  336. self::addExternalResource($application, $prepend, $path, "style");
  337. }
  338. /**
  339. * add a css file from the vendor sub folder
  340. *
  341. * @param string $application application id
  342. * @param string|null $file filename
  343. * @param bool $prepend prepend the Style to the beginning of the list
  344. * @return void
  345. */
  346. public static function addVendorStyle($application, $file = null, $prepend = false) {
  347. $path = OC_Util::generatePath($application, 'vendor', $file);
  348. self::addExternalResource($application, $prepend, $path, "style");
  349. }
  350. /**
  351. * add an external resource css/js file
  352. *
  353. * @param string $application application id
  354. * @param bool $prepend prepend the file to the beginning of the list
  355. * @param string $path
  356. * @param string $type (script or style)
  357. * @return void
  358. */
  359. private static function addExternalResource($application, $prepend, $path, $type = "script") {
  360. if ($type === "style") {
  361. if (!in_array($path, self::$styles)) {
  362. if ($prepend === true) {
  363. array_unshift(self::$styles, $path);
  364. } else {
  365. self::$styles[] = $path;
  366. }
  367. }
  368. } elseif ($type === "script") {
  369. if (!in_array($path, self::$scripts)) {
  370. if ($prepend === true) {
  371. array_unshift(self::$scripts, $path);
  372. } else {
  373. self::$scripts [] = $path;
  374. }
  375. }
  376. }
  377. }
  378. /**
  379. * Add a custom element to the header
  380. * If $text is null then the element will be written as empty element.
  381. * So use "" to get a closing tag.
  382. * @param string $tag tag name of the element
  383. * @param array $attributes array of attributes for the element
  384. * @param string $text the text content for the element
  385. * @param bool $prepend prepend the header to the beginning of the list
  386. */
  387. public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
  388. $header = [
  389. 'tag' => $tag,
  390. 'attributes' => $attributes,
  391. 'text' => $text
  392. ];
  393. if ($prepend === true) {
  394. array_unshift(self::$headers, $header);
  395. } else {
  396. self::$headers[] = $header;
  397. }
  398. }
  399. /**
  400. * check if the current server configuration is suitable for ownCloud
  401. *
  402. * @param \OC\SystemConfig $config
  403. * @return array arrays with error messages and hints
  404. */
  405. public static function checkServer(\OC\SystemConfig $config) {
  406. $l = \OC::$server->getL10N('lib');
  407. $errors = [];
  408. $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
  409. if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
  410. // this check needs to be done every time
  411. $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
  412. }
  413. // Assume that if checkServer() succeeded before in this session, then all is fine.
  414. if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
  415. return $errors;
  416. }
  417. $webServerRestart = false;
  418. $setup = \OCP\Server::get(\OC\Setup::class);
  419. $urlGenerator = \OC::$server->getURLGenerator();
  420. $availableDatabases = $setup->getSupportedDatabases();
  421. if (empty($availableDatabases)) {
  422. $errors[] = [
  423. 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
  424. 'hint' => '' //TODO: sane hint
  425. ];
  426. $webServerRestart = true;
  427. }
  428. // Check if config folder is writable.
  429. if (!OC_Helper::isReadOnlyConfigEnabled()) {
  430. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  431. $errors[] = [
  432. 'error' => $l->t('Cannot write into "config" directory.'),
  433. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
  434. [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
  435. . $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',
  436. [ $urlGenerator->linkToDocs('admin-config') ])
  437. ];
  438. }
  439. }
  440. // Check if there is a writable install folder.
  441. if ($config->getValue('appstoreenabled', true)) {
  442. if (OC_App::getInstallPath() === null
  443. || !is_writable(OC_App::getInstallPath())
  444. || !is_readable(OC_App::getInstallPath())
  445. ) {
  446. $errors[] = [
  447. 'error' => $l->t('Cannot write into "apps" directory.'),
  448. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
  449. . ' or disabling the App Store in the config file.')
  450. ];
  451. }
  452. }
  453. // Create root dir.
  454. if ($config->getValue('installed', false)) {
  455. if (!is_dir($CONFIG_DATADIRECTORY)) {
  456. $success = @mkdir($CONFIG_DATADIRECTORY);
  457. if ($success) {
  458. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  459. } else {
  460. $errors[] = [
  461. 'error' => $l->t('Cannot create "data" directory.'),
  462. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
  463. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  464. ];
  465. }
  466. } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  467. // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
  468. $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
  469. $handle = fopen($testFile, 'w');
  470. if (!$handle || fwrite($handle, 'Test write operation') === false) {
  471. $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
  472. [$urlGenerator->linkToDocs('admin-dir_permissions')]);
  473. $errors[] = [
  474. 'error' => $l->t('Your data directory is not writable.'),
  475. 'hint' => $permissionsHint
  476. ];
  477. } else {
  478. fclose($handle);
  479. unlink($testFile);
  480. }
  481. } else {
  482. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  483. }
  484. }
  485. if (!OC_Util::isSetLocaleWorking()) {
  486. $errors[] = [
  487. 'error' => $l->t('Setting locale to %s failed.',
  488. ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  489. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
  490. 'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
  491. ];
  492. }
  493. // Contains the dependencies that should be checked against
  494. // classes = class_exists
  495. // functions = function_exists
  496. // defined = defined
  497. // ini = ini_get
  498. // If the dependency is not found the missing module name is shown to the EndUser
  499. // When adding new checks always verify that they pass on Travis as well
  500. // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
  501. $dependencies = [
  502. 'classes' => [
  503. 'ZipArchive' => 'zip',
  504. 'DOMDocument' => 'dom',
  505. 'XMLWriter' => 'XMLWriter',
  506. 'XMLReader' => 'XMLReader',
  507. ],
  508. 'functions' => [
  509. 'xml_parser_create' => 'libxml',
  510. 'mb_strcut' => 'mbstring',
  511. 'ctype_digit' => 'ctype',
  512. 'json_encode' => 'JSON',
  513. 'gd_info' => 'GD',
  514. 'gzencode' => 'zlib',
  515. 'simplexml_load_string' => 'SimpleXML',
  516. 'hash' => 'HASH Message Digest Framework',
  517. 'curl_init' => 'cURL',
  518. 'openssl_verify' => 'OpenSSL',
  519. ],
  520. 'defined' => [
  521. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  522. ],
  523. 'ini' => [
  524. 'default_charset' => 'UTF-8',
  525. ],
  526. ];
  527. $missingDependencies = [];
  528. $invalidIniSettings = [];
  529. $iniWrapper = \OC::$server->get(IniGetWrapper::class);
  530. foreach ($dependencies['classes'] as $class => $module) {
  531. if (!class_exists($class)) {
  532. $missingDependencies[] = $module;
  533. }
  534. }
  535. foreach ($dependencies['functions'] as $function => $module) {
  536. if (!function_exists($function)) {
  537. $missingDependencies[] = $module;
  538. }
  539. }
  540. foreach ($dependencies['defined'] as $defined => $module) {
  541. if (!defined($defined)) {
  542. $missingDependencies[] = $module;
  543. }
  544. }
  545. foreach ($dependencies['ini'] as $setting => $expected) {
  546. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  547. $invalidIniSettings[] = [$setting, $expected];
  548. }
  549. }
  550. foreach ($missingDependencies as $missingDependency) {
  551. $errors[] = [
  552. 'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
  553. 'hint' => $l->t('Please ask your server administrator to install the module.'),
  554. ];
  555. $webServerRestart = true;
  556. }
  557. foreach ($invalidIniSettings as $setting) {
  558. $errors[] = [
  559. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  560. 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
  561. ];
  562. $webServerRestart = true;
  563. }
  564. /**
  565. * The mbstring.func_overload check can only be performed if the mbstring
  566. * module is installed as it will return null if the checking setting is
  567. * not available and thus a check on the boolean value fails.
  568. *
  569. * TODO: Should probably be implemented in the above generic dependency
  570. * check somehow in the long-term.
  571. */
  572. if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
  573. $iniWrapper->getBool('mbstring.func_overload') === true) {
  574. $errors[] = [
  575. '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')]),
  576. 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
  577. ];
  578. }
  579. if (!self::isAnnotationsWorking()) {
  580. $errors[] = [
  581. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  582. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  583. ];
  584. }
  585. if (!\OC::$CLI && $webServerRestart) {
  586. $errors[] = [
  587. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  588. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  589. ];
  590. }
  591. foreach (['secret', 'instanceid', 'passwordsalt'] as $requiredConfig) {
  592. if ($config->getValue($requiredConfig, '') === '' && !\OC::$CLI && $config->getValue('installed', false)) {
  593. $errors[] = [
  594. 'error' => $l->t('The required %s config variable is not configured in the config.php file.', [$requiredConfig]),
  595. 'hint' => $l->t('Please ask your server administrator to check the Nextcloud configuration.')
  596. ];
  597. }
  598. }
  599. // Cache the result of this function
  600. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  601. return $errors;
  602. }
  603. /**
  604. * Check for correct file permissions of data directory
  605. *
  606. * @param string $dataDirectory
  607. * @return array arrays with error messages and hints
  608. */
  609. public static function checkDataDirectoryPermissions($dataDirectory) {
  610. if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
  611. return [];
  612. }
  613. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  614. if (substr($perms, -1) !== '0') {
  615. chmod($dataDirectory, 0770);
  616. clearstatcache();
  617. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  618. if ($perms[2] !== '0') {
  619. $l = \OC::$server->getL10N('lib');
  620. return [[
  621. 'error' => $l->t('Your data directory is readable by other people.'),
  622. 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other people.'),
  623. ]];
  624. }
  625. }
  626. return [];
  627. }
  628. /**
  629. * Check that the data directory exists and is valid by
  630. * checking the existence of the ".ncdata" file.
  631. *
  632. * @param string $dataDirectory data directory path
  633. * @return array errors found
  634. */
  635. public static function checkDataDirectoryValidity($dataDirectory) {
  636. $l = \OC::$server->getL10N('lib');
  637. $errors = [];
  638. if ($dataDirectory[0] !== '/') {
  639. $errors[] = [
  640. 'error' => $l->t('Your data directory must be an absolute path.'),
  641. 'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
  642. ];
  643. }
  644. if (!file_exists($dataDirectory . '/.ncdata')) {
  645. $errors[] = [
  646. 'error' => $l->t('Your data directory is invalid.'),
  647. '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']),
  648. ];
  649. }
  650. return $errors;
  651. }
  652. /**
  653. * Check if the user is logged in, redirects to home if not. With
  654. * redirect URL parameter to the request URI.
  655. *
  656. * @return void
  657. */
  658. public static function checkLoggedIn() {
  659. // Check if we are a user
  660. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  661. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  662. 'core.login.showLoginForm',
  663. [
  664. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  665. ]
  666. )
  667. );
  668. exit();
  669. }
  670. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  671. if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  672. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  673. exit();
  674. }
  675. }
  676. /**
  677. * Check if the user is a admin, redirects to home if not
  678. *
  679. * @return void
  680. */
  681. public static function checkAdminUser() {
  682. OC_Util::checkLoggedIn();
  683. if (!OC_User::isAdminUser(OC_User::getUser())) {
  684. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  685. exit();
  686. }
  687. }
  688. /**
  689. * Returns the URL of the default page
  690. * based on the system configuration and
  691. * the apps visible for the current user
  692. *
  693. * @return string URL
  694. * @suppress PhanDeprecatedFunction
  695. */
  696. public static function getDefaultPageUrl() {
  697. /** @var IURLGenerator $urlGenerator */
  698. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  699. return $urlGenerator->linkToDefaultPageUrl();
  700. }
  701. /**
  702. * Redirect to the user default page
  703. *
  704. * @return void
  705. */
  706. public static function redirectToDefaultPage() {
  707. $location = self::getDefaultPageUrl();
  708. header('Location: ' . $location);
  709. exit();
  710. }
  711. /**
  712. * get an id unique for this instance
  713. *
  714. * @return string
  715. */
  716. public static function getInstanceId() {
  717. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  718. if (is_null($id)) {
  719. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  720. $id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  721. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  722. }
  723. return $id;
  724. }
  725. /**
  726. * Public function to sanitize HTML
  727. *
  728. * This function is used to sanitize HTML and should be applied on any
  729. * string or array of strings before displaying it on a web page.
  730. *
  731. * @param string|string[] $value
  732. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  733. */
  734. public static function sanitizeHTML($value) {
  735. if (is_array($value)) {
  736. /** @var string[] $value */
  737. $value = array_map(function ($value) {
  738. return self::sanitizeHTML($value);
  739. }, $value);
  740. } else {
  741. // Specify encoding for PHP<5.4
  742. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  743. }
  744. return $value;
  745. }
  746. /**
  747. * Public function to encode url parameters
  748. *
  749. * This function is used to encode path to file before output.
  750. * Encoding is done according to RFC 3986 with one exception:
  751. * Character '/' is preserved as is.
  752. *
  753. * @param string $component part of URI to encode
  754. * @return string
  755. */
  756. public static function encodePath($component) {
  757. $encoded = rawurlencode($component);
  758. $encoded = str_replace('%2F', '/', $encoded);
  759. return $encoded;
  760. }
  761. public function createHtaccessTestFile(\OCP\IConfig $config) {
  762. // php dev server does not support htaccess
  763. if (php_sapi_name() === 'cli-server') {
  764. return false;
  765. }
  766. // testdata
  767. $fileName = '/htaccesstest.txt';
  768. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  769. // creating a test file
  770. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  771. if (file_exists($testFile)) {// already running this test, possible recursive call
  772. return false;
  773. }
  774. $fp = @fopen($testFile, 'w');
  775. if (!$fp) {
  776. throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
  777. 'Make sure it is possible for the web server to write to ' . $testFile);
  778. }
  779. fwrite($fp, $testContent);
  780. fclose($fp);
  781. return $testContent;
  782. }
  783. /**
  784. * Check if the .htaccess file is working
  785. *
  786. * @param \OCP\IConfig $config
  787. * @return bool
  788. * @throws Exception
  789. * @throws \OCP\HintException If the test file can't get written.
  790. */
  791. public function isHtaccessWorking(\OCP\IConfig $config) {
  792. if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
  793. return true;
  794. }
  795. $testContent = $this->createHtaccessTestFile($config);
  796. if ($testContent === false) {
  797. return false;
  798. }
  799. $fileName = '/htaccesstest.txt';
  800. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  801. // accessing the file via http
  802. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  803. try {
  804. $content = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  805. } catch (\Exception $e) {
  806. $content = false;
  807. }
  808. if (str_starts_with($url, 'https:')) {
  809. $url = 'http:' . substr($url, 6);
  810. } else {
  811. $url = 'https:' . substr($url, 5);
  812. }
  813. try {
  814. $fallbackContent = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  815. } catch (\Exception $e) {
  816. $fallbackContent = false;
  817. }
  818. // cleanup
  819. @unlink($testFile);
  820. /*
  821. * If the content is not equal to test content our .htaccess
  822. * is working as required
  823. */
  824. return $content !== $testContent && $fallbackContent !== $testContent;
  825. }
  826. /**
  827. * Check if current locale is non-UTF8
  828. *
  829. * @return bool
  830. */
  831. private static function isNonUTF8Locale() {
  832. if (function_exists('escapeshellcmd')) {
  833. return escapeshellcmd('§') === '';
  834. } elseif (function_exists('escapeshellarg')) {
  835. return escapeshellarg('§') === '\'\'';
  836. } else {
  837. return preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0)) === 0;
  838. }
  839. }
  840. /**
  841. * Check if the setlocale call does not work. This can happen if the right
  842. * local packages are not available on the server.
  843. *
  844. * @return bool
  845. */
  846. public static function isSetLocaleWorking() {
  847. if (self::isNonUTF8Locale()) {
  848. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  849. setlocale(LC_ALL, 'C.UTF-8', 'C');
  850. 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');
  851. // Check again
  852. if (self::isNonUTF8Locale()) {
  853. return false;
  854. }
  855. }
  856. return true;
  857. }
  858. /**
  859. * Check if it's possible to get the inline annotations
  860. *
  861. * @return bool
  862. */
  863. public static function isAnnotationsWorking() {
  864. $reflection = new \ReflectionMethod(__METHOD__);
  865. $docs = $reflection->getDocComment();
  866. return (is_string($docs) && strlen($docs) > 50);
  867. }
  868. /**
  869. * Check if the PHP module fileinfo is loaded.
  870. *
  871. * @return bool
  872. */
  873. public static function fileInfoLoaded() {
  874. return function_exists('finfo_open');
  875. }
  876. /**
  877. * clear all levels of output buffering
  878. *
  879. * @return void
  880. */
  881. public static function obEnd() {
  882. while (ob_get_level()) {
  883. ob_end_clean();
  884. }
  885. }
  886. /**
  887. * Checks whether the server is running on Mac OS X
  888. *
  889. * @return bool true if running on Mac OS X, false otherwise
  890. */
  891. public static function runningOnMac() {
  892. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  893. }
  894. /**
  895. * Handles the case that there may not be a theme, then check if a "default"
  896. * theme exists and take that one
  897. *
  898. * @return string the theme
  899. */
  900. public static function getTheme() {
  901. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  902. if ($theme === '') {
  903. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  904. $theme = 'default';
  905. }
  906. }
  907. return $theme;
  908. }
  909. /**
  910. * Normalize a unicode string
  911. *
  912. * @param string $value a not normalized string
  913. * @return bool|string
  914. */
  915. public static function normalizeUnicode($value) {
  916. if (Normalizer::isNormalized($value)) {
  917. return $value;
  918. }
  919. $normalizedValue = Normalizer::normalize($value);
  920. if ($normalizedValue === null || $normalizedValue === false) {
  921. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  922. return $value;
  923. }
  924. return $normalizedValue;
  925. }
  926. /**
  927. * A human readable string is generated based on version and build number
  928. *
  929. * @return string
  930. */
  931. public static function getHumanVersion() {
  932. $version = OC_Util::getVersionString();
  933. $build = OC_Util::getBuild();
  934. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  935. $version .= ' Build:' . $build;
  936. }
  937. return $version;
  938. }
  939. /**
  940. * Check whether the instance needs to perform an upgrade,
  941. * either when the core version is higher or any app requires
  942. * an upgrade.
  943. *
  944. * @param \OC\SystemConfig $config
  945. * @return bool whether the core or any app needs an upgrade
  946. * @throws \OCP\HintException When the upgrade from the given version is not allowed
  947. */
  948. public static function needUpgrade(\OC\SystemConfig $config) {
  949. if ($config->getValue('installed', false)) {
  950. $installedVersion = $config->getValue('version', '0.0.0');
  951. $currentVersion = implode('.', \OCP\Util::getVersion());
  952. $versionDiff = version_compare($currentVersion, $installedVersion);
  953. if ($versionDiff > 0) {
  954. return true;
  955. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  956. // downgrade with debug
  957. $installedMajor = explode('.', $installedVersion);
  958. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  959. $currentMajor = explode('.', $currentVersion);
  960. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  961. if ($installedMajor === $currentMajor) {
  962. // Same major, allow downgrade for developers
  963. return true;
  964. } else {
  965. // downgrade attempt, throw exception
  966. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  967. }
  968. } elseif ($versionDiff < 0) {
  969. // downgrade attempt, throw exception
  970. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  971. }
  972. // also check for upgrades for apps (independently from the user)
  973. $apps = \OC_App::getEnabledApps(false, true);
  974. $shouldUpgrade = false;
  975. foreach ($apps as $app) {
  976. if (\OC_App::shouldUpgrade($app)) {
  977. $shouldUpgrade = true;
  978. break;
  979. }
  980. }
  981. return $shouldUpgrade;
  982. } else {
  983. return false;
  984. }
  985. }
  986. }