util.php 47 KB

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