OC_Util.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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 = \OCP\Server::get(\OC\Setup::class);
  474. $urlGenerator = \OC::$server->getURLGenerator();
  475. $availableDatabases = $setup->getSupportedDatabases();
  476. if (empty($availableDatabases)) {
  477. $errors[] = [
  478. 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
  479. 'hint' => '' //TODO: sane hint
  480. ];
  481. $webServerRestart = true;
  482. }
  483. // Check if config folder is writable.
  484. if (!OC_Helper::isReadOnlyConfigEnabled()) {
  485. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  486. $errors[] = [
  487. 'error' => $l->t('Cannot write into "config" directory.'),
  488. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
  489. [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
  490. . $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',
  491. [ $urlGenerator->linkToDocs('admin-config') ])
  492. ];
  493. }
  494. }
  495. // Check if there is a writable install folder.
  496. if ($config->getValue('appstoreenabled', true)) {
  497. if (OC_App::getInstallPath() === null
  498. || !is_writable(OC_App::getInstallPath())
  499. || !is_readable(OC_App::getInstallPath())
  500. ) {
  501. $errors[] = [
  502. 'error' => $l->t('Cannot write into "apps" directory.'),
  503. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
  504. . ' or disabling the App Store in the config file.')
  505. ];
  506. }
  507. }
  508. // Create root dir.
  509. if ($config->getValue('installed', false)) {
  510. if (!is_dir($CONFIG_DATADIRECTORY)) {
  511. $success = @mkdir($CONFIG_DATADIRECTORY);
  512. if ($success) {
  513. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  514. } else {
  515. $errors[] = [
  516. 'error' => $l->t('Cannot create "data" directory.'),
  517. 'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
  518. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  519. ];
  520. }
  521. } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  522. // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
  523. $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
  524. $handle = fopen($testFile, 'w');
  525. if (!$handle || fwrite($handle, 'Test write operation') === false) {
  526. $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
  527. [$urlGenerator->linkToDocs('admin-dir_permissions')]);
  528. $errors[] = [
  529. 'error' => $l->t('Your data directory is not writable.'),
  530. 'hint' => $permissionsHint
  531. ];
  532. } else {
  533. fclose($handle);
  534. unlink($testFile);
  535. }
  536. } else {
  537. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  538. }
  539. }
  540. if (!OC_Util::isSetLocaleWorking()) {
  541. $errors[] = [
  542. 'error' => $l->t('Setting locale to %s failed.',
  543. ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  544. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
  545. 'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
  546. ];
  547. }
  548. // Contains the dependencies that should be checked against
  549. // classes = class_exists
  550. // functions = function_exists
  551. // defined = defined
  552. // ini = ini_get
  553. // If the dependency is not found the missing module name is shown to the EndUser
  554. // When adding new checks always verify that they pass on Travis as well
  555. // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
  556. $dependencies = [
  557. 'classes' => [
  558. 'ZipArchive' => 'zip',
  559. 'DOMDocument' => 'dom',
  560. 'XMLWriter' => 'XMLWriter',
  561. 'XMLReader' => 'XMLReader',
  562. ],
  563. 'functions' => [
  564. 'xml_parser_create' => 'libxml',
  565. 'mb_strcut' => 'mbstring',
  566. 'ctype_digit' => 'ctype',
  567. 'json_encode' => 'JSON',
  568. 'gd_info' => 'GD',
  569. 'gzencode' => 'zlib',
  570. 'simplexml_load_string' => 'SimpleXML',
  571. 'hash' => 'HASH Message Digest Framework',
  572. 'curl_init' => 'cURL',
  573. 'openssl_verify' => 'OpenSSL',
  574. ],
  575. 'defined' => [
  576. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  577. ],
  578. 'ini' => [
  579. 'default_charset' => 'UTF-8',
  580. ],
  581. ];
  582. $missingDependencies = [];
  583. $invalidIniSettings = [];
  584. $iniWrapper = \OC::$server->get(IniGetWrapper::class);
  585. foreach ($dependencies['classes'] as $class => $module) {
  586. if (!class_exists($class)) {
  587. $missingDependencies[] = $module;
  588. }
  589. }
  590. foreach ($dependencies['functions'] as $function => $module) {
  591. if (!function_exists($function)) {
  592. $missingDependencies[] = $module;
  593. }
  594. }
  595. foreach ($dependencies['defined'] as $defined => $module) {
  596. if (!defined($defined)) {
  597. $missingDependencies[] = $module;
  598. }
  599. }
  600. foreach ($dependencies['ini'] as $setting => $expected) {
  601. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  602. $invalidIniSettings[] = [$setting, $expected];
  603. }
  604. }
  605. foreach ($missingDependencies as $missingDependency) {
  606. $errors[] = [
  607. 'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
  608. 'hint' => $l->t('Please ask your server administrator to install the module.'),
  609. ];
  610. $webServerRestart = true;
  611. }
  612. foreach ($invalidIniSettings as $setting) {
  613. $errors[] = [
  614. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  615. 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
  616. ];
  617. $webServerRestart = true;
  618. }
  619. /**
  620. * The mbstring.func_overload check can only be performed if the mbstring
  621. * module is installed as it will return null if the checking setting is
  622. * not available and thus a check on the boolean value fails.
  623. *
  624. * TODO: Should probably be implemented in the above generic dependency
  625. * check somehow in the long-term.
  626. */
  627. if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
  628. $iniWrapper->getBool('mbstring.func_overload') === true) {
  629. $errors[] = [
  630. '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')]),
  631. 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
  632. ];
  633. }
  634. if (!self::isAnnotationsWorking()) {
  635. $errors[] = [
  636. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  637. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  638. ];
  639. }
  640. if (!\OC::$CLI && $webServerRestart) {
  641. $errors[] = [
  642. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  643. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  644. ];
  645. }
  646. foreach (['secret', 'instanceid', 'passwordsalt'] as $requiredConfig) {
  647. if ($config->getValue($requiredConfig, '') === '' && !\OC::$CLI && $config->getValue('installed', false)) {
  648. $errors[] = [
  649. 'error' => $l->t('The required %s config variable is not configured in the config.php file.', [$requiredConfig]),
  650. 'hint' => $l->t('Please ask your server administrator to check the Nextcloud configuration.')
  651. ];
  652. }
  653. }
  654. // Cache the result of this function
  655. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  656. return $errors;
  657. }
  658. /**
  659. * Check for correct file permissions of data directory
  660. *
  661. * @param string $dataDirectory
  662. * @return array arrays with error messages and hints
  663. */
  664. public static function checkDataDirectoryPermissions($dataDirectory) {
  665. if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
  666. return [];
  667. }
  668. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  669. if (substr($perms, -1) !== '0') {
  670. chmod($dataDirectory, 0770);
  671. clearstatcache();
  672. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  673. if ($perms[2] !== '0') {
  674. $l = \OC::$server->getL10N('lib');
  675. return [[
  676. 'error' => $l->t('Your data directory is readable by other people.'),
  677. 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other people.'),
  678. ]];
  679. }
  680. }
  681. return [];
  682. }
  683. /**
  684. * Check that the data directory exists and is valid by
  685. * checking the existence of the ".ocdata" file.
  686. *
  687. * @param string $dataDirectory data directory path
  688. * @return array errors found
  689. */
  690. public static function checkDataDirectoryValidity($dataDirectory) {
  691. $l = \OC::$server->getL10N('lib');
  692. $errors = [];
  693. if ($dataDirectory[0] !== '/') {
  694. $errors[] = [
  695. 'error' => $l->t('Your data directory must be an absolute path.'),
  696. 'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
  697. ];
  698. }
  699. if (!file_exists($dataDirectory . '/.ocdata')) {
  700. $errors[] = [
  701. 'error' => $l->t('Your data directory is invalid.'),
  702. 'hint' => $l->t('Ensure there is a file called ".ocdata"' .
  703. ' in the root of the data directory.')
  704. ];
  705. }
  706. return $errors;
  707. }
  708. /**
  709. * Check if the user is logged in, redirects to home if not. With
  710. * redirect URL parameter to the request URI.
  711. *
  712. * @return void
  713. */
  714. public static function checkLoggedIn() {
  715. // Check if we are a user
  716. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  717. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  718. 'core.login.showLoginForm',
  719. [
  720. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  721. ]
  722. )
  723. );
  724. exit();
  725. }
  726. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  727. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  728. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  729. exit();
  730. }
  731. }
  732. /**
  733. * Check if the user is a admin, redirects to home if not
  734. *
  735. * @return void
  736. */
  737. public static function checkAdminUser() {
  738. OC_Util::checkLoggedIn();
  739. if (!OC_User::isAdminUser(OC_User::getUser())) {
  740. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  741. exit();
  742. }
  743. }
  744. /**
  745. * Returns the URL of the default page
  746. * based on the system configuration and
  747. * the apps visible for the current user
  748. *
  749. * @return string URL
  750. * @suppress PhanDeprecatedFunction
  751. */
  752. public static function getDefaultPageUrl() {
  753. /** @var IURLGenerator $urlGenerator */
  754. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  755. return $urlGenerator->linkToDefaultPageUrl();
  756. }
  757. /**
  758. * Redirect to the user default page
  759. *
  760. * @return void
  761. */
  762. public static function redirectToDefaultPage() {
  763. $location = self::getDefaultPageUrl();
  764. header('Location: ' . $location);
  765. exit();
  766. }
  767. /**
  768. * get an id unique for this instance
  769. *
  770. * @return string
  771. */
  772. public static function getInstanceId() {
  773. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  774. if (is_null($id)) {
  775. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  776. $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  777. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  778. }
  779. return $id;
  780. }
  781. /**
  782. * Public function to sanitize HTML
  783. *
  784. * This function is used to sanitize HTML and should be applied on any
  785. * string or array of strings before displaying it on a web page.
  786. *
  787. * @param string|string[] $value
  788. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  789. */
  790. public static function sanitizeHTML($value) {
  791. if (is_array($value)) {
  792. /** @var string[] $value */
  793. $value = array_map(function ($value) {
  794. return self::sanitizeHTML($value);
  795. }, $value);
  796. } else {
  797. // Specify encoding for PHP<5.4
  798. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  799. }
  800. return $value;
  801. }
  802. /**
  803. * Public function to encode url parameters
  804. *
  805. * This function is used to encode path to file before output.
  806. * Encoding is done according to RFC 3986 with one exception:
  807. * Character '/' is preserved as is.
  808. *
  809. * @param string $component part of URI to encode
  810. * @return string
  811. */
  812. public static function encodePath($component) {
  813. $encoded = rawurlencode($component);
  814. $encoded = str_replace('%2F', '/', $encoded);
  815. return $encoded;
  816. }
  817. public function createHtaccessTestFile(\OCP\IConfig $config) {
  818. // php dev server does not support htaccess
  819. if (php_sapi_name() === 'cli-server') {
  820. return false;
  821. }
  822. // testdata
  823. $fileName = '/htaccesstest.txt';
  824. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  825. // creating a test file
  826. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  827. if (file_exists($testFile)) {// already running this test, possible recursive call
  828. return false;
  829. }
  830. $fp = @fopen($testFile, 'w');
  831. if (!$fp) {
  832. throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
  833. 'Make sure it is possible for the web server to write to ' . $testFile);
  834. }
  835. fwrite($fp, $testContent);
  836. fclose($fp);
  837. return $testContent;
  838. }
  839. /**
  840. * Check if the .htaccess file is working
  841. *
  842. * @param \OCP\IConfig $config
  843. * @return bool
  844. * @throws Exception
  845. * @throws \OCP\HintException If the test file can't get written.
  846. */
  847. public function isHtaccessWorking(\OCP\IConfig $config) {
  848. if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
  849. return true;
  850. }
  851. $testContent = $this->createHtaccessTestFile($config);
  852. if ($testContent === false) {
  853. return false;
  854. }
  855. $fileName = '/htaccesstest.txt';
  856. $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  857. // accessing the file via http
  858. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  859. try {
  860. $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  861. } catch (\Exception $e) {
  862. $content = false;
  863. }
  864. if (str_starts_with($url, 'https:')) {
  865. $url = 'http:' . substr($url, 6);
  866. } else {
  867. $url = 'https:' . substr($url, 5);
  868. }
  869. try {
  870. $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  871. } catch (\Exception $e) {
  872. $fallbackContent = false;
  873. }
  874. // cleanup
  875. @unlink($testFile);
  876. /*
  877. * If the content is not equal to test content our .htaccess
  878. * is working as required
  879. */
  880. return $content !== $testContent && $fallbackContent !== $testContent;
  881. }
  882. /**
  883. * Check if current locale is non-UTF8
  884. *
  885. * @return bool
  886. */
  887. private static function isNonUTF8Locale() {
  888. if (function_exists('escapeshellcmd')) {
  889. return '' === escapeshellcmd('§');
  890. } elseif (function_exists('escapeshellarg')) {
  891. return '\'\'' === escapeshellarg('§');
  892. } else {
  893. return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
  894. }
  895. }
  896. /**
  897. * Check if the setlocale call does not work. This can happen if the right
  898. * local packages are not available on the server.
  899. *
  900. * @return bool
  901. */
  902. public static function isSetLocaleWorking() {
  903. if (self::isNonUTF8Locale()) {
  904. // Borrowed from \Patchwork\Utf8\Bootup::initLocale
  905. setlocale(LC_ALL, 'C.UTF-8', 'C');
  906. 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');
  907. // Check again
  908. if (self::isNonUTF8Locale()) {
  909. return false;
  910. }
  911. }
  912. return true;
  913. }
  914. /**
  915. * Check if it's possible to get the inline annotations
  916. *
  917. * @return bool
  918. */
  919. public static function isAnnotationsWorking() {
  920. $reflection = new \ReflectionMethod(__METHOD__);
  921. $docs = $reflection->getDocComment();
  922. return (is_string($docs) && strlen($docs) > 50);
  923. }
  924. /**
  925. * Check if the PHP module fileinfo is loaded.
  926. *
  927. * @return bool
  928. */
  929. public static function fileInfoLoaded() {
  930. return function_exists('finfo_open');
  931. }
  932. /**
  933. * clear all levels of output buffering
  934. *
  935. * @return void
  936. */
  937. public static function obEnd() {
  938. while (ob_get_level()) {
  939. ob_end_clean();
  940. }
  941. }
  942. /**
  943. * Checks whether the server is running on Mac OS X
  944. *
  945. * @return bool true if running on Mac OS X, false otherwise
  946. */
  947. public static function runningOnMac() {
  948. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  949. }
  950. /**
  951. * Handles the case that there may not be a theme, then check if a "default"
  952. * theme exists and take that one
  953. *
  954. * @return string the theme
  955. */
  956. public static function getTheme() {
  957. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  958. if ($theme === '') {
  959. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  960. $theme = 'default';
  961. }
  962. }
  963. return $theme;
  964. }
  965. /**
  966. * Normalize a unicode string
  967. *
  968. * @param string $value a not normalized string
  969. * @return bool|string
  970. */
  971. public static function normalizeUnicode($value) {
  972. if (Normalizer::isNormalized($value)) {
  973. return $value;
  974. }
  975. $normalizedValue = Normalizer::normalize($value);
  976. if ($normalizedValue === null || $normalizedValue === false) {
  977. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  978. return $value;
  979. }
  980. return $normalizedValue;
  981. }
  982. /**
  983. * A human readable string is generated based on version and build number
  984. *
  985. * @return string
  986. */
  987. public static function getHumanVersion() {
  988. $version = OC_Util::getVersionString();
  989. $build = OC_Util::getBuild();
  990. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  991. $version .= ' Build:' . $build;
  992. }
  993. return $version;
  994. }
  995. /**
  996. * Returns whether the given file name is valid
  997. *
  998. * @param string $file file name to check
  999. * @return bool true if the file name is valid, false otherwise
  1000. * @deprecated use \OC\Files\View::verifyPath()
  1001. */
  1002. public static function isValidFileName($file) {
  1003. $trimmed = trim($file);
  1004. if ($trimmed === '') {
  1005. return false;
  1006. }
  1007. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  1008. return false;
  1009. }
  1010. // detect part files
  1011. if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
  1012. return false;
  1013. }
  1014. foreach (str_split($trimmed) as $char) {
  1015. if (str_contains(\OCP\Constants::FILENAME_INVALID_CHARS, $char)) {
  1016. return false;
  1017. }
  1018. }
  1019. return true;
  1020. }
  1021. /**
  1022. * Check whether the instance needs to perform an upgrade,
  1023. * either when the core version is higher or any app requires
  1024. * an upgrade.
  1025. *
  1026. * @param \OC\SystemConfig $config
  1027. * @return bool whether the core or any app needs an upgrade
  1028. * @throws \OCP\HintException When the upgrade from the given version is not allowed
  1029. */
  1030. public static function needUpgrade(\OC\SystemConfig $config) {
  1031. if ($config->getValue('installed', false)) {
  1032. $installedVersion = $config->getValue('version', '0.0.0');
  1033. $currentVersion = implode('.', \OCP\Util::getVersion());
  1034. $versionDiff = version_compare($currentVersion, $installedVersion);
  1035. if ($versionDiff > 0) {
  1036. return true;
  1037. } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
  1038. // downgrade with debug
  1039. $installedMajor = explode('.', $installedVersion);
  1040. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  1041. $currentMajor = explode('.', $currentVersion);
  1042. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  1043. if ($installedMajor === $currentMajor) {
  1044. // Same major, allow downgrade for developers
  1045. return true;
  1046. } else {
  1047. // downgrade attempt, throw exception
  1048. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1049. }
  1050. } elseif ($versionDiff < 0) {
  1051. // downgrade attempt, throw exception
  1052. throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1053. }
  1054. // also check for upgrades for apps (independently from the user)
  1055. $apps = \OC_App::getEnabledApps(false, true);
  1056. $shouldUpgrade = false;
  1057. foreach ($apps as $app) {
  1058. if (\OC_App::shouldUpgrade($app)) {
  1059. $shouldUpgrade = true;
  1060. break;
  1061. }
  1062. }
  1063. return $shouldUpgrade;
  1064. } else {
  1065. return false;
  1066. }
  1067. }
  1068. }