1
0

OC_Util.php 36 KB

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