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 config folder is writable.
  516. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  517. $errors[] = array(
  518. 'error' => $l->t('Cannot write into "config" directory'),
  519. 'hint' => $l->t('This can usually be fixed by '
  520. . '%sgiving the webserver write access to the config directory%s.',
  521. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'))
  522. );
  523. }
  524. // Check if there is a writable install folder.
  525. if ($config->getSystemValue('appstoreenabled', true)) {
  526. if (OC_App::getInstallPath() === null
  527. || !is_writable(OC_App::getInstallPath())
  528. || !is_readable(OC_App::getInstallPath())
  529. ) {
  530. $errors[] = array(
  531. 'error' => $l->t('Cannot write into "apps" directory'),
  532. 'hint' => $l->t('This can usually be fixed by '
  533. . '%sgiving the webserver write access to the apps directory%s'
  534. . ' or disabling the appstore in the config file.',
  535. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'))
  536. );
  537. }
  538. }
  539. // Create root dir.
  540. if ($config->getSystemValue('installed', false)) {
  541. if (!is_dir($CONFIG_DATADIRECTORY)) {
  542. $success = @mkdir($CONFIG_DATADIRECTORY);
  543. if ($success) {
  544. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  545. } else {
  546. $errors[] = array(
  547. 'error' => $l->t('Cannot create "data" directory (%s)', array($CONFIG_DATADIRECTORY)),
  548. 'hint' => $l->t('This can usually be fixed by '
  549. . '<a href="%s" target="_blank">giving the webserver write access to the root directory</a>.',
  550. array(OC_Helper::linkToDocs('admin-dir_permissions')))
  551. );
  552. }
  553. } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  554. //common hint for all file permissions error messages
  555. $permissionsHint = $l->t('Permissions can usually be fixed by '
  556. . '%sgiving the webserver write access to the root directory%s.',
  557. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'));
  558. $errors[] = array(
  559. 'error' => 'Data directory (' . $CONFIG_DATADIRECTORY . ') not writable by ownCloud',
  560. 'hint' => $permissionsHint
  561. );
  562. } else {
  563. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  564. }
  565. }
  566. if (!OC_Util::isSetLocaleWorking()) {
  567. $errors[] = array(
  568. 'error' => $l->t('Setting locale to %s failed',
  569. array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  570. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
  571. 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
  572. );
  573. }
  574. // Contains the dependencies that should be checked against
  575. // classes = class_exists
  576. // functions = function_exists
  577. // defined = defined
  578. // ini = ini_get
  579. // If the dependency is not found the missing module name is shown to the EndUser
  580. // When adding new checks always verify that they pass on Travis as well
  581. // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
  582. $dependencies = array(
  583. 'classes' => array(
  584. 'ZipArchive' => 'zip',
  585. 'DOMDocument' => 'dom',
  586. 'XMLWriter' => 'XMLWriter'
  587. ),
  588. 'functions' => [
  589. 'xml_parser_create' => 'libxml',
  590. 'mb_detect_encoding' => 'mb multibyte',
  591. 'ctype_digit' => 'ctype',
  592. 'json_encode' => 'JSON',
  593. 'gd_info' => 'GD',
  594. 'gzencode' => 'zlib',
  595. 'iconv' => 'iconv',
  596. 'simplexml_load_string' => 'SimpleXML',
  597. 'hash' => 'HASH Message Digest Framework',
  598. 'curl_init' => 'cURL',
  599. ],
  600. 'defined' => array(
  601. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  602. ),
  603. 'ini' => [
  604. 'mbstring.func_overload' => 0,
  605. 'output_buffering' => false,
  606. 'default_charset' => 'UTF-8',
  607. ],
  608. );
  609. $missingDependencies = array();
  610. $invalidIniSettings = [];
  611. $moduleHint = $l->t('Please ask your server administrator to install the module.');
  612. /**
  613. * FIXME: The dependency check does not work properly on HHVM on the moment
  614. * and prevents installation. Once HHVM is more compatible with our
  615. * approach to check for these values we should re-enable those
  616. * checks.
  617. */
  618. if (!self::runningOnHhvm()) {
  619. foreach ($dependencies['classes'] as $class => $module) {
  620. if (!class_exists($class)) {
  621. $missingDependencies[] = $module;
  622. }
  623. }
  624. foreach ($dependencies['functions'] as $function => $module) {
  625. if (!function_exists($function)) {
  626. $missingDependencies[] = $module;
  627. }
  628. }
  629. foreach ($dependencies['defined'] as $defined => $module) {
  630. if (!defined($defined)) {
  631. $missingDependencies[] = $module;
  632. }
  633. }
  634. foreach ($dependencies['ini'] as $setting => $expected) {
  635. $iniWrapper = \OC::$server->getIniWrapper();
  636. if (is_bool($expected)) {
  637. if ($iniWrapper->getBool($setting) !== $expected) {
  638. $invalidIniSettings[] = [$setting, $expected];
  639. }
  640. }
  641. if (is_int($expected)) {
  642. if ($iniWrapper->getNumeric($setting) !== $expected) {
  643. $invalidIniSettings[] = [$setting, $expected];
  644. }
  645. }
  646. if (is_string($expected)) {
  647. if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
  648. $invalidIniSettings[] = [$setting, $expected];
  649. }
  650. }
  651. }
  652. }
  653. foreach($missingDependencies as $missingDependency) {
  654. $errors[] = array(
  655. 'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
  656. 'hint' => $moduleHint
  657. );
  658. $webServerRestart = true;
  659. }
  660. foreach($invalidIniSettings as $setting) {
  661. if(is_bool($setting[1])) {
  662. $setting[1] = ($setting[1]) ? 'on' : 'off';
  663. }
  664. $errors[] = [
  665. 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
  666. 'hint' => $l->t('Adjusting this setting in php.ini will make ownCloud run again')
  667. ];
  668. $webServerRestart = true;
  669. }
  670. if (version_compare(phpversion(), '5.4.0', '<')) {
  671. $errors[] = array(
  672. 'error' => $l->t('PHP %s or higher is required.', '5.4.0'),
  673. 'hint' => $l->t('Please ask your server administrator to update PHP to the latest version.'
  674. . ' Your PHP version is no longer supported by ownCloud and the PHP community.')
  675. );
  676. $webServerRestart = true;
  677. }
  678. /**
  679. * PHP 5.6 ships with a PHP setting which throws notices by default for a
  680. * lot of endpoints. Thus we need to ensure that the value is set to -1
  681. *
  682. * FIXME: Due to https://github.com/owncloud/core/pull/13593#issuecomment-71178078
  683. * this check is disabled for HHVM at the moment. This should get re-evaluated
  684. * at a later point.
  685. *
  686. * @link https://github.com/owncloud/core/issues/13592
  687. */
  688. if(version_compare(phpversion(), '5.6.0', '>=') &&
  689. !self::runningOnHhvm() &&
  690. \OC::$server->getIniWrapper()->getNumeric('always_populate_raw_post_data') !== -1) {
  691. $errors[] = array(
  692. 'error' => $l->t('PHP is configured to populate raw post data. Since PHP 5.6 this will lead to PHP throwing notices for perfectly valid code.'),
  693. 'hint' => $l->t('To fix this issue set <code>always_populate_raw_post_data</code> to <code>-1</code> in your php.ini')
  694. );
  695. }
  696. if (!self::isAnnotationsWorking()) {
  697. $errors[] = array(
  698. 'error' => $l->t('PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible.'),
  699. 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
  700. );
  701. }
  702. if (!\OC::$CLI && $webServerRestart) {
  703. $errors[] = array(
  704. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  705. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  706. );
  707. }
  708. $errors = array_merge($errors, self::checkDatabaseVersion());
  709. // Cache the result of this function
  710. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  711. return $errors;
  712. }
  713. /**
  714. * Check the database version
  715. *
  716. * @return array errors array
  717. */
  718. public static function checkDatabaseVersion() {
  719. $l = \OC::$server->getL10N('lib');
  720. $errors = array();
  721. $dbType = \OC_Config::getValue('dbtype', 'sqlite');
  722. if ($dbType === 'pgsql') {
  723. // check PostgreSQL version
  724. try {
  725. $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
  726. $data = $result->fetchRow();
  727. if (isset($data['server_version'])) {
  728. $version = $data['server_version'];
  729. if (version_compare($version, '9.0.0', '<')) {
  730. $errors[] = array(
  731. 'error' => $l->t('PostgreSQL >= 9 required'),
  732. 'hint' => $l->t('Please upgrade your database version')
  733. );
  734. }
  735. }
  736. } catch (\Doctrine\DBAL\DBALException $e) {
  737. \OCP\Util::logException('core', $e);
  738. $errors[] = array(
  739. 'error' => $l->t('Error occurred while checking PostgreSQL version'),
  740. 'hint' => $l->t('Please make sure you have PostgreSQL >= 9 or'
  741. . ' check the logs for more information about the error')
  742. );
  743. }
  744. }
  745. return $errors;
  746. }
  747. /**
  748. * Check for correct file permissions of data directory
  749. *
  750. * @param string $dataDirectory
  751. * @return array arrays with error messages and hints
  752. */
  753. public static function checkDataDirectoryPermissions($dataDirectory) {
  754. $l = \OC::$server->getL10N('lib');
  755. $errors = array();
  756. if (self::runningOnWindows()) {
  757. //TODO: permissions checks for windows hosts
  758. } else {
  759. $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
  760. . ' cannot be listed by other users.');
  761. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  762. if (substr($perms, -1) != '0') {
  763. chmod($dataDirectory, 0770);
  764. clearstatcache();
  765. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  766. if (substr($perms, 2, 1) != '0') {
  767. $errors[] = array(
  768. 'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
  769. 'hint' => $permissionsModHint
  770. );
  771. }
  772. }
  773. }
  774. return $errors;
  775. }
  776. /**
  777. * Check that the data directory exists and is valid by
  778. * checking the existence of the ".ocdata" file.
  779. *
  780. * @param string $dataDirectory data directory path
  781. * @return array errors found
  782. */
  783. public static function checkDataDirectoryValidity($dataDirectory) {
  784. $l = \OC::$server->getL10N('lib');
  785. $errors = [];
  786. if (!self::runningOnWindows() && $dataDirectory[0] !== '/') {
  787. $errors[] = [
  788. 'error' => $l->t('Data directory (%s) must be an absolute path', [$dataDirectory]),
  789. 'hint' => $l->t('Check the value of "datadirectory" in your configuration')
  790. ];
  791. }
  792. if (!file_exists($dataDirectory . '/.ocdata')) {
  793. $errors[] = [
  794. 'error' => $l->t('Data directory (%s) is invalid', [$dataDirectory]),
  795. 'hint' => $l->t('Please check that the data directory contains a file' .
  796. ' ".ocdata" in its root.')
  797. ];
  798. }
  799. return $errors;
  800. }
  801. /**
  802. * @param array $errors
  803. * @param string[] $messages
  804. */
  805. public static function displayLoginPage($errors = array(), $messages = []) {
  806. $parameters = array();
  807. foreach ($errors as $value) {
  808. $parameters[$value] = true;
  809. }
  810. $parameters['messages'] = $messages;
  811. if (!empty($_REQUEST['user'])) {
  812. $parameters["username"] = $_REQUEST['user'];
  813. $parameters['user_autofocus'] = false;
  814. } else {
  815. $parameters["username"] = '';
  816. $parameters['user_autofocus'] = true;
  817. }
  818. if (isset($_REQUEST['redirect_url'])) {
  819. $parameters['redirect_url'] = $_REQUEST['redirect_url'];
  820. }
  821. $parameters['alt_login'] = OC_App::getAlternativeLogIns();
  822. $parameters['rememberLoginAllowed'] = self::rememberLoginAllowed();
  823. OC_Template::printGuestPage("", "login", $parameters);
  824. }
  825. /**
  826. * Check if the app is enabled, redirects to home if not
  827. *
  828. * @param string $app
  829. * @return void
  830. */
  831. public static function checkAppEnabled($app) {
  832. if (!OC_App::isEnabled($app)) {
  833. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  834. exit();
  835. }
  836. }
  837. /**
  838. * Check if the user is logged in, redirects to home if not. With
  839. * redirect URL parameter to the request URI.
  840. *
  841. * @return void
  842. */
  843. public static function checkLoggedIn() {
  844. // Check if we are a user
  845. if (!OC_User::isLoggedIn()) {
  846. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php',
  847. [
  848. 'redirect_url' => \OC::$server->getRequest()->getRequestUri()
  849. ]
  850. )
  851. );
  852. exit();
  853. }
  854. }
  855. /**
  856. * Check if the user is a admin, redirects to home if not
  857. *
  858. * @return void
  859. */
  860. public static function checkAdminUser() {
  861. OC_Util::checkLoggedIn();
  862. if (!OC_User::isAdminUser(OC_User::getUser())) {
  863. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  864. exit();
  865. }
  866. }
  867. /**
  868. * Check if it is allowed to remember login.
  869. *
  870. * @note Every app can set 'rememberlogin' to 'false' to disable the remember login feature
  871. *
  872. * @return bool
  873. */
  874. public static function rememberLoginAllowed() {
  875. $apps = OC_App::getEnabledApps();
  876. foreach ($apps as $app) {
  877. $appInfo = OC_App::getAppInfo($app);
  878. if (isset($appInfo['rememberlogin']) && $appInfo['rememberlogin'] === 'false') {
  879. return false;
  880. }
  881. }
  882. return true;
  883. }
  884. /**
  885. * Check if the user is a subadmin, redirects to home if not
  886. *
  887. * @return null|boolean $groups where the current user is subadmin
  888. */
  889. public static function checkSubAdminUser() {
  890. OC_Util::checkLoggedIn();
  891. if (!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
  892. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  893. exit();
  894. }
  895. return true;
  896. }
  897. /**
  898. * Returns the URL of the default page
  899. * based on the system configuration and
  900. * the apps visible for the current user
  901. *
  902. * @return string URL
  903. */
  904. public static function getDefaultPageUrl() {
  905. $urlGenerator = \OC::$server->getURLGenerator();
  906. // Deny the redirect if the URL contains a @
  907. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  908. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  909. $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  910. } else {
  911. $defaultPage = OC_Appconfig::getValue('core', 'defaultpage');
  912. if ($defaultPage) {
  913. $location = $urlGenerator->getAbsoluteURL($defaultPage);
  914. } else {
  915. $appId = 'files';
  916. $defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
  917. // find the first app that is enabled for the current user
  918. foreach ($defaultApps as $defaultApp) {
  919. $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
  920. if (static::getAppManager()->isEnabledForUser($defaultApp)) {
  921. $appId = $defaultApp;
  922. break;
  923. }
  924. }
  925. $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  926. }
  927. }
  928. return $location;
  929. }
  930. /**
  931. * Redirect to the user default page
  932. *
  933. * @return void
  934. */
  935. public static function redirectToDefaultPage() {
  936. $location = self::getDefaultPageUrl();
  937. header('Location: ' . $location);
  938. exit();
  939. }
  940. /**
  941. * get an id unique for this instance
  942. *
  943. * @return string
  944. */
  945. public static function getInstanceId() {
  946. $id = OC_Config::getValue('instanceid', null);
  947. if (is_null($id)) {
  948. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  949. $id = 'oc' . \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  950. OC_Config::$object->setValue('instanceid', $id);
  951. }
  952. return $id;
  953. }
  954. /**
  955. * Register an get/post call. Important to prevent CSRF attacks.
  956. *
  957. * @return string Generated token.
  958. * @description
  959. * Creates a 'request token' (random) and stores it inside the session.
  960. * Ever subsequent (ajax) request must use such a valid token to succeed,
  961. * otherwise the request will be denied as a protection against CSRF.
  962. * @see OC_Util::isCallRegistered()
  963. */
  964. public static function callRegister() {
  965. // Check if a token exists
  966. if (!\OC::$server->getSession()->exists('requesttoken')) {
  967. // No valid token found, generate a new one.
  968. $requestToken = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(30);
  969. \OC::$server->getSession()->set('requesttoken', $requestToken);
  970. } else {
  971. // Valid token already exists, send it
  972. $requestToken = \OC::$server->getSession()->get('requesttoken');
  973. }
  974. return ($requestToken);
  975. }
  976. /**
  977. * Check an ajax get/post call if the request token is valid.
  978. *
  979. * @return boolean False if request token is not set or is invalid.
  980. * @see OC_Util::callRegister()
  981. */
  982. public static function isCallRegistered() {
  983. return \OC::$server->getRequest()->passesCSRFCheck();
  984. }
  985. /**
  986. * Check an ajax get/post call if the request token is valid. Exit if not.
  987. *
  988. * @return void
  989. */
  990. public static function callCheck() {
  991. if (!OC_Util::isCallRegistered()) {
  992. exit();
  993. }
  994. }
  995. /**
  996. * Public function to sanitize HTML
  997. *
  998. * This function is used to sanitize HTML and should be applied on any
  999. * string or array of strings before displaying it on a web page.
  1000. *
  1001. * @param string|array &$value
  1002. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  1003. */
  1004. public static function sanitizeHTML(&$value) {
  1005. if (is_array($value)) {
  1006. array_walk_recursive($value, 'OC_Util::sanitizeHTML');
  1007. } else {
  1008. //Specify encoding for PHP<5.4
  1009. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  1010. }
  1011. return $value;
  1012. }
  1013. /**
  1014. * Public function to encode url parameters
  1015. *
  1016. * This function is used to encode path to file before output.
  1017. * Encoding is done according to RFC 3986 with one exception:
  1018. * Character '/' is preserved as is.
  1019. *
  1020. * @param string $component part of URI to encode
  1021. * @return string
  1022. */
  1023. public static function encodePath($component) {
  1024. $encoded = rawurlencode($component);
  1025. $encoded = str_replace('%2F', '/', $encoded);
  1026. return $encoded;
  1027. }
  1028. /**
  1029. * Check if the .htaccess file is working
  1030. * @param \OCP\IConfig $config
  1031. * @return bool
  1032. * @throws Exception
  1033. * @throws \OC\HintException If the test file can't get written.
  1034. */
  1035. public function isHtaccessWorking(\OCP\IConfig $config) {
  1036. if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
  1037. return true;
  1038. }
  1039. // php dev server does not support htaccess
  1040. if (php_sapi_name() === 'cli-server') {
  1041. return false;
  1042. }
  1043. // testdata
  1044. $fileName = '/htaccesstest.txt';
  1045. $testContent = 'testcontent';
  1046. // creating a test file
  1047. $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  1048. if (file_exists($testFile)) {// already running this test, possible recursive call
  1049. return false;
  1050. }
  1051. $fp = @fopen($testFile, 'w');
  1052. if (!$fp) {
  1053. throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
  1054. 'Make sure it is possible for the webserver to write to ' . $testFile);
  1055. }
  1056. fwrite($fp, $testContent);
  1057. fclose($fp);
  1058. // accessing the file via http
  1059. $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT . '/data' . $fileName);
  1060. $content = self::getUrlContent($url);
  1061. // cleanup
  1062. @unlink($testFile);
  1063. /*
  1064. * If the content is not equal to test content our .htaccess
  1065. * is working as required
  1066. */
  1067. return $content !== $testContent;
  1068. }
  1069. /**
  1070. * Check if the setlocal call does not work. This can happen if the right
  1071. * local packages are not available on the server.
  1072. *
  1073. * @return bool
  1074. */
  1075. public static function isSetLocaleWorking() {
  1076. // setlocale test is pointless on Windows
  1077. if (OC_Util::runningOnWindows()) {
  1078. return true;
  1079. }
  1080. \Patchwork\Utf8\Bootup::initLocale();
  1081. if ('' === basename('§')) {
  1082. return false;
  1083. }
  1084. return true;
  1085. }
  1086. /**
  1087. * Check if it's possible to get the inline annotations
  1088. *
  1089. * @return bool
  1090. */
  1091. public static function isAnnotationsWorking() {
  1092. $reflection = new \ReflectionMethod(__METHOD__);
  1093. $docs = $reflection->getDocComment();
  1094. return (is_string($docs) && strlen($docs) > 50);
  1095. }
  1096. /**
  1097. * Check if the PHP module fileinfo is loaded.
  1098. *
  1099. * @return bool
  1100. */
  1101. public static function fileInfoLoaded() {
  1102. return function_exists('finfo_open');
  1103. }
  1104. /**
  1105. * clear all levels of output buffering
  1106. *
  1107. * @return void
  1108. */
  1109. public static function obEnd() {
  1110. while (ob_get_level()) {
  1111. ob_end_clean();
  1112. }
  1113. }
  1114. /**
  1115. * Generates a cryptographic secure pseudo-random string
  1116. *
  1117. * @param int $length of the random string
  1118. * @return string
  1119. * @deprecated Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
  1120. */
  1121. public static function generateRandomBytes($length = 30) {
  1122. return \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  1123. }
  1124. /**
  1125. * Get URL content
  1126. * @param string $url Url to get content
  1127. * @deprecated Use \OC::$server->getHTTPHelper()->getUrlContent($url);
  1128. * @throws Exception If the URL does not start with http:// or https://
  1129. * @return string of the response or false on error
  1130. * This function get the content of a page via curl, if curl is enabled.
  1131. * If not, file_get_contents is used.
  1132. */
  1133. public static function getUrlContent($url) {
  1134. try {
  1135. return \OC::$server->getHTTPHelper()->getUrlContent($url);
  1136. } catch (\Exception $e) {
  1137. throw $e;
  1138. }
  1139. }
  1140. /**
  1141. * Checks whether the server is running on Windows
  1142. *
  1143. * @return bool true if running on Windows, false otherwise
  1144. */
  1145. public static function runningOnWindows() {
  1146. return (substr(PHP_OS, 0, 3) === "WIN");
  1147. }
  1148. /**
  1149. * Checks whether the server is running on Mac OS X
  1150. *
  1151. * @return bool true if running on Mac OS X, false otherwise
  1152. */
  1153. public static function runningOnMac() {
  1154. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  1155. }
  1156. /**
  1157. * Checks whether server is running on HHVM
  1158. *
  1159. * @return bool True if running on HHVM, false otherwise
  1160. */
  1161. public static function runningOnHhvm() {
  1162. return defined('HHVM_VERSION');
  1163. }
  1164. /**
  1165. * Handles the case that there may not be a theme, then check if a "default"
  1166. * theme exists and take that one
  1167. *
  1168. * @return string the theme
  1169. */
  1170. public static function getTheme() {
  1171. $theme = OC_Config::getValue("theme", '');
  1172. if ($theme === '') {
  1173. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1174. $theme = 'default';
  1175. }
  1176. }
  1177. return $theme;
  1178. }
  1179. /**
  1180. * Clear a single file from the opcode cache
  1181. * This is useful for writing to the config file
  1182. * in case the opcode cache does not re-validate files
  1183. * Returns true if successful, false if unsuccessful:
  1184. * caller should fall back on clearing the entire cache
  1185. * with clearOpcodeCache() if unsuccessful
  1186. *
  1187. * @param string $path the path of the file to clear from the cache
  1188. * @return bool true if underlying function returns true, otherwise false
  1189. */
  1190. public static function deleteFromOpcodeCache($path) {
  1191. $ret = false;
  1192. if ($path) {
  1193. // APC >= 3.1.1
  1194. if (function_exists('apc_delete_file')) {
  1195. $ret = @apc_delete_file($path);
  1196. }
  1197. // Zend OpCache >= 7.0.0, PHP >= 5.5.0
  1198. if (function_exists('opcache_invalidate')) {
  1199. $ret = opcache_invalidate($path);
  1200. }
  1201. }
  1202. return $ret;
  1203. }
  1204. /**
  1205. * Clear the opcode cache if one exists
  1206. * This is necessary for writing to the config file
  1207. * in case the opcode cache does not re-validate files
  1208. *
  1209. * @return void
  1210. */
  1211. public static function clearOpcodeCache() {
  1212. // APC
  1213. if (function_exists('apc_clear_cache')) {
  1214. apc_clear_cache();
  1215. }
  1216. // Zend Opcache
  1217. if (function_exists('accelerator_reset')) {
  1218. accelerator_reset();
  1219. }
  1220. // XCache
  1221. if (function_exists('xcache_clear_cache')) {
  1222. if (ini_get('xcache.admin.enable_auth')) {
  1223. OC_Log::write('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OC_Log::WARN);
  1224. } else {
  1225. xcache_clear_cache(XC_TYPE_PHP, 0);
  1226. }
  1227. }
  1228. // Opcache (PHP >= 5.5)
  1229. if (function_exists('opcache_reset')) {
  1230. opcache_reset();
  1231. }
  1232. }
  1233. /**
  1234. * Normalize a unicode string
  1235. *
  1236. * @param string $value a not normalized string
  1237. * @return bool|string
  1238. */
  1239. public static function normalizeUnicode($value) {
  1240. if(Normalizer::isNormalized($value)) {
  1241. return $value;
  1242. }
  1243. $normalizedValue = Normalizer::normalize($value);
  1244. if ($normalizedValue === null || $normalizedValue === false) {
  1245. \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
  1246. return $value;
  1247. }
  1248. return $normalizedValue;
  1249. }
  1250. /**
  1251. * @param boolean|string $file
  1252. * @return string
  1253. */
  1254. public static function basename($file) {
  1255. $file = rtrim($file, '/');
  1256. $t = explode('/', $file);
  1257. return array_pop($t);
  1258. }
  1259. /**
  1260. * A human readable string is generated based on version, channel and build number
  1261. *
  1262. * @return string
  1263. */
  1264. public static function getHumanVersion() {
  1265. $version = OC_Util::getVersionString() . ' (' . OC_Util::getChannel() . ')';
  1266. $build = OC_Util::getBuild();
  1267. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1268. $version .= ' Build:' . $build;
  1269. }
  1270. return $version;
  1271. }
  1272. /**
  1273. * Returns whether the given file name is valid
  1274. *
  1275. * @param string $file file name to check
  1276. * @return bool true if the file name is valid, false otherwise
  1277. * @deprecated use \OC\Files\View::verifyPath()
  1278. */
  1279. public static function isValidFileName($file) {
  1280. $trimmed = trim($file);
  1281. if ($trimmed === '') {
  1282. return false;
  1283. }
  1284. if ($trimmed === '.' || $trimmed === '..') {
  1285. return false;
  1286. }
  1287. foreach (str_split($trimmed) as $char) {
  1288. if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
  1289. return false;
  1290. }
  1291. }
  1292. return true;
  1293. }
  1294. /**
  1295. * Check whether the instance needs to perform an upgrade,
  1296. * either when the core version is higher or any app requires
  1297. * an upgrade.
  1298. *
  1299. * @param \OCP\IConfig $config
  1300. * @return bool whether the core or any app needs an upgrade
  1301. */
  1302. public static function needUpgrade(\OCP\IConfig $config) {
  1303. if ($config->getSystemValue('installed', false)) {
  1304. $installedVersion = $config->getSystemValue('version', '0.0.0');
  1305. $currentVersion = implode('.', OC_Util::getVersion());
  1306. if (version_compare($currentVersion, $installedVersion, '>')) {
  1307. return true;
  1308. }
  1309. // also check for upgrades for apps (independently from the user)
  1310. $apps = \OC_App::getEnabledApps(false, true);
  1311. $shouldUpgrade = false;
  1312. foreach ($apps as $app) {
  1313. if (\OC_App::shouldUpgrade($app)) {
  1314. $shouldUpgrade = true;
  1315. break;
  1316. }
  1317. }
  1318. return $shouldUpgrade;
  1319. } else {
  1320. return false;
  1321. }
  1322. }
  1323. }