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

util.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. if( !OC_User::isAdminUser(OC_User::getUser())) {
  314. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  315. exit();
  316. }
  317. }
  318. /**
  319. * Check if the user is a subadmin, redirects to home if not
  320. * @return array $groups where the current user is subadmin
  321. */
  322. public static function checkSubAdminUser() {
  323. if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
  324. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  325. exit();
  326. }
  327. return true;
  328. }
  329. /**
  330. * Redirect to the user default page
  331. */
  332. public static function redirectToDefaultPage() {
  333. if(isset($_REQUEST['redirect_url'])) {
  334. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  335. }
  336. else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) {
  337. $location = OC_Helper::linkToAbsolute( OC::$REQUESTEDAPP, 'index.php' );
  338. }
  339. else {
  340. $defaultpage = OC_Appconfig::getValue('core', 'defaultpage');
  341. if ($defaultpage) {
  342. $location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultpage);
  343. }
  344. else {
  345. $location = OC_Helper::linkToAbsolute( 'files', 'index.php' );
  346. }
  347. }
  348. OC_Log::write('core', 'redirectToDefaultPage: '.$location, OC_Log::DEBUG);
  349. header( 'Location: '.$location );
  350. exit();
  351. }
  352. /**
  353. * get an id unqiue for this instance
  354. * @return string
  355. */
  356. public static function getInstanceId() {
  357. $id=OC_Config::getValue('instanceid', null);
  358. if(is_null($id)) {
  359. $id=uniqid();
  360. OC_Config::setValue('instanceid', $id);
  361. }
  362. return $id;
  363. }
  364. /**
  365. * @brief Register an get/post call. Important to prevent CSRF attacks.
  366. * @todo Write howto: CSRF protection guide
  367. * @return $token Generated token.
  368. * @description
  369. * Creates a 'request token' (random) and stores it inside the session.
  370. * Ever subsequent (ajax) request must use such a valid token to succeed,
  371. * otherwise the request will be denied as a protection against CSRF.
  372. * @see OC_Util::isCallRegistered()
  373. */
  374. public static function callRegister() {
  375. // Check if a token exists
  376. if(!isset($_SESSION['requesttoken'])) {
  377. // No valid token found, generate a new one.
  378. $requestToken = self::generate_random_bytes(20);
  379. $_SESSION['requesttoken']=$requestToken;
  380. } else {
  381. // Valid token already exists, send it
  382. $requestToken = $_SESSION['requesttoken'];
  383. }
  384. return($requestToken);
  385. }
  386. /**
  387. * @brief Check an ajax get/post call if the request token is valid.
  388. * @return boolean False if request token is not set or is invalid.
  389. * @see OC_Util::callRegister()
  390. */
  391. public static function isCallRegistered() {
  392. if(isset($_GET['requesttoken'])) {
  393. $token=$_GET['requesttoken'];
  394. }elseif(isset($_POST['requesttoken'])) {
  395. $token=$_POST['requesttoken'];
  396. }elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])) {
  397. $token=$_SERVER['HTTP_REQUESTTOKEN'];
  398. }else{
  399. //no token found.
  400. return false;
  401. }
  402. // Check if the token is valid
  403. if($token !== $_SESSION['requesttoken']) {
  404. // Not valid
  405. return false;
  406. } else {
  407. // Valid token
  408. return true;
  409. }
  410. }
  411. /**
  412. * @brief Check an ajax get/post call if the request token is valid. exit if not.
  413. * Todo: Write howto
  414. */
  415. public static function callCheck() {
  416. if(!OC_Util::isCallRegistered()) {
  417. exit;
  418. }
  419. }
  420. /**
  421. * @brief Public function to sanitize HTML
  422. *
  423. * This function is used to sanitize HTML and should be applied on any
  424. * string or array of strings before displaying it on a web page.
  425. *
  426. * @param string or array of strings
  427. * @return array with sanitized strings or a single sanitized string, depends on the input parameter.
  428. */
  429. public static function sanitizeHTML( &$value ) {
  430. if (is_array($value) || is_object($value)) {
  431. array_walk_recursive($value, 'OC_Util::sanitizeHTML');
  432. } else {
  433. $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
  434. }
  435. return $value;
  436. }
  437. /**
  438. * Check if the htaccess file is working by creating a test file in the data directory and trying to access via http
  439. */
  440. public static function ishtaccessworking() {
  441. // testdata
  442. $filename='/htaccesstest.txt';
  443. $testcontent='testcontent';
  444. // creating a test file
  445. $testfile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$filename;
  446. if(file_exists($testfile)) {// already running this test, possible recursive call
  447. return false;
  448. }
  449. $fp = @fopen($testfile, 'w');
  450. @fwrite($fp, $testcontent);
  451. @fclose($fp);
  452. // accessing the file via http
  453. $url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$filename);
  454. $fp = @fopen($url, 'r');
  455. $content=@fread($fp, 2048);
  456. @fclose($fp);
  457. // cleanup
  458. @unlink($testfile);
  459. // does it work ?
  460. if($content==$testcontent) {
  461. return(false);
  462. }else{
  463. return(true);
  464. }
  465. }
  466. /**
  467. * Check if the setlocal call doesn't work. This can happen if the right local packages are not available on the server.
  468. */
  469. public static function issetlocaleworking() {
  470. $result=setlocale(LC_ALL, 'en_US.UTF-8');
  471. if($result==false) {
  472. return(false);
  473. }else{
  474. return(true);
  475. }
  476. }
  477. /**
  478. * Check if the ownCloud server can connect to the internet
  479. */
  480. public static function isinternetconnectionworking() {
  481. // try to connect to owncloud.org to see if http connections to the internet are possible.
  482. $connected = @fsockopen("www.owncloud.org", 80);
  483. if ($connected) {
  484. fclose($connected);
  485. return true;
  486. }else{
  487. // second try in case one server is down
  488. $connected = @fsockopen("apps.owncloud.com", 80);
  489. if ($connected) {
  490. fclose($connected);
  491. return true;
  492. }else{
  493. return false;
  494. }
  495. }
  496. }
  497. /**
  498. * clear all levels of output buffering
  499. */
  500. public static function obEnd(){
  501. while (ob_get_level()) {
  502. ob_end_clean();
  503. }
  504. }
  505. /**
  506. * @brief Generates a cryptographical secure pseudorandom string
  507. * @param Int with the length of the random string
  508. * @return String
  509. * Please also update secureRNG_available if you change something here
  510. */
  511. public static function generate_random_bytes($length = 30) {
  512. // Try to use openssl_random_pseudo_bytes
  513. if(function_exists('openssl_random_pseudo_bytes')) {
  514. $pseudo_byte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
  515. if($strong == true) {
  516. return substr($pseudo_byte, 0, $length); // Truncate it to match the length
  517. }
  518. }
  519. // Try to use /dev/urandom
  520. $fp = @file_get_contents('/dev/urandom', false, null, 0, $length);
  521. if ($fp !== false) {
  522. $string = substr(bin2hex($fp), 0, $length);
  523. return $string;
  524. }
  525. // Fallback to mt_rand()
  526. $characters = '0123456789';
  527. $characters .= 'abcdefghijklmnopqrstuvwxyz';
  528. $charactersLength = strlen($characters)-1;
  529. $pseudo_byte = "";
  530. // Select some random characters
  531. for ($i = 0; $i < $length; $i++) {
  532. $pseudo_byte .= $characters[mt_rand(0, $charactersLength)];
  533. }
  534. return $pseudo_byte;
  535. }
  536. /**
  537. * @brief Checks if a secure random number generator is available
  538. * @return bool
  539. */
  540. public static function secureRNG_available() {
  541. // Check openssl_random_pseudo_bytes
  542. if(function_exists('openssl_random_pseudo_bytes')) {
  543. openssl_random_pseudo_bytes(1, $strong);
  544. if($strong == true) {
  545. return true;
  546. }
  547. }
  548. // Check /dev/urandom
  549. $fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
  550. if ($fp !== false) {
  551. return true;
  552. }
  553. return false;
  554. }
  555. /**
  556. * @Brief Get file content via curl.
  557. * @param string $url Url to get content
  558. * @return string of the response or false on error
  559. * This function get the content of a page via curl, if curl is enabled.
  560. * If not, file_get_element is used.
  561. */
  562. public static function getUrlContent($url){
  563. if (function_exists('curl_init')) {
  564. $curl = curl_init();
  565. curl_setopt($curl, CURLOPT_HEADER, 0);
  566. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  567. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  568. curl_setopt($curl, CURLOPT_URL, $url);
  569. curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
  570. if(OC_Config::getValue('proxy','')<>'') {
  571. curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
  572. }
  573. if(OC_Config::getValue('proxyuserpwd','')<>'') {
  574. curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
  575. }
  576. $data = curl_exec($curl);
  577. curl_close($curl);
  578. } else {
  579. $contextArray = null;
  580. if(OC_Config::getValue('proxy','')<>'') {
  581. $contextArray = array(
  582. 'http' => array(
  583. 'timeout' => 10,
  584. 'proxy' => OC_Config::getValue('proxy')
  585. )
  586. );
  587. } else {
  588. $contextArray = array(
  589. 'http' => array(
  590. 'timeout' => 10
  591. )
  592. );
  593. }
  594. $ctx = stream_context_create(
  595. $contextArray
  596. );
  597. $data=@file_get_contents($url, 0, $ctx);
  598. }
  599. return $data;
  600. }
  601. }