Clean up \OC\Util

- Use camelCase

 - Add some phpdoc

 - Fix some indents

 - Use some more spacing
This commit is contained in:
kondou 2013-08-15 08:49:19 +02:00
parent b9f3bb2426
commit 9c5416fe4a
17 changed files with 290 additions and 222 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

@ -413,7 +413,7 @@ class OC {
}
self::initPaths();
OC_Util::issetlocaleworking();
OC_Util::isSetlocaleWorking();
// set debug mode if an xdebug session is active
if (!defined('DEBUG') || !DEBUG) {
@ -522,7 +522,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);
@ -735,7 +735,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
@ -774,7 +774,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($_POST['user'], 'login_token', $token, time());
OC_User::setMagicInCookie($_POST["user"], $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,16 @@ 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 user string
* @return boolean
*/
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
return false;
}
@ -37,42 +41,45 @@ 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
$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);
$quotaProxy=new OC_FileProxy_Quota();
$quotaProxy = new OC_FileProxy_Quota();
$fileOperationProxy = new OC_FileProxy_FileOperations();
OC_FileProxy::register($quotaProxy);
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;
}
/**
* @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() {
@ -82,7 +89,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() {
@ -90,7 +97,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
@ -100,37 +107,39 @@ class OC_Util {
}
/**
* add a javascript file
* @brief add a javascript file
*
* @param appid $application
* @param filename $file
* @param appid $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 appid $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";
}
}
@ -140,63 +149,74 @@ class OC_Util {
* @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
* @return string timestamp
*/
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')) { //adjust to clients timezone if we know it
$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
$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>.'
);
}
@ -208,7 +228,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.'
);
}
@ -223,94 +244,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
@ -330,20 +388,25 @@ class OC_Util {
} 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 ) {
@ -357,8 +420,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();
@ -367,7 +430,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)) {
@ -379,18 +443,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())) {
@ -400,7 +467,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() {
@ -412,7 +479,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'])) {
@ -420,13 +488,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' );
}
}
@ -435,19 +501,19 @@ 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.
@ -476,7 +542,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
@ -497,11 +563,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;
@ -519,11 +585,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();
}
}
@ -562,12 +629,13 @@ 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 by creating a test file in the data directory and trying to access via http
* @return bool
*/
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;
@ -591,19 +659,20 @@ class OC_Util {
// does it work ?
if($content==$testcontent) {
return(false);
}else{
return(true);
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)
*
@ -617,7 +686,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);
@ -631,15 +700,15 @@ 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;
}
@ -647,8 +716,9 @@ class OC_Util {
/**
* Check if the setlocal call doesn't 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;
@ -662,7 +732,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() {
@ -670,7 +740,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
@ -683,30 +754,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()) {
@ -719,44 +789,44 @@ class OC_Util {
* @brief Generates a cryptographical secure pseudorandom string
* @param Int with the 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);
@ -766,9 +836,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;
@ -781,11 +853,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);
@ -796,10 +865,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);
@ -808,7 +877,7 @@ class OC_Util {
} else {
$contextArray = null;
if(OC_Config::getValue('proxy', '')<>'') {
if(OC_Config::getValue('proxy', '') != '') {
$contextArray = array(
'http' => array(
'timeout' => 10,
@ -823,11 +892,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;
@ -840,7 +908,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
@ -850,20 +917,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
* @return void
*/
public static function clearOpcodeCache() {
// APC
@ -902,8 +968,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)?true:false;
@ -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);
}