util.php 46 KB

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