util.php 47 KB

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