1
0

util.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  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 \RuntimeException
  355. * @suppress PhanDeprecatedFunction
  356. */
  357. public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
  358. $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
  359. $userLang = \OC::$server->getL10NFactory()->findLanguage();
  360. $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
  361. if (!file_exists($skeletonDirectory)) {
  362. $dialectStart = strpos($userLang, '_');
  363. if ($dialectStart !== false) {
  364. $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
  365. }
  366. if ($dialectStart === false || !file_exists($skeletonDirectory)) {
  367. $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
  368. }
  369. if (!file_exists($skeletonDirectory)) {
  370. $skeletonDirectory = '';
  371. }
  372. }
  373. $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
  374. if ($instanceId === null) {
  375. throw new \RuntimeException('no instance id!');
  376. }
  377. $appdata = 'appdata_' . $instanceId;
  378. if ($userId === $appdata) {
  379. throw new \RuntimeException('username is reserved name: ' . $appdata);
  380. }
  381. if (!empty($skeletonDirectory)) {
  382. \OCP\Util::writeLog(
  383. 'files_skeleton',
  384. 'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
  385. ILogger::DEBUG
  386. );
  387. self::copyr($skeletonDirectory, $userDirectory);
  388. // update the file cache
  389. $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
  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 $timestamp int */
  489. self::$versionCache['OC_Version_Timestamp'] = $timestamp;
  490. /** @var $OC_Version string */
  491. self::$versionCache['OC_Version'] = $OC_Version;
  492. /** @var $OC_VersionString string */
  493. self::$versionCache['OC_VersionString'] = $OC_VersionString;
  494. /** @var $OC_Build string */
  495. self::$versionCache['OC_Build'] = $OC_Build;
  496. /** @var $OC_Channel string */
  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 = array(
  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 = array();
  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->getIniWrapper(),
  659. \OC::$server->getL10N('lib'),
  660. \OC::$server->query(\OCP\Defaults::class),
  661. \OC::$server->getLogger(),
  662. \OC::$server->getSecureRandom(),
  663. \OC::$server->query(\OC\Installer::class)
  664. );
  665. $urlGenerator = \OC::$server->getURLGenerator();
  666. $availableDatabases = $setup->getSupportedDatabases();
  667. if (empty($availableDatabases)) {
  668. $errors[] = array(
  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[] = array(
  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[] = array(
  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 appstore in the config file. See %s',
  696. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  697. );
  698. }
  699. }
  700. // Create root dir.
  701. if ($config->getValue('installed', false)) {
  702. if (!is_dir($CONFIG_DATADIRECTORY)) {
  703. $success = @mkdir($CONFIG_DATADIRECTORY);
  704. if ($success) {
  705. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  706. } else {
  707. $errors[] = [
  708. 'error' => $l->t('Cannot create "data" directory'),
  709. 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
  710. [$urlGenerator->linkToDocs('admin-dir_permissions')])
  711. ];
  712. }
  713. } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  714. //common hint for all file permissions error messages
  715. $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
  716. [$urlGenerator->linkToDocs('admin-dir_permissions')]);
  717. $errors[] = [
  718. 'error' => 'Your data directory is not writable',
  719. 'hint' => $permissionsHint
  720. ];
  721. } else {
  722. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  723. }
  724. }
  725. if (!OC_Util::isSetLocaleWorking()) {
  726. $errors[] = array(
  727. 'error' => $l->t('Setting locale to %s failed',
  728. array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  729. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
  730. 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
  731. );
  732. }
  733. // Contains the dependencies that should be checked against
  734. // classes = class_exists
  735. // functions = function_exists
  736. // defined = defined
  737. // ini = ini_get
  738. // If the dependency is not found the missing module name is shown to the EndUser
  739. // When adding new checks always verify that they pass on Travis as well
  740. // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
  741. $dependencies = array(
  742. 'classes' => array(
  743. 'ZipArchive' => 'zip',
  744. 'DOMDocument' => 'dom',
  745. 'XMLWriter' => 'XMLWriter',
  746. 'XMLReader' => 'XMLReader',
  747. ),
  748. 'functions' => [
  749. 'xml_parser_create' => 'libxml',
  750. 'mb_strcut' => 'mb multibyte',
  751. 'ctype_digit' => 'ctype',
  752. 'json_encode' => 'JSON',
  753. 'gd_info' => 'GD',
  754. 'gzencode' => 'zlib',
  755. 'iconv' => 'iconv',
  756. 'simplexml_load_string' => 'SimpleXML',
  757. 'hash' => 'HASH Message Digest Framework',
  758. 'curl_init' => 'cURL',
  759. 'openssl_verify' => 'OpenSSL',
  760. ],
  761. 'defined' => array(
  762. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  763. ),
  764. 'ini' => [
  765. 'default_charset' => 'UTF-8',
  766. ],
  767. );
  768. $missingDependencies = array();
  769. $invalidIniSettings = [];
  770. $moduleHint = $l->t('Please ask your server administrator to install the module.');
  771. /**
  772. * FIXME: The dependency check does not work properly on HHVM on the moment
  773. * and prevents installation. Once HHVM is more compatible with our
  774. * approach to check for these values we should re-enable those
  775. * checks.
  776. */
  777. $iniWrapper = \OC::$server->getIniWrapper();
  778. if (!self::runningOnHhvm()) {
  779. foreach ($dependencies['classes'] as $class => $module) {
  780. if (!class_exists($class)) {
  781. $missingDependencies[] = $module;
  782. }
  783. }
  784. foreach ($dependencies['functions'] as $function => $module) {
  785. if (!function_exists($function)) {
  786. $missingDependencies[] = $module;
  787. }
  788. }
  789. foreach ($dependencies['defined'] as $defined => $module) {
  790. if (!defined($defined)) {
  791. $missingDependencies[] = $module;
  792. }
  793. }
  794. foreach ($dependencies['ini'] as $setting => $expected) {
  795. if (is_bool($expected)) {
  796. if ($iniWrapper->getBool($setting) !== $expected) {
  797. $invalidIniSettings[] = [$setting, $expected];
  798. }
  799. }
  800. if (is_int($expected)) {
  801. if ($iniWrapper->getNumeric($setting) !== $expected) {
  802. $invalidIniSettings[] = [$setting, $expected];
  803. }
  804. }
  805. if (is_string($expected)) {
  806. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  807. $invalidIniSettings[] = [$setting, $expected];
  808. }
  809. }
  810. }
  811. }
  812. foreach($missingDependencies as $missingDependency) {
  813. $errors[] = array(
  814. 'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
  815. 'hint' => $moduleHint
  816. );
  817. $webServerRestart = true;
  818. }
  819. foreach($invalidIniSettings as $setting) {
  820. if(is_bool($setting[1])) {
  821. $setting[1] = $setting[1] ? 'on' : 'off';
  822. }
  823. $errors[] = [
  824. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  825. 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
  826. ];
  827. $webServerRestart = true;
  828. }
  829. /**
  830. * The mbstring.func_overload check can only be performed if the mbstring
  831. * module is installed as it will return null if the checking setting is
  832. * not available and thus a check on the boolean value fails.
  833. *
  834. * TODO: Should probably be implemented in the above generic dependency
  835. * check somehow in the long-term.
  836. */
  837. if($iniWrapper->getBool('mbstring.func_overload') !== null &&
  838. $iniWrapper->getBool('mbstring.func_overload') === true) {
  839. $errors[] = array(
  840. 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
  841. 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
  842. );
  843. }
  844. if(function_exists('xml_parser_create') &&
  845. LIBXML_LOADED_VERSION < 20700 ) {
  846. $version = LIBXML_LOADED_VERSION;
  847. $major = floor($version/10000);
  848. $version -= ($major * 10000);
  849. $minor = floor($version/100);
  850. $version -= ($minor * 100);
  851. $patch = $version;
  852. $errors[] = array(
  853. 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
  854. 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
  855. );
  856. }
  857. if (!self::isAnnotationsWorking()) {
  858. $errors[] = array(
  859. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  860. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  861. );
  862. }
  863. if (!\OC::$CLI && $webServerRestart) {
  864. $errors[] = array(
  865. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  866. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  867. );
  868. }
  869. $errors = array_merge($errors, self::checkDatabaseVersion());
  870. // Cache the result of this function
  871. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  872. return $errors;
  873. }
  874. /**
  875. * Check the database version
  876. *
  877. * @return array errors array
  878. */
  879. public static function checkDatabaseVersion() {
  880. $l = \OC::$server->getL10N('lib');
  881. $errors = array();
  882. $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
  883. if ($dbType === 'pgsql') {
  884. // check PostgreSQL version
  885. try {
  886. $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
  887. $data = $result->fetchRow();
  888. if (isset($data['server_version'])) {
  889. $version = $data['server_version'];
  890. if (version_compare($version, '9.0.0', '<')) {
  891. $errors[] = array(
  892. 'error' => $l->t('PostgreSQL >= 9 required'),
  893. 'hint' => $l->t('Please upgrade your database version')
  894. );
  895. }
  896. }
  897. } catch (\Doctrine\DBAL\DBALException $e) {
  898. $logger = \OC::$server->getLogger();
  899. $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
  900. $logger->logException($e);
  901. }
  902. }
  903. return $errors;
  904. }
  905. /**
  906. * Check for correct file permissions of data directory
  907. *
  908. * @param string $dataDirectory
  909. * @return array arrays with error messages and hints
  910. */
  911. public static function checkDataDirectoryPermissions($dataDirectory) {
  912. if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
  913. return [];
  914. }
  915. $l = \OC::$server->getL10N('lib');
  916. $errors = [];
  917. $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
  918. . ' cannot be listed by other users.');
  919. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  920. if (substr($perms, -1) !== '0') {
  921. chmod($dataDirectory, 0770);
  922. clearstatcache();
  923. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  924. if ($perms[2] !== '0') {
  925. $errors[] = [
  926. 'error' => $l->t('Your data directory is readable by other users'),
  927. 'hint' => $permissionsModHint
  928. ];
  929. }
  930. }
  931. return $errors;
  932. }
  933. /**
  934. * Check that the data directory exists and is valid by
  935. * checking the existence of the ".ocdata" file.
  936. *
  937. * @param string $dataDirectory data directory path
  938. * @return array errors found
  939. */
  940. public static function checkDataDirectoryValidity($dataDirectory) {
  941. $l = \OC::$server->getL10N('lib');
  942. $errors = [];
  943. if ($dataDirectory[0] !== '/') {
  944. $errors[] = [
  945. 'error' => $l->t('Your data directory must be an absolute path'),
  946. 'hint' => $l->t('Check the value of "datadirectory" in your configuration')
  947. ];
  948. }
  949. if (!file_exists($dataDirectory . '/.ocdata')) {
  950. $errors[] = [
  951. 'error' => $l->t('Your data directory is invalid'),
  952. 'hint' => $l->t('Ensure there is a file called ".ocdata"' .
  953. ' in the root of the data directory.')
  954. ];
  955. }
  956. return $errors;
  957. }
  958. /**
  959. * Check if the user is logged in, redirects to home if not. With
  960. * redirect URL parameter to the request URI.
  961. *
  962. * @return void
  963. */
  964. public static function checkLoggedIn() {
  965. // Check if we are a user
  966. if (!\OC::$server->getUserSession()->isLoggedIn()) {
  967. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  968. 'core.login.showLoginForm',
  969. [
  970. 'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
  971. ]
  972. )
  973. );
  974. exit();
  975. }
  976. // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
  977. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
  978. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  979. exit();
  980. }
  981. }
  982. /**
  983. * Check if the user is a admin, redirects to home if not
  984. *
  985. * @return void
  986. */
  987. public static function checkAdminUser() {
  988. OC_Util::checkLoggedIn();
  989. if (!OC_User::isAdminUser(OC_User::getUser())) {
  990. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  991. exit();
  992. }
  993. }
  994. /**
  995. * Check if the user is a subadmin, redirects to home if not
  996. *
  997. * @return null|boolean $groups where the current user is subadmin
  998. */
  999. public static function checkSubAdminUser() {
  1000. OC_Util::checkLoggedIn();
  1001. $userObject = \OC::$server->getUserSession()->getUser();
  1002. $isSubAdmin = false;
  1003. if($userObject !== null) {
  1004. $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
  1005. }
  1006. if (!$isSubAdmin) {
  1007. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  1008. exit();
  1009. }
  1010. return true;
  1011. }
  1012. /**
  1013. * Returns the URL of the default page
  1014. * based on the system configuration and
  1015. * the apps visible for the current user
  1016. *
  1017. * @return string URL
  1018. * @suppress PhanDeprecatedFunction
  1019. */
  1020. public static function getDefaultPageUrl() {
  1021. $urlGenerator = \OC::$server->getURLGenerator();
  1022. // Deny the redirect if the URL contains a @
  1023. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  1024. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  1025. $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  1026. } else {
  1027. $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
  1028. if ($defaultPage) {
  1029. $location = $urlGenerator->getAbsoluteURL($defaultPage);
  1030. } else {
  1031. $appId = 'files';
  1032. $config = \OC::$server->getConfig();
  1033. $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
  1034. // find the first app that is enabled for the current user
  1035. foreach ($defaultApps as $defaultApp) {
  1036. $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
  1037. if (static::getAppManager()->isEnabledForUser($defaultApp)) {
  1038. $appId = $defaultApp;
  1039. break;
  1040. }
  1041. }
  1042. if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
  1043. $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
  1044. } else {
  1045. $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  1046. }
  1047. }
  1048. }
  1049. return $location;
  1050. }
  1051. /**
  1052. * Redirect to the user default page
  1053. *
  1054. * @return void
  1055. */
  1056. public static function redirectToDefaultPage() {
  1057. $location = self::getDefaultPageUrl();
  1058. header('Location: ' . $location);
  1059. exit();
  1060. }
  1061. /**
  1062. * get an id unique for this instance
  1063. *
  1064. * @return string
  1065. */
  1066. public static function getInstanceId() {
  1067. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  1068. if (is_null($id)) {
  1069. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  1070. $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  1071. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  1072. }
  1073. return $id;
  1074. }
  1075. /**
  1076. * Public function to sanitize HTML
  1077. *
  1078. * This function is used to sanitize HTML and should be applied on any
  1079. * string or array of strings before displaying it on a web page.
  1080. *
  1081. * @param string|array $value
  1082. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  1083. */
  1084. public static function sanitizeHTML($value) {
  1085. if (is_array($value)) {
  1086. $value = array_map(function($value) {
  1087. return self::sanitizeHTML($value);
  1088. }, $value);
  1089. } else {
  1090. // Specify encoding for PHP<5.4
  1091. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  1092. }
  1093. return $value;
  1094. }
  1095. /**
  1096. * Public function to encode url parameters
  1097. *
  1098. * This function is used to encode path to file before output.
  1099. * Encoding is done according to RFC 3986 with one exception:
  1100. * Character '/' is preserved as is.
  1101. *
  1102. * @param string $component part of URI to encode
  1103. * @return string
  1104. */
  1105. public static function encodePath($component) {
  1106. $encoded = rawurlencode($component);
  1107. $encoded = str_replace('%2F', '/', $encoded);
  1108. return $encoded;
  1109. }
  1110. public function createHtaccessTestFile(\OCP\IConfig $config) {
  1111. // php dev server does not support htaccess
  1112. if (php_sapi_name() === 'cli-server') {
  1113. return false;
  1114. }
  1115. // testdata
  1116. $fileName = '/htaccesstest.txt';
  1117. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  1118. // creating a test file
  1119. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1120. if (file_exists($testFile)) {// already running this test, possible recursive call
  1121. return false;
  1122. }
  1123. $fp = @fopen($testFile, 'w');
  1124. if (!$fp) {
  1125. throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
  1126. 'Make sure it is possible for the webserver to write to ' . $testFile);
  1127. }
  1128. fwrite($fp, $testContent);
  1129. fclose($fp);
  1130. return $testContent;
  1131. }
  1132. /**
  1133. * Check if the .htaccess file is working
  1134. * @param \OCP\IConfig $config
  1135. * @return bool
  1136. * @throws Exception
  1137. * @throws \OC\HintException If the test file can't get written.
  1138. */
  1139. public function isHtaccessWorking(\OCP\IConfig $config) {
  1140. if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
  1141. return true;
  1142. }
  1143. $testContent = $this->createHtaccessTestFile($config);
  1144. if ($testContent === false) {
  1145. return false;
  1146. }
  1147. $fileName = '/htaccesstest.txt';
  1148. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1149. // accessing the file via http
  1150. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  1151. try {
  1152. $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  1153. } catch (\Exception $e) {
  1154. $content = false;
  1155. }
  1156. // cleanup
  1157. @unlink($testFile);
  1158. /*
  1159. * If the content is not equal to test content our .htaccess
  1160. * is working as required
  1161. */
  1162. return $content !== $testContent;
  1163. }
  1164. /**
  1165. * Check if the setlocal call does not work. This can happen if the right
  1166. * local packages are not available on the server.
  1167. *
  1168. * @return bool
  1169. */
  1170. public static function isSetLocaleWorking() {
  1171. \Patchwork\Utf8\Bootup::initLocale();
  1172. if ('' === basename('§')) {
  1173. return false;
  1174. }
  1175. return true;
  1176. }
  1177. /**
  1178. * Check if it's possible to get the inline annotations
  1179. *
  1180. * @return bool
  1181. */
  1182. public static function isAnnotationsWorking() {
  1183. $reflection = new \ReflectionMethod(__METHOD__);
  1184. $docs = $reflection->getDocComment();
  1185. return (is_string($docs) && strlen($docs) > 50);
  1186. }
  1187. /**
  1188. * Check if the PHP module fileinfo is loaded.
  1189. *
  1190. * @return bool
  1191. */
  1192. public static function fileInfoLoaded() {
  1193. return function_exists('finfo_open');
  1194. }
  1195. /**
  1196. * clear all levels of output buffering
  1197. *
  1198. * @return void
  1199. */
  1200. public static function obEnd() {
  1201. while (ob_get_level()) {
  1202. ob_end_clean();
  1203. }
  1204. }
  1205. /**
  1206. * Checks whether the server is running on Mac OS X
  1207. *
  1208. * @return bool true if running on Mac OS X, false otherwise
  1209. */
  1210. public static function runningOnMac() {
  1211. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  1212. }
  1213. /**
  1214. * Checks whether server is running on HHVM
  1215. *
  1216. * @return bool True if running on HHVM, false otherwise
  1217. */
  1218. public static function runningOnHhvm() {
  1219. return defined('HHVM_VERSION');
  1220. }
  1221. /**
  1222. * Handles the case that there may not be a theme, then check if a "default"
  1223. * theme exists and take that one
  1224. *
  1225. * @return string the theme
  1226. */
  1227. public static function getTheme() {
  1228. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  1229. if ($theme === '') {
  1230. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1231. $theme = 'default';
  1232. }
  1233. }
  1234. return $theme;
  1235. }
  1236. /**
  1237. * Clear a single file from the opcode cache
  1238. * This is useful for writing to the config file
  1239. * in case the opcode cache does not re-validate files
  1240. * Returns true if successful, false if unsuccessful:
  1241. * caller should fall back on clearing the entire cache
  1242. * with clearOpcodeCache() if unsuccessful
  1243. *
  1244. * @param string $path the path of the file to clear from the cache
  1245. * @return bool true if underlying function returns true, otherwise false
  1246. */
  1247. public static function deleteFromOpcodeCache($path) {
  1248. $ret = false;
  1249. if ($path) {
  1250. // APC >= 3.1.1
  1251. if (function_exists('apc_delete_file')) {
  1252. $ret = @apc_delete_file($path);
  1253. }
  1254. // Zend OpCache >= 7.0.0, PHP >= 5.5.0
  1255. if (function_exists('opcache_invalidate')) {
  1256. $ret = @opcache_invalidate($path);
  1257. }
  1258. }
  1259. return $ret;
  1260. }
  1261. /**
  1262. * Clear the opcode cache if one exists
  1263. * This is necessary for writing to the config file
  1264. * in case the opcode cache does not re-validate files
  1265. *
  1266. * @return void
  1267. * @suppress PhanDeprecatedFunction
  1268. * @suppress PhanUndeclaredConstant
  1269. */
  1270. public static function clearOpcodeCache() {
  1271. // APC
  1272. if (function_exists('apc_clear_cache')) {
  1273. apc_clear_cache();
  1274. }
  1275. // Zend Opcache
  1276. if (function_exists('accelerator_reset')) {
  1277. accelerator_reset();
  1278. }
  1279. // Opcache (PHP >= 5.5)
  1280. if (function_exists('opcache_reset')) {
  1281. @opcache_reset();
  1282. }
  1283. }
  1284. /**
  1285. * Normalize a unicode string
  1286. *
  1287. * @param string $value a not normalized string
  1288. * @return bool|string
  1289. */
  1290. public static function normalizeUnicode($value) {
  1291. if(Normalizer::isNormalized($value)) {
  1292. return $value;
  1293. }
  1294. $normalizedValue = Normalizer::normalize($value);
  1295. if ($normalizedValue === null || $normalizedValue === false) {
  1296. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  1297. return $value;
  1298. }
  1299. return $normalizedValue;
  1300. }
  1301. /**
  1302. * A human readable string is generated based on version and build number
  1303. *
  1304. * @return string
  1305. */
  1306. public static function getHumanVersion() {
  1307. $version = OC_Util::getVersionString();
  1308. $build = OC_Util::getBuild();
  1309. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1310. $version .= ' Build:' . $build;
  1311. }
  1312. return $version;
  1313. }
  1314. /**
  1315. * Returns whether the given file name is valid
  1316. *
  1317. * @param string $file file name to check
  1318. * @return bool true if the file name is valid, false otherwise
  1319. * @deprecated use \OC\Files\View::verifyPath()
  1320. */
  1321. public static function isValidFileName($file) {
  1322. $trimmed = trim($file);
  1323. if ($trimmed === '') {
  1324. return false;
  1325. }
  1326. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  1327. return false;
  1328. }
  1329. // detect part files
  1330. if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
  1331. return false;
  1332. }
  1333. foreach (str_split($trimmed) as $char) {
  1334. if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
  1335. return false;
  1336. }
  1337. }
  1338. return true;
  1339. }
  1340. /**
  1341. * Check whether the instance needs to perform an upgrade,
  1342. * either when the core version is higher or any app requires
  1343. * an upgrade.
  1344. *
  1345. * @param \OC\SystemConfig $config
  1346. * @return bool whether the core or any app needs an upgrade
  1347. * @throws \OC\HintException When the upgrade from the given version is not allowed
  1348. */
  1349. public static function needUpgrade(\OC\SystemConfig $config) {
  1350. if ($config->getValue('installed', false)) {
  1351. $installedVersion = $config->getValue('version', '0.0.0');
  1352. $currentVersion = implode('.', \OCP\Util::getVersion());
  1353. $versionDiff = version_compare($currentVersion, $installedVersion);
  1354. if ($versionDiff > 0) {
  1355. return true;
  1356. } else if ($config->getValue('debug', false) && $versionDiff < 0) {
  1357. // downgrade with debug
  1358. $installedMajor = explode('.', $installedVersion);
  1359. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  1360. $currentMajor = explode('.', $currentVersion);
  1361. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  1362. if ($installedMajor === $currentMajor) {
  1363. // Same major, allow downgrade for developers
  1364. return true;
  1365. } else {
  1366. // downgrade attempt, throw exception
  1367. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1368. }
  1369. } else if ($versionDiff < 0) {
  1370. // downgrade attempt, throw exception
  1371. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1372. }
  1373. // also check for upgrades for apps (independently from the user)
  1374. $apps = \OC_App::getEnabledApps(false, true);
  1375. $shouldUpgrade = false;
  1376. foreach ($apps as $app) {
  1377. if (\OC_App::shouldUpgrade($app)) {
  1378. $shouldUpgrade = true;
  1379. break;
  1380. }
  1381. }
  1382. return $shouldUpgrade;
  1383. } else {
  1384. return false;
  1385. }
  1386. }
  1387. /**
  1388. * is this Internet explorer ?
  1389. *
  1390. * @return boolean
  1391. */
  1392. public static function isIe() {
  1393. if (!isset($_SERVER['HTTP_USER_AGENT'])) {
  1394. return false;
  1395. }
  1396. return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
  1397. }
  1398. }