util.php 48 KB

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