util.php 43 KB

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