util.php 46 KB

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