util.php 46 KB

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