util.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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. $prevLogging = \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($prevLogging);
  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. }