util.php 42 KB

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