OC_Util.php 37 KB

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