OC_Util.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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 ".ocdata" 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 . '/.ocdata')) {
  645. $errors[] = [
  646. 'error' => $l->t('Your data directory is invalid.'),
  647. 'hint' => $l->t('Ensure there is a file called ".ocdata"' .
  648. ' in the root of the data directory.')
  649. ];
  650. }
  651. return $errors;
  652. }
  653. /**
  654. * Check if the user is logged in, redirects to home if not. With
  655. * redirect URL parameter to the request URI.
  656. *
  657. * @return void
  658. */
  659. public static function checkLoggedIn() {
  660. // Check if we are a user
  661. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  662. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  663. 'core.login.showLoginForm',
  664. [
  665. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  666. ]
  667. )
  668. );
  669. exit();
  670. }
  671. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  672. if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  673. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  674. exit();
  675. }
  676. }
  677. /**
  678. * Check if the user is a admin, redirects to home if not
  679. *
  680. * @return void
  681. */
  682. public static function checkAdminUser() {
  683. OC_Util::checkLoggedIn();
  684. if (!OC_User::isAdminUser(OC_User::getUser())) {
  685. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  686. exit();
  687. }
  688. }
  689. /**
  690. * Returns the URL of the default page
  691. * based on the system configuration and
  692. * the apps visible for the current user
  693. *
  694. * @return string URL
  695. * @suppress PhanDeprecatedFunction
  696. */
  697. public static function getDefaultPageUrl() {
  698. /** @var IURLGenerator $urlGenerator */
  699. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  700. return $urlGenerator->linkToDefaultPageUrl();
  701. }
  702. /**
  703. * Redirect to the user default page
  704. *
  705. * @return void
  706. */
  707. public static function redirectToDefaultPage() {
  708. $location = self::getDefaultPageUrl();
  709. header('Location: ' . $location);
  710. exit();
  711. }
  712. /**
  713. * get an id unique for this instance
  714. *
  715. * @return string
  716. */
  717. public static function getInstanceId() {
  718. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  719. if (is_null($id)) {
  720. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  721. $id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  722. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  723. }
  724. return $id;
  725. }
  726. /**
  727. * Public function to sanitize HTML
  728. *
  729. * This function is used to sanitize HTML and should be applied on any
  730. * string or array of strings before displaying it on a web page.
  731. *
  732. * @param string|string[] $value
  733. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  734. */
  735. public static function sanitizeHTML($value) {
  736. if (is_array($value)) {
  737. /** @var string[] $value */
  738. $value = array_map(function ($value) {
  739. return self::sanitizeHTML($value);
  740. }, $value);
  741. } else {
  742. // Specify encoding for PHP<5.4
  743. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  744. }
  745. return $value;
  746. }
  747. /**
  748. * Public function to encode url parameters
  749. *
  750. * This function is used to encode path to file before output.
  751. * Encoding is done according to RFC 3986 with one exception:
  752. * Character '/' is preserved as is.
  753. *
  754. * @param string $component part of URI to encode
  755. * @return string
  756. */
  757. public static function encodePath($component) {
  758. $encoded = rawurlencode($component);
  759. $encoded = str_replace('%2F', '/', $encoded);
  760. return $encoded;
  761. }
  762. public function createHtaccessTestFile(\OCP\IConfig $config) {
  763. // php dev server does not support htaccess
  764. if (php_sapi_name() === 'cli-server') {
  765. return false;
  766. }
  767. // testdata
  768. $fileName = '/htaccesstest.txt';
  769. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  770. // creating a test file
  771. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  772. if (file_exists($testFile)) {// already running this test, possible recursive call
  773. return false;
  774. }
  775. $fp = @fopen($testFile, 'w');
  776. if (!$fp) {
  777. throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
  778. 'Make sure it is possible for the web server to write to ' . $testFile);
  779. }
  780. fwrite($fp, $testContent);
  781. fclose($fp);
  782. return $testContent;
  783. }
  784. /**
  785. * Check if the .htaccess file is working
  786. *
  787. * @param \OCP\IConfig $config
  788. * @return bool
  789. * @throws Exception
  790. * @throws \OCP\HintException If the test file can't get written.
  791. */
  792. public function isHtaccessWorking(\OCP\IConfig $config) {
  793. if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
  794. return true;
  795. }
  796. $testContent = $this->createHtaccessTestFile($config);
  797. if ($testContent === false) {
  798. return false;
  799. }
  800. $fileName = '/htaccesstest.txt';
  801. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  802. // accessing the file via http
  803. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  804. try {
  805. $content = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  806. } catch (\Exception $e) {
  807. $content = false;
  808. }
  809. if (str_starts_with($url, 'https:')) {
  810. $url = 'http:' . substr($url, 6);
  811. } else {
  812. $url = 'https:' . substr($url, 5);
  813. }
  814. try {
  815. $fallbackContent = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody();
  816. } catch (\Exception $e) {
  817. $fallbackContent = false;
  818. }
  819. // cleanup
  820. @unlink($testFile);
  821. /*
  822. * If the content is not equal to test content our .htaccess
  823. * is working as required
  824. */
  825. return $content !== $testContent && $fallbackContent !== $testContent;
  826. }
  827. /**
  828. * Check if current locale is non-UTF8
  829. *
  830. * @return bool
  831. */
  832. private static function isNonUTF8Locale() {
  833. if (function_exists('escapeshellcmd')) {
  834. return escapeshellcmd('§') === '';
  835. } elseif (function_exists('escapeshellarg')) {
  836. return escapeshellarg('§') === '\'\'';
  837. } else {
  838. return preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0)) === 0;
  839. }
  840. }
  841. /**
  842. * Check if the setlocale call does not work. This can happen if the right
  843. * local packages are not available on the server.
  844. *
  845. * @return bool
  846. */
  847. public static function isSetLocaleWorking() {
  848. if (self::isNonUTF8Locale()) {
  849. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  850. setlocale(LC_ALL, 'C.UTF-8', 'C');
  851. 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');
  852. // Check again
  853. if (self::isNonUTF8Locale()) {
  854. return false;
  855. }
  856. }
  857. return true;
  858. }
  859. /**
  860. * Check if it's possible to get the inline annotations
  861. *
  862. * @return bool
  863. */
  864. public static function isAnnotationsWorking() {
  865. $reflection = new \ReflectionMethod(__METHOD__);
  866. $docs = $reflection->getDocComment();
  867. return (is_string($docs) && strlen($docs) > 50);
  868. }
  869. /**
  870. * Check if the PHP module fileinfo is loaded.
  871. *
  872. * @return bool
  873. */
  874. public static function fileInfoLoaded() {
  875. return function_exists('finfo_open');
  876. }
  877. /**
  878. * clear all levels of output buffering
  879. *
  880. * @return void
  881. */
  882. public static function obEnd() {
  883. while (ob_get_level()) {
  884. ob_end_clean();
  885. }
  886. }
  887. /**
  888. * Checks whether the server is running on Mac OS X
  889. *
  890. * @return bool true if running on Mac OS X, false otherwise
  891. */
  892. public static function runningOnMac() {
  893. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  894. }
  895. /**
  896. * Handles the case that there may not be a theme, then check if a "default"
  897. * theme exists and take that one
  898. *
  899. * @return string the theme
  900. */
  901. public static function getTheme() {
  902. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  903. if ($theme === '') {
  904. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  905. $theme = 'default';
  906. }
  907. }
  908. return $theme;
  909. }
  910. /**
  911. * Normalize a unicode string
  912. *
  913. * @param string $value a not normalized string
  914. * @return bool|string
  915. */
  916. public static function normalizeUnicode($value) {
  917. if (Normalizer::isNormalized($value)) {
  918. return $value;
  919. }
  920. $normalizedValue = Normalizer::normalize($value);
  921. if ($normalizedValue === null || $normalizedValue === false) {
  922. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  923. return $value;
  924. }
  925. return $normalizedValue;
  926. }
  927. /**
  928. * A human readable string is generated based on version and build number
  929. *
  930. * @return string
  931. */
  932. public static function getHumanVersion() {
  933. $version = OC_Util::getVersionString();
  934. $build = OC_Util::getBuild();
  935. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  936. $version .= ' Build:' . $build;
  937. }
  938. return $version;
  939. }
  940. /**
  941. * Returns whether the given file name is valid
  942. *
  943. * @param string $file file name to check
  944. * @return bool true if the file name is valid, false otherwise
  945. * @deprecated use \OC\Files\View::verifyPath()
  946. */
  947. public static function isValidFileName($file) {
  948. $trimmed = trim($file);
  949. if ($trimmed === '') {
  950. return false;
  951. }
  952. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  953. return false;
  954. }
  955. // detect part files
  956. if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
  957. return false;
  958. }
  959. foreach (\OCP\Util::getForbiddenFileNameChars() as $char) {
  960. if (str_contains($trimmed, $char)) {
  961. return false;
  962. }
  963. }
  964. return true;
  965. }
  966. /**
  967. * Check whether the instance needs to perform an upgrade,
  968. * either when the core version is higher or any app requires
  969. * an upgrade.
  970. *
  971. * @param \OC\SystemConfig $config
  972. * @return bool whether the core or any app needs an upgrade
  973. * @throws \OCP\HintException When the upgrade from the given version is not allowed
  974. */
  975. public static function needUpgrade(\OC\SystemConfig $config) {
  976. if ($config->getValue('installed', false)) {
  977. $installedVersion = $config->getValue('version', '0.0.0');
  978. $currentVersion = implode('.', \OCP\Util::getVersion());
  979. $versionDiff = version_compare($currentVersion, $installedVersion);
  980. if ($versionDiff > 0) {
  981. return true;
  982. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  983. // downgrade with debug
  984. $installedMajor = explode('.', $installedVersion);
  985. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  986. $currentMajor = explode('.', $currentVersion);
  987. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  988. if ($installedMajor === $currentMajor) {
  989. // Same major, allow downgrade for developers
  990. return true;
  991. } else {
  992. // downgrade attempt, throw exception
  993. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  994. }
  995. } elseif ($versionDiff < 0) {
  996. // downgrade attempt, throw exception
  997. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  998. }
  999. // also check for upgrades for apps (independently from the user)
  1000. $apps = \OC_App::getEnabledApps(false, true);
  1001. $shouldUpgrade = false;
  1002. foreach ($apps as $app) {
  1003. if (\OC_App::shouldUpgrade($app)) {
  1004. $shouldUpgrade = true;
  1005. break;
  1006. }
  1007. }
  1008. return $shouldUpgrade;
  1009. } else {
  1010. return false;
  1011. }
  1012. }
  1013. }