You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OC_Util.php 46KB

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