util.php 44 KB

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