OC_Util.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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\IDBConnection;
  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. require OC::$SERVERROOT . '/version.php';
  301. /** @var int $timestamp */
  302. self::$versionCache['OC_Version_Timestamp'] = \OC::$VERSION_MTIME;
  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. $errors = array_merge($errors, self::checkDatabaseVersion());
  663. // Cache the result of this function
  664. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  665. return $errors;
  666. }
  667. /**
  668. * Check the database version
  669. *
  670. * @return array errors array
  671. */
  672. public static function checkDatabaseVersion() {
  673. $l = \OC::$server->getL10N('lib');
  674. $errors = [];
  675. $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
  676. if ($dbType === 'pgsql') {
  677. // check PostgreSQL version
  678. // TODO latest postgresql 8 released was 8 years ago, maybe remove the
  679. // check completely?
  680. try {
  681. /** @var IDBConnection $connection */
  682. $connection = \OC::$server->get(IDBConnection::class);
  683. $result = $connection->executeQuery('SHOW SERVER_VERSION');
  684. $data = $result->fetch();
  685. $result->closeCursor();
  686. if (isset($data['server_version'])) {
  687. $version = $data['server_version'];
  688. if (version_compare($version, '9.0.0', '<')) {
  689. $errors[] = [
  690. 'error' => $l->t('PostgreSQL >= 9 required.'),
  691. 'hint' => $l->t('Please upgrade your database version.')
  692. ];
  693. }
  694. }
  695. } catch (\Doctrine\DBAL\Exception $e) {
  696. $logger = \OC::$server->getLogger();
  697. $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
  698. $logger->logException($e);
  699. }
  700. }
  701. return $errors;
  702. }
  703. /**
  704. * Check for correct file permissions of data directory
  705. *
  706. * @param string $dataDirectory
  707. * @return array arrays with error messages and hints
  708. */
  709. public static function checkDataDirectoryPermissions($dataDirectory) {
  710. if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
  711. return [];
  712. }
  713. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  714. if (substr($perms, -1) !== '0') {
  715. chmod($dataDirectory, 0770);
  716. clearstatcache();
  717. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  718. if ($perms[2] !== '0') {
  719. $l = \OC::$server->getL10N('lib');
  720. return [[
  721. 'error' => $l->t('Your data directory is readable by other users.'),
  722. 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
  723. ]];
  724. }
  725. }
  726. return [];
  727. }
  728. /**
  729. * Check that the data directory exists and is valid by
  730. * checking the existence of the ".ocdata" file.
  731. *
  732. * @param string $dataDirectory data directory path
  733. * @return array errors found
  734. */
  735. public static function checkDataDirectoryValidity($dataDirectory) {
  736. $l = \OC::$server->getL10N('lib');
  737. $errors = [];
  738. if ($dataDirectory[0] !== '/') {
  739. $errors[] = [
  740. 'error' => $l->t('Your data directory must be an absolute path.'),
  741. 'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
  742. ];
  743. }
  744. if (!file_exists($dataDirectory . '/.ocdata')) {
  745. $errors[] = [
  746. 'error' => $l->t('Your data directory is invalid.'),
  747. 'hint' => $l->t('Ensure there is a file called ".ocdata"' .
  748. ' in the root of the data directory.')
  749. ];
  750. }
  751. return $errors;
  752. }
  753. /**
  754. * Check if the user is logged in, redirects to home if not. With
  755. * redirect URL parameter to the request URI.
  756. *
  757. * @return void
  758. */
  759. public static function checkLoggedIn() {
  760. // Check if we are a user
  761. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  762. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  763. 'core.login.showLoginForm',
  764. [
  765. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  766. ]
  767. )
  768. );
  769. exit();
  770. }
  771. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  772. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  773. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  774. exit();
  775. }
  776. }
  777. /**
  778. * Check if the user is a admin, redirects to home if not
  779. *
  780. * @return void
  781. */
  782. public static function checkAdminUser() {
  783. OC_Util::checkLoggedIn();
  784. if (!OC_User::isAdminUser(OC_User::getUser())) {
  785. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  786. exit();
  787. }
  788. }
  789. /**
  790. * Returns the URL of the default page
  791. * based on the system configuration and
  792. * the apps visible for the current user
  793. *
  794. * @return string URL
  795. * @suppress PhanDeprecatedFunction
  796. */
  797. public static function getDefaultPageUrl() {
  798. /** @var IURLGenerator $urlGenerator */
  799. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  800. return $urlGenerator->linkToDefaultPageUrl();
  801. }
  802. /**
  803. * Redirect to the user default page
  804. *
  805. * @return void
  806. */
  807. public static function redirectToDefaultPage() {
  808. $location = self::getDefaultPageUrl();
  809. header('Location: ' . $location);
  810. exit();
  811. }
  812. /**
  813. * get an id unique for this instance
  814. *
  815. * @return string
  816. */
  817. public static function getInstanceId() {
  818. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  819. if (is_null($id)) {
  820. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  821. $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  822. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  823. }
  824. return $id;
  825. }
  826. /**
  827. * Public function to sanitize HTML
  828. *
  829. * This function is used to sanitize HTML and should be applied on any
  830. * string or array of strings before displaying it on a web page.
  831. *
  832. * @param string|string[] $value
  833. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  834. */
  835. public static function sanitizeHTML($value) {
  836. if (is_array($value)) {
  837. /** @var string[] $value */
  838. $value = array_map(function ($value) {
  839. return self::sanitizeHTML($value);
  840. }, $value);
  841. } else {
  842. // Specify encoding for PHP<5.4
  843. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  844. }
  845. return $value;
  846. }
  847. /**
  848. * Public function to encode url parameters
  849. *
  850. * This function is used to encode path to file before output.
  851. * Encoding is done according to RFC 3986 with one exception:
  852. * Character '/' is preserved as is.
  853. *
  854. * @param string $component part of URI to encode
  855. * @return string
  856. */
  857. public static function encodePath($component) {
  858. $encoded = rawurlencode($component);
  859. $encoded = str_replace('%2F', '/', $encoded);
  860. return $encoded;
  861. }
  862. public function createHtaccessTestFile(\OCP\IConfig $config) {
  863. // php dev server does not support htaccess
  864. if (php_sapi_name() === 'cli-server') {
  865. return false;
  866. }
  867. // testdata
  868. $fileName = '/htaccesstest.txt';
  869. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  870. // creating a test file
  871. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  872. if (file_exists($testFile)) {// already running this test, possible recursive call
  873. return false;
  874. }
  875. $fp = @fopen($testFile, 'w');
  876. if (!$fp) {
  877. throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
  878. 'Make sure it is possible for the web server to write to ' . $testFile);
  879. }
  880. fwrite($fp, $testContent);
  881. fclose($fp);
  882. return $testContent;
  883. }
  884. /**
  885. * Check if the .htaccess file is working
  886. *
  887. * @param \OCP\IConfig $config
  888. * @return bool
  889. * @throws Exception
  890. * @throws \OCP\HintException If the test file can't get written.
  891. */
  892. public function isHtaccessWorking(\OCP\IConfig $config) {
  893. if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
  894. return true;
  895. }
  896. $testContent = $this->createHtaccessTestFile($config);
  897. if ($testContent === false) {
  898. return false;
  899. }
  900. $fileName = '/htaccesstest.txt';
  901. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  902. // accessing the file via http
  903. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  904. try {
  905. $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  906. } catch (\Exception $e) {
  907. $content = false;
  908. }
  909. if (str_starts_with($url, 'https:')) {
  910. $url = 'http:' . substr($url, 6);
  911. } else {
  912. $url = 'https:' . substr($url, 5);
  913. }
  914. try {
  915. $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  916. } catch (\Exception $e) {
  917. $fallbackContent = false;
  918. }
  919. // cleanup
  920. @unlink($testFile);
  921. /*
  922. * If the content is not equal to test content our .htaccess
  923. * is working as required
  924. */
  925. return $content !== $testContent && $fallbackContent !== $testContent;
  926. }
  927. /**
  928. * Check if current locale is non-UTF8
  929. *
  930. * @return bool
  931. */
  932. private static function isNonUTF8Locale() {
  933. if (function_exists('escapeshellcmd')) {
  934. return '' === escapeshellcmd('§');
  935. } elseif (function_exists('escapeshellarg')) {
  936. return '\'\'' === escapeshellarg('§');
  937. } else {
  938. return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
  939. }
  940. }
  941. /**
  942. * Check if the setlocale call does not work. This can happen if the right
  943. * local packages are not available on the server.
  944. *
  945. * @return bool
  946. */
  947. public static function isSetLocaleWorking() {
  948. if (self::isNonUTF8Locale()) {
  949. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  950. setlocale(LC_ALL, 'C.UTF-8', 'C');
  951. 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');
  952. // Check again
  953. if (self::isNonUTF8Locale()) {
  954. return false;
  955. }
  956. }
  957. return true;
  958. }
  959. /**
  960. * Check if it's possible to get the inline annotations
  961. *
  962. * @return bool
  963. */
  964. public static function isAnnotationsWorking() {
  965. $reflection = new \ReflectionMethod(__METHOD__);
  966. $docs = $reflection->getDocComment();
  967. return (is_string($docs) && strlen($docs) > 50);
  968. }
  969. /**
  970. * Check if the PHP module fileinfo is loaded.
  971. *
  972. * @return bool
  973. */
  974. public static function fileInfoLoaded() {
  975. return function_exists('finfo_open');
  976. }
  977. /**
  978. * clear all levels of output buffering
  979. *
  980. * @return void
  981. */
  982. public static function obEnd() {
  983. while (ob_get_level()) {
  984. ob_end_clean();
  985. }
  986. }
  987. /**
  988. * Checks whether the server is running on Mac OS X
  989. *
  990. * @return bool true if running on Mac OS X, false otherwise
  991. */
  992. public static function runningOnMac() {
  993. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  994. }
  995. /**
  996. * Handles the case that there may not be a theme, then check if a "default"
  997. * theme exists and take that one
  998. *
  999. * @return string the theme
  1000. */
  1001. public static function getTheme() {
  1002. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  1003. if ($theme === '') {
  1004. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1005. $theme = 'default';
  1006. }
  1007. }
  1008. return $theme;
  1009. }
  1010. /**
  1011. * Normalize a unicode string
  1012. *
  1013. * @param string $value a not normalized string
  1014. * @return bool|string
  1015. */
  1016. public static function normalizeUnicode($value) {
  1017. if (Normalizer::isNormalized($value)) {
  1018. return $value;
  1019. }
  1020. $normalizedValue = Normalizer::normalize($value);
  1021. if ($normalizedValue === null || $normalizedValue === false) {
  1022. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  1023. return $value;
  1024. }
  1025. return $normalizedValue;
  1026. }
  1027. /**
  1028. * A human readable string is generated based on version and build number
  1029. *
  1030. * @return string
  1031. */
  1032. public static function getHumanVersion() {
  1033. $version = OC_Util::getVersionString();
  1034. $build = OC_Util::getBuild();
  1035. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1036. $version .= ' Build:' . $build;
  1037. }
  1038. return $version;
  1039. }
  1040. /**
  1041. * Returns whether the given file name is valid
  1042. *
  1043. * @param string $file file name to check
  1044. * @return bool true if the file name is valid, false otherwise
  1045. * @deprecated use \OC\Files\View::verifyPath()
  1046. */
  1047. public static function isValidFileName($file) {
  1048. $trimmed = trim($file);
  1049. if ($trimmed === '') {
  1050. return false;
  1051. }
  1052. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  1053. return false;
  1054. }
  1055. // detect part files
  1056. if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
  1057. return false;
  1058. }
  1059. foreach (str_split($trimmed) as $char) {
  1060. if (str_contains(\OCP\Constants::FILENAME_INVALID_CHARS, $char)) {
  1061. return false;
  1062. }
  1063. }
  1064. return true;
  1065. }
  1066. /**
  1067. * Check whether the instance needs to perform an upgrade,
  1068. * either when the core version is higher or any app requires
  1069. * an upgrade.
  1070. *
  1071. * @param \OC\SystemConfig $config
  1072. * @return bool whether the core or any app needs an upgrade
  1073. * @throws \OCP\HintException When the upgrade from the given version is not allowed
  1074. */
  1075. public static function needUpgrade(\OC\SystemConfig $config) {
  1076. if ($config->getValue('installed', false)) {
  1077. $installedVersion = $config->getValue('version', '0.0.0');
  1078. $currentVersion = implode('.', \OCP\Util::getVersion());
  1079. $versionDiff = version_compare($currentVersion, $installedVersion);
  1080. if ($versionDiff > 0) {
  1081. return true;
  1082. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  1083. // downgrade with debug
  1084. $installedMajor = explode('.', $installedVersion);
  1085. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  1086. $currentMajor = explode('.', $currentVersion);
  1087. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  1088. if ($installedMajor === $currentMajor) {
  1089. // Same major, allow downgrade for developers
  1090. return true;
  1091. } else {
  1092. // downgrade attempt, throw exception
  1093. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1094. }
  1095. } elseif ($versionDiff < 0) {
  1096. // downgrade attempt, throw exception
  1097. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1098. }
  1099. // also check for upgrades for apps (independently from the user)
  1100. $apps = \OC_App::getEnabledApps(false, true);
  1101. $shouldUpgrade = false;
  1102. foreach ($apps as $app) {
  1103. if (\OC_App::shouldUpgrade($app)) {
  1104. $shouldUpgrade = true;
  1105. break;
  1106. }
  1107. }
  1108. return $shouldUpgrade;
  1109. } else {
  1110. return false;
  1111. }
  1112. }
  1113. }