1
0

OC_Util.php 37 KB

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