Merge pull request #4449 from owncloud/clean_up_util

Clean up \OC\Util
This commit is contained in:
Morris Jobke 2013-09-03 22:53:03 -07:00
commit 09187f3b3b
17 changed files with 318 additions and 242 deletions

View File

@ -42,7 +42,7 @@ class OC_Core_LostPassword_Controller {
}
if (OC_User::userExists($_POST['user']) && $continue) {
$token = hash('sha256', OC_Util::generate_random_bytes(30).OC_Config::getValue('passwordsalt', ''));
$token = hash('sha256', OC_Util::generateRandomBytes(30).OC_Config::getValue('passwordsalt', ''));
OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword',
hash('sha256', $token)); // Hash the token again to prevent timing attacks
$email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', '');

View File

@ -5,11 +5,11 @@ OC_App::loadApps();
if ($service == 'core.css') {
$minimizer = new OC_Minimizer_CSS();
$files = OC_TemplateLayout::findStylesheetFiles(OC_Util::$core_styles);
$files = OC_TemplateLayout::findStylesheetFiles(OC_Util::$coreStyles);
$minimizer->output($files, $service);
}
else if ($service == 'core.js') {
$minimizer = new OC_Minimizer_JS();
$files = OC_TemplateLayout::findJavascriptFiles(OC_Util::$core_scripts);
$files = OC_TemplateLayout::findJavascriptFiles(OC_Util::$coreScripts);
$minimizer->output($files, $service);
}

View File

@ -33,8 +33,8 @@ $opts = array(
'hasOracle' => $hasOracle,
'hasMSSQL' => $hasMSSQL,
'directory' => $datadir,
'secureRNG' => OC_Util::secureRNG_available(),
'htaccessWorking' => OC_Util::ishtaccessworking(),
'secureRNG' => OC_Util::secureRNGAvailable(),
'htaccessWorking' => OC_Util::isHtAccessWorking(),
'vulnerableToNullByte' => $vulnerableToNullByte,
'errors' => array(),
);

View File

