util.php 29 KB

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