PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/util.php

https://github.com/jlgg/simple_trash
PHP | 705 lines | 567 code | 47 blank | 91 comment | 48 complexity | 854703b1e02434f5776ba8c9f0e4d457 MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  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 $core_styles=array();
  13. public static $core_scripts=array();
  14. // Can be set up
  15. public static function setupFS( $user = '' ) {// configure the initial filesystem based on the configuration
  16. if(self::$fsSetup) {//setting up the filesystem twice can only lead to trouble
  17. return false;
  18. }
  19. // If we are not forced to load a specific user we load the one that is logged in
  20. if( $user == "" && OC_User::isLoggedIn()) {
  21. $user = OC_User::getUser();
  22. }
  23. // load all filesystem apps before, so no setup-hook gets lost
  24. if(!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) {
  25. OC_App::loadApps(array('filesystem'));
  26. }
  27. // the filesystem will finish when $user is not empty,
  28. // mark fs setup here to avoid doing the setup from loading
  29. // OC_Filesystem
  30. if ($user != '') {
  31. self::$fsSetup=true;
  32. }
  33. $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  34. //first set up the local "root" storage
  35. if(!self::$rootMounted) {
  36. OC_Filesystem::mount('OC_Filestorage_Local', array('datadir'=>$CONFIG_DATADIRECTORY), '/');
  37. self::$rootMounted=true;
  38. }
  39. if( $user != "" ) { //if we aren't logged in, there is no use to set up the filesystem
  40. $user_dir = '/'.$user.'/files';
  41. $user_root = OC_User::getHome($user);
  42. $userdirectory = $user_root . '/files';
  43. if( !is_dir( $userdirectory )) {
  44. mkdir( $userdirectory, 0755, true );
  45. }
  46. //jail the user into his "home" directory
  47. OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user);
  48. OC_Filesystem::init($user_dir, $user);
  49. $quotaProxy=new OC_FileProxy_Quota();
  50. $fileOperationProxy = new OC_FileProxy_FileOperations();
  51. OC_FileProxy::register($quotaProxy);
  52. OC_FileProxy::register($fileOperationProxy);
  53. // Load personal mount config
  54. self::loadUserMountPoints($user);
  55. OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir));
  56. }
  57. }
  58. public static function tearDownFS() {
  59. OC_Filesystem::tearDown();
  60. self::$fsSetup=false;
  61. }
  62. public static function loadUserMountPoints($user) {
  63. $user_dir = '/'.$user.'/files';
  64. $user_root = OC_User::getHome($user);
  65. $userdirectory = $user_root . '/files';
  66. if (is_file($user_root.'/mount.php')) {
  67. $mountConfig = include $user_root.'/mount.php';
  68. if (isset($mountConfig['user'][$user])) {
  69. foreach ($mountConfig['user'][$user] as $mountPoint => $options) {
  70. OC_Filesystem::mount($options['class'], $options['options'], $mountPoint);
  71. }
  72. }
  73. $mtime=filemtime($user_root.'/mount.php');
  74. $previousMTime=OC_Preferences::getValue($user, 'files', 'mountconfigmtime', 0);
  75. if($mtime>$previousMTime) {//mount config has changed, filecache needs to be updated
  76. OC_FileCache::triggerUpdate($user);
  77. OC_Preferences::setValue($user, 'files', 'mountconfigmtime', $mtime);
  78. }
  79. }
  80. }
  81. /**
  82. * get the current installed version of ownCloud
  83. * @return array
  84. */
  85. public static function getVersion() {
  86. // hint: We only can count up. So the internal version number of ownCloud 4.5 will be 4.90.0. This is not visible to the user
  87. return array(4, 91, 02);
  88. }
  89. /**
  90. * get the current installed version string of ownCloud
  91. * @return string
  92. */
  93. public static function getVersionString() {
  94. return '5.0 pre alpha';
  95. }
  96. /**
  97. * get the current installed edition of ownCloud. There is the community edition that just returns an empty string and the enterprise edition that returns "Enterprise".
  98. * @return string
  99. */
  100. public static function getEditionString() {
  101. return '';
  102. }
  103. /**
  104. * add a javascript file
  105. *
  106. * @param appid $application
  107. * @param filename $file
  108. */
  109. public static function addScript( $application, $file = null ) {
  110. if( is_null( $file )) {
  111. $file = $application;
  112. $application = "";
  113. }
  114. if( !empty( $application )) {
  115. self::$scripts[] = "$application/js/$file";
  116. }else{
  117. self::$scripts[] = "js/$file";
  118. }
  119. }
  120. /**
  121. * add a css file
  122. *
  123. * @param appid $application
  124. * @param filename $file
  125. */
  126. public static function addStyle( $application, $file = null ) {
  127. if( is_null( $file )) {
  128. $file = $application;
  129. $application = "";
  130. }
  131. if( !empty( $application )) {
  132. self::$styles[] = "$application/css/$file";
  133. }else{
  134. self::$styles[] = "css/$file";
  135. }
  136. }
  137. /**
  138. * @brief Add a custom element to the header
  139. * @param string tag tag name of the element
  140. * @param array $attributes array of attributes for the element
  141. * @param string $text the text content for the element
  142. */
  143. public static function addHeader( $tag, $attributes, $text='') {
  144. self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes, 'text'=>$text);
  145. }
  146. /**
  147. * formats a timestamp in the "right" way
  148. *
  149. * @param int timestamp $timestamp
  150. * @param bool dateOnly option to ommit time from the result
  151. */
  152. public static function formatDate( $timestamp, $dateOnly=false) {
  153. if(isset($_SESSION['timezone'])) {//adjust to clients timezone if we know it
  154. $systemTimeZone = intval(date('O'));
  155. $systemTimeZone=(round($systemTimeZone/100, 0)*60)+($systemTimeZone%100);
  156. $clientTimeZone=$_SESSION['timezone']*60;
  157. $offset=$clientTimeZone-$systemTimeZone;
  158. $timestamp=$timestamp+$offset*60;
  159. }
  160. $l=OC_L10N::get('lib');
  161. return $l->l($dateOnly ? 'date' : 'datetime', $timestamp);
  162. }
  163. /**
  164. * check if the current server configuration is suitable for ownCloud
  165. * @return array arrays with error messages and hints
  166. */
  167. public static function checkServer() {
  168. $errors=array();
  169. $web_server_restart= false;
  170. //check for database drivers
  171. if(!(is_callable('sqlite_open') or class_exists('SQLite3')) and !is_callable('mysql_connect') and !is_callable('pg_connect')) {
  172. $errors[]=array('error'=>'No database drivers (sqlite, mysql, or postgresql) installed.<br/>', 'hint'=>'');//TODO: sane hint
  173. $web_server_restart= true;
  174. }
  175. //common hint for all file permissons error messages
  176. $permissionsHint="Permissions can usually be fixed by giving the webserver write access to the ownCloud directory";
  177. // Check if config folder is writable.
  178. if(!is_writable(OC::$SERVERROOT."/config/") or !is_readable(OC::$SERVERROOT."/config/")) {
  179. $errors[]=array('error'=>"Can't write into config directory 'config'", 'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud");
  180. }
  181. // Check if there is a writable install folder.
  182. if(OC_Config::getValue('appstoreenabled', true)) {
  183. if( OC_App::getInstallPath() === null || !is_writable(OC_App::getInstallPath()) || !is_readable(OC_App::getInstallPath()) ) {
  184. $errors[]=array('error'=>"Can't write into apps directory", 'hint'=>"You can usually fix this by giving the webserver user write access to the apps directory
  185. in owncloud or disabling the appstore in the config file.");
  186. }
  187. }
  188. $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  189. //check for correct file permissions
  190. if(!stristr(PHP_OS, 'WIN')) {
  191. $permissionsModHint="Please change the permissions to 0770 so that the directory cannot be listed by other users.";
  192. $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)), -3);
  193. if(substr($prems, -1)!='0') {
  194. OC_Helper::chmodr($CONFIG_DATADIRECTORY, 0770);
  195. clearstatcache();
  196. $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)), -3);
  197. if(substr($prems, 2, 1)!='0') {
  198. $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') is readable for other users<br/>', 'hint'=>$permissionsModHint);
  199. }
  200. }
  201. if( OC_Config::getValue( "enablebackup", false )) {
  202. $CONFIG_BACKUPDIRECTORY = OC_Config::getValue( "backupdirectory", OC::$SERVERROOT."/backup" );
  203. $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)), -3);
  204. if(substr($prems, -1)!='0') {
  205. OC_Helper::chmodr($CONFIG_BACKUPDIRECTORY, 0770);
  206. clearstatcache();
  207. $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)), -3);
  208. if(substr($prems, 2, 1)!='0') {
  209. $errors[]=array('error'=>'Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable for other users<br/>', 'hint'=>$permissionsModHint);
  210. }
  211. }
  212. }
  213. }else{
  214. //TODO: permissions checks for windows hosts
  215. }
  216. // Create root dir.
  217. if(!is_dir($CONFIG_DATADIRECTORY)) {
  218. $success=@mkdir($CONFIG_DATADIRECTORY);
  219. if(!$success) {
  220. $errors[]=array('error'=>"Can't create data directory (".$CONFIG_DATADIRECTORY.")", 'hint'=>"You can usually fix this by giving the webserver write access to the ownCloud directory '".OC::$SERVERROOT."' (in a terminal, use the command 'chown -R www-data:www-data /path/to/your/owncloud/install/data' ");
  221. }
  222. } else if(!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
  223. $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud<br/>', 'hint'=>$permissionsHint);
  224. }
  225. // check if all required php modules are present
  226. if(!class_exists('ZipArchive')) {
  227. $errors[]=array('error'=>'PHP module zip not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  228. $web_server_restart= false;
  229. }
  230. if(!function_exists('mb_detect_encoding')) {
  231. $errors[]=array('error'=>'PHP module mb multibyte not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  232. $web_server_restart= false;
  233. }
  234. if(!function_exists('ctype_digit')) {
  235. $errors[]=array('error'=>'PHP module ctype is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  236. $web_server_restart= false;
  237. }
  238. if(!function_exists('json_encode')) {
  239. $errors[]=array('error'=>'PHP module JSON is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  240. $web_server_restart= false;
  241. }
  242. if(!function_exists('imagepng')) {
  243. $errors[]=array('error'=>'PHP module GD is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  244. $web_server_restart= false;
  245. }
  246. if(!function_exists('gzencode')) {
  247. $errors[]=array('error'=>'PHP module zlib is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  248. $web_server_restart= false;
  249. }
  250. if(!function_exists('iconv')) {
  251. $errors[]=array('error'=>'PHP module iconv is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  252. $web_server_restart= false;
  253. }
  254. if(!function_exists('simplexml_load_string')) {
  255. $errors[]=array('error'=>'PHP module SimpleXML is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  256. $web_server_restart= false;
  257. }
  258. if(floatval(phpversion())<5.3) {
  259. $errors[]=array('error'=>'PHP 5.3 is required.<br/>', 'hint'=>'Please ask your server administrator to update PHP to version 5.3 or higher. PHP 5.2 is no longer supported by ownCloud and the PHP community.');
  260. $web_server_restart= false;
  261. }
  262. if(!defined('PDO::ATTR_DRIVER_NAME')) {
  263. $errors[]=array('error'=>'PHP PDO module is not installed.<br/>', 'hint'=>'Please ask your server administrator to install the module.');
  264. $web_server_restart= false;
  265. }
  266. if($web_server_restart) {
  267. $errors[]=array('error'=>'PHP modules have been installed, but they are still listed as missing?<br/>', 'hint'=>'Please ask your server administrator to restart the web server.');
  268. }
  269. return $errors;
  270. }
  271. public static function displayLoginPage($errors = array()) {
  272. $parameters = array();
  273. foreach( $errors as $key => $value ) {
  274. $parameters[$value] = true;
  275. }
  276. if (!empty($_POST['user'])) {
  277. $parameters["username"] = OC_Util::sanitizeHTML($_POST['user']).'"';
  278. $parameters['user_autofocus'] = false;
  279. } else {
  280. $parameters["username"] = '';
  281. $parameters['user_autofocus'] = true;
  282. }
  283. if (isset($_REQUEST['redirect_url'])) {
  284. $redirect_url = OC_Util::sanitizeHTML($_REQUEST['redirect_url']);
  285. $parameters['redirect_url'] = urlencode($redirect_url);
  286. }
  287. OC_Template::printGuestPage("", "login", $parameters);
  288. }
  289. /**
  290. * Check if the app is enabled, redirects to home if not
  291. */
  292. public static function checkAppEnabled($app) {
  293. if( !OC_App::isEnabled($app)) {
  294. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  295. exit();
  296. }
  297. }
  298. /**
  299. * Check if the user is logged in, redirects to home if not. With
  300. * redirect URL parameter to the request URI.
  301. */
  302. public static function checkLoggedIn() {
  303. // Check if we are a user
  304. if( !OC_User::isLoggedIn()) {
  305. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php', array('redirect_url' => $_SERVER["REQUEST_URI"])));
  306. exit();
  307. }
  308. }
  309. /**
  310. * Check if the user is a admin, redirects to home if not
  311. */
  312. public static function checkAdminUser() {
  313. // Check if we are a user
  314. self::checkLoggedIn();
  315. self::verifyUser();
  316. if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
  317. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  318. exit();
  319. }
  320. }
  321. /**
  322. * Check if the user is a subadmin, redirects to home if not
  323. * @return array $groups where the current user is subadmin
  324. */
  325. public static function checkSubAdminUser() {
  326. // Check if we are a user
  327. self::checkLoggedIn();
  328. self::verifyUser();
  329. if(OC_Group::inGroup(OC_User::getUser(), 'admin')) {
  330. return true;
  331. }
  332. if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
  333. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  334. exit();
  335. }
  336. return true;
  337. }
  338. /**
  339. * Check if the user verified the login with his password in the last 15 minutes
  340. * If not, the user will be shown a password verification page
  341. */
  342. public static function verifyUser() {
  343. if(OC_Config::getValue('enhancedauth', false) === true) {
  344. // Check password to set session
  345. if(isset($_POST['password'])) {
  346. if (OC_User::login(OC_User::getUser(), $_POST["password"] ) === true) {
  347. $_SESSION['verifiedLogin']=time() + OC_Config::getValue('enhancedauthtime', 15 * 60);
  348. }
  349. }
  350. // Check if the user verified his password
  351. if(!isset($_SESSION['verifiedLogin']) OR $_SESSION['verifiedLogin'] < time()) {
  352. OC_Template::printGuestPage("", "verify", array('username' => OC_User::getUser()));
  353. exit();
  354. }
  355. }
  356. }
  357. /**
  358. * Check if the user verified the login with his password
  359. * @return bool
  360. */
  361. public static function isUserVerified() {
  362. if(OC_Config::getValue('enhancedauth', false) === true) {
  363. if(!isset($_SESSION['verifiedLogin']) OR $_SESSION['verifiedLogin'] < time()) {
  364. return false;
  365. }
  366. }
  367. return true;
  368. }
  369. /**
  370. * Redirect to the user default page
  371. */
  372. public static function redirectToDefaultPage() {
  373. if(isset($_REQUEST['redirect_url'])) {
  374. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  375. }
  376. else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) {
  377. $location = OC_Helper::linkToAbsolute( OC::$REQUESTEDAPP, 'index.php' );
  378. }
  379. else {
  380. $defaultpage = OC_Appconfig::getValue('core', 'defaultpage');
  381. if ($defaultpage) {
  382. $location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultpage);
  383. }
  384. else {
  385. $location = OC_Helper::linkToAbsolute( 'files', 'index.php' );
  386. }
  387. }
  388. OC_Log::write('core', 'redirectToDefaultPage: '.$location, OC_Log::DEBUG);
  389. header( 'Location: '.$location );
  390. exit();
  391. }
  392. /**
  393. * get an id unqiue for this instance
  394. * @return string
  395. */
  396. public static function getInstanceId() {
  397. $id=OC_Config::getValue('instanceid', null);
  398. if(is_null($id)) {
  399. $id=uniqid();
  400. OC_Config::setValue('instanceid', $id);
  401. }
  402. return $id;
  403. }
  404. /**
  405. * @brief Register an get/post call. Important to prevent CSRF attacks.
  406. * @todo Write howto: CSRF protection guide
  407. * @return $token Generated token.
  408. * @description
  409. * Creates a 'request token' (random) and stores it inside the session.
  410. * Ever subsequent (ajax) request must use such a valid token to succeed,
  411. * otherwise the request will be denied as a protection against CSRF.
  412. * @see OC_Util::isCallRegistered()
  413. */
  414. public static function callRegister() {
  415. // Check if a token exists
  416. if(!isset($_SESSION['requesttoken'])) {
  417. // No valid token found, generate a new one.
  418. $requestToken = self::generate_random_bytes(20);
  419. $_SESSION['requesttoken']=$requestToken;
  420. } else {
  421. // Valid token already exists, send it
  422. $requestToken = $_SESSION['requesttoken'];
  423. }
  424. return($requestToken);
  425. }
  426. /**
  427. * @brief Check an ajax get/post call if the request token is valid.
  428. * @return boolean False if request token is not set or is invalid.
  429. * @see OC_Util::callRegister()
  430. */
  431. public static function isCallRegistered() {
  432. if(isset($_GET['requesttoken'])) {
  433. $token=$_GET['requesttoken'];
  434. }elseif(isset($_POST['requesttoken'])) {
  435. $token=$_POST['requesttoken'];
  436. }elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])) {
  437. $token=$_SERVER['HTTP_REQUESTTOKEN'];
  438. }else{
  439. //no token found.
  440. return false;
  441. }
  442. // Check if the token is valid
  443. if($token !== $_SESSION['requesttoken']) {
  444. // Not valid
  445. return false;
  446. } else {
  447. // Valid token
  448. return true;
  449. }
  450. }
  451. /**
  452. * @brief Check an ajax get/post call if the request token is valid. exit if not.
  453. * Todo: Write howto
  454. */
  455. public static function callCheck() {
  456. if(!OC_Util::isCallRegistered()) {
  457. exit;
  458. }
  459. }
  460. /**
  461. * @brief Public function to sanitize HTML
  462. *
  463. * This function is used to sanitize HTML and should be applied on any
  464. * string or array of strings before displaying it on a web page.
  465. *
  466. * @param string or array of strings
  467. * @return array with sanitized strings or a single sanitized string, depends on the input parameter.
  468. */
  469. public static function sanitizeHTML( &$value ) {
  470. if (is_array($value) || is_object($value)) array_walk_recursive($value, 'OC_Util::sanitizeHTML');
  471. else $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
  472. return $value;
  473. }
  474. /**
  475. * Check if the htaccess file is working by creating a test file in the data directory and trying to access via http
  476. */
  477. public static function ishtaccessworking() {
  478. // testdata
  479. $filename='/htaccesstest.txt';
  480. $testcontent='testcontent';
  481. // creating a test file
  482. $testfile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$filename;
  483. if(file_exists($testfile)) {// already running this test, possible recursive call
  484. return false;
  485. }
  486. $fp = @fopen($testfile, 'w');
  487. @fwrite($fp, $testcontent);
  488. @fclose($fp);
  489. // accessing the file via http
  490. $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$filename);
  491. $fp = @fopen($url, 'r');
  492. $content=@fread($fp, 2048);
  493. @fclose($fp);
  494. // cleanup
  495. @unlink($testfile);
  496. // does it work ?
  497. if($content==$testcontent) {
  498. return(false);
  499. }else{
  500. return(true);
  501. }
  502. }
  503. /**
  504. * Check if the setlocal call doesn't work. This can happen if the right local packages are not available on the server.
  505. */
  506. public static function issetlocaleworking() {
  507. $result=setlocale(LC_ALL, 'en_US.UTF-8');
  508. if($result==false) {
  509. return(false);
  510. }else{
  511. return(true);
  512. }
  513. }
  514. /**
  515. * Check if the ownCloud server can connect to the internet
  516. */
  517. public static function isinternetconnectionworking() {
  518. // try to connect to owncloud.org to see if http connections to the internet are possible.
  519. $connected = @fsockopen("www.owncloud.org", 80);
  520. if ($connected) {
  521. fclose($connected);
  522. return true;
  523. }else{
  524. // second try in case one server is down
  525. $connected = @fsockopen("apps.owncloud.com", 80);
  526. if ($connected) {
  527. fclose($connected);
  528. return true;
  529. }else{
  530. return false;
  531. }
  532. }
  533. }
  534. /**
  535. * clear all levels of output buffering
  536. */
  537. public static function obEnd(){
  538. while (ob_get_level()) {
  539. ob_end_clean();
  540. }
  541. }
  542. /**
  543. * @brief Generates a cryptographical secure pseudorandom string
  544. * @param Int with the length of the random string
  545. * @return String
  546. * Please also update secureRNG_available if you change something here
  547. */
  548. public static function generate_random_bytes($length = 30) {
  549. // Try to use openssl_random_pseudo_bytes
  550. if(function_exists('openssl_random_pseudo_bytes')) {
  551. $pseudo_byte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
  552. if($strong == true) {
  553. return substr($pseudo_byte, 0, $length); // Truncate it to match the length
  554. }
  555. }
  556. // Try to use /dev/urandom
  557. $fp = @file_get_contents('/dev/urandom', false, null, 0, $length);
  558. if ($fp !== false) {
  559. $string = substr(bin2hex($fp), 0, $length);
  560. return $string;
  561. }
  562. // Fallback to mt_rand()
  563. $characters = '0123456789';
  564. $characters .= 'abcdefghijklmnopqrstuvwxyz';
  565. $charactersLength = strlen($characters)-1;
  566. $pseudo_byte = "";
  567. // Select some random characters
  568. for ($i = 0; $i < $length; $i++) {
  569. $pseudo_byte .= $characters[mt_rand(0, $charactersLength)];
  570. }
  571. return $pseudo_byte;
  572. }
  573. /**
  574. * @brief Checks if a secure random number generator is available
  575. * @return bool
  576. */
  577. public static function secureRNG_available() {
  578. // Check openssl_random_pseudo_bytes
  579. if(function_exists('openssl_random_pseudo_bytes')) {
  580. openssl_random_pseudo_bytes(1, $strong);
  581. if($strong == true) {
  582. return true;
  583. }
  584. }
  585. // Check /dev/urandom
  586. $fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
  587. if ($fp !== false) {
  588. return true;
  589. }
  590. return false;
  591. }
  592. /**
  593. * @Brief Get file content via curl.
  594. * @param string $url Url to get content
  595. * @return string of the response or false on error
  596. * This function get the content of a page via curl, if curl is enabled.
  597. * If not, file_get_element is used.
  598. */
  599. public static function getUrlContent($url){
  600. if (function_exists('curl_init')) {
  601. $curl = curl_init();
  602. curl_setopt($curl, CURLOPT_HEADER, 0);
  603. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  604. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  605. curl_setopt($curl, CURLOPT_URL, $url);
  606. curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
  607. if(OC_Config::getValue('proxy','')<>'') {
  608. curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
  609. }
  610. if(OC_Config::getValue('proxyuserpwd','')<>'') {
  611. curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
  612. }
  613. $data = curl_exec($curl);
  614. curl_close($curl);
  615. } else {
  616. $ctx = stream_context_create(
  617. array(
  618. 'http' => array(
  619. 'timeout' => 10
  620. )
  621. )
  622. );
  623. $data=@file_get_contents($url, 0, $ctx);
  624. }
  625. return $data;
  626. }
  627. }