util.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. <?php
  2. /**
  3. * @author Adam Williamson <awilliam@redhat.com>
  4. * @author Andreas Fischer <bantu@owncloud.com>
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Birk Borkason <daniel.niccoli@gmail.com>
  9. * @author Björn Schießle <bjoern@schiessle.org>
  10. * @author Brice Maron <brice@bmaron.net>
  11. * @author Christoph Wurst <christoph@owncloud.com>
  12. * @author Christopher Schäpers <kondou@ts.unde.re>
  13. * @author Clark Tomlinson <fallen013@gmail.com>
  14. * @author cmeh <cmeh@users.noreply.github.com>
  15. * @author Florin Peter <github@florin-peter.de>
  16. * @author Frank Karlitschek <frank@karlitschek.de>
  17. * @author Georg Ehrke <georg@owncloud.com>
  18. * @author helix84 <helix84@centrum.sk>
  19. * @author Individual IT Services <info@individual-it.net>
  20. * @author Jakob Sack <mail@jakobsack.de>
  21. * @author Joas Schilling <nickvergessen@owncloud.com>
  22. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  23. * @author Lukas Reschke <lukas@statuscode.ch>
  24. * @author Markus Goetz <markus@woboq.com>
  25. * @author Martin Mattel <martin.mattel@diemattels.at>
  26. * @author Marvin Thomas Rabe <mrabe@marvinrabe.de>
  27. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  28. * @author Morris Jobke <hey@morrisjobke.de>
  29. * @author Robin Appelman <icewind@owncloud.com>
  30. * @author Robin McCorkell <robin@mccorkell.me.uk>
  31. * @author Roeland Jago Douma <rullzer@owncloud.com>
  32. * @author Stefan Rado <owncloud@sradonia.net>
  33. * @author Stefan Weil <sw@weilnetz.de>
  34. * @author Thomas Müller <thomas.mueller@tmit.eu>
  35. * @author Thomas Tanghus <thomas@tanghus.net>
  36. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  37. * @author Vincent Petry <pvince81@owncloud.com>
  38. * @author Volkan Gezer <volkangezer@gmail.com>
  39. *
  40. * @copyright Copyright (c) 2016, ownCloud, Inc.
  41. * @license AGPL-3.0
  42. *
  43. * This code is free software: you can redistribute it and/or modify
  44. * it under the terms of the GNU Affero General Public License, version 3,
  45. * as published by the Free Software Foundation.
  46. *
  47. * This program is distributed in the hope that it will be useful,
  48. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  49. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  50. * GNU Affero General Public License for more details.
  51. *
  52. * You should have received a copy of the GNU Affero General Public License, version 3,
  53. * along with this program. If not, see <http://www.gnu.org/licenses/>
  54. *
  55. */
  56. use OCP\IConfig;
  57. use OCP\IGroupManager;
  58. use OCP\IUser;
  59. class OC_Util {
  60. public static $scripts = array();
  61. public static $styles = array();
  62. public static $headers = array();
  63. private static $rootMounted = false;
  64. private static $fsSetup = false;
  65. protected static function getAppManager() {
  66. return \OC::$server->getAppManager();
  67. }
  68. private static function initLocalStorageRootFS() {
  69. // mount local file backend as root
  70. $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
  71. //first set up the local "root" storage
  72. \OC\Files\Filesystem::initMountManager();
  73. if (!self::$rootMounted) {
  74. \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
  75. self::$rootMounted = true;
  76. }
  77. }
  78. /**
  79. * mounting an object storage as the root fs will in essence remove the
  80. * necessity of a data folder being present.
  81. * TODO make home storage aware of this and use the object storage instead of local disk access
  82. *
  83. * @param array $config containing 'class' and optional 'arguments'
  84. */
  85. private static function initObjectStoreRootFS($config) {
  86. // check misconfiguration
  87. if (empty($config['class'])) {
  88. \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
  89. }
  90. if (!isset($config['arguments'])) {
  91. $config['arguments'] = array();
  92. }
  93. // instantiate object store implementation
  94. $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
  95. // mount with plain / root object store implementation
  96. $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
  97. // mount object storage as root
  98. \OC\Files\Filesystem::initMountManager();
  99. if (!self::$rootMounted) {
  100. \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
  101. self::$rootMounted = true;
  102. }
  103. }
  104. /**
  105. * Can be set up
  106. *
  107. * @param string $user
  108. * @return boolean
  109. * @description configure the initial filesystem based on the configuration
  110. */
  111. public static function setupFS($user = '') {
  112. //setting up the filesystem twice can only lead to trouble
  113. if (self::$fsSetup) {
  114. return false;
  115. }
  116. \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
  117. // If we are not forced to load a specific user we load the one that is logged in
  118. if ($user === null) {
  119. $user = '';
  120. } else if ($user == "" && OC_User::isLoggedIn()) {
  121. $user = OC_User::getUser();
  122. }
  123. // load all filesystem apps before, so no setup-hook gets lost
  124. OC_App::loadApps(array('filesystem'));
  125. // the filesystem will finish when $user is not empty,
  126. // mark fs setup here to avoid doing the setup from loading
  127. // OC_Filesystem
  128. if ($user != '') {
  129. self::$fsSetup = true;
  130. }
  131. \OC\Files\Filesystem::initMountManager();
  132. \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
  133. \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  134. if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
  135. /** @var \OC\Files\Storage\Common $storage */
  136. $storage->setMountOptions($mount->getOptions());
  137. }
  138. return $storage;
  139. });
  140. \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  141. if (!$mount->getOption('enable_sharing', true)) {
  142. return new \OC\Files\Storage\Wrapper\PermissionsMask([
  143. 'storage' => $storage,
  144. 'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
  145. ]);
  146. }
  147. return $storage;
  148. });
  149. // install storage availability wrapper, before most other wrappers
  150. \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
  151. if (!$storage->instanceOfStorage('\OC\Files\Storage\Shared') && !$storage->isLocal()) {
  152. return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
  153. }
  154. return $storage;
  155. });
  156. \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
  157. if ($mount->getOption('encoding_compatibility', true) && !$storage->instanceOfStorage('\OC\Files\Storage\Shared') && !$storage->isLocal()) {
  158. return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
  159. }
  160. return $storage;
  161. });
  162. \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
  163. // set up quota for home storages, even for other users
  164. // which can happen when using sharing
  165. /**
  166. * @var \OC\Files\Storage\Storage $storage
  167. */
  168. if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
  169. || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
  170. ) {
  171. /** @var \OC\Files\Storage\Home $storage */
  172. if (is_object($storage->getUser())) {
  173. $user = $storage->getUser()->getUID();
  174. $quota = OC_Util::getUserQuota($user);
  175. if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  176. return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
  177. }
  178. }
  179. }
  180. return $storage;
  181. });
  182. OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
  183. \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
  184. //check if we are using an object storage
  185. $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
  186. if (isset($objectStore)) {
  187. self::initObjectStoreRootFS($objectStore);
  188. } else {
  189. self::initLocalStorageRootFS();
  190. }
  191. if ($user != '' && !OCP\User::userExists($user)) {
  192. \OC::$server->getEventLogger()->end('setup_fs');
  193. return false;
  194. }
  195. //if we aren't logged in, there is no use to set up the filesystem
  196. if ($user != "") {
  197. $userDir = '/' . $user . '/files';
  198. //jail the user into his "home" directory
  199. \OC\Files\Filesystem::init($user, $userDir);
  200. OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
  201. }
  202. \OC::$server->getEventLogger()->end('setup_fs');
  203. return true;
  204. }
  205. /**
  206. * check if a password is required for each public link
  207. *
  208. * @return boolean
  209. */
  210. public static function isPublicLinkPasswordRequired() {
  211. $appConfig = \OC::$server->getAppConfig();
  212. $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
  213. return ($enforcePassword === 'yes') ? true : false;
  214. }
  215. /**
  216. * check if sharing is disabled for the current user
  217. * @param IConfig $config
  218. * @param IGroupManager $groupManager
  219. * @param IUser|null $user
  220. * @return bool
  221. */
  222. public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
  223. if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
  224. $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  225. $excludedGroups = json_decode($groupsList);
  226. if (is_null($excludedGroups)) {
  227. $excludedGroups = explode(',', $groupsList);
  228. $newValue = json_encode($excludedGroups);
  229. $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
  230. }
  231. $usersGroups = $groupManager->getUserGroupIds($user);
  232. if (!empty($usersGroups)) {
  233. $remainingGroups = array_diff($usersGroups, $excludedGroups);
  234. // if the user is only in groups which are disabled for sharing then
  235. // sharing is also disabled for the user
  236. if (empty($remainingGroups)) {
  237. return true;
  238. }
  239. }
  240. }
  241. return false;
  242. }
  243. /**
  244. * check if share API enforces a default expire date
  245. *
  246. * @return boolean
  247. */
  248. public static function isDefaultExpireDateEnforced() {
  249. $isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
  250. $enforceDefaultExpireDate = false;
  251. if ($isDefaultExpireDateEnabled === 'yes') {
  252. $value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
  253. $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
  254. }
  255. return $enforceDefaultExpireDate;
  256. }
  257. /**
  258. * Get the quota of a user
  259. *
  260. * @param string $user
  261. * @return int Quota bytes
  262. */
  263. public static function getUserQuota($user) {
  264. $userQuota = \OC::$server->getUserManager()->get($user)->getQuota();
  265. if($userQuota === 'none') {
  266. return \OCP\Files\FileInfo::SPACE_UNLIMITED;
  267. }else{
  268. return OC_Helper::computerFileSize($userQuota);
  269. }
  270. }
  271. /**
  272. * copies the skeleton to the users /files
  273. *
  274. * @param String $userId
  275. * @param \OCP\Files\Folder $userDirectory
  276. */
  277. public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
  278. $skeletonDirectory = \OCP\Config::getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
  279. if (!empty($skeletonDirectory)) {
  280. \OCP\Util::writeLog(
  281. 'files_skeleton',
  282. 'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
  283. \OCP\Util::DEBUG
  284. );
  285. self::copyr($skeletonDirectory, $userDirectory);
  286. // update the file cache
  287. $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
  288. }
  289. }
  290. /**
  291. * copies a directory recursively by using streams
  292. *
  293. * @param string $source
  294. * @param \OCP\Files\Folder $target
  295. * @return void
  296. */
  297. public static function copyr($source, \OCP\Files\Folder $target) {
  298. $dir = opendir($source);
  299. while (false !== ($file = readdir($dir))) {
  300. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  301. if (is_dir($source . '/' . $file)) {
  302. $child = $target->newFolder($file);
  303. self::copyr($source . '/' . $file, $child);
  304. } else {
  305. $child = $target->newFile($file);
  306. stream_copy_to_stream(fopen($source . '/' . $file,'r'), $child->fopen('w'));
  307. }
  308. }
  309. }
  310. closedir($dir);
  311. }
  312. /**
  313. * @return void
  314. */
  315. public static function tearDownFS() {
  316. \OC\Files\Filesystem::tearDown();
  317. self::$fsSetup = false;
  318. self::$rootMounted = false;
  319. }
  320. /**
  321. * get the current installed version of ownCloud
  322. *
  323. * @return array
  324. */
  325. public static function getVersion() {
  326. OC_Util::loadVersion();
  327. return \OC::$server->getSession()->get('OC_Version');
  328. }
  329. /**
  330. * get the current installed version string of ownCloud
  331. *
  332. * @return string
  333. */
  334. public static function getVersionString() {
  335. OC_Util::loadVersion();
  336. return \OC::$server->getSession()->get('OC_VersionString');
  337. }
  338. /**
  339. * @description get the current installed edition of ownCloud. There is the community
  340. * edition that just returns an empty string and the enterprise edition
  341. * that returns "Enterprise".
  342. * @return string
  343. */
  344. public static function getEditionString() {
  345. if (OC_App::isEnabled('enterprise_key')) {
  346. return "Enterprise";
  347. } else {
  348. return "";
  349. }
  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. new \OC_Defaults(), \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. version_compare('2.7.0', LIBXML_DOTTED_VERSION) === 1) {
  762. $errors[] = array(
  763. 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [LIBXML_DOTTED_VERSION]),
  764. 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
  765. );
  766. }
  767. if (!self::isAnnotationsWorking()) {
  768. $errors[] = array(
  769. 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
  770. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  771. );
  772. }
  773. if (!\OC::$CLI && $webServerRestart) {
  774. $errors[] = array(
  775. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  776. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  777. );
  778. }
  779. $errors = array_merge($errors, self::checkDatabaseVersion());
  780. // Cache the result of this function
  781. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  782. return $errors;
  783. }
  784. /**
  785. * Check the database version
  786. *
  787. * @return array errors array
  788. */
  789. public static function checkDatabaseVersion() {
  790. $l = \OC::$server->getL10N('lib');
  791. $errors = array();
  792. $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
  793. if ($dbType === 'pgsql') {
  794. // check PostgreSQL version
  795. try {
  796. $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
  797. $data = $result->fetchRow();
  798. if (isset($data['server_version'])) {
  799. $version = $data['server_version'];
  800. if (version_compare($version, '9.0.0', '<')) {
  801. $errors[] = array(
  802. 'error' => $l->t('PostgreSQL >= 9 required'),
  803. 'hint' => $l->t('Please upgrade your database version')
  804. );
  805. }
  806. }
  807. } catch (\Doctrine\DBAL\DBALException $e) {
  808. $logger = \OC::$server->getLogger();
  809. $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
  810. $logger->logException($e);
  811. }
  812. }
  813. return $errors;
  814. }
  815. /**
  816. * Check for correct file permissions of data directory
  817. *
  818. * @param string $dataDirectory
  819. * @return array arrays with error messages and hints
  820. */
  821. public static function checkDataDirectoryPermissions($dataDirectory) {
  822. $l = \OC::$server->getL10N('lib');
  823. $errors = array();
  824. if (self::runningOnWindows()) {
  825. //TODO: permissions checks for windows hosts
  826. } else {
  827. $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
  828. . ' cannot be listed by other users.');
  829. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  830. if (substr($perms, -1) != '0') {
  831. chmod($dataDirectory, 0770);
  832. clearstatcache();
  833. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  834. if (substr($perms, 2, 1) != '0') {
  835. $errors[] = array(
  836. 'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
  837. 'hint' => $permissionsModHint
  838. );
  839. }
  840. }
  841. }
  842. return $errors;
  843. }
  844. /**
  845. * Check that the data directory exists and is valid by
  846. * checking the existence of the ".ocdata" file.
  847. *
  848. * @param string $dataDirectory data directory path
  849. * @return array errors found
  850. */
  851. public static function checkDataDirectoryValidity($dataDirectory) {
  852. $l = \OC::$server->getL10N('lib');
  853. $errors = [];
  854. if (!self::runningOnWindows() && $dataDirectory[0] !== '/') {
  855. $errors[] = [
  856. 'error' => $l->t('Data directory (%s) must be an absolute path', [$dataDirectory]),
  857. 'hint' => $l->t('Check the value of "datadirectory" in your configuration')
  858. ];
  859. }
  860. if (!file_exists($dataDirectory . '/.ocdata')) {
  861. $errors[] = [
  862. 'error' => $l->t('Data directory (%s) is invalid', [$dataDirectory]),
  863. 'hint' => $l->t('Please check that the data directory contains a file' .
  864. ' ".ocdata" in its root.')
  865. ];
  866. }
  867. return $errors;
  868. }
  869. /**
  870. * Check if the user is logged in, redirects to home if not. With
  871. * redirect URL parameter to the request URI.
  872. *
  873. * @return void
  874. */
  875. public static function checkLoggedIn() {
  876. // Check if we are a user
  877. if (!OC_User::isLoggedIn()) {
  878. header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
  879. 'core.login.showLoginForm',
  880. [
  881. 'redirect_url' => urlencode(\OC::$server->getRequest()->getRequestUri()),
  882. ]
  883. )
  884. );
  885. exit();
  886. }
  887. // Redirect to index page if 2FA challenge was not solved yet
  888. if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor()) {
  889. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  890. exit();
  891. }
  892. }
  893. /**
  894. * Check if the user is a admin, redirects to home if not
  895. *
  896. * @return void
  897. */
  898. public static function checkAdminUser() {
  899. OC_Util::checkLoggedIn();
  900. if (!OC_User::isAdminUser(OC_User::getUser())) {
  901. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  902. exit();
  903. }
  904. }
  905. /**
  906. * Check if it is allowed to remember login.
  907. *
  908. * @note Every app can set 'rememberlogin' to 'false' to disable the remember login feature
  909. *
  910. * @return bool
  911. */
  912. public static function rememberLoginAllowed() {
  913. $apps = OC_App::getEnabledApps();
  914. foreach ($apps as $app) {
  915. $appInfo = OC_App::getAppInfo($app);
  916. if (isset($appInfo['rememberlogin']) && $appInfo['rememberlogin'] === 'false') {
  917. return false;
  918. }
  919. }
  920. return true;
  921. }
  922. /**
  923. * Check if the user is a subadmin, redirects to home if not
  924. *
  925. * @return null|boolean $groups where the current user is subadmin
  926. */
  927. public static function checkSubAdminUser() {
  928. OC_Util::checkLoggedIn();
  929. $userObject = \OC::$server->getUserSession()->getUser();
  930. $isSubAdmin = false;
  931. if($userObject !== null) {
  932. $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
  933. }
  934. if (!$isSubAdmin) {
  935. header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
  936. exit();
  937. }
  938. return true;
  939. }
  940. /**
  941. * Returns the URL of the default page
  942. * based on the system configuration and
  943. * the apps visible for the current user
  944. *
  945. * @return string URL
  946. */
  947. public static function getDefaultPageUrl() {
  948. $urlGenerator = \OC::$server->getURLGenerator();
  949. // Deny the redirect if the URL contains a @
  950. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  951. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  952. $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  953. } else {
  954. $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
  955. if ($defaultPage) {
  956. $location = $urlGenerator->getAbsoluteURL($defaultPage);
  957. } else {
  958. $appId = 'files';
  959. $defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
  960. // find the first app that is enabled for the current user
  961. foreach ($defaultApps as $defaultApp) {
  962. $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
  963. if (static::getAppManager()->isEnabledForUser($defaultApp)) {
  964. $appId = $defaultApp;
  965. break;
  966. }
  967. }
  968. if(getenv('front_controller_active') === 'true') {
  969. $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
  970. } else {
  971. $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  972. }
  973. }
  974. }
  975. return $location;
  976. }
  977. /**
  978. * Redirect to the user default page
  979. *
  980. * @return void
  981. */
  982. public static function redirectToDefaultPage() {
  983. $location = self::getDefaultPageUrl();
  984. header('Location: ' . $location);
  985. exit();
  986. }
  987. /**
  988. * get an id unique for this instance
  989. *
  990. * @return string
  991. */
  992. public static function getInstanceId() {
  993. $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  994. if (is_null($id)) {
  995. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  996. $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  997. \OC::$server->getSystemConfig()->setValue('instanceid', $id);
  998. }
  999. return $id;
  1000. }
  1001. /**
  1002. * Public function to sanitize HTML
  1003. *
  1004. * This function is used to sanitize HTML and should be applied on any
  1005. * string or array of strings before displaying it on a web page.
  1006. *
  1007. * @param string|array $value
  1008. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  1009. */
  1010. public static function sanitizeHTML($value) {
  1011. if (is_array($value)) {
  1012. $value = array_map(function($value) {
  1013. return self::sanitizeHTML($value);
  1014. }, $value);
  1015. } else {
  1016. // Specify encoding for PHP<5.4
  1017. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  1018. }
  1019. return $value;
  1020. }
  1021. /**
  1022. * Public function to encode url parameters
  1023. *
  1024. * This function is used to encode path to file before output.
  1025. * Encoding is done according to RFC 3986 with one exception:
  1026. * Character '/' is preserved as is.
  1027. *
  1028. * @param string $component part of URI to encode
  1029. * @return string
  1030. */
  1031. public static function encodePath($component) {
  1032. $encoded = rawurlencode($component);
  1033. $encoded = str_replace('%2F', '/', $encoded);
  1034. return $encoded;
  1035. }
  1036. public function createHtaccessTestFile(\OCP\IConfig $config) {
  1037. // php dev server does not support htaccess
  1038. if (php_sapi_name() === 'cli-server') {
  1039. return false;
  1040. }
  1041. // testdata
  1042. $fileName = '/htaccesstest.txt';
  1043. $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
  1044. // creating a test file
  1045. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1046. if (file_exists($testFile)) {// already running this test, possible recursive call
  1047. return false;
  1048. }
  1049. $fp = @fopen($testFile, 'w');
  1050. if (!$fp) {
  1051. throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
  1052. 'Make sure it is possible for the webserver to write to ' . $testFile);
  1053. }
  1054. fwrite($fp, $testContent);
  1055. fclose($fp);
  1056. }
  1057. /**
  1058. * Check if the .htaccess file is working
  1059. * @param \OCP\IConfig $config
  1060. * @return bool
  1061. * @throws Exception
  1062. * @throws \OC\HintException If the test file can't get written.
  1063. */
  1064. public function isHtaccessWorking(\OCP\IConfig $config) {
  1065. if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
  1066. return true;
  1067. }
  1068. $testContent = $this->createHtaccessTestFile($config);
  1069. if ($testContent === false) {
  1070. return false;
  1071. }
  1072. $fileName = '/htaccesstest.txt';
  1073. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1074. // accessing the file via http
  1075. $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
  1076. try {
  1077. $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
  1078. } catch (\Exception $e) {
  1079. $content = false;
  1080. }
  1081. // cleanup
  1082. @unlink($testFile);
  1083. /*
  1084. * If the content is not equal to test content our .htaccess
  1085. * is working as required
  1086. */
  1087. return $content !== $testContent;
  1088. }
  1089. /**
  1090. * Check if the setlocal call does not work. This can happen if the right
  1091. * local packages are not available on the server.
  1092. *
  1093. * @return bool
  1094. */
  1095. public static function isSetLocaleWorking() {
  1096. // setlocale test is pointless on Windows
  1097. if (OC_Util::runningOnWindows()) {
  1098. return true;
  1099. }
  1100. \Patchwork\Utf8\Bootup::initLocale();
  1101. if ('' === basename('§')) {
  1102. return false;
  1103. }
  1104. return true;
  1105. }
  1106. /**
  1107. * Check if it's possible to get the inline annotations
  1108. *
  1109. * @return bool
  1110. */
  1111. public static function isAnnotationsWorking() {
  1112. $reflection = new \ReflectionMethod(__METHOD__);
  1113. $docs = $reflection->getDocComment();
  1114. return (is_string($docs) && strlen($docs) > 50);
  1115. }
  1116. /**
  1117. * Check if the PHP module fileinfo is loaded.
  1118. *
  1119. * @return bool
  1120. */
  1121. public static function fileInfoLoaded() {
  1122. return function_exists('finfo_open');
  1123. }
  1124. /**
  1125. * clear all levels of output buffering
  1126. *
  1127. * @return void
  1128. */
  1129. public static function obEnd() {
  1130. while (ob_get_level()) {
  1131. ob_end_clean();
  1132. }
  1133. }
  1134. /**
  1135. * Checks whether the server is running on Windows
  1136. *
  1137. * @return bool true if running on Windows, false otherwise
  1138. */
  1139. public static function runningOnWindows() {
  1140. return (substr(PHP_OS, 0, 3) === "WIN");
  1141. }
  1142. /**
  1143. * Checks whether the server is running on Mac OS X
  1144. *
  1145. * @return bool true if running on Mac OS X, false otherwise
  1146. */
  1147. public static function runningOnMac() {
  1148. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  1149. }
  1150. /**
  1151. * Checks whether server is running on HHVM
  1152. *
  1153. * @return bool True if running on HHVM, false otherwise
  1154. */
  1155. public static function runningOnHhvm() {
  1156. return defined('HHVM_VERSION');
  1157. }
  1158. /**
  1159. * Handles the case that there may not be a theme, then check if a "default"
  1160. * theme exists and take that one
  1161. *
  1162. * @return string the theme
  1163. */
  1164. public static function getTheme() {
  1165. $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
  1166. if ($theme === '') {
  1167. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1168. $theme = 'default';
  1169. }
  1170. }
  1171. return $theme;
  1172. }
  1173. /**
  1174. * Clear a single file from the opcode cache
  1175. * This is useful for writing to the config file
  1176. * in case the opcode cache does not re-validate files
  1177. * Returns true if successful, false if unsuccessful:
  1178. * caller should fall back on clearing the entire cache
  1179. * with clearOpcodeCache() if unsuccessful
  1180. *
  1181. * @param string $path the path of the file to clear from the cache
  1182. * @return bool true if underlying function returns true, otherwise false
  1183. */
  1184. public static function deleteFromOpcodeCache($path) {
  1185. $ret = false;
  1186. if ($path) {
  1187. // APC >= 3.1.1
  1188. if (function_exists('apc_delete_file')) {
  1189. $ret = @apc_delete_file($path);
  1190. }
  1191. // Zend OpCache >= 7.0.0, PHP >= 5.5.0
  1192. if (function_exists('opcache_invalidate')) {
  1193. $ret = opcache_invalidate($path);
  1194. }
  1195. }
  1196. return $ret;
  1197. }
  1198. /**
  1199. * Clear the opcode cache if one exists
  1200. * This is necessary for writing to the config file
  1201. * in case the opcode cache does not re-validate files
  1202. *
  1203. * @return void
  1204. */
  1205. public static function clearOpcodeCache() {
  1206. // APC
  1207. if (function_exists('apc_clear_cache')) {
  1208. apc_clear_cache();
  1209. }
  1210. // Zend Opcache
  1211. if (function_exists('accelerator_reset')) {
  1212. accelerator_reset();
  1213. }
  1214. // XCache
  1215. if (function_exists('xcache_clear_cache')) {
  1216. if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
  1217. \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
  1218. } else {
  1219. @xcache_clear_cache(XC_TYPE_PHP, 0);
  1220. }
  1221. }
  1222. // Opcache (PHP >= 5.5)
  1223. if (function_exists('opcache_reset')) {
  1224. opcache_reset();
  1225. }
  1226. }
  1227. /**
  1228. * Normalize a unicode string
  1229. *
  1230. * @param string $value a not normalized string
  1231. * @return bool|string
  1232. */
  1233. public static function normalizeUnicode($value) {
  1234. if(Normalizer::isNormalized($value)) {
  1235. return $value;
  1236. }
  1237. $normalizedValue = Normalizer::normalize($value);
  1238. if ($normalizedValue === null || $normalizedValue === false) {
  1239. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  1240. return $value;
  1241. }
  1242. return $normalizedValue;
  1243. }
  1244. /**
  1245. * @param boolean|string $file
  1246. * @return string
  1247. */
  1248. public static function basename($file) {
  1249. $file = rtrim($file, '/');
  1250. $t = explode('/', $file);
  1251. return array_pop($t);
  1252. }
  1253. /**
  1254. * A human readable string is generated based on version, channel and build number
  1255. *
  1256. * @return string
  1257. */
  1258. public static function getHumanVersion() {
  1259. $version = OC_Util::getVersionString() . ' (' . OC_Util::getChannel() . ')';
  1260. $build = OC_Util::getBuild();
  1261. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1262. $version .= ' Build:' . $build;
  1263. }
  1264. return $version;
  1265. }
  1266. /**
  1267. * Returns whether the given file name is valid
  1268. *
  1269. * @param string $file file name to check
  1270. * @return bool true if the file name is valid, false otherwise
  1271. * @deprecated use \OC\Files\View::verifyPath()
  1272. */
  1273. public static function isValidFileName($file) {
  1274. $trimmed = trim($file);
  1275. if ($trimmed === '') {
  1276. return false;
  1277. }
  1278. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  1279. return false;
  1280. }
  1281. foreach (str_split($trimmed) as $char) {
  1282. if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
  1283. return false;
  1284. }
  1285. }
  1286. return true;
  1287. }
  1288. /**
  1289. * Check whether the instance needs to perform an upgrade,
  1290. * either when the core version is higher or any app requires
  1291. * an upgrade.
  1292. *
  1293. * @param \OCP\IConfig $config
  1294. * @return bool whether the core or any app needs an upgrade
  1295. * @throws \OC\HintException When the upgrade from the given version is not allowed
  1296. */
  1297. public static function needUpgrade(\OCP\IConfig $config) {
  1298. if ($config->getSystemValue('installed', false)) {
  1299. $installedVersion = $config->getSystemValue('version', '0.0.0');
  1300. $currentVersion = implode('.', \OCP\Util::getVersion());
  1301. $versionDiff = version_compare($currentVersion, $installedVersion);
  1302. if ($versionDiff > 0) {
  1303. return true;
  1304. } else if ($config->getSystemValue('debug', false) && $versionDiff < 0) {
  1305. // downgrade with debug
  1306. $installedMajor = explode('.', $installedVersion);
  1307. $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
  1308. $currentMajor = explode('.', $currentVersion);
  1309. $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
  1310. if ($installedMajor === $currentMajor) {
  1311. // Same major, allow downgrade for developers
  1312. return true;
  1313. } else {
  1314. // downgrade attempt, throw exception
  1315. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1316. }
  1317. } else if ($versionDiff < 0) {
  1318. // downgrade attempt, throw exception
  1319. throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
  1320. }
  1321. // also check for upgrades for apps (independently from the user)
  1322. $apps = \OC_App::getEnabledApps(false, true);
  1323. $shouldUpgrade = false;
  1324. foreach ($apps as $app) {
  1325. if (\OC_App::shouldUpgrade($app)) {
  1326. $shouldUpgrade = true;
  1327. break;
  1328. }
  1329. }
  1330. return $shouldUpgrade;
  1331. } else {
  1332. return false;
  1333. }
  1334. }
  1335. }