Merge pull request #143 from kijin/pr/misc-refactor

자질구레한 리팩토링 및 라이브러리 추가
This commit is contained in:
Kijin Sung 2016-01-23 14:15:38 +09:00
commit a0c22efe3f
16 changed files with 1141 additions and 633 deletions

View file

@ -1,10 +1,6 @@
<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */
define('FOLLOW_REQUEST_SSL', 0);
define('ENFORCE_SSL', 1);
define('RELEASE_SSL', 2);
/**
* Manages Context such as request arguments/environment variables
* It has dual method structure, easy-to use methods which can be called as self::methodname(),and methods called with static object.
@ -1276,11 +1272,26 @@ class Context
{
self::$_instance->js_callback_func = self::$_instance->getJSCallbackFunc();
($type && self::$_instance->request_method = $type) or
((strpos($_SERVER['CONTENT_TYPE'], 'json') || strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json')) && self::$_instance->request_method = 'JSON') or
($GLOBALS['HTTP_RAW_POST_DATA'] && self::$_instance->request_method = 'XMLRPC') or
(self::$_instance->js_callback_func && self::$_instance->request_method = 'JS_CALLBACK') or
(self::$_instance->request_method = $_SERVER['REQUEST_METHOD']);
if ($type)
{
self::$_instance->request_method = $type;
}
elseif (strpos($_SERVER['CONTENT_TYPE'], 'json') !== false || strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json') !== false)
{
self::$_instance->request_method = 'JSON';
}
elseif ($GLOBALS['HTTP_RAW_POST_DATA'])
{
self::$_instance->request_method = 'XMLRPC';
}
elseif (self::$_instance->js_callback_func)
{
self::$_instance->request_method = 'JS_CALLBACK';
}
else
{
self::$_instance->request_method = $_SERVER['REQUEST_METHOD'];
}
}
/**
@ -1600,15 +1611,7 @@ class Context
static $url = null;
if(is_null($url))
{
$url = self::getRequestUri();
if(count($_GET) > 0)
{
foreach($_GET as $key => $val)
{
$vars[] = $key . '=' . ($val ? urlencode(self::convertEncodingStr($val)) : '');
}
$url .= '?' . join('&', $vars);
}
$url = self::getRequestUri() . RX_REQUEST_URL;
}
return $url;
}
@ -1678,7 +1681,7 @@ class Context
$domain_info = parse_url($domain);
if(is_null($current_info))
{
$current_info = parse_url(($_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . getScriptPath());
$current_info = parse_url((RX_SSL ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . RX_BASEURL);
}
if($domain_info['host'] . $domain_info['path'] == $current_info['host'] . $current_info['path'])
{
@ -1686,11 +1689,7 @@ class Context
}
else
{
$domain = preg_replace('/^(http|https):\/\//i', '', trim($domain));
if(substr_compare($domain, '/', -1) !== 0)
{
$domain .= '/';
}
$domain = rtrim(preg_replace('/^(http|https):\/\//i', '', trim($domain)), '/') . '/';
}
}
@ -1746,7 +1745,7 @@ class Context
'dispDocumentAdminManageDocument' => 'dispDocumentManageDocument',
'dispModuleAdminSelectList' => 'dispModuleSelectList'
);
if($act_alias[$act])
if(isset($act_alias[$act]))
{
$get_vars['act'] = $act_alias[$act];
}
@ -1794,27 +1793,9 @@ class Context
$query = $target_map[$target];
}
if(!$query)
if(!$query && count($get_vars) > 0)
{
$queries = array();
foreach($get_vars as $key => $val)
{
if(is_array($val) && count($val) > 0)
{
foreach($val as $k => $v)
{
$queries[] = $key . '[' . $k . ']=' . urlencode($v);
}
}
elseif(!is_array($val))
{
$queries[] = $key . '=' . urlencode($val);
}
}
if(count($queries) > 0)
{
$query = 'index.php?' . join('&', $queries);
}
$query = 'index.php?' . http_build_query($get_vars);
}
}
@ -1823,18 +1804,18 @@ class Context
if($_use_ssl == 'always')
{
$query = self::getRequestUri(ENFORCE_SSL, $domain) . $query;
// optional SSL use
}
// optional SSL use
elseif($_use_ssl == 'optional')
{
$ssl_mode = ((self::get('module') === 'admin') || ($get_vars['module'] === 'admin') || (isset($get_vars['act']) && self::isExistsSSLAction($get_vars['act']))) ? ENFORCE_SSL : RELEASE_SSL;
$query = self::getRequestUri($ssl_mode, $domain) . $query;
// no SSL
}
// no SSL
else
{
// currently on SSL but target is not based on SSL
if($_SERVER['HTTPS'] == 'on')
if(RX_SSL)
{
$query = self::getRequestUri(ENFORCE_SSL, $domain) . $query;
}
@ -1844,7 +1825,7 @@ class Context
}
else
{
$query = getScriptPath() . $query;
$query = RX_BASEURL . $query;
}
}
@ -1910,11 +1891,9 @@ class Context
return $url[$ssl_mode][$domain_key];
}
$current_use_ssl = ($_SERVER['HTTPS'] == 'on');
switch($ssl_mode)
{
case FOLLOW_REQUEST_SSL: $use_ssl = $current_use_ssl;
case FOLLOW_REQUEST_SSL: $use_ssl = RX_SSL;
break;
case ENFORCE_SSL: $use_ssl = TRUE;
break;
@ -1924,20 +1903,16 @@ class Context
if($domain)
{
$target_url = trim($domain);
if(substr_compare($target_url, '/', -1) !== 0)
{
$target_url.= '/';
}
$target_url = rtrim(trim($domain), '/') . '/';
}
else
{
$target_url = $_SERVER['HTTP_HOST'] . getScriptPath();
$target_url = $_SERVER['HTTP_HOST'] . RX_BASEURL;
}
$url_info = parse_url('http://' . $target_url);
if($current_use_ssl != $use_ssl)
if($use_ssl != RX_SSL)
{
unset($url_info['port']);
}

View file

@ -22,7 +22,7 @@ class DisplayHandler extends Handler
* @param ModuleObject $oModule the module object
* @return void
*/
function printContent(&$oModule)
public function printContent(&$oModule)
{
// Check if the gzip encoding supported
if(
@ -85,28 +85,24 @@ class DisplayHandler extends Handler
$httpStatusCode = $oModule->getHttpStatusCode();
if($httpStatusCode && $httpStatusCode != 200)
{
$this->_printHttpStatusCode($httpStatusCode);
self::_printHttpStatusCode($httpStatusCode);
}
else
{
if(Context::getResponseMethod() == 'JSON' || Context::getResponseMethod() == 'JS_CALLBACK')
{
$this->_printJSONHeader();
self::_printJSONHeader();
}
else if(Context::getResponseMethod() != 'HTML')
{
$this->_printXMLHeader();
self::_printXMLHeader();
}
else
{
$this->_printHTMLHeader();
self::_printHTMLHeader();
}
}
// debugOutput output
$this->content_size = strlen($output);
$output .= $this->_debugOutput();
// disable gzip if output already exists
ob_flush();
if(headers_sent())
@ -123,6 +119,10 @@ class DisplayHandler extends Handler
// results directly output
print $output;
// debugOutput output
$this->content_size = strlen($output);
print $this->_debugOutput();
// call a trigger after display
ModuleHandler::triggerCall('display', 'after', $output);
@ -135,7 +135,7 @@ class DisplayHandler extends Handler
* __DEBUG_OUTPUT__ == 0, messages are written in ./files/_debug_message.php
* @return void
*/
function _debugOutput()
public function _debugOutput()
{
if(!__DEBUG__)
{
@ -179,14 +179,14 @@ class DisplayHandler extends Handler
);
$firephp->fb(
array(
'Elapsed time >>> Total : ' . sprintf('%0.5f sec', $end - __StartTime__),
'Elapsed time >>> Total : ' . sprintf('%0.5f sec', $end - RX_MICROTIME),
array(array('DB queries', 'class file load', 'Template compile', 'XmlParse compile', 'PHP', 'Widgets', 'Trans Content'),
array(
sprintf('%0.5f sec', $GLOBALS['__db_elapsed_time__']),
sprintf('%0.5f sec', $GLOBALS['__elapsed_class_load__']),
sprintf('%0.5f sec (%d called)', $GLOBALS['__template_elapsed__'], $GLOBALS['__TemplateHandlerCalled__']),
sprintf('%0.5f sec', $GLOBALS['__xmlparse_elapsed__']),
sprintf('%0.5f sec', $end - __StartTime__ - $GLOBALS['__template_elapsed__'] - $GLOBALS['__xmlparse_elapsed__'] - $GLOBALS['__db_elapsed_time__'] - $GLOBALS['__elapsed_class_load__']),
sprintf('%0.5f sec', $end - RX_MICROTIME - $GLOBALS['__template_elapsed__'] - $GLOBALS['__xmlparse_elapsed__'] - $GLOBALS['__db_elapsed_time__'] - $GLOBALS['__elapsed_class_load__']),
sprintf('%0.5f sec', $GLOBALS['__widget_excute_elapsed__']),
sprintf('%0.5f sec', $GLOBALS['__trans_content_elapsed__'])
)
@ -234,12 +234,12 @@ class DisplayHandler extends Handler
$buff[] = sprintf("\tResponse contents size\t: %d byte", $this->content_size);
// total execution time
$buff[] = sprintf("\n- Total elapsed time : %0.5f sec", $end - __StartTime__);
$buff[] = sprintf("\n- Total elapsed time : %0.5f sec", $end - RX_MICROTIME);
$buff[] = sprintf("\tclass file load elapsed time \t: %0.5f sec", $GLOBALS['__elapsed_class_load__']);
$buff[] = sprintf("\tTemplate compile elapsed time\t: %0.5f sec (%d called)", $GLOBALS['__template_elapsed__'], $GLOBALS['__TemplateHandlerCalled__']);
$buff[] = sprintf("\tXmlParse compile elapsed time\t: %0.5f sec", $GLOBALS['__xmlparse_elapsed__']);
$buff[] = sprintf("\tPHP elapsed time \t\t\t\t: %0.5f sec", $end - __StartTime__ - $GLOBALS['__template_elapsed__'] - $GLOBALS['__xmlparse_elapsed__'] - $GLOBALS['__db_elapsed_time__'] - $GLOBALS['__elapsed_class_load__']);
$buff[] = sprintf("\tPHP elapsed time \t\t\t\t: %0.5f sec", $end - RX_MICROTIME - $GLOBALS['__template_elapsed__'] - $GLOBALS['__xmlparse_elapsed__'] - $GLOBALS['__db_elapsed_time__'] - $GLOBALS['__elapsed_class_load__']);
$buff[] = sprintf("\tDB class elapsed time \t\t\t: %0.5f sec", $GLOBALS['__dbclass_elapsed_time__'] - $GLOBALS['__db_elapsed_time__']);
// widget execution time
@ -318,7 +318,7 @@ class DisplayHandler extends Handler
* print a HTTP HEADER for XML, which is encoded in UTF-8
* @return void
*/
function _printXMLHeader()
public static function _printXMLHeader()
{
header("Content-Type: text/xml; charset=UTF-8");
}
@ -327,7 +327,7 @@ class DisplayHandler extends Handler
* print a HTTP HEADER for HTML, which is encoded in UTF-8
* @return void
*/
function _printHTMLHeader()
public static function _printHTMLHeader()
{
header("Content-Type: text/html; charset=UTF-8");
}
@ -336,16 +336,16 @@ class DisplayHandler extends Handler
* print a HTTP HEADER for JSON, which is encoded in UTF-8
* @return void
*/
function _printJSONHeader()
public static function _printJSONHeader()
{
header("Content-Type: text/html; charset=UTF-8");
header("Content-Type: text/javascript; charset=UTF-8");
}
/**
* print a HTTP HEADER for HTML, which is encoded in UTF-8
* @return void
*/
function _printHttpStatusCode($code)
public static function _printHttpStatusCode($code)
{
$statusMessage = Context::get('http_status_message');
header("HTTP/1.0 $code $statusMessage");

View file

@ -8,19 +8,18 @@
*/
class Mobile
{
/**
* Whether mobile or not mobile mode
* @var bool
*/
var $ismobile = NULL;
public $ismobile = NULL;
/**
* Get instance of Mobile class(for singleton)
*
* @return Mobile
*/
function &getInstance()
public function getInstance()
{
static $theInstance;
if(!isset($theInstance))
@ -35,10 +34,9 @@ class Mobile
*
* @return bool If mobile mode returns true or false
*/
function isFromMobilePhone()
public static function isFromMobilePhone()
{
$oMobile = & Mobile::getInstance();
return $oMobile->_isFromMobilePhone();
return self::getInstance()->_isFromMobilePhone();
}
/**
@ -46,7 +44,7 @@ class Mobile
*
* @return bool
*/
function _isFromMobilePhone()
public function _isFromMobilePhone()
{
if($this->ismobile !== NULL)
{
@ -92,7 +90,7 @@ class Mobile
$this->ismobile = FALSE;
setcookie("mobile", FALSE, 0, $xe_web_path);
setcookie("user-agent", FALSE, 0, $xe_web_path);
if(!$this->isMobilePadCheckByAgent() && $this->isMobileCheckByAgent())
if(!self::isMobilePadCheckByAgent() && self::isMobileCheckByAgent())
{
$this->ismobile = TRUE;
}
@ -100,13 +98,13 @@ class Mobile
}
else
{
if($this->isMobilePadCheckByAgent())
if(self::isMobilePadCheckByAgent())
{
$this->ismobile = FALSE;
}
else
{
if($this->isMobileCheckByAgent())
if(self::isMobileCheckByAgent())
{
$this->ismobile = TRUE;
}
@ -143,7 +141,7 @@ class Mobile
*
* @return bool Returns true on mobile device or false.
*/
function isMobileCheckByAgent()
public static function isMobileCheckByAgent()
{
static $UACheck;
if(isset($UACheck))
@ -177,7 +175,7 @@ class Mobile
*
* @return bool TRUE for tablet, and FALSE for else.
*/
function isMobilePadCheckByAgent()
public static function isMobilePadCheckByAgent()
{
static $UACheck;
if(isset($UACheck))
@ -226,15 +224,13 @@ class Mobile
* @param bool $ismobile
* @return void
*/
function setMobile($ismobile)
public static function setMobile($ismobile)
{
$oMobile = Mobile::getInstance();
$oMobile->ismobile = $ismobile;
self::getInstance()->ismobile = (bool)$ismobile;
}
function isMobileEnabled()
public static function isMobileEnabled()
{
$db_info = Context::getDBInfo();
return ($db_info->use_mobile_view === 'Y');
return (Context::getDBInfo()->use_mobile_view === 'Y');
}
}

View file

@ -32,7 +32,7 @@ class ModuleHandler extends Handler
* @return void
* */
function __construct($module = '', $act = '', $mid = '', $document_srl = '', $module_srl = '')
public function __construct($module = '', $act = '', $mid = '', $document_srl = '', $module_srl = '')
{
// If XE has not installed yet, set module as install
if(!Context::isInstalled())
@ -94,7 +94,7 @@ class ModuleHandler extends Handler
if(isset($this->act) && (strlen($this->act) >= 4 && substr_compare($this->act, 'disp', 0, 4) === 0))
{
if(Context::get('_use_ssl') == 'optional' && Context::isExistsSSLAction($this->act) && $_SERVER['HTTPS'] != 'on')
if(Context::get('_use_ssl') == 'optional' && Context::isExistsSSLAction($this->act) && !RX_SSL)
{
if(Context::get('_https_port')!=null) {
header('location:https://' . $_SERVER['HTTP_HOST'] . ':' . Context::get('_https_port') . $_SERVER['REQUEST_URI']);
@ -106,7 +106,7 @@ class ModuleHandler extends Handler
}
// call a trigger before moduleHandler init
ModuleHandler::triggerCall('moduleHandler.init', 'before', $this);
self::triggerCall('moduleHandler.init', 'before', $this);
// execute addon (before module initialization)
$called_position = 'before_module_init';
@ -119,7 +119,7 @@ class ModuleHandler extends Handler
* Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action
* @return boolean true: OK, false: redirected
* */
function init()
public function init()
{
$oModuleModel = getModel('module');
$site_module_info = Context::get('site_module_info');
@ -301,7 +301,7 @@ class ModuleHandler extends Handler
}
// Call a trigger after moduleHandler init
$output = ModuleHandler::triggerCall('moduleHandler.init', 'after', $this->module_info);
$output = self::triggerCall('moduleHandler.init', 'after', $this->module_info);
if(!$output->toBool())
{
$this->error = $output->getMessage();
@ -318,7 +318,7 @@ class ModuleHandler extends Handler
* get a module instance and execute an action
* @return ModuleObject executed module instance
* */
function procModule()
public function procModule()
{
$oModuleModel = getModel('module');
$display_mode = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
@ -326,8 +326,8 @@ class ModuleHandler extends Handler
// If error occurred while preparation, return a message instance
if($this->error)
{
$this->_setInputErrorToContext();
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
self::_setInputErrorToContext();
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -362,8 +362,8 @@ class ModuleHandler extends Handler
$this->error = 'msg_module_is_not_exists';
$this->httpStatusCode = '404';
$this->_setInputErrorToContext();
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
self::_setInputErrorToContext();
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -400,7 +400,7 @@ class ModuleHandler extends Handler
if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
{
$this->error = "msg_invalid_request";
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -433,9 +433,9 @@ class ModuleHandler extends Handler
// Admin ip
if($kind == 'admin' && $_SESSION['denied_admin'] == 'Y')
{
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$this->error = "msg_not_permitted_act";
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -448,24 +448,24 @@ class ModuleHandler extends Handler
$orig_type = "view";
$type = "mobile";
// create a module instance
$oModule = $this->getModuleInstance($this->module, $type, $kind);
$oModule = self::getModuleInstance($this->module, $type, $kind);
if(!is_object($oModule) || !method_exists($oModule, $this->act))
{
$type = $orig_type;
Mobile::setMobile(FALSE);
$oModule = $this->getModuleInstance($this->module, $type, $kind);
$oModule = self::getModuleInstance($this->module, $type, $kind);
}
}
else
{
// create a module instance
$oModule = $this->getModuleInstance($this->module, $type, $kind);
$oModule = self::getModuleInstance($this->module, $type, $kind);
}
if(!is_object($oModule))
{
$this->_setInputErrorToContext();
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
self::_setInputErrorToContext();
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -482,9 +482,9 @@ class ModuleHandler extends Handler
if(!Context::isInstalled())
{
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$this->error = 'msg_invalid_request';
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -513,7 +513,7 @@ class ModuleHandler extends Handler
else
{
$this->error = 'msg_invalid_request';
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -555,7 +555,7 @@ class ModuleHandler extends Handler
if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
{
$this->error = "msg_invalid_request";
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -583,23 +583,23 @@ class ModuleHandler extends Handler
$orig_type = "view";
$type = "mobile";
// create a module instance
$oModule = $this->getModuleInstance($forward->module, $type, $kind);
$oModule = self::getModuleInstance($forward->module, $type, $kind);
if(!is_object($oModule) || !method_exists($oModule, $this->act))
{
$type = $orig_type;
Mobile::setMobile(FALSE);
$oModule = $this->getModuleInstance($forward->module, $type, $kind);
$oModule = self::getModuleInstance($forward->module, $type, $kind);
}
}
else
{
$oModule = $this->getModuleInstance($forward->module, $type, $kind);
$oModule = self::getModuleInstance($forward->module, $type, $kind);
}
if(!is_object($oModule))
{
$this->_setInputErrorToContext();
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
self::_setInputErrorToContext();
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage('msg_module_is_not_exists');
$oMessageObject->dispMessage();
@ -624,10 +624,10 @@ class ModuleHandler extends Handler
}
else
{
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$this->error = 'msg_is_not_administrator';
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -639,9 +639,9 @@ class ModuleHandler extends Handler
$grant = $oModuleModel->getGrant($this->module_info, $logged_info);
if(!$grant->manager)
{
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$this->error = 'msg_is_not_manager';
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -651,9 +651,9 @@ class ModuleHandler extends Handler
{
if(!$grant->is_admin && $this->module != $this->orig_module->module && $xml_info->permission->{$this->act} != 'manager')
{
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$this->error = 'msg_is_not_administrator';
$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
$oMessageObject = self::getModuleInstance('message', $display_mode);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
@ -710,7 +710,7 @@ class ModuleHandler extends Handler
$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = 'error';
$_SESSION['XE_VALIDATOR_RETURN_URL'] = $returnUrl;
$_SESSION['XE_VALIDATOR_ID'] = Context::get('xe_validator_id');
$this->_setInputValueToSession();
self::_setInputValueToSession();
return $oModule;
}
}
@ -753,7 +753,7 @@ class ModuleHandler extends Handler
}
// if failed message exists in session, set context
$this->_setInputErrorToContext();
self::_setInputErrorToContext();
$procResult = $oModule->proc();
@ -773,7 +773,7 @@ class ModuleHandler extends Handler
{
$redirectUrl = Context::get('error_return_url');
}
$this->_setInputValueToSession();
self::_setInputValueToSession();
}
else
{
@ -807,7 +807,7 @@ class ModuleHandler extends Handler
* set error message to Session.
* @return void
* */
function _setInputErrorToContext()
public static function _setInputErrorToContext()
{
if($_SESSION['XE_VALIDATOR_ERROR'] && !Context::get('XE_VALIDATOR_ERROR'))
{
@ -834,14 +834,14 @@ class ModuleHandler extends Handler
Context::set('INPUT_ERROR', $_SESSION['INPUT_ERROR']);
}
$this->_clearErrorSession();
self::_clearErrorSession();
}
/**
* clear error message to Session.
* @return void
* */
function _clearErrorSession()
public static function _clearErrorSession()
{
unset($_SESSION['XE_VALIDATOR_ERROR']);
unset($_SESSION['XE_VALIDATOR_MESSAGE']);
@ -855,7 +855,7 @@ class ModuleHandler extends Handler
* occured error when, set input values to session.
* @return void
* */
function _setInputValueToSession()
public static function _setInputValueToSession()
{
$requestVars = Context::getRequestVars();
unset($requestVars->act, $requestVars->mid, $requestVars->vid, $requestVars->success_return_url, $requestVars->error_return_url);
@ -870,7 +870,7 @@ class ModuleHandler extends Handler
* @param ModuleObject $oModule module instance
* @return void
* */
function displayContent($oModule = NULL)
public function displayContent($oModule = NULL)
{
// If the module is not set or not an object, set error
if(!$oModule || !is_object($oModule))
@ -886,7 +886,7 @@ class ModuleHandler extends Handler
}
// Call trigger after moduleHandler proc
$output = ModuleHandler::triggerCall('moduleHandler.proc', 'after', $oModule);
$output = self::triggerCall('moduleHandler.proc', 'after', $oModule);
if(!$output->toBool())
{
$this->error = $output->getMessage();
@ -912,14 +912,14 @@ class ModuleHandler extends Handler
{
// display content with message module instance
$type = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
$oMessageObject = ModuleHandler::getModuleInstance('message', $type);
$oMessageObject = self::getModuleInstance('message', $type);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
if($oMessageObject->getHttpStatusCode() && $oMessageObject->getHttpStatusCode() != '200')
{
$this->_setHttpStatusMessage($oMessageObject->getHttpStatusCode());
self::_setHttpStatusMessage($oMessageObject->getHttpStatusCode());
$oMessageObject->setTemplateFile('http_status_code');
}
@ -935,7 +935,7 @@ class ModuleHandler extends Handler
$oModule = $oMessageObject;
}
$this->_clearErrorSession();
self::_clearErrorSession();
}
// Check if layout_srl exists for the module
@ -1065,7 +1065,7 @@ class ModuleHandler extends Handler
* @param string $module module name
* @return string path of the module
* */
function getModulePath($module)
public static function getModulePath($module)
{
return sprintf('./modules/%s/', $module);
}
@ -1078,7 +1078,7 @@ class ModuleHandler extends Handler
* @return ModuleObject module instance (if failed it returns null)
* @remarks if there exists a module instance created before, returns it.
* */
function &getModuleInstance($module, $type = 'view', $kind = '')
public static function getModuleInstance($module, $type = 'view', $kind = '')
{
if(__DEBUG__ == 3)
@ -1106,12 +1106,12 @@ class ModuleHandler extends Handler
// if there is no instance of the module in global variable, create a new one
if(!isset($GLOBALS['_loaded_module'][$module][$type][$kind]))
{
ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
self::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
if($extend_module && (!is_readable($high_class_file) || !is_readable($class_file)))
{
$module = $parent_module;
ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
self::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
}
// Check if the base class and instance class exist
@ -1142,16 +1142,6 @@ class ModuleHandler extends Handler
$oModule->setModule($module);
$oModule->setModulePath($class_path);
// If the module has a constructor, run it.
if(!isset($GLOBALS['_called_constructor'][$instance_name]))
{
$GLOBALS['_called_constructor'][$instance_name] = TRUE;
if(@method_exists($oModule, $instance_name))
{
$oModule->{$instance_name}();
}
}
// Store the created instance into GLOBALS variable
$GLOBALS['_loaded_module'][$module][$type][$kind] = $oModule;
}
@ -1165,9 +1155,9 @@ class ModuleHandler extends Handler
return $GLOBALS['_loaded_module'][$module][$type][$kind];
}
function _getModuleFilePath($module, $type, $kind, &$classPath, &$highClassFile, &$classFile, &$instanceName)
public static function _getModuleFilePath($module, $type, $kind, &$classPath, &$highClassFile, &$classFile, &$instanceName)
{
$classPath = ModuleHandler::getModulePath($module);
$classPath = self::getModulePath($module);
$highClassFile = sprintf('%s%s%s.class.php', _XE_PATH_, $classPath, $module);
$highClassFile = FileHandler::getRealPath($highClassFile);
@ -1204,7 +1194,7 @@ class ModuleHandler extends Handler
* @param object $obj an object as a parameter to trigger
* @return Object
* */
function triggerCall($trigger_name, $called_position, &$obj)
public static function triggerCall($trigger_name, $called_position, &$obj)
{
// skip if not installed
if(!Context::isInstalled())
@ -1267,12 +1257,12 @@ class ModuleHandler extends Handler
* @param string $code
* @return string
* */
function _setHttpStatusMessage($code)
public static function _setHttpStatusMessage($code)
{
$statusMessageList = array(
'100' => 'Continue',
'101' => 'Switching Protocols',
'201' => 'OK', // todo check array key '201'
'200' => 'OK',
'201' => 'Created',
'202' => 'Accepted',
'203' => 'Non-Authoritative Information',

View file

@ -1,357 +0,0 @@
<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */
/**
* This class makes encryption and digital signing easy to use in XE.
*
* The encryption methods use AES-128, and is fully compatible with
* https://github.com/defuse/php-encryption
* except that it uses base64-encoded keys and ciphertexts.
*
* The digital signature methods is based on the same SHA-256 based
* key derivation function used by the encryption methods.
*
* A key is automatically generated and saved to the files/config directory
* when first invoked. The same key will be used for all subsequent
* method calls that do not specify a different key.
* The key must be a binary string exactly 16 bytes long.
*
* @file Crypto.class.php
* @author Kijin Sung (kijin@kijinsung.com)
* @package /classes/security
* @version 1.0
*/
class Crypto
{
/**
* @brief Default configuration
*/
const ENCRYPTION_ALGO = 'aes-128';
const ENCRYPTION_MODE = 'cbc';
const ENCRYPTION_BLOCK_SIZE = 16;
const ENCRYPTION_KEY_SIZE = 16;
const ENCRYPTION_KEY_INFO = 'DefusePHP|KeyForEncryption';
const ENCRYPTION_MAC_ALGO = 'sha256';
const ENCRYPTION_MAC_SIZE = 32;
const ENCRYPTION_MAC_INFO = 'DefusePHP|KeyForAuthentication';
const SIGNATURE_ALGO = 'sha256';
const SIGNATURE_SIZE = '32';
/**
* @brief The default key
*/
protected static $_default_key = null;
/**
* @brief The currently selected extension
*/
protected static $_extension = null;
/**
* @brief If this is true, encryption and signature are only valid in current session
*/
protected $_current_session_only = false;
/**
* @brief Constructor
*/
public function __construct()
{
if(function_exists('openssl_encrypt'))
{
self::$_extension = 'openssl';
}
elseif(function_exists('mcrypt_encrypt'))
{
self::$_extension = 'mcrypt';
}
else
{
throw new Exception('Crypto class requires openssl or mcrypt extension.');
}
}
/**
* @brief Check if cryptography is supported on this server
* @return bool
*/
public static function isSupported()
{
return (function_exists('openssl_encrypt') || function_exists('mcrypt_encrypt'));
}
/**
* @brief Make encryption and signature only valid in current session
* @return void
*/
public function currentSessionOnly()
{
$this->_current_session_only = true;
}
/**
* @brief Encrypt a string
* @param string $plaintext The string to encrypt
* @param string $key Optional key. If empty, default key will be used.
* @return string
*/
public function encrypt($plaintext, $key = null)
{
if($key === null || $key === '')
{
$key = $this->_getSessionKey();
}
// Generate subkey for encryption
$enc_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_KEY_INFO);
// Generate IV
$iv = self::_createIV();
// Encrypt the plaintext
if(self::$_extension === 'openssl')
{
$openssl_method = self::ENCRYPTION_ALGO . '-' . self::ENCRYPTION_MODE;
$ciphertext = openssl_encrypt($plaintext, $openssl_method, $enc_key, OPENSSL_RAW_DATA, $iv);
}
else
{
$mcrypt_method = str_replace('aes', 'rijndael', self::ENCRYPTION_ALGO);
$plaintext = self::_applyPKCS7Padding($plaintext, self::ENCRYPTION_BLOCK_SIZE);
$ciphertext = mcrypt_encrypt($mcrypt_method, $enc_key, $plaintext, self::ENCRYPTION_MODE, $iv);
}
// Generate MAC
$mac_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_MAC_INFO);
$mac = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($iv . $ciphertext), $mac_key, true);
// Return the MAC, IV, and ciphertext as a base64 encoded string
return base64_encode($mac . $iv . $ciphertext);
}
/**
* @brief Decrypt a string
* @param string $ciphertext The string to decrypt
* @param string $key Optional key. If empty, default key will be used.
* @return string
*/
public function decrypt($ciphertext, $key = null)
{
if($key === null || $key === '')
{
$key = $this->_getSessionKey();
}
// Base64 decode the ciphertext and check the length
$ciphertext = @base64_decode($ciphertext);
if(strlen($ciphertext) < (self::ENCRYPTION_MAC_SIZE + (self::ENCRYPTION_BLOCK_SIZE * 2)))
{
return false;
}
// Extract MAC and IV from the remainder of the ciphertext
$mac = substr($ciphertext, 0, self::ENCRYPTION_MAC_SIZE);
$iv = substr($ciphertext, self::ENCRYPTION_MAC_SIZE, self::ENCRYPTION_BLOCK_SIZE);
$ciphertext = substr($ciphertext, self::ENCRYPTION_MAC_SIZE + self::ENCRYPTION_BLOCK_SIZE);
// Validate MAC
$mac_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_MAC_INFO);
$mac_compare = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($iv . $ciphertext), $mac_key, true);
$oPassword = new Password();
if(!$oPassword->strcmpConstantTime($mac, $mac_compare))
{
return false;
}
// Generate subkey for encryption
$enc_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_KEY_INFO);
// Decrypt the ciphertext
if (self::$_extension === 'openssl')
{
$openssl_method = self::ENCRYPTION_ALGO . '-' . self::ENCRYPTION_MODE;
$plaintext = openssl_decrypt($ciphertext, $openssl_method, $enc_key, OPENSSL_RAW_DATA, $iv);
}
else
{
$mcrypt_method = str_replace('aes', 'rijndael', self::ENCRYPTION_ALGO);
$plaintext = @mcrypt_decrypt($mcrypt_method, $enc_key, $ciphertext, self::ENCRYPTION_MODE, $iv);
if($plaintext === false)
{
return false;
}
$plaintext = self::_stripPKCS7Padding($plaintext, self::ENCRYPTION_BLOCK_SIZE);
if($plaintext === false)
{
return false;
}
}
// Return the plaintext
return $plaintext;
}
/**
* @brief Create a digital signature of a string
* @param string $plaintext The string to sign
* @param string $key Optional key. If empty, default key will be used.
* @return string
*/
public function createSignature($plaintext, $key = null)
{
if($key === null || $key === '')
{
$key = $this->_getSessionKey();
}
// Generate a signature using HMAC
return bin2hex(self::_defuseCompatibleHKDF($plaintext, $key));
}
/**
* @brief Verify a digital signature
* @param string $signature The signature to verify
* @param string $plaintext The string to verify
* @param string $key Optional key. If empty, default key will be used.
* @return bool
*/
public function verifySignature($signature, $plaintext, $key = null)
{
if($key === null || $key === '')
{
$key = $this->_getSessionKey();
}
// Verify the signature using HMAC
$oPassword = new Password();
$compare = bin2hex(self::_defuseCompatibleHKDF($plaintext, $key));
return $oPassword->strcmpConstantTime($signature, $compare);
}
/**
* @brief Get the default key applicable to this instance
* @return string
*/
protected function _getSessionKey()
{
if($this->_current_session_only)
{
if(!isset($_SESSION['XE_CRYPTO_SESSKEY']))
{
$_SESSION['XE_CRYPTO_SESSKEY'] = self::_createSecureKey();
}
$session_key = base64_decode($_SESSION['XE_CRYPTO_SESSKEY']);
return strval(self::_getDefaultKey()) ^ strval($session_key);
}
else
{
return strval(self::_getDefaultKey());
}
}
/**
* @brief Get the default key
* @return string
*/
protected static function _getDefaultKey()
{
if(self::$_default_key !== null)
{
return base64_decode(self::$_default_key);
}
else
{
$file_name = _XE_PATH_ . 'files/config/crypto.config.php';
if(file_exists($file_name) && is_readable($file_name))
{
$key = (include $file_name);
}
if(!isset($key) || !is_string($key))
{
$key = self::_createSecureKey();
self::_setDefaultKey($key);
}
return base64_decode(self::$_default_key = $key);
}
}
/**
* @brief Set the default key
* @param string $key The default key
* @return void
*/
protected static function _setDefaultKey($key)
{
self::$_default_key = $key = trim($key);
$file_name = _XE_PATH_ . 'files/config/crypto.config.php';
$file_content = '<?php return ' . var_export($key, true) . ';' . PHP_EOL;
FileHandler::writeFile($file_name, $file_content);
}
/**
* @brief Create a secure key
* @return string
*/
protected static function _createSecureKey()
{
$oPassword = new Password();
return base64_encode($oPassword->createSecureSalt(ENCRYPTION_KEY_SIZE, 'binary'));
}
/**
* @brief Create an IV
* @return string
*/
protected static function _createIV()
{
$oPassword = new Password();
return $oPassword->createSecureSalt(self::ENCRYPTION_BLOCK_SIZE, 'binary');
}
/**
* @brief Apply PKCS#7 padding to a string
* @param string $str The string
* @param int $block_size The block size
* @return string
*/
protected static function _applyPKCS7Padding($str, $block_size)
{
$padding_size = $block_size - (strlen($str) % $block_size);
if ($padding_size === 0) $padding_size = $block_size;
return $str . str_repeat(chr($padding_size), $padding_size);
}
/**
* @brief Remove PKCS#7 padding from a string
* @param string $str The string
* @param int $block_size The block size
* @return string
*/
protected static function _stripPKCS7Padding($str, $block_size)
{
if (strlen($str) % $block_size !== 0) return false;
$padding_size = ord(substr($str, -1));
if ($padding_size < 1 || $padding_size > $block_size) return false;
if (substr($str, (-1 * $padding_size)) !== str_repeat(chr($padding_size), $padding_size)) return false;
return substr($str, 0, strlen($str) - $padding_size);
}
/**
* @brief HKDF function compatible with defuse/php-encryption
* @return string
*/
protected static function _defuseCompatibleHKDF($key, $info)
{
$salt = str_repeat("\x00", self::ENCRYPTION_MAC_SIZE);
$prk = hash_hmac(self::ENCRYPTION_MAC_ALGO, $key, $salt, true);
$t = $last_block = '';
for ($block_index = 1; strlen($t) < self::ENCRYPTION_KEY_SIZE; $block_index++)
{
$t .= $last_block = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($last_block . $info . chr($block_index)), $prk, true);
}
return substr($t, 0, self::ENCRYPTION_KEY_SIZE);
}
}
/* End of file : Crypto.class.php */
/* Location: ./classes/security/Crypto.class.php */

View file

@ -21,7 +21,7 @@ class TemplateHandler
private $config = NULL;
private $skipTags = NULL;
private $handler_mtime = 0;
static private $rootTpl = NULL;
private static $rootTpl = NULL;
/**
* constructor
@ -38,7 +38,7 @@ class TemplateHandler
* returns TemplateHandler's singleton object
* @return TemplateHandler instance
*/
static public function &getInstance()
public static function getInstance()
{
static $oTemplate = NULL;
@ -495,7 +495,7 @@ class TemplateHandler
foreach($matches[1] as $n => $stmt)
{
$expr = $matches[2][$n];
$expr = $this->_replaceVar($expr);
$expr = self::_replaceVar($expr);
$closing++;
switch($stmt)
@ -568,7 +568,7 @@ class TemplateHandler
if(strpos($node, '|cond="') !== false)
{
$node = preg_replace('@(\s[-\w:]+(?:="[^"]+?")?)\|cond="(.+?)"@s', '<?php if($2){ ?>$1<?php } ?>', $node);
$node = $this->_replaceVar($node);
$node = self::_replaceVar($node);
}
if($nodes[$idx] != $node)
@ -600,7 +600,7 @@ class TemplateHandler
if($m[1]{0} == '@')
{
$m[1] = $this->_replaceVar(substr($m[1], 1));
$m[1] = self::_replaceVar(substr($m[1], 1));
return "<?php {$m[1]} ?>";
}
else
@ -615,7 +615,7 @@ class TemplateHandler
{
$escape_option = 'noescape';
}
$m[1] = $this->_replaceVar($m[1]);
$m[1] = self::_replaceVar($m[1]);
switch($escape_option)
{
case 'auto':
@ -674,7 +674,7 @@ class TemplateHandler
return "<?php \$__tpl=TemplateHandler::getInstance();echo \$__tpl->compile('{$fileDir}','{$pathinfo['basename']}') ?>";
// <!--%load_js_plugin-->
case 'load_js_plugin':
$plugin = $this->_replaceVar($m[5]);
$plugin = self::_replaceVar($m[5]);
$s = "<!--#JSPLUGIN:{$plugin}-->";
if(strpos($plugin, '$__Context') === false)
{
@ -780,7 +780,7 @@ class TemplateHandler
$m[7] = substr($m[7], 1);
if(!$m[7])
{
return '<?php ' . $this->_replaceVar($m[8]) . '{ ?>' . $m[9];
return '<?php ' . self::_replaceVar($m[8]) . '{ ?>' . $m[9];
}
if(!preg_match('/^(?:((?:end)?(?:if|switch|for(?:each)?|while)|end)|(else(?:if)?)|(break@)?(case|default)|(break))$/', $m[7], $mm))
{
@ -803,11 +803,11 @@ class TemplateHandler
$var = preg_replace('/^\s*\(\s*(.+?) .*$/', '$1', $m[8]);
$precheck = "if({$var}&&count({$var}))";
}
return '<?php ' . $this->_replaceVar($precheck . $m[7] . $m[8]) . '{ ?>' . $m[9];
return '<?php ' . self::_replaceVar($precheck . $m[7] . $m[8]) . '{ ?>' . $m[9];
}
if($mm[2])
{
return "<?php }{$m[7]}" . $this->_replaceVar($m[8]) . "{ ?>" . $m[9];
return "<?php }{$m[7]}" . self::_replaceVar($m[8]) . "{ ?>" . $m[9];
}
if($mm[4])
{
@ -827,7 +827,7 @@ class TemplateHandler
* @param string $path
* @return string
*/
function _getRelativeDir($path)
private function _getRelativeDir($path)
{
$_path = $path;
@ -865,7 +865,7 @@ class TemplateHandler
* @param string $php
* @return string $__Context->varname
*/
function _replaceVar($php)
private static function _replaceVar($php)
{
if(!strlen($php))
{

View file

@ -99,7 +99,6 @@ $GLOBALS['RX_AUTOLOAD_FILE_MAP'] = array_change_key_case(array(
'ModuleObject' => 'classes/module/ModuleObject.class.php',
'Object' => 'classes/object/Object.class.php',
'PageHandler' => 'classes/page/PageHandler.class.php',
'Crypto' => 'classes/security/Crypto.class.php',
'EmbedFilter' => 'classes/security/EmbedFilter.class.php',
'IpFilter' => 'classes/security/IpFilter.class.php',
'Password' => 'classes/security/Password.class.php',
@ -145,8 +144,11 @@ $GLOBALS['RX_AUTOLOAD_FILE_MAP'] = array_change_key_case(array(
'HintTableTag' => 'classes/xml/xmlquery/tags/table/HintTableTag.class.php',
'TableTag' => 'classes/xml/xmlquery/tags/table/TableTag.class.php',
'TablesTag' => 'classes/xml/xmlquery/tags/table/TablesTag.class.php',
'Bmp' => 'common/libraries/bmp.php',
'Ftp' => 'common/libraries/ftp.php',
'Tar' => 'common/libraries/tar.php',
'CryptoCompat' => 'common/libraries/cryptocompat.php',
'VendorPass' => 'common/libraries/vendorpass.php',
), CASE_LOWER);
/**

View file

@ -18,18 +18,18 @@ define('RX_TIME', intval(RX_MICROTIME));
/**
* RX_BASEDIR is the SERVER-SIDE absolute path of Rhymix (with trailing slash).
*/
define('RX_BASEDIR', dirname(__DIR__) . '/');
define('RX_BASEDIR', str_replace('\\', '/', dirname(__DIR__)) . '/');
/**
* RX_BASEURL is the CLIENT-SIDE absolute path of Rhymix (with trailing slash, relative to the document root).
*/
if (isset($_SERVER['DOCUMENT_ROOT']) && !strncmp(RX_BASEDIR, $_SERVER['DOCUMENT_ROOT'], strlen($_SERVER['DOCUMENT_ROOT'])))
if (isset($_SERVER['DOCUMENT_ROOT']) && !strncmp(RX_BASEDIR, str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), strlen($_SERVER['DOCUMENT_ROOT'])))
{
define('RX_BASEURL', rtrim(substr(RX_BASEDIR, strlen($_SERVER['DOCUMENT_ROOT'])), '/') . '/');
}
elseif (isset($_SERVER['PHP_SELF']) && ($len = strlen($_SERVER['PHP_SELF'])) && $len >= 10 && substr($_SERVER['PHP_SELF'], $len - 10) === '/index.php')
{
define('RX_BASEURL', rtrim(substr($_SERVER['PHP_SELF'], 0, $len - 10), '/') . '/');
define('RX_BASEURL', rtrim(str_replace('\\', '/', substr($_SERVER['PHP_SELF'], 0, $len - 10)), '/') . '/');
}
else
{
@ -140,3 +140,6 @@ define('LOWER', 'abcdefghijklmnopqrstuvwxyz');
define('CR', "\r");
define('CRLF', "\r\n");
define('LF', "\n");
define('FOLLOW_REQUEST_SSL', 0);
define('ENFORCE_SSL', 1);
define('RELEASE_SSL', 2);

View file

@ -6,6 +6,428 @@
* Copyright (c) Rhymix Developers and Contributors
*/
/** Get the first value of an array.
*
* @param array $array The input array
* @return mixed
*/
function array_first(array $array)
{
return reset($array);
}
/** Get the first key of an array.
*
* @param array $array The input array
* @return mixed
*/
function array_first_key(array $array)
{
reset($array);
return key($array);
}
/** Get the last value of an array.
*
* @param array $array The input array
* @return mixed
*/
function array_last(array $array)
{
return end($array);
}
/** Get the last key of an array.
*
* @param array $array The input array
* @return mixed
*/
function array_last_key(array $array)
{
end($array);
return key($array);
}
/**
* Flatten a multi-dimensional array into a one-dimensional array.
* Based on util.php <https://github.com/brandonwamboldt/utilphp>
* Contributed by Theodore R. Smith of PHP Experts, Inc. <http://www.phpexperts.pro/>
*
* @param array $array The array to flatten
* @param bool $preserve_keys Whether or not to preserve array keys (default: true)
* @return array
*/
function array_flatten(array $array, $preserve_keys = true)
{
$result = array();
array_walk_recursive($array, function($value, $key) use(&$result, $preserve_keys) {
if ($preserve_keys && !is_int($key))
{
$result[$key] = $value;
}
else
{
$result[] = $value;
}
});
return $result;
}
/**
* Get the base name of a class name (without namespaces).
* Based on Laravel helper function <http://laravel.com/docs/5.0/helpers>
*
* @param string|object $class The class name
* @return string
*/
function class_basename($class)
{
return basename(str_replace('\\', '/', is_object($class) ? get_class($class) : $class));
}
/**
* This function is a shortcut to htmlspecialchars().
*
* @param string $str The string to escape
* @param bool $double_escape Set this to false to skip symbols that are already escaped (default: true)
* @return string
*/
function escape($str, $double_escape = true)
{
$flags = defined('ENT_SUBSTITUTE') ? (ENT_QUOTES | ENT_SUBSTITUTE) : (ENT_QUOTES | ENT_IGNORE);
return htmlspecialchars($str, $flags, 'UTF-8', $double_escape);
}
/**
* This function escapes a string to be used in a CSS property.
*
* @param string $str The string to escape
* @return string
*/
function escape_css($str)
{
return preg_replace('/[^a-zA-Z0-9_.#\/-]/', '', $str);
}
/**
* This function escapes a string to be used in a JavaScript string literal.
*
* @param string $str The string to escape
* @return string
*/
function escape_js($str)
{
$flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
if (defined('JSON_UNESCAPED_UNICODE')) $flags = $flags | JSON_UNESCAPED_UNICODE;
$str = json_encode((string)$str, $flags);
return substr($str, 1, strlen($str) - 2);
}
/**
* This function escapes a string to be used in a 'single-quoted' PHP string literal.
* Null bytes are removed.
*
* @param string $str The string to escape
* @return string
*/
function escape_sqstr($str)
{
return str_replace(array('\\0', '\\"'), array('', '"'), addslashes($str));
}
/**
* This function escapes a string to be used in a "double-quoted" PHP string literal.
* Null bytes are removed.
*
* @param string $str The string to escape
* @return string
*/
function escape_dqstr($str)
{
return str_replace(array('\\0', "\\'", '$'), array('', "'", '\\$'), addslashes($str));
}
/**
* This function splits a string into an array, but allows the delimter to be escaped.
* For example, 'A|B\|C|D' will be split into 'A', 'B|C', and 'D'
* because the bar between B and C is escaped.
*
* @param string $delimiter The delimiter
* @param string $str The string to split
* @param int $limit The maximum number of items to return, 0 for unlimited (default: 0)
* @param string $escape_char The escape character (default: backslash)
* @return array
*/
function explode_with_escape($delimiter, $str, $limit = 0, $escape_char = '\\')
{
if ($limit < 1) $limit = null;
$result = array();
$split = preg_split('/(?<!' . preg_quote($escape_char, '/') . ')' . preg_quote($delimiter, '/') . '/', $str, $limit);
foreach ($split as $piece)
{
if (trim($piece) !== '')
{
$result[] = trim(str_replace($escape_char . $delimiter, $delimiter, $piece));
}
}
return $result;
}
/**
* This function returns true if $haystack starts with $needle, and false otherwise.
*
* @param string $needle The needle
* @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
* @return bool
*/
function starts_with($needle, $haystack, $case_sensitive = true)
{
if (strlen($needle) > strlen($haystack)) return false;
if ($case_sensitive)
{
return !strncmp($needle, $haystack, strlen($needle));
}
else
{
!strncasecmp($needle, $haystack, strlen($needle));
}
}
/**
* This function returns true if $haystack ends with $needle, and false otherwise.
*
* @param string $needle The needle
* @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
* @return bool
*/
function ends_with($needle, $haystack, $case_sensitive = true)
{
if (strlen($needle) > strlen($haystack)) return false;
if ($case_sensitive)
{
return (substr($haystack, -strlen($needle)) === $needle);
}
else
{
return (strtolower(substr($haystack, -strlen($needle))) === strtolower($needle));
}
}
/**
* This function returns true if $haystack contains $needle, and false otherwise.
*
* @param string $needle The needle
* @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
* @return bool
*/
function contains($needle, $haystack, $case_sensitive = true)
{
return $case_sensitive ? (strpos($haystack, $needle) !== false) : (stripos($haystack, $needle) !== false);
}
/**
* This function returns true if $needle is between $min and $max, and false otherwise.
* Non-numeric values are compared according to PHP defaults.
*
* @param mixed $needle The needle
* @param mixed $min The minimum value
* @param mixed $max The maximum value
* @param bool $exclusive Set this to true to exclude endpoints (default: false)
* @return bool
*/
function is_between($needle, $min, $max, $exclusive = false)
{
if ($exclusive)
{
return ($needle > $min && $needle < $max);
}
else
{
return ($needle >= $min && $needle <= $max);
}
}
/**
* This function restricts $input to be between $min and $max.
* All values less than $min are converted to $min, and all values greater than $max are converted to $max.
* Non-numeric values are compared according to PHP defaults.
*
* @param mixed $input The value to convert
* @param mixed $min The minimum value
* @param mixed $max The maximum value
* @return mixed
*/
function force_range($input, $min, $max)
{
if ($input < $min) $input = $min;
if ($input > $max) $input = $max;
return $input;
}
/**
* This function encodes a string with base64, using a URL-safe character set.
*
* @param string $str The string to encode
* @return string
*/
function base64_encode_urlsafe($str)
{
return strtr(rtrim(base64_encode($str), '='), '+/', '-_');
}
/**
* This function decodes a string with base64, using a URL-safe character set.
*
* @param string $str The string to decode
* @return string
*/
function base64_decode_urlsafe($str)
{
return @base64_decode(str_pad(strtr($str, '-_', '+/'), ceil(strlen($str) / 4) * 4, '=', STR_PAD_RIGHT));
}
/**
* Convert hexadecimal color codes to an array of R, G, B values.
* This function can handle both 6-digit and 3-digit notations, optionally prefixed with '#'.
* If the color code is illegal, this function will return all nulls.
*
* @param string $hex The color to convert
* @return array
*/
function hex2rgb($hex)
{
$hex = ltrim($hex, '#');
if (strlen($hex) == 3)
{
$r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
$g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
$b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
}
elseif (strlen($hex) == 6)
{
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
else
{
$r = $g = $b = null;
}
return array($r, $g, $b);
}
/**
* Convert an array of R, G, B values to hexadecimal color codes.
* If the RGB values are illegal, this function will return #000000.
*
* @param array $rgb The color to convert
* @param bool $hash_prefix Whether or not to prefix the result with '#' (default: true)
* @return string
*/
function rgb2hex(array $rgb, $hash_prefix = true)
{
if (!isset($rgb[0]) || !isset($rgb[1]) || !isset($rgb[2]) || $rgb[0] > 255 || $rgb[1] > 255 || $rgb[2] > 255)
{
return '#000000';
}
$hex = $hash_prefix ? '#' : '';
$hex .= str_pad(dechex(max(0, $rgb[0])), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex(max(0, $rgb[1])), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex(max(0, $rgb[2])), 2, '0', STR_PAD_LEFT);
return $hex;
}
/**
* This function includes another file in a clean scope.
* This is useful if the included file tries to define global variables.
*
* @param string $filename The name of the file to include
* @return mixed
*/
function include_in_clean_scope($filename)
{
return (include $filename);
}
/**
* This function includes another file while ignoring all errors inside of it.
*
* @param string $filename The name of the file to include
* @return mixed
*/
function include_and_ignore_errors($filename)
{
error_reporting(0);
$result = (include $filename);
error_reporting(~0);
return $result;
}
/**
* This function includes another file while ignoring all output.
*
* @param string $filename The name of the file to include
* @return mixed
*/
function include_and_ignore_output($filename)
{
ob_start();
$result = (include $filename);
ob_end_clean();
return $result;
}
/**
* Polyfill for hex2bin() which does not exist in PHP 5.3.
*
* @param string $hex The hexadecimal string to convert to binary
* @return string
*/
if (!function_exists('hex2bin'))
{
function hex2bin($hex)
{
if (strlen($hex) % 2) $hex = '0' . $hex;
return pack('H*', $hex);
}
}
/**
* Converts any value to either true or false.
* Based on util.php <https://github.com/brandonwamboldt/utilphp>
*
* @param string $input The input value
* @return bool
*/
function tobool($input)
{
if (preg_match('/^(1|[ty].*|on|oui|si|vrai|aye)$/i', $input)) return true;
if (preg_match('/^(0|[fn].*|off)$/i', $input)) return false;
return (bool)$input;
}
/**
* Checks if the given string contains valid UTF-8.
*
* @param string $str The input string
* @return bool
*/
function utf8_check($str)
{
if (function_exists('mb_check_encoding'))
{
return mb_check_encoding($str, 'UTF-8');
}
else
{
return ($str === @iconv('UTF-8', 'UTF-8', $str));
}
}
/**
* Encode UTF-8 characters outside of the Basic Multilingual Plane in the &#xxxxxx format.
* This allows emoticons and other characters to be stored in MySQL without utf8mb4 support.
@ -21,3 +443,28 @@ function utf8_mbencode($str)
return '&#x' . dechex($codepoint) . ';';
}, $str);
}
/**
* This function replaces all whitespace characters with a single regular space (0x20).
* Unicode whitespace characters are also replaced.
*
* @param string $str The input string
* @param bool $multiline Set this to true to permit newlines inside the string (default: false)
* @return string
*/
function utf8_normalize_spaces($str, $multiline = false)
{
return $multiline ? preg_replace('/((?!\x0A)[\pZ\pC])+/u', ' ', $str) : preg_replace('/[\pZ\pC]+/u', ' ', $str);
}
/**
* This function trims all space from the beginning and end of a string.
* Unicode whitespace characters are also trimmed.
*
* @param string $str The input string
* @return string
*/
function utf8_trim($str)
{
return preg_replace('/^[\s\pZ\pC]+|[\s\pZ\pC]+$/u', '', $str);
}

View file

@ -457,9 +457,7 @@ function getFullSiteUrl()
*/
function getCurrentPageUrl()
{
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return htmlspecialchars($url, ENT_COMPAT, 'UTF-8', FALSE);
return escape((RX_SSL ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}
/**
@ -1179,63 +1177,17 @@ function removeSrcHack($match)
return "<{$match[1]}{$tag}{$attr}{$match[4]}>";
}
// convert hexa value to RGB
if(!function_exists('hexrgb'))
{
/**
/**
* Convert hexa value to RGB
*
* @param string $hexstr
* @return array
*/
if(!function_exists('hexrgb'))
{
function hexrgb($hex)
{
$hex = ltrim($hex, '#');
if(strlen($hex) == 3)
{
$r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
$g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
$b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
}
elseif(strlen($hex) == 6)
{
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
else
{
$r = $g = $b = null;
}
return array('red' => $r, 'green' => $g, 'blue' => $b, 'r' => $r, 'g' => $g, 'b' => $b);
}
}
// convert RGB value to hexa
if(!function_exists('rgbhex'))
{
/**
* convert RGB value to hexa
*
* @param array $rgb
* @param bool $hash_prefix
* @return string
*/
function rgbhex(array $rgb, $hash_prefix = true)
{
if(!isset($rgb['r']) && !isset($rgb['g']) && !isset($rgb['b']) && count($rgb) >= 3)
{
list($rgb['r'], $rgb['g'], $rgb['b']) = $rgb;
}
if(!isset($rgb['r']) || !isset($rgb['g']) || !isset($rgb['b']) || $rgb['r'] > 255 || $rgb['g'] > 255 || $rgb['b'] > 255)
{
return '#000000';
}
$hex = $hash_prefix ? '#' : '';
$hex .= str_pad(dechex(max(0, $rgb['r'])), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex(max(0, $rgb['g'])), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex(max(0, $rgb['b'])), 2, '0', STR_PAD_LEFT);
return $hex;
return hex2rgb($hex);
}
}
@ -1249,36 +1201,7 @@ if(!function_exists('rgbhex'))
*/
function mysql_pre4_hash_password($password)
{
$nr = 1345345333;
$add = 7;
$nr2 = 0x12345671;
settype($password, "string");
for($i = 0; $i < strlen($password); $i++)
{
if($password[$i] == ' ' || $password[$i] == '\t')
{
continue;
}
$tmp = ord($password[$i]);
$nr ^= ((($nr & 63) + $add) * $tmp) + ($nr << 8);
$nr2 += ($nr2 << 8) ^ $nr;
$add += $tmp;
}
$result1 = sprintf("%08lx", $nr & ((1 << 31) - 1));
$result2 = sprintf("%08lx", $nr2 & ((1 << 31) - 1));
if($result1 == '80000000')
{
$nr += 0x80000000;
}
if($result2 == '80000000')
{
$nr2 += 0x80000000;
}
return sprintf("%08lx%08lx", $nr, $nr2);
return VendorPass::mysql_old_password($password);
}
/**
@ -1288,12 +1211,7 @@ function mysql_pre4_hash_password($password)
*/
function getScriptPath()
{
static $url = NULL;
if($url == NULL)
{
$url = str_ireplace('/tools/', '/', preg_replace('/index.php$/i', '', str_replace('\\', '/', $_SERVER['SCRIPT_NAME'])));
}
return $url;
return RX_BASEURL;
}
/**

257
common/libraries/bmp.php Normal file
View file

@ -0,0 +1,257 @@
<?php
// Read 1,4,8,24,32bit BMP files
// Save 24bit BMP files
// Author: de77
// Licence: MIT
// Webpage: de77.com
// Article about this class: http://de77.com/php/read-and-write-bmp-in-php-imagecreatefrombmp-imagebmp
// First-version: 07.02.2010
// Version: 21.08.2010
// Modified by Kijin Sung, April 6, 2013: Remove die() and global functions
class BMP
{
public static function imagebmp(&$img, $filename = false)
{
$wid = imagesx($img);
$hei = imagesy($img);
$wid_pad = str_pad('', $wid % 4, "\0");
$size = 54 + ($wid + $wid_pad) * $hei * 3; //fixed
//prepare & save header
$header['identifier'] = 'BM';
$header['file_size'] = self::dword($size);
$header['reserved'] = self::dword(0);
$header['bitmap_data'] = self::dword(54);
$header['header_size'] = self::dword(40);
$header['width'] = self::dword($wid);
$header['height'] = self::dword($hei);
$header['planes'] = self::word(1);
$header['bits_per_pixel'] = self::word(24);
$header['compression'] = self::dword(0);
$header['data_size'] = self::dword(0);
$header['h_resolution'] = self::dword(0);
$header['v_resolution'] = self::dword(0);
$header['colors'] = self::dword(0);
$header['important_colors'] = self::dword(0);
if ($filename)
{
$f = fopen($filename, "wb");
foreach ($header AS $h)
{
fwrite($f, $h);
}
//save pixels
for ($y=$hei-1; $y>=0; $y--)
{
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
fwrite($f, byte3($rgb));
}
fwrite($f, $wid_pad);
}
fclose($f);
}
else
{
foreach ($header AS $h)
{
echo $h;
}
//save pixels
for ($y=$hei-1; $y>=0; $y--)
{
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
echo self::byte3($rgb);
}
echo $wid_pad;
}
}
}
public static function getimagesize($filename)
{
$f = fopen($filename, "rb");
//read header
$header = fread($f, 54);
$header = unpack( 'c2identifier/Vfile_size/Vreserved/Vbitmap_data/Vheader_size/' .
'Vwidth/Vheight/vplanes/vbits_per_pixel/Vcompression/Vdata_size/'.
'Vh_resolution/Vv_resolution/Vcolors/Vimportant_colors', $header);
if ($header['identifier1'] != 66 or $header['identifier2'] != 77)
{
return false;
}
if (!in_array($header['bits_per_pixel'], array(24, 32, 8, 4, 1)))
{
return false;
}
$bps = $header['bits_per_pixel']; //bits per pixel
$wid2 = ceil(($bps/8 * $header['width']) / 4) * 4;
$colors = pow(2, $bps);
$wid = $header['width'];
$hei = $header['height'];
return array($wid, $hei, 'BMP');
}
public static function imagecreatefrombmp($filename)
{
$f = fopen($filename, "rb");
//read header
$header = fread($f, 54);
$header = unpack( 'c2identifier/Vfile_size/Vreserved/Vbitmap_data/Vheader_size/' .
'Vwidth/Vheight/vplanes/vbits_per_pixel/Vcompression/Vdata_size/'.
'Vh_resolution/Vv_resolution/Vcolors/Vimportant_colors', $header);
if ($header['identifier1'] != 66 or $header['identifier2'] != 77)
{
return false;
}
if (!in_array($header['bits_per_pixel'], array(24, 32, 8, 4, 1)))
{
return false;
}
$bps = $header['bits_per_pixel']; //bits per pixel
$wid2 = ceil(($bps/8 * $header['width']) / 4) * 4;
$colors = pow(2, $bps);
$wid = $header['width'];
$hei = $header['height'];
$img = imagecreatetruecolor($header['width'], $header['height']);
//read palette
if ($bps < 9)
{
for ($i=0; $i<$colors; $i++)
{
$palette[] = self::undword(fread($f, 4));
}
}
else
{
if ($bps == 32)
{
imagealphablending($img, false);
imagesavealpha($img, true);
}
$palette = array();
}
//read pixels
for ($y=$hei-1; $y>=0; $y--)
{
$row = fread($f, $wid2);
$pixels = self::str_split2($row, $bps, $palette);
for ($x=0; $x<$wid; $x++)
{
self::makepixel($img, $x, $y, $pixels[$x], $bps);
}
}
fclose($f);
return $img;
}
private static function str_split2($row, $bps, $palette)
{
switch ($bps)
{
case 32:
case 24: return str_split($row, $bps/8);
case 8: $out = array();
$count = strlen($row);
for ($i=0; $i<$count; $i++)
{
$out[] = $palette[ ord($row[$i]) ];
}
return $out;
case 4: $out = array();
$count = strlen($row);
for ($i=0; $i<$count; $i++)
{
$roww = ord($row[$i]);
$out[] = $palette[ ($roww & 240) >> 4 ];
$out[] = $palette[ ($roww & 15) ];
}
return $out;
case 1: $out = array();
$count = strlen($row);
for ($i=0; $i<$count; $i++)
{
$roww = ord($row[$i]);
$out[] = $palette[ ($roww & 128) >> 7 ];
$out[] = $palette[ ($roww & 64) >> 6 ];
$out[] = $palette[ ($roww & 32) >> 5 ];
$out[] = $palette[ ($roww & 16) >> 4 ];
$out[] = $palette[ ($roww & 8) >> 3 ];
$out[] = $palette[ ($roww & 4) >> 2 ];
$out[] = $palette[ ($roww & 2) >> 1 ];
$out[] = $palette[ ($roww & 1) ];
}
return $out;
}
}
private static function makepixel($img, $x, $y, $str, $bps)
{
switch ($bps)
{
case 32 : $a = ord($str[0]);
$b = ord($str[1]);
$c = ord($str[2]);
$d = 256 - ord($str[3]); //TODO: gives imperfect results
$pixel = $d*256*256*256 + $c*256*256 + $b*256 + $a;
imagesetpixel($img, $x, $y, $pixel);
break;
case 24 : $a = ord($str[0]);
$b = ord($str[1]);
$c = ord($str[2]);
$pixel = $c*256*256 + $b*256 + $a;
imagesetpixel($img, $x, $y, $pixel);
break;
case 8 :
case 4 :
case 1 : imagesetpixel($img, $x, $y, $str);
break;
}
}
private static function byte3($n)
{
return chr($n & 255) . chr(($n >> 8) & 255) . chr(($n >> 16) & 255);
}
private static function undword($n)
{
$r = unpack("V", $n);
return $r[1];
}
private static function dword($n)
{
return pack("V", $n);
}
private static function word($n)
{
return pack("v", $n);
}
}

View file

@ -0,0 +1,129 @@
<?php
/**
* This class uses mcrypt to perform encryption and decryption in a way
* that is fully compatible with https://github.com/defuse/php-encryption
*/
class CryptoCompat
{
// Default configuration
const ENCRYPTION_ALGO = 'aes-128';
const ENCRYPTION_MODE = 'cbc';
const ENCRYPTION_BLOCK_SIZE = 16;
const ENCRYPTION_KEY_SIZE = 16;
const ENCRYPTION_KEY_INFO = 'DefusePHP|KeyForEncryption';
const ENCRYPTION_MAC_ALGO = 'sha256';
const ENCRYPTION_MAC_SIZE = 32;
const ENCRYPTION_MAC_INFO = 'DefusePHP|KeyForAuthentication';
// Encrypt method
public static function encrypt($plaintext, $key)
{
// Generate subkey for encryption
$enc_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_KEY_INFO);
// Generate IV
$iv = self::_createIV();
// Encrypt the plaintext
$mcrypt_method = str_replace('aes', 'rijndael', self::ENCRYPTION_ALGO);
$plaintext = self::_applyPKCS7Padding($plaintext, self::ENCRYPTION_BLOCK_SIZE);
$ciphertext = mcrypt_encrypt($mcrypt_method, $enc_key, $plaintext, self::ENCRYPTION_MODE, $iv);
// Generate MAC
$mac_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_MAC_INFO);
$mac = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($iv . $ciphertext), $mac_key, true);
// Return the MAC, IV, and ciphertext
return $mac . $iv . $ciphertext;
}
// Decrypt method
public static function decrypt($ciphertext, $key)
{
// Extract MAC and IV from the remainder of the ciphertext
$mac = substr($ciphertext, 0, self::ENCRYPTION_MAC_SIZE);
$iv = substr($ciphertext, self::ENCRYPTION_MAC_SIZE, self::ENCRYPTION_BLOCK_SIZE);
$ciphertext = substr($ciphertext, self::ENCRYPTION_MAC_SIZE + self::ENCRYPTION_BLOCK_SIZE);
// Validate MAC
$mac_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_MAC_INFO);
$mac_compare = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($iv . $ciphertext), $mac_key, true);
if (!Password::strcmpConstantTime($mac, $mac_compare))
{
return false;
}
// Generate subkey for encryption
$enc_key = self::_defuseCompatibleHKDF($key, self::ENCRYPTION_KEY_INFO);
// Decrypt the ciphertext
$mcrypt_method = str_replace('aes', 'rijndael', self::ENCRYPTION_ALGO);
$plaintext = @mcrypt_decrypt($mcrypt_method, $enc_key, $ciphertext, self::ENCRYPTION_MODE, $iv);
if ($plaintext === false)
{
return false;
}
$plaintext = self::_stripPKCS7Padding($plaintext, self::ENCRYPTION_BLOCK_SIZE);
if ($plaintext === false)
{
return false;
}
// Return the plaintext
return $plaintext;
}
/**
* @brief Create an IV
* @return string
*/
protected static function _createIV()
{
return hex2bin(Password::createSecureSalt(self::ENCRYPTION_BLOCK_SIZE * 2, 'hex'));
}
/**
* @brief Apply PKCS#7 padding to a string
* @param string $str The string
* @param int $block_size The block size
* @return string
*/
protected static function _applyPKCS7Padding($str, $block_size)
{
$padding_size = $block_size - (strlen($str) % $block_size);
if ($padding_size === 0) $padding_size = $block_size;
return $str . str_repeat(chr($padding_size), $padding_size);
}
/**
* @brief Remove PKCS#7 padding from a string
* @param string $str The string
* @param int $block_size The block size
* @return string
*/
protected static function _stripPKCS7Padding($str, $block_size)
{
if (strlen($str) % $block_size !== 0) return false;
$padding_size = ord(substr($str, -1));
if ($padding_size < 1 || $padding_size > $block_size) return false;
if (substr($str, (-1 * $padding_size)) !== str_repeat(chr($padding_size), $padding_size)) return false;
return substr($str, 0, strlen($str) - $padding_size);
}
/**
* @brief HKDF function compatible with defuse/php-encryption
* @return string
*/
protected static function _defuseCompatibleHKDF($key, $info)
{
$salt = str_repeat("\x00", self::ENCRYPTION_MAC_SIZE);
$prk = hash_hmac(self::ENCRYPTION_MAC_ALGO, $key, $salt, true);
$t = $last_block = '';
for ($block_index = 1; strlen($t) < self::ENCRYPTION_KEY_SIZE; $block_index++)
{
$t .= $last_block = hash_hmac(self::ENCRYPTION_MAC_ALGO, ($last_block . $info . chr($block_index)), $prk, true);
}
return substr($t, 0, self::ENCRYPTION_KEY_SIZE);
}
}

View file

@ -0,0 +1,150 @@
<?php
// PHP implementation of several vendor-specific password hashing functions.
class VendorPass
{
// MySQL's OLD_PASSWORD() function.
// Minor modification of the code written by Dustin Fineout, 10/9/2009
// Source: http://stackoverflow.com/questions/260236/mysql-hashing-function-implementation
public static function mysql_old_password($password)
{
$password = strval($password);
$length = strlen($password);
$nr1 = 0x50305735; $nr2 = 0x12345671; $add = 7; $tmp = null;
for ($i = 0; $i < $length; $i++) {
$byte = substr($password, $i, 1);
if ($byte === ' ' || $byte === "\t") continue;
$tmp = ord($byte);
$nr1 ^= (($nr1 << 8) & 0x7FFFFFFF) + ((($nr1 & 63) + $add) * $tmp);
$nr2 += (($nr2 << 8) & 0x7FFFFFFF) ^ $nr1;
$add += $tmp;
}
return sprintf("%08x%08x", $nr1 & 0x7FFFFFFF, $nr2 & 0x7FFFFFFF);
}
// MySQL's PASSWORD() function.
public static function mysql_new_password($password)
{
return '*' . strtoupper(sha1(sha1($password, true)));
}
// MS SQL Server's PWDENCRYPT() function.
public static function mssql_pwdencrypt($password, $salt = null)
{
if ($salt !== null && strlen($salt) === 54)
{
$salt = substr($salt, 6, 8);
}
else
{
$salt = strtoupper(str_pad(dechex(mt_rand(0, 65535)), 4, '0') .
str_pad(dechex(mt_rand(0, 65535)), 4, '0'));
}
$password = mb_convert_encoding($password, 'UTF-16LE', 'UTF-8');
return '0x0100' . strtoupper($salt . sha1($password . pack('H*', $salt)));
}
// Drupal's SHA512-based password hashing algorithm.
public static function drupal($password, $salt = null)
{
$itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($salt !== null && strlen($salt) > 12)
{
$iterations = intval(strpos($itoa64, substr($salt, 3, 1)));
$salt = substr($salt, 4, 8);
}
else
{
$iterations = 15;
$salt = Password::createSecureSalt(8, 'hex');
}
$count = 1 << $iterations;
$hash = hash('sha512', $salt . $password, true);
do
{
$hash = hash('sha512', $hash . $password, true);
} while (--$count);
$hash = self::drupal_base64($hash, strlen($hash), $itoa64);
return substr('$S$' . $itoa64[$iterations] . $salt . $hash, 0, 55);
}
// Drupal's own Base64 implementation.
protected static function drupal_base64($input, $count, $chars)
{
$output = '';
$i = 0;
do
{
$value = ord($input[$i++]);
$output .= $chars[$value & 0x3f];
if ($i < $count) $value |= ord($input[$i]) << 8;
$output .= $chars[($value >> 6) & 0x3f];
if ($i++ >= $count) break;
if ($i < $count) $value |= ord($input[$i]) << 16;
$output .= $chars[($value >> 12) & 0x3f];
if ($i++ >= $count) break;
$output .= $chars[($value >> 18) & 0x3f];
} while ($i < $count);
return $output;
}
// Joomla's MD5-based password hashing algorithm.
public static function joomla($password, $salt = null)
{
if ($salt !== null && strlen($salt) > 33)
{
$salt = substr($salt, 33);
}
else
{
$salt = Password::createSecureSalt(32, 'hex');
}
return md5($password . $salt) . ':' . $salt;
}
// KimsQ Rb's algorithms.
public static function kimsqrb($password, $salt = null)
{
if (preg_match('/(\$[1-4])\$([0-9]{14})$/', $salt, $matches))
{
$date = '$' . $matches[2];
$fakesalt = substr(base64_encode(substr($date, 1) . 'salt'), 0, 22);
switch ($matches[1])
{
case '$1': return self::password_hash($password, 1, ['cost' =>10, 'salt' => $fakesalt]) . '$1' . $date;
case '$2': return hash('sha512', $password . $fakesalt) . '$2' . $date;
case '$3': return hash('sha256', $password . $fakesalt) . '$3' . $date;
case '$4': return md5(sha1(md5($password . $fakesalt))) . '$4' . $date;
}
}
$date = '$' . date('YmdHis');
$fakesalt = substr(base64_encode(substr($date, 1) . 'salt'), 0, 22);
return self::password_hash($password, 1, ['cost' =>10, 'salt' => $fakesalt]) . '$1' . $date;
}
// Bcrypt wrapper for PHP 5.4.
public static function password_hash($password, $algo = 1, $options = [])
{
if (!isset($options['salt']) || !preg_match('/^[0-9a-zA-Z\.\/]{22,}$/', $options['salt']))
{
$options['salt'] = Password::createSecureSalt(22, 'alnum');
}
if (!isset($options['cost']) || $options['cost'] < 4 || $options['cost'] > 31)
{
$options['cost'] = 10;
}
$salt = '$2y$' . sprintf('%02d', $options['cost']) . '$' . $options['salt'];
return @crypt($password, $salt);
}
}

View file

@ -63,8 +63,7 @@ class image_link extends EditorHandler
if(substr($src, 0,2)=='./') $src = Context::getRequestUri().substr($src, 2);
else if(substr($src , 0, 1)=='/')
{
if($_SERVER['HTTPS']=='on') $http_src = 'https://';
else $http_src = 'http://';
$http_src = RX_SSL ? 'https://' : 'http://';
$src = $http_src.$_SERVER['HTTP_HOST'].$src;
}
else if(!strpos($temp_src[0],':') && $src) $src = Context::getRequestUri().$src;

View file

@ -153,7 +153,7 @@ class installView extends install
Context::set('progressMenu', '4');
$error_return_url = getNotEncodedUrl('', 'act', Context::get('act'), 'db_type', Context::get('db_type'));
if($_SERVER['HTTPS'] == 'on')
if(RX_SSL)
{
// Error occured when using https protocol at "ModuleHandler::init() '
$parsedUrl = parse_url($error_return_url);
@ -182,7 +182,7 @@ class installView extends install
include _XE_PATH_.'files/config/tmpDB.config.php';
Context::set('use_rewrite', $_SESSION['use_rewrite']);
Context::set('use_ssl', $_SERVER['HTTPS'] === 'on' ? 'always' : 'none');
Context::set('use_ssl', RX_SSL ? 'always' : 'none');
Context::set('time_zone', $GLOBALS['time_zone']);
Context::set('db_type', $db_info->db_type);
$this->setTemplateFile('admin_form');

View file

@ -157,8 +157,7 @@ class rssView extends rss
break;
}
if($_SERVER['HTTPS']=='on') $proctcl = 'https://';
else $proctcl = 'http://';
$proctcl = RX_SSL ? 'https://' : 'http://';
$temp_link = explode('/', $info->link);
if($temp_link[0]=='' && $info->link)