@ -73,11 +73,11 @@ class OC_App{
if (!defined('DEBUG') || !DEBUG) {
if (is_null($types)
&& empty(OC_Util::$core_scripts)
&& empty(OC_Util::$core_styles)) {
OC_Util::$core_scripts = OC_Util::$scripts;
&& empty(OC_Util::$coreScripts)
&& empty(OC_Util::$coreStyles)) {
OC_Util::$coreScripts = OC_Util::$scripts;
OC_Util::$scripts = array();
OC_Util::$core_styles = OC_Util::$styles;
OC_Util::$coreStyles = OC_Util::$styles;
OC_Util::$styles = array();
}
}

View File

@ -417,7 +417,7 @@ class OC {
}
self::initPaths();
OC_Util::issetlocaleworking();
OC_Util::isSetLocaleWorking();
// set debug mode if an xdebug session is active
if (!defined('DEBUG') || !DEBUG) {
@ -529,7 +529,7 @@ class OC {
}
// write error into log if locale can't be set
if (OC_Util::issetlocaleworking() == false) {
if (OC_Util::isSetLocaleWorking() == false) {
OC_Log::write('core',
'setting locale to en_US.UTF-8/en_US.UTF8 failed. Support is probably not installed on your system',
OC_Log::ERROR);
@ -768,7 +768,7 @@ class OC {
if (in_array($_COOKIE['oc_token'], $tokens, true)) {
// replace successfully used token with a new one
OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
$token = OC_Util::generate_random_bytes(32);
$token = OC_Util::generateRandomBytes(32);
OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
// login
@ -808,7 +808,7 @@ class OC {
if (defined("DEBUG") && DEBUG) {
OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
}
$token = OC_Util::generate_random_bytes(32);
$token = OC_Util::generateRandomBytes(32);
OC_Preferences::setValue($userid, 'login_token', $token, time());
OC_User::setMagicInCookie($userid, $token);
} else {

View File

@ -463,7 +463,7 @@ class Share {
if (isset($oldToken)) {
$token = $oldToken;
} else {
$token = \OC_Util::generate_random_bytes(self::TOKEN_LENGTH);
$token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
}
$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
null, $token);

View File

@ -61,7 +61,7 @@ class OC_Setup {
}
//generate a random salt that is used to salt the local user passwords
$salt = OC_Util::generate_random_bytes(30);
$salt = OC_Util::generateRandomBytes(30);
OC_Config::setValue('passwordsalt', $salt);
//write the config file

View File

@ -23,7 +23,7 @@ class MySQL extends AbstractDatabase {
$this->dbuser=substr('oc_'.$username, 0, 16);
if($this->dbuser!=$oldUser) {
//hash the password so we don't need to store the admin config in the config file
$this->dbpassword=\OC_Util::generate_random_bytes(30);
$this->dbpassword=\OC_Util::generateRandomBytes(30);
$this->createDBUser($connection);

View File

@ -65,7 +65,7 @@ class OCI extends AbstractDatabase {
//add prefix to the oracle user name to prevent collisions
$this->dbuser='oc_'.$username;
//create a new password so we don't need to store the admin config in the config file
$this->dbpassword=\OC_Util::generate_random_bytes(30);
$this->dbpassword=\OC_Util::generateRandomBytes(30);
//oracle passwords are treated as identifiers:
// must start with aphanumeric char

View File

@ -33,7 +33,7 @@ class PostgreSQL extends AbstractDatabase {
//add prefix to the postgresql user name to prevent collisions
$this->dbuser='oc_'.$username;
//create a new password so we don't need to store the admin config in the config file
$this->dbpassword=\OC_Util::generate_random_bytes(30);
$this->dbpassword=\OC_Util::generateRandomBytes(30);
$this->createDBUser($connection);

View File

@ -58,7 +58,7 @@ class OC_TemplateLayout extends OC_Template {
if (OC_Config::getValue('installed', false) && $renderas!='error') {
$this->append( 'jsfiles', OC_Helper::linkToRoute('js_config') . $versionParameter);
}
if (!empty(OC_Util::$core_scripts)) {
if (!empty(OC_Util::$coreScripts)) {
$this->append( 'jsfiles', OC_Helper::linkToRemoteBase('core.js', false) . $versionParameter);
}
foreach($jsfiles as $info) {
@ -71,7 +71,7 @@ class OC_TemplateLayout extends OC_Template {
// Add the css files
$cssfiles = self::findStylesheetFiles(OC_Util::$styles);
$this->assign('cssfiles', array());
if (!empty(OC_Util::$core_styles)) {
if (!empty(OC_Util::$coreStyles)) {
$this->append( 'cssfiles', OC_Helper::linkToRemoteBase('core.css', false) . $versionParameter);
}
foreach($cssfiles as $info) {

View File

@ -353,7 +353,7 @@ class OC_User {
* generates a password
*/
public static function generatePassword() {
return OC_Util::generate_random_bytes(30);
return OC_Util::generateRandomBytes(30);
}
/**

View File

@ -11,12 +11,18 @@ class OC_Util {
public static $headers=array();
private static $rootMounted=false;
private static $fsSetup=false;
public static $core_styles=array();
public static $core_scripts=array();
public static $coreStyles=array();
public static $coreScripts=array();
// Can be set up
public static function setupFS( $user = '' ) {// configure the initial filesystem based on the configuration
if(self::$fsSetup) {//setting up the filesystem twice can only lead to trouble
/**
* @brief Can be set up
* @param string $user
* @return boolean
* @description configure the initial filesystem based on the configuration
*/
public static function setupFS( $user = '' ) {
//setting up the filesystem twice can only lead to trouble
if(self::$fsSetup) {
return false;
}
@ -37,15 +43,16 @@ class OC_Util {
self::$fsSetup=true;
}
$CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
$configDataDirectory = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
//first set up the local "root" storage
\OC\Files\Filesystem::initMounts();
if(!self::$rootMounted) {
\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir'=>$CONFIG_DATADIRECTORY), '/');
self::$rootMounted=true;
\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir'=>$configDataDirectory), '/');
self::$rootMounted = true;
}
if( $user != "" ) { //if we aren't logged in, there is no use to set up the filesystem
//if we aren't logged in, there is no use to set up the filesystem
if( $user != "" ) {
$quota = self::getUserQuota($user);
if ($quota !== \OC\Files\SPACE_UNLIMITED) {
\OC\Files\Filesystem::addStorageWrapper(function($mountPoint, $storage) use ($quota, $user) {
@ -56,19 +63,19 @@ class OC_Util {
}
});
}
$user_dir = '/'.$user.'/files';
$user_root = OC_User::getHome($user);
$userdirectory = $user_root . '/files';
if( !is_dir( $userdirectory )) {
mkdir( $userdirectory, 0755, true );
$userDir = '/'.$user.'/files';
$userRoot = OC_User::getHome($user);
$userDirectory = $userRoot . '/files';
if( !is_dir( $userDirectory )) {
mkdir( $userDirectory, 0755, true );
}
//jail the user into his "home" directory
\OC\Files\Filesystem::init($user, $user_dir);
\OC\Files\Filesystem::init($user, $userDir);
$fileOperationProxy = new OC_FileProxy_FileOperations();
OC_FileProxy::register($fileOperationProxy);
OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir));
OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
}
return true;
}
@ -85,14 +92,17 @@ class OC_Util {
}
}
/**
* @return void
*/
public static function tearDownFS() {
\OC\Files\Filesystem::tearDown();
self::$fsSetup=false;
self::$rootMounted=false;
self::$rootMounted=false;
}
/**
* get the current installed version of ownCloud
* @brief get the current installed version of ownCloud
* @return array
*/
public static function getVersion() {
@ -102,7 +112,7 @@ class OC_Util {
}
/**
* get the current installed version string of ownCloud
* @brief get the current installed version string of ownCloud
* @return string
*/
public static function getVersionString() {
@ -110,7 +120,7 @@ class OC_Util {
}
/**
* get the current installed edition of ownCloud. There is the community
* @description 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".
* @return string
@ -120,103 +130,117 @@ class OC_Util {
}
/**
* add a javascript file
* @brief add a javascript file
*
* @param appid $application
* @param filename $file
* @param string $application
* @param filename $file
* @return void
*/
public static function addScript( $application, $file = null ) {
if( is_null( $file )) {
if ( is_null( $file )) {
$file = $application;
$application = "";
}
if( !empty( $application )) {
if ( !empty( $application )) {
self::$scripts[] = "$application/js/$file";
}else{
} else {
self::$scripts[] = "js/$file";
}
}
/**
* add a css file
* @brief add a css file
*
* @param appid $application
* @param filename $file
* @param string $application
* @param filename $file
* @return void
*/
public static function addStyle( $application, $file = null ) {
if( is_null( $file )) {
if ( is_null( $file )) {
$file = $application;
$application = "";
}
if( !empty( $application )) {
if ( !empty( $application )) {
self::$styles[] = "$application/css/$file";
}else{
} else {
self::$styles[] = "css/$file";
}
}
/**
* @brief Add a custom element to the header
* @param string tag tag name of the element
* @param string $tag tag name of the element
* @param array $attributes array of attributes for the element
* @param string $text the text content for the element
* @return void
*/
public static function addHeader( $tag, $attributes, $text='') {
self::$headers[] = array('tag'=>$tag, 'attributes'=>$attributes, 'text'=>$text);
self::$headers[] = array(
'tag'=>$tag,
'attributes'=>$attributes,
'text'=>$text
);
}
/**
* formats a timestamp in the "right" way
* @brief formats a timestamp in the "right" way
*
* @param int timestamp $timestamp
* @param bool dateOnly option to omit time from the result
* @param int $timestamp
* @param bool $dateOnly option to omit time from the result
* @return string timestamp
* @description adjust to clients timezone if we know it
*/
public static function formatDate( $timestamp, $dateOnly=false) {
if(\OC::$session->exists('timezone')) {//adjust to clients timezone if we know it
if(\OC::$session->exists('timezone')) {
$systemTimeZone = intval(date('O'));
$systemTimeZone=(round($systemTimeZone/100, 0)*60)+($systemTimeZone%100);
$clientTimeZone=\OC::$session->get('timezone')*60;
$offset=$clientTimeZone-$systemTimeZone;
$timestamp=$timestamp+$offset*60;
$systemTimeZone = (round($systemTimeZone/100, 0)*60) + ($systemTimeZone%100);
$clientTimeZone = \OC::$session->get('timezone')*60;
$offset = $clientTimeZone - $systemTimeZone;
$timestamp = $timestamp + $offset*60;
}
$l=OC_L10N::get('lib');
$l = OC_L10N::get('lib');
return $l->l($dateOnly ? 'date' : 'datetime', $timestamp);
}
/**
* check if the current server configuration is suitable for ownCloud
* @brief check if the current server configuration is suitable for ownCloud
* @return array arrays with error messages and hints
*/
public static function checkServer() {
// Assume that if checkServer() succeeded before in this session, then all is fine.
if(\OC::$session->exists('checkServer_suceeded') && \OC::$session->get('checkServer_suceeded'))
if(\OC::$session->exists('checkServer_suceeded') && \OC::$session->get('checkServer_suceeded')) {
return array();
}
$errors=array();
$errors = array();
$defaults = new \OC_Defaults();
$web_server_restart= false;
$webServerRestart = false;
//check for database drivers
if(!(is_callable('sqlite_open') or class_exists('SQLite3'))
and !is_callable('mysql_connect')
and !is_callable('pg_connect')
and !is_callable('oci_connect')) {
$errors[]=array('error'=>'No database drivers (sqlite, mysql, or postgresql) installed.',
'hint'=>'');//TODO: sane hint
$web_server_restart= true;
$errors[] = array(
'error'=>'No database drivers (sqlite, mysql, or postgresql) installed.',
'hint'=>'' //TODO: sane hint
);
$webServerRestart = true;
}
//common hint for all file permissons error messages
//common hint for all file permissions error messages
$permissionsHint = 'Permissions can usually be fixed by '
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html#set-the-directory-permissions" target="_blank">giving the webserver write access to the root directory</a>.';
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html'
.'#set-the-directory-permissions" target="_blank">giving the webserver write access to the root directory</a>.';
// Check if config folder is writable.
if(!is_writable(OC::$SERVERROOT."/config/") or !is_readable(OC::$SERVERROOT."/config/")) {
$errors[] = array(
'error' => "Can't write into config directory",
'hint' => 'This can usually be fixed by '
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html#set-the-directory-permissions" target="_blank">giving the webserver write access to the config directory</a>.'
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html'
.'#set-the-directory-permissions" target="_blank">giving the webserver write access to the config directory</a>.'
);
}
@ -228,7 +252,8 @@ class OC_Util {
$errors[] = array(
'error' => "Can't write into apps directory",
'hint' => 'This can usually be fixed by '
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html#set-the-directory-permissions" target="_blank">giving the webserver write access to the apps directory</a> '
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html'
.'#set-the-directory-permissions" target="_blank">giving the webserver write access to the apps directory</a> '
.'or disabling the appstore in the config file.'
);
}
@ -243,94 +268,131 @@ class OC_Util {
$errors[] = array(
'error' => "Can't create data directory (".$CONFIG_DATADIRECTORY.")",
'hint' => 'This can usually be fixed by '
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html#set-the-directory-permissions" target="_blank">giving the webserver write access to the root directory</a>.'
.'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html'
.'#set-the-directory-permissions" target="_blank">giving the webserver write access to the root directory</a>.'
);
}
} else if(!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
$errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud',
'hint'=>$permissionsHint);
$errors[] = array(
'error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud',
'hint'=>$permissionsHint
);
} else {
$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
}
$moduleHint = "Please ask your server administrator to install the module.";
// check if all required php modules are present
if(!class_exists('ZipArchive')) {
$errors[]=array('error'=>'PHP module zip not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module zip not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!class_exists('DOMDocument')) {
$errors[] = array('error' => 'PHP module dom not installed.',
'hint' => 'Please ask your server administrator to install the module.');
$web_server_restart =true;
$errors[] = array(
'error' => 'PHP module dom not installed.',
'hint' => $moduleHint
);
$webServerRestart =true;
}
if(!function_exists('xml_parser_create')) {
$errors[] = array('error' => 'PHP module libxml not installed.',
'hint' => 'Please ask your server administrator to install the module.');
$web_server_restart =true;
$errors[] = array(
'error' => 'PHP module libxml not installed.',
'hint' => $moduleHint
);
$webServerRestart = true;
}
if(!function_exists('mb_detect_encoding')) {
$errors[]=array('error'=>'PHP module mb multibyte not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module mb multibyte not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!function_exists('ctype_digit')) {
$errors[]=array('error'=>'PHP module ctype is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module ctype is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!function_exists('json_encode')) {
$errors[]=array('error'=>'PHP module JSON is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module JSON is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!extension_loaded('gd') || !function_exists('gd_info')) {
$errors[]=array('error'=>'PHP module GD is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module GD is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!function_exists('gzencode')) {
$errors[]=array('error'=>'PHP module zlib is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module zlib is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!function_exists('iconv')) {
$errors[]=array('error'=>'PHP module iconv is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module iconv is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(!function_exists('simplexml_load_string')) {
$errors[]=array('error'=>'PHP module SimpleXML is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP module SimpleXML is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if(floatval(phpversion())<5.3) {
$errors[]=array('error'=>'PHP 5.3 is required.',
if(floatval(phpversion()) < 5.3) {
$errors[] = array(
'error'=>'PHP 5.3 is required.',
'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.');
$web_server_restart=true;
.' PHP 5.2 is no longer supported by ownCloud and the PHP community.'
);
$webServerRestart = true;
}
if(!defined('PDO::ATTR_DRIVER_NAME')) {
$errors[]=array('error'=>'PHP PDO module is not installed.',
'hint'=>'Please ask your server administrator to install the module.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP PDO module is not installed.',
'hint'=>$moduleHint
);
$webServerRestart = true;
}
if (((strtolower(@ini_get('safe_mode')) == 'on')
|| (strtolower(@ini_get('safe_mode')) == 'yes')
|| (strtolower(@ini_get('safe_mode')) == 'true')
|| (ini_get("safe_mode") == 1 ))) {
$errors[]=array('error'=>'PHP Safe Mode is enabled. ownCloud requires that it is disabled to work properly.',
'hint'=>'PHP Safe Mode is a deprecated and mostly useless setting that should be disabled. Please ask your server administrator to disable it in php.ini or in your webserver config.');
$web_server_restart=true;
$errors[] = array(
'error'=>'PHP Safe Mode is enabled. ownCloud requires that it is disabled to work properly.',
'hint'=>'PHP Safe Mode is a deprecated and mostly useless setting that should be disabled. '
.'Please ask your server administrator to disable it in php.ini or in your webserver config.'
);
$webServerRestart = true;
}
if (get_magic_quotes_gpc() == 1 ) {
$errors[]=array('error'=>'Magic Quotes is enabled. ownCloud requires that it is disabled to work properly.',
'hint'=>'Magic Quotes is a deprecated and mostly useless setting that should be disabled. Please ask your server administrator to disable it in php.ini or in your webserver config.');
$web_server_restart=true;
$errors[] = array(
'error'=>'Magic Quotes is enabled. ownCloud requires that it is disabled to work properly.',
'hint'=>'Magic Quotes is a deprecated and mostly useless setting that should be disabled. '
.'Please ask your server administrator to disable it in php.ini or in your webserver config.'
);
$webServerRestart = true;
}
if($web_server_restart) {
$errors[]=array('error'=>'PHP modules have been installed, but they are still listed as missing?',
'hint'=>'Please ask your server administrator to restart the web server.');
if($webServerRestart) {
$errors[] = array(
'error'=>'PHP modules have been installed, but they are still listed as missing?',
'hint'=>'Please ask your server administrator to restart the web server.'
);
}
// Cache the result of this function
@ -357,30 +419,36 @@ class OC_Util {
}
/**
* Check for correct file permissions of data directory
* @return array arrays with error messages and hints
*/
* @brief Check for correct file permissions of data directory
* @paran string $dataDirectory
* @return array arrays with error messages and hints
*/
public static function checkDataDirectoryPermissions($dataDirectory) {
$errors = array();
if (stristr(PHP_OS, 'WIN')) {
if (self::runningOnWindows()) {
//TODO: permissions checks for windows hosts
} else {
$permissionsModHint = 'Please change the permissions to 0770 so that the directory'
.' cannot be listed by other users.';
$prems = substr(decoct(@fileperms($dataDirectory)), -3);
if (substr($prems, -1) != '0') {
$perms = substr(decoct(@fileperms($dataDirectory)), -3);
if (substr($perms, -1) != '0') {
OC_Helper::chmodr($dataDirectory, 0770);
clearstatcache();
$prems = substr(decoct(@fileperms($dataDirectory)), -3);
if (substr($prems, 2, 1) != '0') {
$errors[] = array('error' => 'Data directory ('.$dataDirectory.') is readable for other users',
'hint' => $permissionsModHint);
$perms = substr(decoct(@fileperms($dataDirectory)), -3);
if (substr($perms, 2, 1) != '0') {
$errors[] = array(
'error' => 'Data directory ('.$dataDirectory.') is readable for other users',
'hint' => $permissionsModHint
);
}
}
}
return $errors;
}
/**
* @return void
*/
public static function displayLoginPage($errors = array()) {
$parameters = array();
foreach( $errors as $key => $value ) {
@ -394,8 +462,8 @@ class OC_Util {
$parameters['user_autofocus'] = true;
}
if (isset($_REQUEST['redirect_url'])) {
$redirect_url = $_REQUEST['redirect_url'];
$parameters['redirect_url'] = urlencode($redirect_url);
$redirectUrl = $_REQUEST['redirect_url'];
$parameters['redirect_url'] = urlencode($redirectUrl);
}
$parameters['alt_login'] = OC_App::getAlternativeLogIns();
@ -404,7 +472,8 @@ class OC_Util {
/**
* Check if the app is enabled, redirects to home if not
* @brief Check if the app is enabled, redirects to home if not
* @return void
*/
public static function checkAppEnabled($app) {
if( !OC_App::isEnabled($app)) {
@ -416,18 +485,21 @@ class OC_Util {
/**
* Check if the user is logged in, redirects to home if not. With
* redirect URL parameter to the request URI.
* @return void
*/
public static function checkLoggedIn() {
// Check if we are a user
if( !OC_User::isLoggedIn()) {
header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php',
array('redirect_url' => OC_Request::requestUri())));
array('redirectUrl' => OC_Request::requestUri())
));
exit();
}
}
/**
* Check if the user is a admin, redirects to home if not
* @brief Check if the user is a admin, redirects to home if not
* @return void
*/
public static function checkAdminUser() {
if( !OC_User::isAdminUser(OC_User::getUser())) {
@ -437,7 +509,7 @@ class OC_Util {
}
/**
* Check if the user is a subadmin, redirects to home if not
* @brief Check if the user is a subadmin, redirects to home if not
* @return array $groups where the current user is subadmin
*/
public static function checkSubAdminUser() {
@ -449,7 +521,8 @@ class OC_Util {
}
/**
* Redirect to the user default page
* @brief Redirect to the user default page
* @return void
*/
public static function redirectToDefaultPage() {
if(isset($_REQUEST['redirect_url'])) {
@ -457,13 +530,11 @@ class OC_Util {
}
else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) {
$location = OC_Helper::linkToAbsolute( OC::$REQUESTEDAPP, 'index.php' );
}
else {
$defaultpage = OC_Appconfig::getValue('core', 'defaultpage');
if ($defaultpage) {
$location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultpage);
}
else {
} else {
$defaultPage = OC_Appconfig::getValue('core', 'defaultpage');
if ($defaultPage) {
$location = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/'.$defaultPage);
} else {
$location = OC_Helper::linkToAbsolute( 'files', 'index.php' );
}
}
@ -472,28 +543,28 @@ class OC_Util {
exit();
}
/**
* get an id unique for this instance
* @return string
*/
public static function getInstanceId() {
$id = OC_Config::getValue('instanceid', null);
if(is_null($id)) {
// We need to guarantee at least one letter in instanceid so it can be used as the session_name
$id = 'oc' . OC_Util::generate_random_bytes(10);
OC_Config::setValue('instanceid', $id);
}
return $id;
}
/**
* @brief get an id unique for this instance
* @return string
*/
public static function getInstanceId() {
$id = OC_Config::getValue('instanceid', null);
if(is_null($id)) {
// We need to guarantee at least one letter in instanceid so it can be used as the session_name
$id = 'oc' . self::generateRandomBytes(10);
OC_Config::setValue('instanceid', $id);
}
return $id;
}
/**
* @brief Static lifespan (in seconds) when a request token expires.
* @see OC_Util::callRegister()
* @see OC_Util::isCallRegistered()
* @description
* Also required for the client side to compute the piont in time when to
* Also required for the client side to compute the point in time when to
* request a fresh token. The client will do so when nearly 97% of the
* timespan coded here has expired.
* time span coded here has expired.
*/
public static $callLifespan = 3600; // 3600 secs = 1 hour
@ -513,7 +584,7 @@ class OC_Util {
// Check if a token exists
if(!\OC::$session->exists('requesttoken')) {
// No valid token found, generate a new one.
$requestToken = self::generate_random_bytes(20);
$requestToken = self::generateRandomBytes(20);
\OC::$session->set('requesttoken', $requestToken);
} else {
// Valid token already exists, send it
@ -534,11 +605,11 @@ class OC_Util {
}
if(isset($_GET['requesttoken'])) {
$token=$_GET['requesttoken'];
$token = $_GET['requesttoken'];
} elseif(isset($_POST['requesttoken'])) {
$token=$_POST['requesttoken'];
$token = $_POST['requesttoken'];
} elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])) {
$token=$_SERVER['HTTP_REQUESTTOKEN'];
$token = $_SERVER['HTTP_REQUESTTOKEN'];
} else {
//no token found.
return false;
@ -556,11 +627,12 @@ class OC_Util {
/**
* @brief Check an ajax get/post call if the request token is valid. exit if not.
* Todo: Write howto
* @todo Write howto
* @return void
*/
public static function callCheck() {
if(!OC_Util::isCallRegistered()) {
exit;
exit();
}
}
@ -570,14 +642,15 @@ class OC_Util {
* This function is used to sanitize HTML and should be applied on any
* string or array of strings before displaying it on a web page.
*
* @param string or array of strings
* @param string|array of strings
* @return array with sanitized strings or a single sanitized string, depends on the input parameter.
*/
public static function sanitizeHTML( &$value ) {
if (is_array($value)) {
array_walk_recursive($value, 'OC_Util::sanitizeHTML');
} else {
$value = htmlentities((string)$value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
//Specify encoding for PHP<5.4
$value = htmlentities((string)$value, ENT_QUOTES, 'UTF-8');
}
return $value;
}
@ -599,17 +672,20 @@ class OC_Util {
}
/**
* Check if the htaccess file is working by creating a test file in the data directory and trying to access via http
* @brief Check if the htaccess file is working
* @return bool
* @description Check if the htaccess file is working by creating a test
* file in the data directory and trying to access via http
*/
public static function ishtaccessworking() {
public static function isHtAccessWorking() {
// testdata
$filename='/htaccesstest.txt';
$testcontent='testcontent';
$fileName = '/htaccesstest.txt';
$testContent = 'testcontent';
// creating a test file
$testfile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$filename;
$testFile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$fileName;
if(file_exists($testfile)) {// already running this test, possible recursive call
if(file_exists($testFile)) {// already running this test, possible recursive call
return false;
}
@ -618,7 +694,7 @@ class OC_Util {
@fclose($fp);
// accessing the file via http
$url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$filename);
$url = OC_Helper::makeURLAbsolute(OC::$WEBROOT.'/data'.$fileName);
$fp = @fopen($url, 'r');
$content=@fread($fp, 2048);
@fclose($fp);
@ -627,20 +703,21 @@ class OC_Util {
@unlink($testfile);
// does it work ?
if($content==$testcontent) {
return(false);
}else{
return(true);
if($content==$testContent) {
return false;
} else {
return true;
}
}
/**
* we test if webDAV is working properly
*
* @brief test if webDAV is working properly
* @return bool
* @description
* The basic assumption is that if the server returns 401/Not Authenticated for an unauthenticated PROPFIND
* the web server it self is setup properly.
*
* Why not an authenticated PROFIND and other verbs?
* Why not an authenticated PROPFIND and other verbs?
* - We don't have the password available
* - We have no idea about other auth methods implemented (e.g. OAuth with Bearer header)
*
@ -654,7 +731,7 @@ class OC_Util {
);
// save the old timeout so that we can restore it later
$old_timeout=ini_get("default_socket_timeout");
$oldTimeout = ini_get("default_socket_timeout");
// use a 5 sec timeout for the check. Should be enough for local requests.
ini_set("default_socket_timeout", 5);
@ -668,24 +745,25 @@ class OC_Util {
try {
// test PROPFIND
$client->propfind('', array('{DAV:}resourcetype'));
} catch(\Sabre_DAV_Exception_NotAuthenticated $e) {
} catch (\Sabre_DAV_Exception_NotAuthenticated $e) {
$return = true;
} catch(\Exception $e) {
} catch (\Exception $e) {
OC_Log::write('core', 'isWebDAVWorking: NO - Reason: '.$e->getMessage(). ' ('.get_class($e).')', OC_Log::WARN);
$return = false;
}
// restore the original timeout
ini_set("default_socket_timeout", $old_timeout);
ini_set("default_socket_timeout", $oldTimeout);
return $return;
}
/**
* Check if the setlocal call doesn't work. This can happen if the right
* Check if the setlocal call does not work. This can happen if the right
* local packages are not available on the server.
* @return bool
*/
public static function issetlocaleworking() {
public static function isSetLocaleWorking() {
// setlocale test is pointless on Windows
if (OC_Util::runningOnWindows() ) {
return true;
@ -699,7 +777,7 @@ class OC_Util {
}
/**
* Check if the PHP module fileinfo is loaded.
* @brief Check if the PHP module fileinfo is loaded.
* @return bool
*/
public static function fileInfoLoaded() {
@ -707,7 +785,8 @@ class OC_Util {
}
/**
* Check if the ownCloud server can connect to the internet
* @brief Check if the ownCloud server can connect to the internet
* @return bool
*/
public static function isInternetConnectionWorking() {
// in case there is no internet connection on purpose return false
@ -720,30 +799,29 @@ class OC_Util {
if ($connected) {
fclose($connected);
return true;
}else{
} else {
// second try in case one server is down
$connected = @fsockopen("apps.owncloud.com", 80);
if ($connected) {
fclose($connected);
return true;
}else{
} else {
return false;
}
}
}
/**
* Check if the connection to the internet is disabled on purpose
* @brief Check if the connection to the internet is disabled on purpose
* @return bool
*/
public static function isInternetConnectionEnabled(){
return \OC_Config::getValue("has_internet_connection", true);
}
/**
* clear all levels of output buffering
* @brief clear all levels of output buffering
* @return void
*/
public static function obEnd(){
while (ob_get_level()) {
@ -753,47 +831,47 @@ class OC_Util {
/**
* @brief Generates a cryptographical secure pseudorandom string
* @param Int with the length of the random string
* @brief Generates a cryptographic secure pseudo-random string
* @param Int $length of the random string
* @return String
* Please also update secureRNG_available if you change something here
* Please also update secureRNGAvailable if you change something here
*/
public static function generate_random_bytes($length = 30) {
public static function generateRandomBytes($length = 30) {
// Try to use openssl_random_pseudo_bytes
if(function_exists('openssl_random_pseudo_bytes')) {
$pseudo_byte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
if (function_exists('openssl_random_pseudo_bytes')) {
$pseudoByte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
if($strong == true) {
return substr($pseudo_byte, 0, $length); // Truncate it to match the length
return substr($pseudoByte, 0, $length); // Truncate it to match the length
}
}
// Try to use /dev/urandom
$fp = @file_get_contents('/dev/urandom', false, null, 0, $length);
if ($fp !== false) {
$string = substr(bin2hex($fp), 0, $length);
return $string;
if (!self::runningOnWindows()) {
$fp = @file_get_contents('/dev/urandom', false, null, 0, $length);
if ($fp !== false) {
$string = substr(bin2hex($fp), 0, $length);
return $string;
}
}
// Fallback to mt_rand()
$characters = '0123456789';
$characters .= 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters)-1;
$pseudo_byte = "";
$pseudoByte = "";
// Select some random characters
for ($i = 0; $i < $length; $i++) {
$pseudo_byte .= $characters[mt_rand(0, $charactersLength)];
$pseudoByte .= $characters[mt_rand(0, $charactersLength)];
}
return $pseudo_byte;
return $pseudoByte;
}
/**
* @brief Checks if a secure random number generator is available
* @return bool
*/
public static function secureRNG_available() {
public static function secureRNGAvailable() {
// Check openssl_random_pseudo_bytes
if(function_exists('openssl_random_pseudo_bytes')) {
openssl_random_pseudo_bytes(1, $strong);
@ -803,9 +881,11 @@ class OC_Util {
}
// Check /dev/urandom
$fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
if ($fp !== false) {
return true;
if (!self::runningOnWindows()) {
$fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
if ($fp !== false) {
return true;
}
}
return false;
@ -818,11 +898,8 @@ class OC_Util {
* This function get the content of a page via curl, if curl is enabled.
* If not, file_get_element is used.
*/
public static function getUrlContent($url){
if (function_exists('curl_init')) {
if (function_exists('curl_init')) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_HEADER, 0);
@ -833,10 +910,10 @@ class OC_Util {
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
if(OC_Config::getValue('proxy', '')<>'') {
if(OC_Config::getValue('proxy', '') != '') {
curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
}
if(OC_Config::getValue('proxyuserpwd', '')<>'') {
if(OC_Config::getValue('proxyuserpwd', '') != '') {
curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
}
$data = curl_exec($curl);
@ -845,7 +922,7 @@ class OC_Util {
} else {
$contextArray = null;
if(OC_Config::getValue('proxy', '')<>'') {
if(OC_Config::getValue('proxy', '') != '') {
$contextArray = array(
'http' => array(
'timeout' => 10,
@ -860,11 +937,10 @@ class OC_Util {
);
}
$ctx = stream_context_create(
$contextArray
);
$data=@file_get_contents($url, 0, $ctx);
$data = @file_get_contents($url, 0, $ctx);
}
return $data;
@ -877,7 +953,6 @@ class OC_Util {
return (substr(PHP_OS, 0, 3) === "WIN");
}
/**
* Handles the case that there may not be a theme, then check if a "default"
* theme exists and take that one
@ -887,20 +962,19 @@ class OC_Util {
$theme = OC_Config::getValue("theme", '');
if($theme === '') {
if(is_dir(OC::$SERVERROOT . '/themes/default')) {
$theme = 'default';
}
}
return $theme;
}
/**
* Clear the opcode cache if one exists
* @brief Clear the opcode cache if one exists
* This is necessary for writing to the config file
* in case the opcode cache doesn't revalidate files
* in case the opcode cache does not re-validate files
* @return void
*/
public static function clearOpcodeCache() {
// APC
@ -939,8 +1013,10 @@ class OC_Util {
return $value;
}
public static function basename($file)
{
/**
* @return string
*/
public static function basename($file) {
$file = rtrim($file, '/');
$t = explode('/', $file);
return array_pop($t);

View File

@ -15,7 +15,7 @@ OC_App::setActiveNavigationEntry( "admin" );
$tmpl = new OC_Template( 'settings', 'admin', 'user');
$forms=OC_App::getForms('admin');
$htaccessworking=OC_Util::ishtaccessworking();
$htaccessworking=OC_Util::isHtAccessWorking();
$entries=OC_Log_Owncloud::getEntries(3);
$entriesremain = count(OC_Log_Owncloud::getEntries(4)) > 3;
@ -25,7 +25,7 @@ $tmpl->assign('entries', $entries);
$tmpl->assign('entriesremain', $entriesremain);
$tmpl->assign('htaccessworking', $htaccessworking);
$tmpl->assign('internetconnectionworking', OC_Util::isInternetConnectionEnabled() ? OC_Util::isInternetConnectionWorking() : false);
$tmpl->assign('islocaleworking', OC_Util::issetlocaleworking());
$tmpl->assign('islocaleworking', OC_Util::isSetLocaleWorking());
$tmpl->assign('isWebDavWorking', OC_Util::isWebDAVWorking());
$tmpl->assign('has_fileinfo', OC_Util::fileInfoLoaded());
$tmpl->assign('backgroundjobs_mode', OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax'));

View File

@ -15,7 +15,7 @@ class Test_DB extends PHPUnit_Framework_TestCase {
public function setUp() {
$dbfile = OC::$SERVERROOT.'/tests/data/db_structure.xml';
$r = '_'.OC_Util::generate_random_bytes('4').'_';
$r = '_'.OC_Util::generateRandomBytes('4').'_';
$content = file_get_contents( $dbfile );
$content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content );
file_put_contents( self::$schema_file, $content );

View File

@ -16,7 +16,7 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase {
$dbfile = OC::$SERVERROOT.'/tests/data/db_structure.xml';
$dbfile2 = OC::$SERVERROOT.'/tests/data/db_structure2.xml';
$r = '_'.OC_Util::generate_random_bytes('4').'_';
$r = '_'.OC_Util::generateRandomBytes('4').'_';
$content = file_get_contents( $dbfile );
$content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content );
file_put_contents( $this->schema_file, $content );

View File

@ -71,8 +71,8 @@ class Test_Util extends PHPUnit_Framework_TestCase {
$this->assertTrue(\OC_Util::isInternetConnectionEnabled());
}
function testGenerate_random_bytes() {
$result = strlen(OC_Util::generate_random_bytes(59));
function testGenerateRandomBytes() {
$result = strlen(OC_Util::generateRandomBytes(59));
$this->assertEquals(59, $result);
}