util.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. public static $coreStyles=array();
  13. public static $coreScripts=array();
  14. /**
  15. * @brief Can be set up
  16. * @param string $user
  17. * @return boolean
  18. * @description configure the initial filesystem based on the configuration
  19. */
  20. public static function setupFS( $user = '' ) {
  21. //setting up the filesystem twice can only lead to trouble
  22. if(self::$fsSetup) {
  23. return false;
  24. }
  25. // If we are not forced to load a specific user we load the one that is logged in
  26. if( $user == "" && OC_User::isLoggedIn()) {
  27. $user = OC_User::getUser();
  28. }
  29. // load all filesystem apps before, so no setup-hook gets lost
  30. if(!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) {
  31. OC_App::loadApps(array('filesystem'));
  32. }
  33. // the filesystem will finish when $user is not empty,
  34. // mark fs setup here to avoid doing the setup from loading
  35. // OC_Filesystem
  36. if ($user != '') {
  37. self::$fsSetup=true;
  38. }
  39. $configDataDirectory = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  40. //first set up the local "root" storage
  41. \OC\Files\Filesystem::initMounts();
  42. if(!self::$rootMounted) {
  43. \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir'=>$configDataDirectory), '/');
  44. self::$rootMounted = true;
  45. }
  46. //if we aren't logged in, there is no use to set up the filesystem
  47. if( $user != "" ) {
  48. \OC\Files\Filesystem::addStorageWrapper(function($mountPoint, $storage){
  49. // set up quota for home storages, even for other users
  50. // which can happen when using sharing
  51. if ($storage instanceof \OC\Files\Storage\Home) {
  52. $user = $storage->getUser()->getUID();
  53. $quota = OC_Util::getUserQuota($user);
  54. if ($quota !== \OC\Files\SPACE_UNLIMITED) {
  55. return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota));
  56. }
  57. }
  58. return $storage;
  59. });
  60. $userDir = '/'.$user.'/files';
  61. $userRoot = OC_User::getHome($user);
  62. $userDirectory = $userRoot . '/files';
  63. if( !is_dir( $userDirectory )) {
  64. mkdir( $userDirectory, 0755, true );
  65. OC_Util::copySkeleton($userDirectory);
  66. }
  67. //jail the user into his "home" directory
  68. \OC\Files\Filesystem::init($user, $userDir);
  69. $fileOperationProxy = new OC_FileProxy_FileOperations();
  70. OC_FileProxy::register($fileOperationProxy);
  71. OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
  72. }
  73. return true;
  74. }
  75. public static function getUserQuota($user){
  76. $userQuota = OC_Preferences::getValue($user, 'files', 'quota', 'default');
  77. if($userQuota === 'default') {
  78. $userQuota = OC_AppConfig::getValue('files', 'default_quota', 'none');
  79. }
  80. if($userQuota === 'none') {
  81. return \OC\Files\SPACE_UNLIMITED;
  82. }else{
  83. return OC_Helper::computerFileSize($userQuota);
  84. }
  85. }
  86. /**
  87. * @brief copies the user skeleton files into the fresh user home files
  88. * @param string $userDirectory
  89. */
  90. public static function copySkeleton($userDirectory) {
  91. OC_Util::copyr(\OC::$SERVERROOT.'/core/skeleton' , $userDirectory);
  92. }
  93. /**
  94. * @brief copies a directory recursively
  95. * @param string $source
  96. * @param string $target
  97. * @return void
  98. */
  99. public static function copyr($source,$target) {
  100. $dir = opendir($source);
  101. @mkdir($target);
  102. while(false !== ( $file = readdir($dir)) ) {
  103. if ( !\OC\Files\Filesystem::isIgnoredDir($file) ) {
  104. if ( is_dir($source . '/' . $file) ) {
  105. OC_Util::copyr($source . '/' . $file , $target . '/' . $file);
  106. } else {
  107. copy($source . '/' . $file,$target . '/' . $file);
  108. }
  109. }
  110. }
  111. closedir($dir);
  112. }
  113. /**
  114. * @return void
  115. */
  116. public static function tearDownFS() {
  117. \OC\Files\Filesystem::tearDown();
  118. self::$fsSetup=false;
  119. self::$rootMounted=false;
  120. }
  121. /**
  122. * @brief get the current installed version of ownCloud
  123. * @return array
  124. */
  125. public static function getVersion() {
  126. OC_Util::loadVersion();
  127. return \OC::$server->getSession()->get('OC_Version');
  128. }
  129. /**
  130. * @brief get the current installed version string of ownCloud
  131. * @return string
  132. */
  133. public static function getVersionString() {
  134. OC_Util::loadVersion();
  135. return \OC::$server->getSession()->get('OC_VersionString');
  136. }
  137. /**
  138. * @description get the current installed edition of ownCloud. There is the community
  139. * edition that just returns an empty string and the enterprise edition
  140. * that returns "Enterprise".
  141. * @return string
  142. */
  143. public static function getEditionString() {
  144. OC_Util::loadVersion();
  145. return \OC::$server->getSession()->get('OC_Edition');
  146. }
  147. /**
  148. * @description get the update channel of the current installed of ownCloud.
  149. * @return string
  150. */
  151. public static function getChannel() {
  152. OC_Util::loadVersion();
  153. return \OC::$server->getSession()->get('OC_Channel');
  154. }
  155. /**
  156. * @description get the build number of the current installed of ownCloud.
  157. * @return string
  158. */
  159. public static function getBuild() {
  160. OC_Util::loadVersion();
  161. return \OC::$server->getSession()->get('OC_Build');
  162. }
  163. /**
  164. * @description load the version.php into the session as cache
  165. */
  166. private static function loadVersion() {
  167. $timestamp = filemtime(OC::$SERVERROOT.'/version.php');
  168. if(!\OC::$server->getSession()->exists('OC_Version') or OC::$server->getSession()->get('OC_Version_Timestamp') != $timestamp) {
  169. require 'version.php';
  170. $session = \OC::$server->getSession();
  171. /** @var $timestamp int */
  172. $session->set('OC_Version_Timestamp', $timestamp);
  173. /** @var $OC_Version string */
  174. $session->set('OC_Version', $OC_Version);
  175. /** @var $OC_VersionString string */
  176. $session->set('OC_VersionString', $OC_VersionString);
  177. /** @var $OC_Edition string */
  178. $session->set('OC_Edition', $OC_Edition);
  179. /** @var $OC_Channel string */
  180. $session->set('OC_Channel', $OC_Channel);
  181. /** @var $OC_Build string */
  182. $session->set('OC_Build', $OC_Build);
  183. }
  184. }
  185. /**
  186. * @brief add a javascript file
  187. *
  188. * @param string $application
  189. * @param filename $file
  190. * @return void
  191. */
  192. public static function addScript( $application, $file = null ) {
  193. if ( is_null( $file )) {
  194. $file = $application;
  195. $application = "";
  196. }
  197. if ( !empty( $application )) {
  198. self::$scripts[] = "$application/js/$file";
  199. } else {
  200. self::$scripts[] = "js/$file";
  201. }
  202. }
  203. /**
  204. * @brief add a css file
  205. *
  206. * @param string $application
  207. * @param filename $file
  208. * @return void
  209. */
  210. public static function addStyle( $application, $file = null ) {
  211. if ( is_null( $file )) {
  212. $file = $application;
  213. $application = "";
  214. }
  215. if ( !empty( $application )) {
  216. self::$styles[] = "$application/css/$file";
  217. } else {
  218. self::$styles[] = "css/$file";
  219. }
  220. }
  221. /**
  222. * @brief Add a custom element to the header
  223. * @param string $tag tag name of the element
  224. * @param array $attributes array of attributes for the element
  225. * @param string $text the text content for the element
  226. * @return void
  227. */
  228. public static function addHeader( $tag, $attributes, $text='') {
  229. self::$headers[] = array(
  230. 'tag'=>$tag,
  231. 'attributes'=>$attributes,
  232. 'text'=>$text
  233. );
  234. }
  235. /**
  236. * @brief formats a timestamp in the "right" way
  237. *
  238. * @param int $timestamp
  239. * @param bool $dateOnly option to omit time from the result
  240. * @return string timestamp
  241. * @description adjust to clients timezone if we know it
  242. */
  243. public static function formatDate( $timestamp, $dateOnly=false) {
  244. if(\OC::$session->exists('timezone')) {
  245. $systemTimeZone = intval(date('O'));
  246. $systemTimeZone = (round($systemTimeZone/100, 0)*60) + ($systemTimeZone%100);
  247. $clientTimeZone = \OC::$session->get('timezone')*60;
  248. $offset = $clientTimeZone - $systemTimeZone;
  249. $timestamp = $timestamp + $offset*60;
  250. }
  251. $l = OC_L10N::get('lib');
  252. return $l->l($dateOnly ? 'date' : 'datetime', $timestamp);
  253. }
  254. /**
  255. * @brief check if the current server configuration is suitable for ownCloud
  256. * @return array arrays with error messages and hints
  257. */
  258. public static function checkServer() {
  259. // Assume that if checkServer() succeeded before in this session, then all is fine.
  260. if(\OC::$session->exists('checkServer_suceeded') && \OC::$session->get('checkServer_suceeded')) {
  261. return array();
  262. }
  263. $errors = array();
  264. $defaults = new \OC_Defaults();
  265. $webServerRestart = false;
  266. //check for database drivers
  267. if(!(is_callable('sqlite_open') or class_exists('SQLite3'))
  268. and !is_callable('mysql_connect')
  269. and !is_callable('pg_connect')
  270. and !is_callable('oci_connect')) {
  271. $errors[] = array(
  272. 'error'=>'No database drivers (sqlite, mysql, or postgresql) installed.',
  273. 'hint'=>'' //TODO: sane hint
  274. );
  275. $webServerRestart = true;
  276. }
  277. //common hint for all file permissions error messages
  278. $permissionsHint = 'Permissions can usually be fixed by '
  279. .'<a href="' . OC_Helper::linkToDocs('admin-dir_permissions')
  280. .'" target="_blank">giving the webserver write access to the root directory</a>.';
  281. // Check if config folder is writable.
  282. if(!is_writable(OC::$SERVERROOT."/config/") or !is_readable(OC::$SERVERROOT."/config/")) {
  283. $errors[] = array(
  284. 'error' => "Can't write into config directory",
  285. 'hint' => 'This can usually be fixed by '
  286. .'<a href="' . OC_Helper::linkToDocs('admin-dir_permissions')
  287. .'" target="_blank">giving the webserver write access to the config directory</a>.'
  288. );
  289. }
  290. // Check if there is a writable install folder.
  291. if(OC_Config::getValue('appstoreenabled', true)) {
  292. if( OC_App::getInstallPath() === null
  293. || !is_writable(OC_App::getInstallPath())
  294. || !is_readable(OC_App::getInstallPath()) ) {
  295. $errors[] = array(
  296. 'error' => "Can't write into apps directory",
  297. 'hint' => 'This can usually be fixed by '
  298. .'<a href="' . OC_Helper::linkToDocs('admin-dir_permissions')
  299. .'" target="_blank">giving the webserver write access to the apps directory</a> '
  300. .'or disabling the appstore in the config file.'
  301. );
  302. }
  303. }
  304. $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  305. // Create root dir.
  306. if(!is_dir($CONFIG_DATADIRECTORY)) {
  307. $success=@mkdir($CONFIG_DATADIRECTORY);
  308. if ($success) {
  309. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  310. } else {
  311. $errors[] = array(
  312. 'error' => "Can't create data directory (".$CONFIG_DATADIRECTORY.")",
  313. 'hint' => 'This can usually be fixed by '
  314. .'<a href="' . OC_Helper::linkToDocs('admin-dir_permissions')
  315. .'" target="_blank">giving the webserver write access to the root directory</a>.'
  316. );
  317. }
  318. } else if(!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  319. $errors[] = array(
  320. 'error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud',
  321. 'hint'=>$permissionsHint
  322. );
  323. } else {
  324. $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
  325. }
  326. if(!OC_Util::isSetLocaleWorking()) {
  327. $errors[] = array(
  328. 'error' => 'Setting locale to en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8 failed',
  329. 'hint' => 'Please install one of theses locales on your system and restart your webserver.'
  330. );
  331. }
  332. $moduleHint = "Please ask your server administrator to install the module.";
  333. // check if all required php modules are present
  334. if(!class_exists('ZipArchive')) {
  335. $errors[] = array(
  336. 'error'=>'PHP module zip not installed.',
  337. 'hint'=>$moduleHint
  338. );
  339. $webServerRestart = true;
  340. }
  341. if(!class_exists('DOMDocument')) {
  342. $errors[] = array(
  343. 'error' => 'PHP module dom not installed.',
  344. 'hint' => $moduleHint
  345. );
  346. $webServerRestart =true;
  347. }
  348. if(!function_exists('xml_parser_create')) {
  349. $errors[] = array(
  350. 'error' => 'PHP module libxml not installed.',
  351. 'hint' => $moduleHint
  352. );
  353. $webServerRestart = true;
  354. }
  355. if(!function_exists('mb_detect_encoding')) {
  356. $errors[] = array(
  357. 'error'=>'PHP module mb multibyte not installed.',
  358. 'hint'=>$moduleHint
  359. );
  360. $webServerRestart = true;
  361. }
  362. if(!function_exists('ctype_digit')) {
  363. $errors[] = array(
  364. 'error'=>'PHP module ctype is not installed.',
  365. 'hint'=>$moduleHint
  366. );
  367. $webServerRestart = true;
  368. }
  369. if(!function_exists('json_encode')) {
  370. $errors[] = array(
  371. 'error'=>'PHP module JSON is not installed.',
  372. 'hint'=>$moduleHint
  373. );
  374. $webServerRestart = true;
  375. }
  376. if(!extension_loaded('gd') || !function_exists('gd_info')) {
  377. $errors[] = array(
  378. 'error'=>'PHP module GD is not installed.',
  379. 'hint'=>$moduleHint
  380. );
  381. $webServerRestart = true;
  382. }
  383. if(!function_exists('gzencode')) {
  384. $errors[] = array(
  385. 'error'=>'PHP module zlib is not installed.',
  386. 'hint'=>$moduleHint
  387. );
  388. $webServerRestart = true;
  389. }
  390. if(!function_exists('iconv')) {
  391. $errors[] = array(
  392. 'error'=>'PHP module iconv is not installed.',
  393. 'hint'=>$moduleHint
  394. );
  395. $webServerRestart = true;
  396. }
  397. if(!function_exists('simplexml_load_string')) {
  398. $errors[] = array(
  399. 'error'=>'PHP module SimpleXML is not installed.',
  400. 'hint'=>$moduleHint
  401. );
  402. $webServerRestart = true;
  403. }
  404. if(floatval(phpversion()) < 5.3) {
  405. $errors[] = array(
  406. 'error'=>'PHP 5.3 is required.',
  407. 'hint'=>'Please ask your server administrator to update PHP to version 5.3 or higher.'
  408. .' PHP 5.2 is no longer supported by ownCloud and the PHP community.'
  409. );
  410. $webServerRestart = true;
  411. }
  412. if(!defined('PDO::ATTR_DRIVER_NAME')) {
  413. $errors[] = array(
  414. 'error'=>'PHP PDO module is not installed.',
  415. 'hint'=>$moduleHint
  416. );
  417. $webServerRestart = true;
  418. }
  419. if (((strtolower(@ini_get('safe_mode')) == 'on')
  420. || (strtolower(@ini_get('safe_mode')) == 'yes')
  421. || (strtolower(@ini_get('safe_mode')) == 'true')
  422. || (ini_get("safe_mode") == 1 ))) {
  423. $errors[] = array(
  424. 'error'=>'PHP Safe Mode is enabled. ownCloud requires that it is disabled to work properly.',
  425. 'hint'=>'PHP Safe Mode is a deprecated and mostly useless setting that should be disabled. '
  426. .'Please ask your server administrator to disable it in php.ini or in your webserver config.'
  427. );
  428. $webServerRestart = true;
  429. }
  430. if (get_magic_quotes_gpc() == 1 ) {
  431. $errors[] = array(
  432. 'error'=>'Magic Quotes is enabled. ownCloud requires that it is disabled to work properly.',
  433. 'hint'=>'Magic Quotes is a deprecated and mostly useless setting that should be disabled. '
  434. .'Please ask your server administrator to disable it in php.ini or in your webserver config.'
  435. );
  436. $webServerRestart = true;
  437. }
  438. if($webServerRestart) {
  439. $errors[] = array(
  440. 'error'=>'PHP modules have been installed, but they are still listed as missing?',
  441. 'hint'=>'Please ask your server administrator to restart the web server.'
  442. );
  443. }
  444. // Cache the result of this function
  445. \OC::$session->set('checkServer_suceeded', count($errors) == 0);
  446. return $errors;
  447. }
  448. /**
  449. * @brief check if there are still some encrypted files stored
  450. * @return boolean
  451. */
  452. public static function encryptedFiles() {
  453. //check if encryption was enabled in the past
  454. $encryptedFiles = false;
  455. if (OC_App::isEnabled('files_encryption') === false) {
  456. $view = new OC\Files\View('/' . OCP\User::getUser());
  457. $keyfilePath = '/files_encryption/keyfiles';
  458. if ($view->is_dir($keyfilePath)) {
  459. $dircontent = $view->getDirectoryContent($keyfilePath);
  460. if (!empty($dircontent)) {
  461. $encryptedFiles = true;
  462. }
  463. }
  464. }
  465. return $encryptedFiles;
  466. }
  467. /**
  468. * @brief Check for correct file permissions of data directory
  469. * @paran string $dataDirectory
  470. * @return array arrays with error messages and hints
  471. */
  472. public static function checkDataDirectoryPermissions($dataDirectory) {
  473. $errors = array();
  474. if (self::runningOnWindows()) {
  475. //TODO: permissions checks for windows hosts
  476. } else {
  477. $permissionsModHint = 'Please change the permissions to 0770 so that the directory'
  478. .' cannot be listed by other users.';
  479. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  480. if (substr($perms, -1) != '0') {
  481. OC_Helper::chmodr($dataDirectory, 0770);
  482. clearstatcache();
  483. $perms = substr(decoct(@fileperms($dataDirectory)), -3);
  484. if (substr($perms, 2, 1) != '0') {
  485. $errors[] = array(
  486. 'error' => 'Data directory ('.$dataDirectory.') is readable for other users',
  487. 'hint' => $permissionsModHint
  488. );
  489. }
  490. }
  491. }
  492. return $errors;
  493. }
  494. /**
  495. * @return void
  496. */
  497. public static function displayLoginPage($errors = array()) {
  498. $parameters = array();
  499. foreach( $errors as $key => $value ) {
  500. $parameters[$value] = true;
  501. }
  502. if (!empty($_POST['user'])) {
  503. $parameters["username"] = $_POST['user'];
  504. $parameters['user_autofocus'] = false;
  505. } else {
  506. $parameters["username"] = '';
  507. $parameters['user_autofocus'] = true;
  508. }
  509. if (isset($_REQUEST['redirect_url'])) {
  510. $redirectUrl = $_REQUEST['redirect_url'];
  511. $parameters['redirect_url'] = urlencode($redirectUrl);
  512. }
  513. $parameters['alt_login'] = OC_App::getAlternativeLogIns();
  514. $parameters['rememberLoginAllowed'] = self::rememberLoginAllowed();
  515. OC_Template::printGuestPage("", "login", $parameters);
  516. }
  517. /**
  518. * @brief Check if the app is enabled, redirects to home if not
  519. * @return void
  520. */
  521. public static function checkAppEnabled($app) {
  522. if( !OC_App::isEnabled($app)) {
  523. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  524. exit();
  525. }
  526. }
  527. /**
  528. * Check if the user is logged in, redirects to home if not. With
  529. * redirect URL parameter to the request URI.
  530. * @return void
  531. */
  532. public static function checkLoggedIn() {
  533. // Check if we are a user
  534. if( !OC_User::isLoggedIn()) {
  535. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php',
  536. array('redirectUrl' => OC_Request::requestUri())
  537. ));
  538. exit();
  539. }
  540. }
  541. /**
  542. * @brief Check if the user is a admin, redirects to home if not
  543. * @return void
  544. */
  545. public static function checkAdminUser() {
  546. OC_Util::checkLoggedIn();
  547. if( !OC_User::isAdminUser(OC_User::getUser())) {
  548. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  549. exit();
  550. }
  551. }
  552. /**
  553. * Check if it is allowed to remember login.
  554. *
  555. * @note Every app can set 'rememberlogin' to 'false' to disable the remember login feature
  556. *
  557. * @return bool
  558. */
  559. public static function rememberLoginAllowed() {
  560. $apps = OC_App::getEnabledApps();
  561. foreach ($apps as $app) {
  562. $appInfo = OC_App::getAppInfo($app);
  563. if (isset($appInfo['rememberlogin']) && $appInfo['rememberlogin'] === 'false') {
  564. return false;
  565. }
  566. }
  567. return true;
  568. }
  569. /**
  570. * @brief Check if the user is a subadmin, redirects to home if not
  571. * @return array $groups where the current user is subadmin
  572. */
  573. public static function checkSubAdminUser() {
  574. OC_Util::checkLoggedIn();
  575. if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
  576. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  577. exit();
  578. }
  579. return true;
  580. }
  581. /**
  582. * @brief Redirect to the user default page
  583. * @return void
  584. */
  585. public static function redirectToDefaultPage() {
  586. if(isset($_REQUEST['redirect_url'])) {
  587. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  588. }
  589. else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) {
  590. $location = OC_Helper::linkToAbsolute( OC::$REQUESTEDAPP, 'index.php' );
  591. } else {
  592. $defaultPage = OC_Appconfig::getValue('core', 'defaultpage');
  593. if ($defaultPage) {
  594. $location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultPage);
  595. } else {
  596. $location = OC_Helper::linkToAbsolute( 'files', 'index.php' );
  597. }
  598. }
  599. OC_Log::write('core', 'redirectToDefaultPage: '.$location, OC_Log::DEBUG);
  600. header( 'Location: '.$location );
  601. exit();
  602. }
  603. /**
  604. * @brief get an id unique for this instance
  605. * @return string
  606. */
  607. public static function getInstanceId() {
  608. $id = OC_Config::getValue('instanceid', null);
  609. if(is_null($id)) {
  610. // We need to guarantee at least one letter in instanceid so it can be used as the session_name
  611. $id = 'oc' . self::generateRandomBytes(10);
  612. OC_Config::$object->setValue('instanceid', $id);
  613. }
  614. return $id;
  615. }
  616. /**
  617. * @brief Static lifespan (in seconds) when a request token expires.
  618. * @see OC_Util::callRegister()
  619. * @see OC_Util::isCallRegistered()
  620. * @description
  621. * Also required for the client side to compute the point in time when to
  622. * request a fresh token. The client will do so when nearly 97% of the
  623. * time span coded here has expired.
  624. */
  625. public static $callLifespan = 3600; // 3600 secs = 1 hour
  626. /**
  627. * @brief Register an get/post call. Important to prevent CSRF attacks.
  628. * @todo Write howto: CSRF protection guide
  629. * @return $token Generated token.
  630. * @description
  631. * Creates a 'request token' (random) and stores it inside the session.
  632. * Ever subsequent (ajax) request must use such a valid token to succeed,
  633. * otherwise the request will be denied as a protection against CSRF.
  634. * The tokens expire after a fixed lifespan.
  635. * @see OC_Util::$callLifespan
  636. * @see OC_Util::isCallRegistered()
  637. */
  638. public static function callRegister() {
  639. // Check if a token exists
  640. if(!\OC::$session->exists('requesttoken')) {
  641. // No valid token found, generate a new one.
  642. $requestToken = self::generateRandomBytes(20);
  643. \OC::$session->set('requesttoken', $requestToken);
  644. } else {
  645. // Valid token already exists, send it
  646. $requestToken = \OC::$session->get('requesttoken');
  647. }
  648. return($requestToken);
  649. }
  650. /**
  651. * @brief Check an ajax get/post call if the request token is valid.
  652. * @return boolean False if request token is not set or is invalid.
  653. * @see OC_Util::$callLifespan
  654. * @see OC_Util::callRegister()
  655. */
  656. public static function isCallRegistered() {
  657. return \OC::$server->getRequest()->passesCSRFCheck();
  658. }
  659. /**
  660. * @brief Check an ajax get/post call if the request token is valid. exit if not.
  661. * @todo Write howto
  662. * @return void
  663. */
  664. public static function callCheck() {
  665. if(!OC_Util::isCallRegistered()) {
  666. exit();
  667. }
  668. }
  669. /**
  670. * @brief Public function to sanitize HTML
  671. *
  672. * This function is used to sanitize HTML and should be applied on any
  673. * string or array of strings before displaying it on a web page.
  674. *
  675. * @param string|array of strings
  676. * @return array with sanitized strings or a single sanitized string, depends on the input parameter.
  677. */
  678. public static function sanitizeHTML( &$value ) {
  679. if (is_array($value)) {
  680. array_walk_recursive($value, 'OC_Util::sanitizeHTML');
  681. } else {
  682. //Specify encoding for PHP<5.4
  683. $value = htmlentities((string)$value, ENT_QUOTES, 'UTF-8');
  684. }
  685. return $value;
  686. }
  687. /**
  688. * @brief Public function to encode url parameters
  689. *
  690. * This function is used to encode path to file before output.
  691. * Encoding is done according to RFC 3986 with one exception:
  692. * Character '/' is preserved as is.
  693. *
  694. * @param string $component part of URI to encode
  695. * @return string
  696. */
  697. public static function encodePath($component) {
  698. $encoded = rawurlencode($component);
  699. $encoded = str_replace('%2F', '/', $encoded);
  700. return $encoded;
  701. }
  702. /**
  703. * @brief Check if the htaccess file is working
  704. * @return bool
  705. * @description Check if the htaccess file is working by creating a test
  706. * file in the data directory and trying to access via http
  707. */
  708. public static function isHtAccessWorking() {
  709. if (!\OC_Config::getValue("check_for_working_htaccess", true)) {
  710. return true;
  711. }
  712. // testdata
  713. $fileName = '/htaccesstest.txt';
  714. $testContent = 'testcontent';
  715. // creating a test file
  716. $testFile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$fileName;
  717. if(file_exists($testFile)) {// already running this test, possible recursive call
  718. return false;
  719. }
  720. $fp = @fopen($testFile, 'w');
  721. @fwrite($fp, $testContent);
  722. @fclose($fp);
  723. // accessing the file via http
  724. $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$fileName);
  725. $fp = @fopen($url, 'r');
  726. $content=@fread($fp, 2048);
  727. @fclose($fp);
  728. // cleanup
  729. @unlink($testFile);
  730. // does it work ?
  731. if($content==$testContent) {
  732. return false;
  733. } else {
  734. return true;
  735. }
  736. }
  737. /**
  738. * @brief test if webDAV is working properly
  739. * @return bool
  740. * @description
  741. * The basic assumption is that if the server returns 401/Not Authenticated for an unauthenticated PROPFIND
  742. * the web server it self is setup properly.
  743. *
  744. * Why not an authenticated PROPFIND and other verbs?
  745. * - We don't have the password available
  746. * - We have no idea about other auth methods implemented (e.g. OAuth with Bearer header)
  747. *
  748. */
  749. public static function isWebDAVWorking() {
  750. if (!function_exists('curl_init')) {
  751. return true;
  752. }
  753. if (!\OC_Config::getValue("check_for_working_webdav", true)) {
  754. return true;
  755. }
  756. $settings = array(
  757. 'baseUri' => OC_Helper::linkToRemote('webdav'),
  758. );
  759. $client = new \OC_DAVClient($settings);
  760. $client->setRequestTimeout(10);
  761. // for this self test we don't care if the ssl certificate is self signed and the peer cannot be verified.
  762. $client->setVerifyPeer(false);
  763. $return = true;
  764. try {
  765. // test PROPFIND
  766. $client->propfind('', array('{DAV:}resourcetype'));
  767. } catch (\Sabre_DAV_Exception_NotAuthenticated $e) {
  768. $return = true;
  769. } catch (\Exception $e) {
  770. OC_Log::write('core', 'isWebDAVWorking: NO - Reason: '.$e->getMessage(). ' ('.get_class($e).')', OC_Log::WARN);
  771. $return = false;
  772. }
  773. return $return;
  774. }
  775. /**
  776. * Check if the setlocal call does not work. This can happen if the right
  777. * local packages are not available on the server.
  778. * @return bool
  779. */
  780. public static function isSetLocaleWorking() {
  781. // setlocale test is pointless on Windows
  782. if (OC_Util::runningOnWindows() ) {
  783. return true;
  784. }
  785. \Patchwork\Utf8\Bootup::initLocale();
  786. if ('' === basename('§')) {
  787. return false;
  788. }
  789. return true;
  790. }
  791. /**
  792. * @brief Check if the PHP module fileinfo is loaded.
  793. * @return bool
  794. */
  795. public static function fileInfoLoaded() {
  796. return function_exists('finfo_open');
  797. }
  798. /**
  799. * @brief Check if the ownCloud server can connect to the internet
  800. * @return bool
  801. */
  802. public static function isInternetConnectionWorking() {
  803. // in case there is no internet connection on purpose return false
  804. if (self::isInternetConnectionEnabled() === false) {
  805. return false;
  806. }
  807. // try to connect to owncloud.org to see if http connections to the internet are possible.
  808. $connected = @fsockopen("www.owncloud.org", 80);
  809. if ($connected) {
  810. fclose($connected);
  811. return true;
  812. } else {
  813. // second try in case one server is down
  814. $connected = @fsockopen("apps.owncloud.com", 80);
  815. if ($connected) {
  816. fclose($connected);
  817. return true;
  818. } else {
  819. return false;
  820. }
  821. }
  822. }
  823. /**
  824. * @brief Check if the connection to the internet is disabled on purpose
  825. * @return bool
  826. */
  827. public static function isInternetConnectionEnabled(){
  828. return \OC_Config::getValue("has_internet_connection", true);
  829. }
  830. /**
  831. * @brief clear all levels of output buffering
  832. * @return void
  833. */
  834. public static function obEnd(){
  835. while (ob_get_level()) {
  836. ob_end_clean();
  837. }
  838. }
  839. /**
  840. * @brief Generates a cryptographic secure pseudo-random string
  841. * @param Int $length of the random string
  842. * @return String
  843. * Please also update secureRNGAvailable if you change something here
  844. */
  845. public static function generateRandomBytes($length = 30) {
  846. // Try to use openssl_random_pseudo_bytes
  847. if (function_exists('openssl_random_pseudo_bytes')) {
  848. $pseudoByte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
  849. if($strong == true) {
  850. return substr($pseudoByte, 0, $length); // Truncate it to match the length
  851. }
  852. }
  853. // Try to use /dev/urandom
  854. if (!self::runningOnWindows()) {
  855. $fp = @file_get_contents('/dev/urandom', false, null, 0, $length);
  856. if ($fp !== false) {
  857. $string = substr(bin2hex($fp), 0, $length);
  858. return $string;
  859. }
  860. }
  861. // Fallback to mt_rand()
  862. $characters = '0123456789';
  863. $characters .= 'abcdefghijklmnopqrstuvwxyz';
  864. $charactersLength = strlen($characters)-1;
  865. $pseudoByte = "";
  866. // Select some random characters
  867. for ($i = 0; $i < $length; $i++) {
  868. $pseudoByte .= $characters[mt_rand(0, $charactersLength)];
  869. }
  870. return $pseudoByte;
  871. }
  872. /**
  873. * @brief Checks if a secure random number generator is available
  874. * @return bool
  875. */
  876. public static function secureRNGAvailable() {
  877. // Check openssl_random_pseudo_bytes
  878. if(function_exists('openssl_random_pseudo_bytes')) {
  879. openssl_random_pseudo_bytes(1, $strong);
  880. if($strong == true) {
  881. return true;
  882. }
  883. }
  884. // Check /dev/urandom
  885. if (!self::runningOnWindows()) {
  886. $fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
  887. if ($fp !== false) {
  888. return true;
  889. }
  890. }
  891. return false;
  892. }
  893. /**
  894. * @Brief Get file content via curl.
  895. * @param string $url Url to get content
  896. * @return string of the response or false on error
  897. * This function get the content of a page via curl, if curl is enabled.
  898. * If not, file_get_contents is used.
  899. */
  900. public static function getUrlContent($url) {
  901. if (function_exists('curl_init')) {
  902. $curl = curl_init();
  903. curl_setopt($curl, CURLOPT_HEADER, 0);
  904. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  905. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  906. curl_setopt($curl, CURLOPT_URL, $url);
  907. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  908. curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
  909. curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
  910. if(OC_Config::getValue('proxy', '') != '') {
  911. curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
  912. }
  913. if(OC_Config::getValue('proxyuserpwd', '') != '') {
  914. curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
  915. }
  916. $data = curl_exec($curl);
  917. curl_close($curl);
  918. } else {
  919. $contextArray = null;
  920. if(OC_Config::getValue('proxy', '') != '') {
  921. $contextArray = array(
  922. 'http' => array(
  923. 'timeout' => 10,
  924. 'proxy' => OC_Config::getValue('proxy')
  925. )
  926. );
  927. } else {
  928. $contextArray = array(
  929. 'http' => array(
  930. 'timeout' => 10
  931. )
  932. );
  933. }
  934. $ctx = stream_context_create(
  935. $contextArray
  936. );
  937. $data = @file_get_contents($url, 0, $ctx);
  938. }
  939. return $data;
  940. }
  941. /**
  942. * @return bool - well are we running on windows or not
  943. */
  944. public static function runningOnWindows() {
  945. return (substr(PHP_OS, 0, 3) === "WIN");
  946. }
  947. /**
  948. * Handles the case that there may not be a theme, then check if a "default"
  949. * theme exists and take that one
  950. * @return string the theme
  951. */
  952. public static function getTheme() {
  953. $theme = OC_Config::getValue("theme", '');
  954. if($theme === '') {
  955. if(is_dir(OC::$SERVERROOT . '/themes/default')) {
  956. $theme = 'default';
  957. }
  958. }
  959. return $theme;
  960. }
  961. /**
  962. * @brief Clear the opcode cache if one exists
  963. * This is necessary for writing to the config file
  964. * in case the opcode cache does not re-validate files
  965. * @return void
  966. */
  967. public static function clearOpcodeCache() {
  968. // APC
  969. if (function_exists('apc_clear_cache')) {
  970. apc_clear_cache();
  971. }
  972. // Zend Opcache
  973. if (function_exists('accelerator_reset')) {
  974. accelerator_reset();
  975. }
  976. // XCache
  977. if (function_exists('xcache_clear_cache')) {
  978. xcache_clear_cache(XC_TYPE_VAR, 0);
  979. }
  980. // Opcache (PHP >= 5.5)
  981. if (function_exists('opcache_reset')) {
  982. opcache_reset();
  983. }
  984. }
  985. /**
  986. * Normalize a unicode string
  987. * @param string $value a not normalized string
  988. * @return bool|string
  989. */
  990. public static function normalizeUnicode($value) {
  991. if(class_exists('Patchwork\PHP\Shim\Normalizer')) {
  992. $normalizedValue = \Patchwork\PHP\Shim\Normalizer::normalize($value);
  993. if($normalizedValue === false) {
  994. \OC_Log::write( 'core', 'normalizing failed for "' . $value . '"', \OC_Log::WARN);
  995. } else {
  996. $value = $normalizedValue;
  997. }
  998. }
  999. return $value;
  1000. }
  1001. /**
  1002. * @return string
  1003. */
  1004. public static function basename($file) {
  1005. $file = rtrim($file, '/');
  1006. $t = explode('/', $file);
  1007. return array_pop($t);
  1008. }
  1009. }