You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.php 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. OC_Util::loadVersion();
  256. return \OC::$server->getSession()->get('OC_Edition');
  257. }
  258. /**
  259. * @description get the update channel of the current installed of ownCloud.
  260. * @return string
  261. */
  262. public static function getChannel() {
  263. OC_Util::loadVersion();
  264. return \OC::$server->getSession()->get('OC_Channel');
  265. }
  266. /**
  267. * @description get the build number of the current installed of ownCloud.
  268. * @return string
  269. */
  270. public static function getBuild() {
  271. OC_Util::loadVersion();
  272. return \OC::$server->getSession()->get('OC_Build');
  273. }
  274. /**
  275. * @description load the version.php into the session as cache
  276. */
  277. private static function loadVersion() {
  278. $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
  279. if (!\OC::$server->getSession()->exists('OC_Version') or OC::$server->getSession()->get('OC_Version_Timestamp') != $timestamp) {
  280. require 'version.php';
  281. $session = \OC::$server->getSession();
  282. /** @var $timestamp int */
  283. $session->set('OC_Version_Timestamp', $timestamp);
  284. /** @var $OC_Version string */
  285. $session->set('OC_Version', $OC_Version);
  286. /** @var $OC_VersionString string */
  287. $session->set('OC_VersionString', $OC_VersionString);
  288. /** @var $OC_Edition string */
  289. $session->set('OC_Edition', $OC_Edition);
  290. /** @var $OC_Channel string */
  291. $session->set('OC_Channel', $OC_Channel);
  292. /** @var $OC_Build string */
  293. $session->set('OC_Build', $OC_Build);
  294. }
  295. }
  296. /**
  297. * generates a path for JS/CSS files. If no application is provided it will create the path for core.
  298. *
  299. * @param $application application to get the files from
  300. * @param $directory directory withing this application (css, js, vendor, etc)
  301. * @param $file the file inside of the above folder
  302. * @return string the path
  303. */
  304. private static function generatePath($application, $directory, $file) {
  305. if (is_null($file)) {
  306. $file = $application;
  307. $application = "";
  308. }
  309. if (!empty($application)) {
  310. return "$application/$directory/$file";
  311. } else {
  312. return "$directory/$file";
  313. }
  314. }
  315. /**
  316. * add a javascript file
  317. *
  318. * @param string $application application id
  319. * @param string|null $file filename
  320. * @return void
  321. */
  322. public static function addScript($application, $file = null) {
  323. self::$scripts[] = OC_Util::generatePath($application, 'js', $file);
  324. }
  325. /**
  326. * add a javascript file from the vendor sub folder
  327. *
  328. * @param string $application application id
  329. * @param string|null $file filename
  330. * @return void
  331. */
  332. public static function addVendorScript($application, $file = null) {
  333. self::$scripts[] = OC_Util::generatePath($application, 'vendor', $file);
  334. }
  335. /**
  336. * add a translation JS file
  337. *
  338. * @param string $application application id
  339. * @param string $languageCode language code, defaults to the current language
  340. */
  341. public static function addTranslations($application, $languageCode = null) {
  342. if (is_null($languageCode)) {
  343. $l = new \OC_L10N($application);
  344. $languageCode = $l->getLanguageCode($application);
  345. }
  346. if (!empty($application)) {
  347. self::$scripts[] = "$application/l10n/$languageCode";
  348. } else {
  349. self::$scripts[] = "l10n/$languageCode";
  350. }
  351. }
  352. /**
  353. * add a css file
  354. *
  355. * @param string $application application id
  356. * @param string|null $file filename
  357. * @return void
  358. */
  359. public static function addStyle($application, $file = null) {
  360. self::$styles[] = OC_Util::generatePath($application, 'css', $file);
  361. }
  362. /**
  363. * add a css file from the vendor sub folder
  364. *
  365. * @param string $application application id
  366. * @param string|null $file filename
  367. * @return void
  368. */
  369. public static function addVendorStyle($application, $file = null) {
  370. self::$styles[] = OC_Util::generatePath($application, 'vendor', $file);
  371. }
  372. /**
  373. * Add a custom element to the header
  374. * If $text is null then the element will be written as empty element.
  375. * So use "" to get a closing tag.
  376. * @param string $tag tag name of the element
  377. * @param array $attributes array of attributes for the element
  378. * @param string $text the text content for the element
  379. */
  380. public static function addHeader($tag, $attributes, $text=null) {
  381. self::$headers[] = array(
  382. 'tag' => $tag,
  383. 'attributes' => $attributes,
  384. 'text' => $text
  385. );
  386. }
  387. /**
  388. * formats a timestamp in the "right" way
  389. *
  390. * @param int $timestamp
  391. * @param bool $dateOnly option to omit time from the result
  392. * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
  393. * @return string timestamp
  394. * @description adjust to clients timezone if we know it
  395. */
  396. public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
  397. if (is_null($timeZone)) {
  398. if (\OC::$server->getSession()->exists('timezone')) {
  399. $systemTimeZone = intval(date('O'));
  400. $systemTimeZone = (round($systemTimeZone / 100, 0) * 60) + ($systemTimeZone % 100);
  401. $clientTimeZone = \OC::$server->getSession()->get('timezone') * 60;
  402. $offset = $clientTimeZone - $systemTimeZone;
  403. $timestamp = $timestamp + $offset * 60;
  404. }
  405. } else {
  406. if (!$timeZone instanceof DateTimeZone) {
  407. $timeZone = new DateTimeZone($timeZone);
  408. }
  409. $dt = new DateTime("@$timestamp");
  410. $offset = $timeZone->getOffset($dt);
  411. $timestamp += $offset;
  412. }
  413. $l = \OC::$server->getL10N('lib');
  414. return $l->l($dateOnly ? 'date' : 'datetime', $timestamp);
  415. }
  416. /**
  417. * check if the current server configuration is suitable for ownCloud
  418. *
  419. * @param \OCP\IConfig $config
  420. * @return array arrays with error messages and hints
  421. */
  422. public static function checkServer(\OCP\IConfig $config) {
  423. $l = \OC::$server->getL10N('lib');
  424. $errors = array();
  425. $CONFIG_DATADIRECTORY = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
  426. if (!self::needUpgrade($config) && $config->getSystemValue('installed', false)) {
  427. // this check needs to be done every time
  428. $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
  429. }
  430. // Assume that if checkServer() succeeded before in this session, then all is fine.
  431. if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
  432. return $errors;
  433. }
  434. $webServerRestart = false;
  435. $setup = new OC_Setup($config);
  436. $availableDatabases = $setup->getSupportedDatabases();
  437. if (empty($availableDatabases)) {
  438. $errors[] = array(
  439. 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
  440. 'hint' => '' //TODO: sane hint
  441. );
  442. $webServerRestart = true;
  443. }
  444. //common hint for all file permissions error messages
  445. $permissionsHint = $l->t('Permissions can usually be fixed by '
  446. . '%sgiving the webserver write access to the root directory%s.',
  447. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'));
  448. // Check if config folder is writable.
  449. if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
  450. $errors[] = array(
  451. 'error' => $l->t('Cannot write into "config" directory'),
  452. 'hint' => $l->t('This can usually be fixed by '
  453. . '%sgiving the webserver write access to the config directory%s.',
  454. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'))
  455. );
  456. }
  457. // Check if there is a writable install folder.
  458. if ($config->getSystemValue('appstoreenabled', true)) {
  459. if (OC_App::getInstallPath() === null
  460. || !is_writable(OC_App::getInstallPath())
  461. || !is_readable(OC_App::getInstallPath())
  462. ) {
  463. $errors[] = array(
  464. 'error' => $l->t('Cannot write into "apps" directory'),
  465. 'hint' => $l->t('This can usually be fixed by '
  466. . '%sgiving the webserver write access to the apps directory%s'
  467. . ' or disabling the appstore in the config file.',
  468. array('<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">', '</a>'))
  469. );
  470. }
  471. }
  472. // Create root dir.
  473. if ($config->getSystemValue('installed', false)) {
  474. if (!is_dir($CONFIG_DATADIRECTORY)) {
  475. $success = @mkdir($CONFIG_DATADIRECTORY);
  476. if ($success) {
  477. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  478. } else {
  479. $errors[] = array(
  480. 'error' => $l->t('Cannot create "data" directory (%s)', array($CONFIG_DATADIRECTORY)),
  481. 'hint' => $l->t('This can usually be fixed by '
  482. . '<a href="%s" target="_blank">giving the webserver write access to the root directory</a>.',
  483. array(OC_Helper::linkToDocs('admin-dir_permissions')))
  484. );
  485. }
  486. } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  487. $errors[] = array(
  488. 'error' => 'Data directory (' . $CONFIG_DATADIRECTORY . ') not writable by ownCloud',
  489. 'hint' => $permissionsHint
  490. );
  491. } else {
  492. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  493. }
  494. }
  495. if (!OC_Util::isSetLocaleWorking()) {
  496. $errors[] = array(
  497. 'error' => $l->t('Setting locale to %s failed',
  498. array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
  499. . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
  500. 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
  501. );
  502. }
  503. // Contains the dependencies that should be checked against
  504. // classes = class_exists
  505. // functions = function_exists
  506. // defined = defined
  507. // If the dependency is not found the missing module name is shown to the EndUser
  508. $dependencies = array(
  509. 'classes' => array(
  510. 'ZipArchive' => 'zip',
  511. 'DOMDocument' => 'dom',
  512. ),
  513. 'functions' => array(
  514. 'xml_parser_create' => 'libxml',
  515. 'mb_detect_encoding' => 'mb multibyte',
  516. 'ctype_digit' => 'ctype',
  517. 'json_encode' => 'JSON',
  518. 'gd_info' => 'GD',
  519. 'gzencode' => 'zlib',
  520. 'iconv' => 'iconv',
  521. 'simplexml_load_string' => 'SimpleXML'
  522. ),
  523. 'defined' => array(
  524. 'PDO::ATTR_DRIVER_NAME' => 'PDO'
  525. )
  526. );
  527. $missingDependencies = array();
  528. $moduleHint = $l->t('Please ask your server administrator to install the module.');
  529. foreach ($dependencies['classes'] as $class => $module) {
  530. if (!class_exists($class)) {
  531. $missingDependencies[] = $module;
  532. }
  533. }
  534. foreach ($dependencies['functions'] as $function => $module) {
  535. if (!function_exists($function)) {
  536. $missingDependencies[] = $module;
  537. }
  538. }
  539. foreach ($dependencies['defined'] as $defined => $module) {
  540. if (!defined($defined)) {
  541. $missingDependencies[] = $module;
  542. }
  543. }
  544. foreach($missingDependencies as $missingDependency) {
  545. $errors[] = array(
  546. 'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
  547. 'hint' => $moduleHint
  548. );
  549. $webServerRestart = true;
  550. }
  551. if (version_compare(phpversion(), '5.3.3', '<')) {
  552. $errors[] = array(
  553. 'error' => $l->t('PHP %s or higher is required.', '5.3.3'),
  554. 'hint' => $l->t('Please ask your server administrator to update PHP to the latest version.'
  555. . ' Your PHP version is no longer supported by ownCloud and the PHP community.')
  556. );
  557. $webServerRestart = true;
  558. }
  559. if (((strtolower(@ini_get('safe_mode')) == 'on')
  560. || (strtolower(@ini_get('safe_mode')) == 'yes')
  561. || (strtolower(@ini_get('safe_mode')) == 'true')
  562. || (ini_get("safe_mode") == 1))
  563. ) {
  564. $errors[] = array(
  565. 'error' => $l->t('PHP Safe Mode is enabled. ownCloud requires that it is disabled to work properly.'),
  566. 'hint' => $l->t('PHP Safe Mode is a deprecated and mostly useless setting that should be disabled. '
  567. . 'Please ask your server administrator to disable it in php.ini or in your webserver config.')
  568. );
  569. $webServerRestart = true;
  570. }
  571. if (get_magic_quotes_gpc() == 1) {
  572. $errors[] = array(
  573. 'error' => $l->t('Magic Quotes is enabled. ownCloud requires that it is disabled to work properly.'),
  574. 'hint' => $l->t('Magic Quotes is a deprecated and mostly useless setting that should be disabled. '
  575. . 'Please ask your server administrator to disable it in php.ini or in your webserver config.')
  576. );
  577. $webServerRestart = true;
  578. }
  579. if (!self::isAnnotationsWorking()) {
  580. $errors[] = array(
  581. 'error' => 'PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible.',
  582. 'hint' => 'This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.'
  583. );
  584. }
  585. if ($webServerRestart) {
  586. $errors[] = array(
  587. 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
  588. 'hint' => $l->t('Please ask your server administrator to restart the web server.')
  589. );
  590. }
  591. $errors = array_merge($errors, self::checkDatabaseVersion());
  592. // Cache the result of this function
  593. \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
  594. return $errors;
  595. }
  596. /**
  597. * Check the database version
  598. *
  599. * @return array errors array
  600. */
  601. public static function checkDatabaseVersion() {
  602. $l = \OC::$server->getL10N('lib');
  603. $errors = array();
  604. $dbType = \OC_Config::getValue('dbtype', 'sqlite');
  605. if ($dbType === 'pgsql') {
  606. // check PostgreSQL version
  607. try {
  608. $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
  609. $data = $result->fetchRow();
  610. if (isset($data['server_version'])) {
  611. $version = $data['server_version'];
  612. if (version_compare($version, '9.0.0', '<')) {
  613. $errors[] = array(
  614. 'error' => $l->t('PostgreSQL >= 9 required'),
  615. 'hint' => $l->t('Please upgrade your database version')
  616. );
  617. }
  618. }
  619. } catch (\Doctrine\DBAL\DBALException $e) {
  620. \OCP\Util::logException('core', $e);
  621. $errors[] = array(
  622. 'error' => $l->t('Error occurred while checking PostgreSQL version'),
  623. 'hint' => $l->t('Please make sure you have PostgreSQL >= 9 or'
  624. . ' check the logs for more information about the error')
  625. );
  626. }
  627. }
  628. return $errors;
  629. }
  630. /**
  631. * check if there are still some encrypted files stored
  632. *
  633. * @return boolean
  634. */
  635. public static function encryptedFiles() {
  636. //check if encryption was enabled in the past
  637. $encryptedFiles = false;
  638. if (OC_App::isEnabled('files_encryption') === false) {
  639. $view = new OC\Files\View('/' . OCP\User::getUser());
  640. $keyfilePath = '/files_encryption/keyfiles';
  641. if ($view->is_dir($keyfilePath)) {
  642. $dircontent = $view->getDirectoryContent($keyfilePath);
  643. if (!empty($dircontent)) {
  644. $encryptedFiles = true;
  645. }
  646. }
  647. }
  648. return $encryptedFiles;
  649. }
  650. /**
  651. * check if a backup from the encryption keys exists
  652. *
  653. * @return boolean
  654. */
  655. public static function backupKeysExists() {
  656. //check if encryption was enabled in the past
  657. $backupExists = false;
  658. if (OC_App::isEnabled('files_encryption') === false) {
  659. $view = new OC\Files\View('/' . OCP\User::getUser());
  660. $backupPath = '/files_encryption/keyfiles.backup';
  661. if ($view->is_dir($backupPath)) {
  662. $dircontent = $view->getDirectoryContent($backupPath);
  663. if (!empty($dircontent)) {
  664. $backupExists = true;
  665. }
  666. }
  667. }
  668. return $backupExists;
  669. }
  670. /**
  671. * Check for correct file permissions of data directory
  672. *
  673. * @param string $dataDirectory
  674. * @return array arrays with error messages and hints
  675. */
  676. public static function checkDataDirectoryPermissions($dataDirectory) {
  677. $l = \OC::$server->getL10N('lib');
  678. $errors = array();
  679. if (self::runningOnWindows()) {
  680. //TODO: permissions checks for windows hosts
  681. } else {
  682. $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
  683. . ' cannot be listed by other users.');
  684. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  685. if (substr($perms, -1) != '0') {
  686. chmod($dataDirectory, 0770);
  687. clearstatcache();
  688. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  689. if (substr($perms, 2, 1) != '0') {
  690. $errors[] = array(
  691. 'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
  692. 'hint' => $permissionsModHint
  693. );
  694. }
  695. }
  696. }
  697. return $errors;
  698. }
  699. /**
  700. * Check that the data directory exists and is valid by
  701. * checking the existence of the ".ocdata" file.
  702. *
  703. * @param string $dataDirectory data directory path
  704. * @return bool true if the data directory is valid, false otherwise
  705. */
  706. public static function checkDataDirectoryValidity($dataDirectory) {
  707. $l = \OC::$server->getL10N('lib');
  708. $errors = array();
  709. if (!file_exists($dataDirectory . '/.ocdata')) {
  710. $errors[] = array(
  711. 'error' => $l->t('Data directory (%s) is invalid', array($dataDirectory)),
  712. 'hint' => $l->t('Please check that the data directory contains a file' .
  713. ' ".ocdata" in its root.')
  714. );
  715. }
  716. return $errors;
  717. }
  718. /**
  719. * @param array $errors
  720. */
  721. public static function displayLoginPage($errors = array()) {
  722. $parameters = array();
  723. foreach ($errors as $value) {
  724. $parameters[$value] = true;
  725. }
  726. if (!empty($_REQUEST['user'])) {
  727. $parameters["username"] = $_REQUEST['user'];
  728. $parameters['user_autofocus'] = false;
  729. } else {
  730. $parameters["username"] = '';
  731. $parameters['user_autofocus'] = true;
  732. }
  733. if (isset($_REQUEST['redirect_url'])) {
  734. $redirectUrl = $_REQUEST['redirect_url'];
  735. $parameters['redirect_url'] = urlencode($redirectUrl);
  736. }
  737. $parameters['alt_login'] = OC_App::getAlternativeLogIns();
  738. $parameters['rememberLoginAllowed'] = self::rememberLoginAllowed();
  739. OC_Template::printGuestPage("", "login", $parameters);
  740. }
  741. /**
  742. * Check if the app is enabled, redirects to home if not
  743. *
  744. * @param string $app
  745. * @return void
  746. */
  747. public static function checkAppEnabled($app) {
  748. if (!OC_App::isEnabled($app)) {
  749. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  750. exit();
  751. }
  752. }
  753. /**
  754. * Check if the user is logged in, redirects to home if not. With
  755. * redirect URL parameter to the request URI.
  756. *
  757. * @return void
  758. */
  759. public static function checkLoggedIn() {
  760. // Check if we are a user
  761. if (!OC_User::isLoggedIn()) {
  762. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php',
  763. array('redirect_url' => OC_Request::requestUri())
  764. ));
  765. exit();
  766. }
  767. }
  768. /**
  769. * Check if the user is a admin, redirects to home if not
  770. *
  771. * @return void
  772. */
  773. public static function checkAdminUser() {
  774. OC_Util::checkLoggedIn();
  775. if (!OC_User::isAdminUser(OC_User::getUser())) {
  776. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  777. exit();
  778. }
  779. }
  780. /**
  781. * Check if it is allowed to remember login.
  782. *
  783. * @note Every app can set 'rememberlogin' to 'false' to disable the remember login feature
  784. *
  785. * @return bool
  786. */
  787. public static function rememberLoginAllowed() {
  788. $apps = OC_App::getEnabledApps();
  789. foreach ($apps as $app) {
  790. $appInfo = OC_App::getAppInfo($app);
  791. if (isset($appInfo['rememberlogin']) && $appInfo['rememberlogin'] === 'false') {
  792. return false;
  793. }
  794. }
  795. return true;
  796. }
  797. /**
  798. * Check if the user is a subadmin, redirects to home if not
  799. *
  800. * @return null|boolean $groups where the current user is subadmin
  801. */
  802. public static function checkSubAdminUser() {
  803. OC_Util::checkLoggedIn();
  804. if (!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
  805. header('Location: ' . OC_Helper::linkToAbsolute('', 'index.php'));
  806. exit();
  807. }
  808. return true;
  809. }
  810. /**
  811. * Returns the URL of the default page
  812. * based on the system configuration and
  813. * the apps visible for the current user
  814. *
  815. * @return string URL
  816. */
  817. public static function getDefaultPageUrl() {
  818. $urlGenerator = \OC::$server->getURLGenerator();
  819. // Deny the redirect if the URL contains a @
  820. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  821. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  822. $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  823. } else {
  824. $defaultPage = OC_Appconfig::getValue('core', 'defaultpage');
  825. if ($defaultPage) {
  826. $location = $urlGenerator->getAbsoluteURL($defaultPage);
  827. } else {
  828. $appId = 'files';
  829. $defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
  830. // find the first app that is enabled for the current user
  831. foreach ($defaultApps as $defaultApp) {
  832. $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
  833. if (OC_App::isEnabled($defaultApp)) {
  834. $appId = $defaultApp;
  835. break;
  836. }
  837. }
  838. $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  839. }
  840. }
  841. return $location;
  842. }
  843. /**
  844. * Redirect to the user default page
  845. *
  846. * @return void
  847. */
  848. public static function redirectToDefaultPage() {
  849. $location = self::getDefaultPageUrl();
  850. header('Location: ' . $location);
  851. exit();
  852. }
  853. /**
  854. * get an id unique for this instance
  855. *
  856. * @return string
  857. */
  858. public static function getInstanceId() {
  859. $id = OC_Config::getValue('instanceid', null);
  860. if (is_null($id)) {
  861. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  862. $id = 'oc' . \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  863. OC_Config::$object->setValue('instanceid', $id);
  864. }
  865. return $id;
  866. }
  867. /**
  868. * Register an get/post call. Important to prevent CSRF attacks.
  869. *
  870. * @return string Generated token.
  871. * @description
  872. * Creates a 'request token' (random) and stores it inside the session.
  873. * Ever subsequent (ajax) request must use such a valid token to succeed,
  874. * otherwise the request will be denied as a protection against CSRF.
  875. * @see OC_Util::isCallRegistered()
  876. */
  877. public static function callRegister() {
  878. // Check if a token exists
  879. if (!\OC::$server->getSession()->exists('requesttoken')) {
  880. // No valid token found, generate a new one.
  881. $requestToken = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(30);
  882. \OC::$server->getSession()->set('requesttoken', $requestToken);
  883. } else {
  884. // Valid token already exists, send it
  885. $requestToken = \OC::$server->getSession()->get('requesttoken');
  886. }
  887. return ($requestToken);
  888. }
  889. /**
  890. * Check an ajax get/post call if the request token is valid.
  891. *
  892. * @return boolean False if request token is not set or is invalid.
  893. * @see OC_Util::callRegister()
  894. */
  895. public static function isCallRegistered() {
  896. return \OC::$server->getRequest()->passesCSRFCheck();
  897. }
  898. /**
  899. * Check an ajax get/post call if the request token is valid. Exit if not.
  900. *
  901. * @return void
  902. */
  903. public static function callCheck() {
  904. if (!OC_Util::isCallRegistered()) {
  905. exit();
  906. }
  907. }
  908. /**
  909. * Public function to sanitize HTML
  910. *
  911. * This function is used to sanitize HTML and should be applied on any
  912. * string or array of strings before displaying it on a web page.
  913. *
  914. * @param string|array &$value
  915. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  916. */
  917. public static function sanitizeHTML(&$value) {
  918. if (is_array($value)) {
  919. array_walk_recursive($value, 'OC_Util::sanitizeHTML');
  920. } else {
  921. //Specify encoding for PHP<5.4
  922. $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  923. }
  924. return $value;
  925. }
  926. /**
  927. * Public function to encode url parameters
  928. *
  929. * This function is used to encode path to file before output.
  930. * Encoding is done according to RFC 3986 with one exception:
  931. * Character '/' is preserved as is.
  932. *
  933. * @param string $component part of URI to encode
  934. * @return string
  935. */
  936. public static function encodePath($component) {
  937. $encoded = rawurlencode($component);
  938. $encoded = str_replace('%2F', '/', $encoded);
  939. return $encoded;
  940. }
  941. /**
  942. * Check if the .htaccess file is working
  943. *
  944. * @throws OC\HintException If the testfile can't get written.
  945. * @return bool
  946. * @description Check if the .htaccess file is working by creating a test
  947. * file in the data directory and trying to access via http
  948. */
  949. public static function isHtaccessWorking() {
  950. if (\OC::$CLI || !OC::$server->getConfig()->getSystemValue('check_for_working_htaccess', true)) {
  951. return true;
  952. }
  953. // testdata
  954. $fileName = '/htaccesstest.txt';
  955. $testContent = 'testcontent';
  956. // creating a test file
  957. $testFile = OC::$server->getConfig()->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
  958. if (file_exists($testFile)) {// already running this test, possible recursive call
  959. return false;
  960. }
  961. $fp = @fopen($testFile, 'w');
  962. if (!$fp) {
  963. throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
  964. 'Make sure it is possible for the webserver to write to ' . $testFile);
  965. }
  966. fwrite($fp, $testContent);
  967. fclose($fp);
  968. // accessing the file via http
  969. $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT . '/data' . $fileName);
  970. $content = self::getUrlContent($url);
  971. // cleanup
  972. @unlink($testFile);
  973. /*
  974. * If the content is not equal to test content our .htaccess
  975. * is working as required
  976. */
  977. return $content !== $testContent;
  978. }
  979. /**
  980. * Check if the setlocal call does not work. This can happen if the right
  981. * local packages are not available on the server.
  982. *
  983. * @return bool
  984. */
  985. public static function isSetLocaleWorking() {
  986. // setlocale test is pointless on Windows
  987. if (OC_Util::runningOnWindows()) {
  988. return true;
  989. }
  990. \Patchwork\Utf8\Bootup::initLocale();
  991. if ('' === basename('§')) {
  992. return false;
  993. }
  994. return true;
  995. }
  996. /**
  997. * Check if it's possible to get the inline annotations
  998. *
  999. * @return bool
  1000. */
  1001. public static function isAnnotationsWorking() {
  1002. $reflection = new \ReflectionMethod(__METHOD__);
  1003. $docs = $reflection->getDocComment();
  1004. return (is_string($docs) && strlen($docs) > 50);
  1005. }
  1006. /**
  1007. * Check if the PHP module fileinfo is loaded.
  1008. *
  1009. * @return bool
  1010. */
  1011. public static function fileInfoLoaded() {
  1012. return function_exists('finfo_open');
  1013. }
  1014. /**
  1015. * Check if a PHP version older then 5.3.8 is installed.
  1016. *
  1017. * @return bool
  1018. */
  1019. public static function isPHPoutdated() {
  1020. return version_compare(phpversion(), '5.3.8', '<');
  1021. }
  1022. /**
  1023. * Check if the ownCloud server can connect to the internet
  1024. *
  1025. * @return bool
  1026. */
  1027. public static function isInternetConnectionWorking() {
  1028. // in case there is no internet connection on purpose return false
  1029. if (self::isInternetConnectionEnabled() === false) {
  1030. return false;
  1031. }
  1032. // in case the connection is via proxy return true to avoid connecting to owncloud.org
  1033. if (OC_Config::getValue('proxy', '') != '') {
  1034. return true;
  1035. }
  1036. // try to connect to owncloud.org to see if http connections to the internet are possible.
  1037. $connected = @fsockopen("www.owncloud.org", 80);
  1038. if ($connected) {
  1039. fclose($connected);
  1040. return true;
  1041. } else {
  1042. // second try in case one server is down
  1043. $connected = @fsockopen("apps.owncloud.com", 80);
  1044. if ($connected) {
  1045. fclose($connected);
  1046. return true;
  1047. } else {
  1048. return false;
  1049. }
  1050. }
  1051. }
  1052. /**
  1053. * Check if the connection to the internet is disabled on purpose
  1054. *
  1055. * @return string
  1056. */
  1057. public static function isInternetConnectionEnabled() {
  1058. return \OC_Config::getValue("has_internet_connection", true);
  1059. }
  1060. /**
  1061. * clear all levels of output buffering
  1062. *
  1063. * @return void
  1064. */
  1065. public static function obEnd() {
  1066. while (ob_get_level()) {
  1067. ob_end_clean();
  1068. }
  1069. }
  1070. /**
  1071. * Generates a cryptographic secure pseudo-random string
  1072. *
  1073. * @param int $length of the random string
  1074. * @return string
  1075. * @deprecated Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
  1076. */
  1077. public static function generateRandomBytes($length = 30) {
  1078. return \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
  1079. }
  1080. /**
  1081. * Checks if a secure random number generator is available
  1082. *
  1083. * @return true
  1084. * @deprecated Function will be removed in the future and does only return true.
  1085. */
  1086. public static function secureRNGAvailable() {
  1087. return true;
  1088. }
  1089. /**
  1090. * Get URL content
  1091. * @param string $url Url to get content
  1092. * @deprecated Use \OC::$server->getHTTPHelper()->getUrlContent($url);
  1093. * @throws Exception If the URL does not start with http:// or https://
  1094. * @return string of the response or false on error
  1095. * This function get the content of a page via curl, if curl is enabled.
  1096. * If not, file_get_contents is used.
  1097. */
  1098. public static function getUrlContent($url) {
  1099. try {
  1100. return \OC::$server->getHTTPHelper()->getUrlContent($url);
  1101. } catch (\Exception $e) {
  1102. throw $e;
  1103. }
  1104. }
  1105. /**
  1106. * Checks whether the server is running on Windows
  1107. *
  1108. * @return bool true if running on Windows, false otherwise
  1109. */
  1110. public static function runningOnWindows() {
  1111. return (substr(PHP_OS, 0, 3) === "WIN");
  1112. }
  1113. /**
  1114. * Checks whether the server is running on Mac OS X
  1115. *
  1116. * @return bool true if running on Mac OS X, false otherwise
  1117. */
  1118. public static function runningOnMac() {
  1119. return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
  1120. }
  1121. /**
  1122. * Handles the case that there may not be a theme, then check if a "default"
  1123. * theme exists and take that one
  1124. *
  1125. * @return string the theme
  1126. */
  1127. public static function getTheme() {
  1128. $theme = OC_Config::getValue("theme", '');
  1129. if ($theme === '') {
  1130. if (is_dir(OC::$SERVERROOT . '/themes/default')) {
  1131. $theme = 'default';
  1132. }
  1133. }
  1134. return $theme;
  1135. }
  1136. /**
  1137. * Clear the opcode cache if one exists
  1138. * This is necessary for writing to the config file
  1139. * in case the opcode cache does not re-validate files
  1140. *
  1141. * @return void
  1142. */
  1143. public static function clearOpcodeCache() {
  1144. // APC
  1145. if (function_exists('apc_clear_cache')) {
  1146. apc_clear_cache();
  1147. }
  1148. // Zend Opcache
  1149. if (function_exists('accelerator_reset')) {
  1150. accelerator_reset();
  1151. }
  1152. // XCache
  1153. if (function_exists('xcache_clear_cache')) {
  1154. if (ini_get('xcache.admin.enable_auth')) {
  1155. OC_Log::write('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OC_Log::WARN);
  1156. } else {
  1157. xcache_clear_cache(XC_TYPE_PHP, 0);
  1158. }
  1159. }
  1160. // Opcache (PHP >= 5.5)
  1161. if (function_exists('opcache_reset')) {
  1162. opcache_reset();
  1163. }
  1164. }
  1165. /**
  1166. * Normalize a unicode string
  1167. *
  1168. * @param string $value a not normalized string
  1169. * @return bool|string
  1170. */
  1171. public static function normalizeUnicode($value) {
  1172. $normalizedValue = normalizer_normalize($value);
  1173. if ($normalizedValue === null || $normalizedValue === false) {
  1174. \OC_Log::write('core', 'normalizing failed for "' . $value . '"', \OC_Log::WARN);
  1175. } else {
  1176. $value = $normalizedValue;
  1177. }
  1178. return $value;
  1179. }
  1180. /**
  1181. * @param boolean|string $file
  1182. * @return string
  1183. */
  1184. public static function basename($file) {
  1185. $file = rtrim($file, '/');
  1186. $t = explode('/', $file);
  1187. return array_pop($t);
  1188. }
  1189. /**
  1190. * A human readable string is generated based on version, channel and build number
  1191. *
  1192. * @return string
  1193. */
  1194. public static function getHumanVersion() {
  1195. $version = OC_Util::getVersionString() . ' (' . OC_Util::getChannel() . ')';
  1196. $build = OC_Util::getBuild();
  1197. if (!empty($build) and OC_Util::getChannel() === 'daily') {
  1198. $version .= ' Build:' . $build;
  1199. }
  1200. return $version;
  1201. }
  1202. /**
  1203. * Returns whether the given file name is valid
  1204. *
  1205. * @param string $file file name to check
  1206. * @return bool true if the file name is valid, false otherwise
  1207. */
  1208. public static function isValidFileName($file) {
  1209. $trimmed = trim($file);
  1210. if ($trimmed === '') {
  1211. return false;
  1212. }
  1213. if ($trimmed === '.' || $trimmed === '..') {
  1214. return false;
  1215. }
  1216. foreach (str_split($trimmed) as $char) {
  1217. if (strpos(\OCP\FILENAME_INVALID_CHARS, $char) !== false) {
  1218. return false;
  1219. }
  1220. }
  1221. return true;
  1222. }
  1223. /**
  1224. * Check whether the instance needs to perform an upgrade,
  1225. * either when the core version is higher or any app requires
  1226. * an upgrade.
  1227. *
  1228. * @param \OCP\IConfig $config
  1229. * @return bool whether the core or any app needs an upgrade
  1230. */
  1231. public static function needUpgrade(\OCP\IConfig $config) {
  1232. if ($config->getSystemValue('installed', false)) {
  1233. $installedVersion = $config->getSystemValue('version', '0.0.0');
  1234. $currentVersion = implode('.', OC_Util::getVersion());
  1235. if (version_compare($currentVersion, $installedVersion, '>')) {
  1236. return true;
  1237. }
  1238. // also check for upgrades for apps (independently from the user)
  1239. $apps = \OC_App::getEnabledApps(false, true);
  1240. $shouldUpgrade = false;
  1241. foreach ($apps as $app) {
  1242. if (\OC_App::shouldUpgrade($app)) {
  1243. $shouldUpgrade = true;
  1244. break;
  1245. }
  1246. }
  1247. return $shouldUpgrade;
  1248. } else {
  1249. return false;
  1250. }
  1251. }
  1252. /**
  1253. * @return string
  1254. */
  1255. public static function isPhpCharSetUtf8() {
  1256. return ini_get('default_charset') === 'UTF-8';
  1257. }
  1258. }