util.php 44 KB

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