OC_Util.php 34 KB

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