merge from 1.5.3 (~r10943)

git-svn-id: http://xe-core.googlecode.com/svn/trunk@10951 201d5d3c-b55e-5fd7-737f-ddc643e51545
This commit is contained in:
flyskyko 2012-07-27 02:47:10 +00:00
parent 7aa4798373
commit 54e3a72065
334 changed files with 13011 additions and 5561 deletions

View file

@ -10,6 +10,9 @@
if(!class_exists('AddonCaptcha')) if(!class_exists('AddonCaptcha'))
{ {
// On the mobile mode, XE Core does not load jquery and xe.js as normal.
Context::loadFile(array('./common/js/jquery.min.js','head', NULL,-100000),true);
Context::loadFile(array('./common/js/xe.min.js','head', NULL,-100000),true);
class AddonCaptcha class AddonCaptcha
{ {
var $addon_info; var $addon_info;
@ -31,6 +34,7 @@
$logged_info = Context::get('logged_info'); $logged_info = Context::get('logged_info');
if($logged_info->is_admin == 'Y' || $logged_info->is_site_admin) return false; if($logged_info->is_admin == 'Y' || $logged_info->is_site_admin) return false;
if($this->addon_info->target != 'all' && Context::get('is_logged')) return false; if($this->addon_info->target != 'all' && Context::get('is_logged')) return false;
if($_SESSION['XE_VALIDATOR_ERROR'] == -1) $_SESSION['captcha_authed'] = false;
if($_SESSION['captcha_authed']) return false; if($_SESSION['captcha_authed']) return false;
$type = Context::get('captchaType'); $type = Context::get('captchaType');
@ -54,7 +58,7 @@
} }
} else { } else {
Context::addHtmlHeader('<script type="text/javascript"> var captchaTargetAct = new Array("'.implode('","',$target_acts).'"); </script>'); Context::addHtmlHeader('<script type="text/javascript"> var captchaTargetAct = new Array("'.implode('","',$target_acts).'"); </script>');
Context::loadFile(array('./addons/captcha/captcha.js', 'body', '', null), true); Context::loadFile(array('./addons/captcha/captcha.min.js', 'body', '', null), true);
} }
} }
@ -286,7 +290,7 @@
$this->createKeyword(); $this->createKeyword();
$swfURL = getUrl().'addons/captcha/swf/play.swf'; $swfURL = getUrl().'addons/captcha/swf/play.swf';
Context::unloadFile('./addons/captcha/captcha.js'); Context::unloadFile('./addons/captcha/captcha.min.js');
Context::loadFile(array('./addons/captcha/inline_captcha.js','body')); Context::loadFile(array('./addons/captcha/inline_captcha.js','body'));
global $lang; global $lang;

View file

@ -80,7 +80,9 @@ var calledArgs = null;
captchaXE = $('<div id="captcha_layer" style="position:fixed; top:0; left:0; width:100%; height:100%;display:none;z-index:10">').appendTo(document.body); captchaXE = $('<div id="captcha_layer" style="position:fixed; top:0; left:0; width:100%; height:100%;display:none;z-index:10">').appendTo(document.body);
var $div = $('<div style="z-index:1000;position:absolute; width:310px; margin:-105px 0 0 -105px; top:50%; left:50%; background:#fff; border:3px solid #ccc;">'+ var top_left = 'margin:-105px 0 0 -105px; top:50%; left:50%;';
if(screen.width<480) { top_left = ''; }
var $div = $('<div style="z-index:1000;position:absolute; width:310px;' + top_left + ' background:#fff; border:3px solid #ccc;">'+
'<form method="post" action="">'+ '<form method="post" action="">'+
'<div style="position:relative; margin:25px 20px 15px 20px">'+ '<div style="position:relative; margin:25px 20px 15px 20px">'+
'<img src="about:blank" id="captcha_image" alt="CAPTCHA" width="240" height="50" style="display:block; width:240px; height:50px; border:1px solid #b0b0b0" />'+ '<img src="about:blank" id="captcha_image" alt="CAPTCHA" width="240" height="50" style="display:block; width:240px; height:50px; border:1px solid #b0b0b0" />'+

File diff suppressed because one or more lines are too long

View file

@ -4,7 +4,7 @@ if(!defined('__XE__')) exit();
/** /**
* @file member_communication.addon.php * @file member_communication.addon.php
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief Promote user communication * @brief Promote user communication
* *
* - Pop-up the message if new message comes in * - Pop-up the message if new message comes in
* - When calling MemberModel::getMemberMenu, feature to send a message is added * - When calling MemberModel::getMemberMenu, feature to send a message is added
@ -46,7 +46,7 @@ if($called_position == 'before_module_init' && $this->module != 'member') {
$mid = Context::get('cur_mid'); $mid = Context::get('cur_mid');
// Creates communication model object // Creates communication model object
$oCommunicationModel = &getModel('communication'); $oCommunicationModel = &getModel('communication');
// Add a feature to display own message box. // Add a feature to display own message box.
if($logged_info->member_srl == $member_srl) { if($logged_info->member_srl == $member_srl) {
// Add your own viewing Note Template // Add your own viewing Note Template
$oMemberController->addMemberPopupMenu(getUrl('','mid',$mid,'act','dispCommunicationMessages'), 'cmd_view_message_box', '', 'self'); $oMemberController->addMemberPopupMenu(getUrl('','mid',$mid,'act','dispCommunicationMessages'), 'cmd_view_message_box', '', 'self');
@ -55,7 +55,7 @@ if($called_position == 'before_module_init' && $this->module != 'member') {
// If not, Add menus to send message and to add friends // If not, Add menus to send message and to add friends
} else { } else {
// Get member information // Get member information
$oMemberModel = &getModel('member'); $oMemberModel = &getModel('member');
$target_member_info = $oMemberModel->getMemberInfoByMemberSrl($member_srl); $target_member_info = $oMemberModel->getMemberInfoByMemberSrl($member_srl);
if(!$target_member_info->member_srl) return; if(!$target_member_info->member_srl) return;
// Get logged-in user information // Get logged-in user information

View file

@ -5,6 +5,10 @@ window.xeNotifyMessage = function(text, count){
if(!$bar.length) { if(!$bar.length) {
$bar = $('<div class="message info" />') $bar = $('<div class="message info" />')
.hide() .hide()
.css({
'position' : 'absolute',
'z-index' : '100',
})
.prependTo(document.body); .prependTo(document.body);
} }
text = text.replace('%d', count); text = text.replace('%d', count);
@ -13,6 +17,6 @@ window.xeNotifyMessage = function(text, count){
// hide after 10 seconds // hide after 10 seconds
setTimeout(function(){ setTimeout(function(){
$bar.slideUp(); $bar.slideUp();
}, 10000); }, 5000);
}; };
})(jQuery); })(jQuery);

View file

@ -17,7 +17,7 @@ if($called_position != "before_display_content" || Context::get('act')=='dispPag
// Include a file having functions to replace member image name/mark // Include a file having functions to replace member image name/mark
require_once('./addons/member_extra_info/member_extra_info.lib.php'); require_once('./addons/member_extra_info/member_extra_info.lib.php');
// 1. Find a part <div class="member_MemberSerialNumber"> content </div> in the output document, change it to image name/mark by using MemberController::transImageName() // 1. Find a part <div class="member_MemberSerialNumber"> content </div> in the output document, change it to image name/mark by using MemberController::transImageName()
$temp_output = preg_replace_callback('!<(div|span|a)([^\>]*)member_([0-9]+)([^\>]*)>([^\<]*)\<\/(div|span|a)\>!is', 'memberTransImageName', $output); $temp_output = preg_replace_callback('!<(div|span|a)([^\>]*)member_([0-9]+)([^\>]*)>(.*?)\<\/(div|span|a)\>!is', 'memberTransImageName', $output);
if($temp_output) $output = $temp_output; if($temp_output) $output = $temp_output;
unset($temp_output); unset($temp_output);
?> ?>

View file

@ -13,7 +13,7 @@ if($called_position != "before_display_content" || Context::get('act')=='dispPag
require_once('./addons/point_level_icon/point_level_icon.lib.php'); require_once('./addons/point_level_icon/point_level_icon.lib.php');
$temp_output = preg_replace_callback('!<(div|span|a)([^\>]*)member_([0-9\-]+)([^\>]*)>([^\<]*)\<\/(div|span|a)\>!is', 'pointLevelIconTrans', $output); $temp_output = preg_replace_callback('!<(div|span|a)([^\>]*)member_([0-9\-]+)([^\>]*)>(.*?)\<\/(div|span|a)\>!is', 'pointLevelIconTrans', $output);
if($temp_output) $output = $temp_output; if($temp_output) $output = $temp_output;
unset($temp_output); unset($temp_output);
?> ?>

View file

@ -1,14 +1,22 @@
<?php <?php
/** /**
* @class CacheApc * Cache class for APC
*
* @author NHN (developer@xpressengine.com) * @author NHN (developer@xpressengine.com)
* @brief APC Handler
* @version 0.1
**/ **/
class CacheApc extends CacheBase { class CacheApc extends CacheBase {
/**
* Default valid time
* @var int
*/
var $valid_time = 36000; var $valid_time = 36000;
/**
* Get instance of CacheApc
*
* @param void $opt Not used
* @return CacheApc instance of CacheApc
*/
function getInstance($opt=null){ function getInstance($opt=null){
if(!$GLOBALS['__CacheApc__']) { if(!$GLOBALS['__CacheApc__']) {
$GLOBALS['__CacheApc__'] = new CacheApc(); $GLOBALS['__CacheApc__'] = new CacheApc();
@ -16,18 +24,46 @@ class CacheApc extends CacheBase {
return $GLOBALS['__CacheApc__']; return $GLOBALS['__CacheApc__'];
} }
/**
* Constructor
*
* @return void
*/
function CacheApc(){ function CacheApc(){
} }
/**
* Return whether support or not support cache
*
* @return bool Return true on support or false on not support
*/
function isSupport(){ function isSupport(){
return function_exists('apc_add'); return function_exists('apc_add');
} }
/**
* Cache a variable in the data store
*
* @param string $key Store the variable using this name. $key are cache-unique, so storing a second value with the same $key will overwrite the original value.
* @param mixed $buff The variable to store
* @param int $valid_time Time To Live; store $buff in the cache for ttl seconds.
* After the ttl has passed., the stored variable will be expunged from the cache (on the next request).
* If no ttl is supplied, use the default valid time CacheApc::valid_time.
* @return bool Returns true on success or false on failure.
*/
function put($key, $buff, $valid_time = 0){ function put($key, $buff, $valid_time = 0){
if($valid_time == 0) $valid_time = $this->valid_time; if($valid_time == 0) $valid_time = $this->valid_time;
return apc_store(md5(_XE_PATH_.$key), array(time(), $buff), $valid_time); return apc_store(md5(_XE_PATH_.$key), array(time(), $buff), $valid_time);
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, the data is invalid.
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time = 0) { function isValid($key, $modified_time = 0) {
$_key = md5(_XE_PATH_.$key); $_key = md5(_XE_PATH_.$key);
$obj = apc_fetch($_key, $success); $obj = apc_fetch($_key, $success);
@ -42,6 +78,14 @@ class CacheApc extends CacheBase {
return true; return true;
} }
/**
* Fetch a stored variable from the cache
*
* @param string $key The $key used to store the value.
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, return false.
* @return false|mixed Return false on failure or older then modified time. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0) { function get($key, $modified_time = 0) {
$_key = md5(_XE_PATH_.$key); $_key = md5(_XE_PATH_.$key);
$obj = apc_fetch($_key, $success); $obj = apc_fetch($_key, $success);
@ -55,15 +99,31 @@ class CacheApc extends CacheBase {
return $obj[1]; return $obj[1];
} }
/**
* Delete variable from the cache(private)
*
* @param string $_key Used to store the value.
* @return void
*/
function _delete($_key) { function _delete($_key) {
$this->put($_key,null,1); $this->put($_key,null,1);
} }
/**
* Delete variable from the cache
*
* @param string $key Used to store the value.
* @return void
*/
function delete($key) { function delete($key) {
$_key = md5(_XE_PATH_.$key); $this->_delete($key);
$this->_delete($_key);
} }
/**
* Truncate all existing variables at the cache
*
* @return bool Returns true on success or false on failure.
*/
function truncate() { function truncate() {
return apc_clear_cache('user'); return apc_clear_cache('user');
} }

View file

@ -1,15 +1,29 @@
<?php <?php
/** /**
* @class CacheFile * Cache class for file
*
* Filedisk Cache Handler
*
* @author Arnia Software (xe_dev@arnia.ro) * @author Arnia Software (xe_dev@arnia.ro)
* @brief Filedisk Cache Handler
* @version 0.1
**/ **/
class CacheFile extends CacheBase { class CacheFile extends CacheBase {
/**
* Default valid time
* @var int
*/
var $valid_time = 36000; var $valid_time = 36000;
/**
* Path that value to stored
* @var string
*/
var $cache_dir = 'files/cache/store/'; var $cache_dir = 'files/cache/store/';
/**
* Get instance of CacheFile
*
* @return CacheFile instance of CacheFile
*/
function getInstance(){ function getInstance(){
if(!$GLOBALS['__CacheFile__']) { if(!$GLOBALS['__CacheFile__']) {
$GLOBALS['__CacheFile__'] = new CacheFile(); $GLOBALS['__CacheFile__'] = new CacheFile();
@ -17,25 +31,56 @@ class CacheFile extends CacheBase {
return $GLOBALS['__CacheFile__']; return $GLOBALS['__CacheFile__'];
} }
/**
* Constructor
*
* @return void
*/
function CacheFile(){ function CacheFile(){
$this->cache_dir = _XE_PATH_ . $this->cache_dir; $this->cache_dir = _XE_PATH_ . $this->cache_dir;
if(!is_dir($this->cache_dir)) FileHandler::makeDir($this->cache_dir); if(!is_dir($this->cache_dir)) FileHandler::makeDir($this->cache_dir);
} }
/**
* Get cache file name by key
*
* @param string $key The key that will be associated with the item.
* @return string Returns cache file path
*/
function getCacheFileName($key){ function getCacheFileName($key){
return $this->cache_dir . str_replace(':', '_', $key); return $this->cache_dir . str_replace(':', '_', $key);
} }
/**
* Return whether support or not support cache
*
* @return true
*/
function isSupport(){ function isSupport(){
return true; return true;
} }
/**
* Cache a variable in the data store
*
* @param string $key Store the variable using this name.
* @param mixed $obj The variable to store
* @param int $valid_time Not used
* @return void
*/
function put($key, $obj, $valid_time = 0){ function put($key, $obj, $valid_time = 0){
$cache_file = $this->getCacheFileName($key); $cache_file = $this->getCacheFileName($key);
$text = serialize($obj); $text = serialize($obj);
FileHandler::writeFile($cache_file, $text); FileHandler::writeFile($cache_file, $text);
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Not used
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time = 0) { function isValid($key, $modified_time = 0) {
$cache_file = $this->getCacheFileName($key); $cache_file = $this->getCacheFileName($key);
if(file_exists($cache_file)) return true; if(file_exists($cache_file)) return true;
@ -43,6 +88,13 @@ class CacheFile extends CacheBase {
return false; return false;
} }
/**
* Fetch a stored variable from the cache
*
* @param string $key The $key used to store the value.
* @param int $modified_time Not used
* @return false|mixed Return false on failure. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0) { function get($key, $modified_time = 0) {
$cache_file = $this->getCacheFileName($key); $cache_file = $this->getCacheFileName($key);
$content = FileHandler::readFile($cache_file); $content = FileHandler::readFile($cache_file);
@ -51,15 +103,32 @@ class CacheFile extends CacheBase {
return unserialize($content); return unserialize($content);
} }
/**
* Delete variable from the cache(private)
*
* @param string $_key Used to store the value.
* @return void
*/
function _delete($_key) { function _delete($_key) {
$cache_file = $this->getCacheFileName($_key); $cache_file = $this->getCacheFileName($_key);
FileHandler::removeFile($cache_file); FileHandler::removeFile($cache_file);
} }
/**
* Delete variable from the cache
*
* @param string $key Used to store the value.
* @return void
*/
function delete($key) { function delete($key) {
$this->_delete($key); $this->_delete($key);
} }
/**
* Truncate all existing variables at the cache
*
* @return bool Returns true on success or false on failure.
*/
function truncate() { function truncate() {
FileHandler::removeFilesInDir($this->cache_dir); FileHandler::removeFilesInDir($this->cache_dir);
} }

View file

@ -1,15 +1,30 @@
<?php <?php
/** /**
* @class CacheHandler * CacheHandler
*
* @author NHN (developer@xpressengine.com) * @author NHN (developer@xpressengine.com)
* @brief Cache Handler
* @version 0.1
**/ **/
class CacheHandler extends Handler { class CacheHandler extends Handler {
/**
* instance of cache handler
* @var CacheBase
*/
var $handler = null; var $handler = null;
/**
* Version of key group
* @var int
*/
var $keyGroupVersions = null; var $keyGroupVersions = null;
/**
* Get a instance of CacheHandler(for singleton)
*
* @param string $target type of cache (object|template)
* @param object $info info. of DB
* @param boolean $always_use_file If set true, use a file cache always
* @return CacheHandler
*/
function &getInstance($target = 'object', $info = null, $always_use_file = false) { function &getInstance($target = 'object', $info = null, $always_use_file = false) {
$cache_handler_key = $target . ($always_use_file ? '_file' : ''); $cache_handler_key = $target . ($always_use_file ? '_file' : '');
if(!$GLOBALS['__XE_CACHE_HANDLER__'][$cache_handler_key]) { if(!$GLOBALS['__XE_CACHE_HANDLER__'][$cache_handler_key]) {
@ -18,6 +33,17 @@ class CacheHandler extends Handler {
return $GLOBALS['__XE_CACHE_HANDLER__'][$cache_handler_key]; return $GLOBALS['__XE_CACHE_HANDLER__'][$cache_handler_key];
} }
/**
* Constructor.
*
* Do not use this directly. You can use getInstance() instead.
*
* @see CacheHandler::getInstance
* @param string $target type of cache (object|template)
* @param object $info info. of DB
* @param boolean $always_use_file If set true, use a file cache always
* @return CacheHandler
*/
function CacheHandler($target, $info = null, $always_use_file = false) { function CacheHandler($target, $info = null, $always_use_file = false) {
if(!$info) $info = Context::getDBInfo(); if(!$info) $info = Context::getDBInfo();
if($info){ if($info){
@ -50,31 +76,73 @@ class CacheHandler extends Handler {
} }
} }
/**
* Return whether support or not support cache
*
* @return boolean
*/
function isSupport(){ function isSupport(){
if($this->handler && $this->handler->isSupport()) return true; if($this->handler && $this->handler->isSupport()) return true;
return false; return false;
} }
/**
* Get cached data
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, return false.
* @return false|mixed Return false on failure or older then modified time. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0){ function get($key, $modified_time = 0){
if(!$this->handler) return false; if(!$this->handler) return false;
return $this->handler->get($key, $modified_time); return $this->handler->get($key, $modified_time);
} }
/**
* Put data into cache
*
* @param string $key Cache key
* @param mixed $obj Value of a variable to store. $value supports all data types except resources, such as file handlers.
* @param int $valid_time Time for the variable to live in the cache in seconds.
* After the value specified in ttl has passed the stored variable will be deleted from the cache.
* If no ttl is supplied, use the default valid time.
* @return bool|void Returns true on success or false on failure. If use CacheFile, returns void.
*/
function put($key, $obj, $valid_time = 0){ function put($key, $obj, $valid_time = 0){
if(!$this->handler) return false; if(!$this->handler) return false;
return $this->handler->put($key, $obj, $valid_time); return $this->handler->put($key, $obj, $valid_time);
} }
/**
* Delete Cache
*
* @param string $key Cache key
* @return void
*/
function delete($key){ function delete($key){
if(!$this->handler) return false; if(!$this->handler) return false;
return $this->handler->delete($key); return $this->handler->delete($key);
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, the data is invalid.
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time){ function isValid($key, $modified_time){
if(!$this->handler) return false; if(!$this->handler) return false;
return $this->handler->isValid($key, $modified_time); return $this->handler->isValid($key, $modified_time);
} }
/**
* Truncate all cache
*
* @return bool|void Returns true on success or false on failure. If use CacheFile, returns void.
*/
function truncate(){ function truncate(){
if(!$this->handler) return false; if(!$this->handler) return false;
return $this->handler->truncate(); return $this->handler->truncate();
@ -91,6 +159,10 @@ class CacheHandler extends Handler {
* *
* The new key will be 2:document:123, thus forcing the document * The new key will be 2:document:123, thus forcing the document
* to be reloaded from the database. * to be reloaded from the database.
*
* @param string $keyGroupName Group name
* @param string $key Cache key
* @return string
*/ */
function getGroupKey($keyGroupName, $key){ function getGroupKey($keyGroupName, $key){
if(!$this->keyGroupVersions[$keyGroupName]){ if(!$this->keyGroupVersions[$keyGroupName]){
@ -101,29 +173,77 @@ class CacheHandler extends Handler {
return $this->keyGroupVersions[$keyGroupName] . ':' . $keyGroupName . ':' . $key; return $this->keyGroupVersions[$keyGroupName] . ':' . $keyGroupName . ':' . $key;
} }
/**
* Make invalid group key (like delete group key)
*
* @param string $keyGroupName Group name
* @return void
*/
function invalidateGroupKey($keyGroupName){ function invalidateGroupKey($keyGroupName){
$this->keyGroupVersions[$keyGroupName]++; $this->keyGroupVersions[$keyGroupName]++;
$this->handler->put('key_group_versions', $this->keyGroupVersions, 0); $this->handler->put('key_group_versions', $this->keyGroupVersions, 0);
} }
} }
/**
* Base class of Cache
*
* @author NHN (developer@xpressengine.com)
*/
class CacheBase{ class CacheBase{
/**
* Get cached data
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, return false.
* @return false|mixed Return false on failure or older then modified time. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0){ function get($key, $modified_time = 0){
return false; return false;
} }
/**
* Put data into cache
*
* @param string $key Cache key
* @param mixed $obj Value of a variable to store. $value supports all data types except resources, such as file handlers.
* @param int $valid_time Time for the variable to live in the cache in seconds.
* After the value specified in ttl has passed the stored variable will be deleted from the cache.
* If no ttl is supplied, use the default valid time.
* @return bool|void Returns true on success or false on failure. If use CacheFile, returns void.
*/
function put($key, $obj, $valid_time = 0){ function put($key, $obj, $valid_time = 0){
return false; return false;
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, the data is invalid.
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time = 0){ function isValid($key, $modified_time = 0){
return false; return false;
} }
/**
* Return whether support or not support cache
*
* @return boolean
*/
function isSupport(){ function isSupport(){
return false; return false;
} }
/**
* Truncate all cache
*
* @return bool|void Returns true on success or false on failure. If use CacheFile, returns void.
*/
function truncate(){ function truncate(){
return false; return false;
} }

View file

@ -1,15 +1,28 @@
<?php <?php
/** /**
* @class CacheMemcache * Cache class for memcache
*
* @author NHN (developer@xpressengine.com) * @author NHN (developer@xpressengine.com)
* @brief Memcache Handler
* @version 0.1
**/ **/
class CacheMemcache extends CacheBase { class CacheMemcache extends CacheBase {
/**
* Default valid time
* @var int
*/
var $valid_time = 36000; var $valid_time = 36000;
/**
* instance of Memcahe
* @var Memcahe
*/
var $Memcache; var $Memcache;
/**
* Get instance of CacheMemcache
*
* @param string $url url of memcache
* @return CacheMemcache instance of CacheMemcache
*/
function getInstance($url){ function getInstance($url){
if(!$GLOBALS['__CacheMemcache__']) { if(!$GLOBALS['__CacheMemcache__']) {
$GLOBALS['__CacheMemcache__'] = new CacheMemcache($url); $GLOBALS['__CacheMemcache__'] = new CacheMemcache($url);
@ -17,6 +30,13 @@ class CacheMemcache extends CacheBase {
return $GLOBALS['__CacheMemcache__']; return $GLOBALS['__CacheMemcache__'];
} }
/**
* Construct
*
* Do not use this directly. You can use getInstance() instead.
* @param string $url url of memcache
* @return void
*/
function CacheMemcache($url){ function CacheMemcache($url){
//$config['url'] = array('memcache://localhost:11211'); //$config['url'] = array('memcache://localhost:11211');
$config['url'] = is_array($url)?$url:array($url); $config['url'] = is_array($url)?$url:array($url);
@ -28,6 +48,11 @@ class CacheMemcache extends CacheBase {
} }
} }
/**
* Return whether support or not support cache
*
* @return bool Return true on support or false on not support
*/
function isSupport(){ function isSupport(){
if($GLOBALS['XE_MEMCACHE_SUPPORT']) return true; if($GLOBALS['XE_MEMCACHE_SUPPORT']) return true;
if($this->Memcache->set('xe', 'xe', MEMCACHE_COMPRESSED, 1)) { if($this->Memcache->set('xe', 'xe', MEMCACHE_COMPRESSED, 1)) {
@ -38,16 +63,47 @@ class CacheMemcache extends CacheBase {
return $GLOBALS['XE_MEMCACHE_SUPPORT']; return $GLOBALS['XE_MEMCACHE_SUPPORT'];
} }
/**
* Get unique key of given key by path of XE
*
* @param string $key Cache key
* @return string Return unique key
*/
function getKey($key){ function getKey($key){
return md5(_XE_PATH_.$key); return md5(_XE_PATH_.$key);
} }
/**
* Store data at the server
*
* CacheMemcache::put() stores an item $buff with $key on the memcached server.
* Parameter $valid_time is expiration time in seconds. If it's 0, the item never expires
* (but memcached server doesn't guarantee this item to be stored all the time, it could be delete from the cache to make place for other items).
*
* Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache,
* because they can not be adequately represented in serialized state.
*
* @param string $key The key that will be associated with the item.
* @param mixed $buff The variable to store. Strings and integers are stored as is, other types are stored serialized.
* @param int $valid_time Expiration time of the item.
* You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).
* If it's equal to zero, use the default valid time CacheMemcache::valid_time.
* @return bool Returns true on success or false on failure.
*/
function put($key, $buff, $valid_time = 0){ function put($key, $buff, $valid_time = 0){
if($valid_time == 0) $valid_time = $this->valid_time; if($valid_time == 0) $valid_time = $this->valid_time;
return $this->Memcache->set($this->getKey($key), array(time(), $buff), MEMCACHE_COMPRESSED, $valid_time); return $this->Memcache->set($this->getKey($key), array(time(), $buff), MEMCACHE_COMPRESSED, $valid_time);
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, the data is invalid.
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time = 0) { function isValid($key, $modified_time = 0) {
$_key = $this->getKey($key); $_key = $this->getKey($key);
@ -63,6 +119,16 @@ class CacheMemcache extends CacheBase {
return true; return true;
} }
/**
* Retrieve item from the server
*
* CacheMemcache::get() returns previously stored data if an item with such $key exists on the server at this moment.
*
* @param string $key The key to fetch
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, return false.
* @return false|mixed Return false on failure or older then modified time. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0) { function get($key, $modified_time = 0) {
$_key = $this->getKey($key); $_key = $this->getKey($key);
$obj = $this->Memcache->get($_key); $obj = $this->Memcache->get($_key);
@ -78,15 +144,39 @@ class CacheMemcache extends CacheBase {
return $obj[1]; return $obj[1];
} }
/**
* Delete item from the server
*
* CacheMemcache::delete() deletes an item with tey $key.
*
* @param string $key The key associated with the item to delete.
* @return void
*/
function delete($key) { function delete($key) {
$_key = $this->getKey($key); $_key = $this->getKey($key);
$this->_delete($_key); $this->_delete($_key);
} }
/**
* Delete item from the server(private)
*
* @see CacheMemcache::delete()
* @param string $_key The key associated with the item to delete.
* @return void
*/
function _delete($_key) { function _delete($_key) {
$this->Memcache->delete($_key); $this->Memcache->delete($_key);
} }
/**
* Flush all existing items at the server
*
* CacheMemcache::truncate() immediately invalidates all existing items.
* CacheMemcache::truncate() doesn't actually free any resources, it only marks all the items as expired,
* so occupied memory will be overwitten by new items.
*
* @return bool Returns true on success or false on failure.
*/
function truncate() { function truncate() {
return $this->Memcache->flush(); return $this->Memcache->flush();
} }

View file

@ -1,14 +1,24 @@
<?php <?php
/** /**
* @class CacheWincache * Cache class for Wincache
*
* Wincache Handler
*
* @author Arnia (support@xpressengine.org) * @author Arnia (support@xpressengine.org)
* @brief Wincache Handler
* @version 0.1
**/ **/
class CacheWincache extends CacheBase { class CacheWincache extends CacheBase {
/**
* Default valid time
* @var int
*/
var $valid_time = 36000; var $valid_time = 36000;
/**
* Get instance of CacheWincache
*
* @param void $opt Not used
* @return CacheWincache instance of CacheWincache
*/
function getInstance($opt=null){ function getInstance($opt=null){
if(!$GLOBALS['__CacheWincache__']) { if(!$GLOBALS['__CacheWincache__']) {
$GLOBALS['__CacheWincache__'] = new CacheWincache(); $GLOBALS['__CacheWincache__'] = new CacheWincache();
@ -16,18 +26,47 @@ class CacheWincache extends CacheBase {
return $GLOBALS['__CacheWincache__']; return $GLOBALS['__CacheWincache__'];
} }
/**
* Constructor
*
* @return void
*/
function CacheWincache(){ function CacheWincache(){
} }
/**
* Return whether support or not support cache
*
* @return bool Return true on support or false on not support
*/
function isSupport(){ function isSupport(){
return function_exists('wincache_ucache_set'); return function_exists('wincache_ucache_set');
} }
/**
* Adds a variable in user cache and overwrites a variable if it already exists in the cache
*
* @param string $key Store the variable using this $key value.
* If a variable with same $key is already present the function will overwrite the previous value with the new one.
* @param mixed $buff Value of a variable to store. $value supports all data types except resources, such as file handlers.
* @param int $valid_time Time for the variable to live in the cache in seconds.
* After the value specified in ttl has passed the stored variable will be deleted from the cache.
* If no ttl is supplied, use the default valid time CacheWincache::valid_time.
* @return bool Returns true on success or false on failure.
*/
function put($key, $buff, $valid_time = 0){ function put($key, $buff, $valid_time = 0){
if($valid_time == 0) $valid_time = $this->valid_time; if($valid_time == 0) $valid_time = $this->valid_time;
return wincache_ucache_set(md5(_XE_PATH_.$key), array(time(), $buff), $valid_time); return wincache_ucache_set(md5(_XE_PATH_.$key), array(time(), $buff), $valid_time);
} }
/**
* Return whether cache is valid or invalid
*
* @param string $key Cache key
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, the data is invalid.
* @return bool Return true on valid or false on invalid.
*/
function isValid($key, $modified_time = 0) { function isValid($key, $modified_time = 0) {
$_key = md5(_XE_PATH_.$key); $_key = md5(_XE_PATH_.$key);
$obj = wincache_ucache_get($_key, $success); $obj = wincache_ucache_get($_key, $success);
@ -42,6 +81,14 @@ class CacheWincache extends CacheBase {
return true; return true;
} }
/**
* Gets a variable stored in the user cache
*
* @param string $key The $key that was used to store the variable in the cache.
* @param int $modified_time Unix time of data modified.
* If stored time is older then modified time, return false.
* @return false|mixed Return false on failure or older then modified time. Return the string associated with the $key on success.
*/
function get($key, $modified_time = 0) { function get($key, $modified_time = 0) {
$_key = md5(_XE_PATH_.$key); $_key = md5(_XE_PATH_.$key);
$obj = wincache_ucache_get($_key, $success); $obj = wincache_ucache_get($_key, $success);
@ -55,15 +102,32 @@ class CacheWincache extends CacheBase {
return $obj[1]; return $obj[1];
} }
/**
* Delete variable from the cache(private)
*
* @param string $_key Used to store the value.
* @return void
*/
function _delete($_key) { function _delete($_key) {
wincache_ucache_delete($_key); wincache_ucache_delete($_key);
} }
/**
* Delete variable from the cache
*
* @param string $key Used to store the value.
* @return void
*/
function delete($key) { function delete($key) {
$_key = md5(_XE_PATH_.$key); $_key = md5(_XE_PATH_.$key);
$this->_delete($_key); $this->_delete($_key);
} }
/**
* Truncate all existing variables at the cache
*
* @return bool Returns true on success or false on failure.
*/
function truncate() { function truncate() {
return wincache_ucache_clear(); return wincache_ucache_clear();
} }

View file

@ -362,7 +362,8 @@ class Context {
function checkSSO() { function checkSSO() {
// pass if it's not GET request or XE is not yet installed // pass if it's not GET request or XE is not yet installed
if($this->db_info->use_sso != 'Y' || isCrawler()) return true; if($this->db_info->use_sso != 'Y' || isCrawler()) return true;
if(Context::getRequestMethod()!='GET' || !Context::isInstalled() || in_array(Context::get('act'),array('rss','atom'))) return true; $checkActList = array('rss'=>1, 'atom'=>1);
if(Context::getRequestMethod()!='GET' || !Context::isInstalled() || isset($checkActList[Context::get('act')])) return true;
// pass if default URL is not set // pass if default URL is not set
$default_url = trim($this->db_info->default_url); $default_url = trim($this->db_info->default_url);
@ -630,8 +631,8 @@ class Context {
function setResponseMethod($method='HTML') { function setResponseMethod($method='HTML') {
is_a($this,'Context')?$self=&$this:$self=&Context::getInstance(); is_a($this,'Context')?$self=&$this:$self=&Context::getInstance();
$methods = array('HTML','XMLRPC','JSON'); $methods = array('HTML'=>1, 'XMLRPC'=>1, 'JSON'=>1);
$self->response_method = in_array($method, $methods)?$method:$methods[0]; $self->response_method = isset($methods[$method]) ? $method : 'HTML';
} }
/* /*
@ -644,9 +645,9 @@ class Context {
if($self->response_method) return $self->response_method; if($self->response_method) return $self->response_method;
$method = $self->getRequestMethod(); $method = $self->getRequestMethod();
$methods = array('HTML','XMLRPC','JSON'); $methods = array('HTML'=>1, 'XMLRPC'=>1, 'JSON'=>1);
return in_array($method, $methods)?$method:$methods[0]; return isset($methods[$method]) ? $method : 'HTML';
} }
/** /**
@ -727,19 +728,42 @@ class Context {
* @return filtered value * @return filtered value
**/ **/
function _filterRequestVar($key, $val, $do_stripslashes = 1) { function _filterRequestVar($key, $val, $do_stripslashes = 1) {
if( ($key == 'page' || $key == 'cpage' || substr($key,-3)=='srl')) return !preg_match('/^[0-9,]+$/',$val)?(int)$val:$val; $isArray = TRUE;
if($key == 'mid' || $key == 'vid' || $key == 'search_keyword') return htmlspecialchars($val); if(!is_array($val))
if(is_array($val) && count($val) ) { {
foreach($val as $k => $v) { $isArray = FALSE;
if($do_stripslashes && version_compare(PHP_VERSION, '5.9.0', '<') && get_magic_quotes_gpc()) $v = stripslashes($v); $val = array($val);
$v = trim($v); }
$val[$k] = $v;
} foreach($val as $k => $v)
} else { {
if($do_stripslashes && version_compare(PHP_VERSION, '5.9.0', '<') && get_magic_quotes_gpc()) $val = stripslashes($val); if($key === 'page' || $key === 'cpage' || substr($key, -3) === 'srl')
$val = trim($val); {
$val[$k] = !preg_match('/^[0-9,]+$/', $v) ? (int)$v : $v;
}
elseif($key === 'mid' || $key === 'vid' || $key === 'search_keyword')
{
$val[$k] = htmlspecialchars($v);
}
else
{
if($do_stripslashes && version_compare(PHP_VERSION, '5.9.0', '<') && get_magic_quotes_gpc())
{
$v = stripslashes($v);
}
$val[$k] = trim($v);
}
}
if($isArray)
{
return $val;
}
else
{
return $val[0];
} }
return $val;
} }
/** /**
@ -891,7 +915,8 @@ class Context {
$key = $get_vars['key']; $key = $get_vars['key'];
$srl = $get_vars['document_srl']; $srl = $get_vars['document_srl'];
$is_feed = in_array($act, array('rss', 'atom', 'api')); $tmpArray = array('rss'=>1, 'atom'=>1, 'api'=>1);
$is_feed = isset($tmpArray[$act]);
$target_map = array( $target_map = array(
'vid'=>$vid, 'vid'=>$vid,

View file

@ -1,18 +1,4 @@
<?php <?php
/**
* @class DB
* @author NHN (developers@xpressengine.com)
* @brief base class of db* classes
* @version 0.1
*
* usage of db in XE is via xml
* there are 2 types of xml - query xml, schema xml
* in case of query xml, DB::executeQuery() method compiles xml file into php code and then execute it
* query xml has unique query id, and will be created in module
*
* queryid = module_name.query_name
**/
if(!defined('__XE_LOADED_DB_CLASS__')){ if(!defined('__XE_LOADED_DB_CLASS__')){
define('__XE_LOADED_DB_CLASS__', 1); define('__XE_LOADED_DB_CLASS__', 1);
@ -45,11 +31,31 @@
require(_XE_PATH_.'classes/db/queryparts/Subquery.class.php'); require(_XE_PATH_.'classes/db/queryparts/Subquery.class.php');
} }
/**
* - DB parent class
* - usage of db in XE is via xml
* - there are 2 types of xml - query xml, schema xml
* - in case of query xml, DB::executeQuery() method compiles xml file into php code and then execute it
* - query xml has unique query id, and will be created in module
* - queryid = module_name.query_name
*
* @author NHN (developers@xpressengine.com)
* @package /classes/db
* @version 0.1
*/
class DB { class DB {
/**
* count cache path
* @var string
*/
var $count_cache_path = 'files/cache/db'; var $count_cache_path = 'files/cache/db';
var $cond_operation = array( ///< operations for condition /**
* operations for condition
* @var array
*/
var $cond_operation = array(
'equal' => '=', 'equal' => '=',
'more' => '>=', 'more' => '>=',
'excess' => '>', 'excess' => '>',
@ -60,35 +66,84 @@
'null' => 'is null', 'null' => 'is null',
); );
var $master_db = NULL; // master database connection string /**
var $slave_db = NULL; // array of slave databases connection strings * master database connection string
* @var array
*/
var $master_db = NULL;
/**
* array of slave databases connection strings
* @var array
*/
var $slave_db = NULL;
var $result = NULL; ///< result var $result = NULL;
var $errno = 0; ///< error code (0 means no error) /**
var $errstr = ''; ///< error message * error code (0 means no error)
var $query = ''; ///< query string of latest executed query * @var int
*/
var $errno = 0;
/**
* error message
* @var string
*/
var $errstr = '';
/**
* query string of latest executed query
* @var string
*/
var $query = '';
var $connection = ''; var $connection = '';
var $elapsed_time = 0; ///< elapsed time of latest executed query /**
var $elapsed_dbclass_time = 0; ///< elapsed time of latest executed query * elapsed time of latest executed query
* @var int
*/
var $elapsed_time = 0;
/**
* elapsed time of latest executed DB class
* @var int
*/
var $elapsed_dbclass_time = 0;
var $transaction_started = false; ///< transaction flag /**
* transaction flag
* @var boolean
*/
var $transaction_started = false;
var $is_connected = false; ///< is db connected var $is_connected = false;
var $supported_list = array(); ///< list of supported db, (will be written by classes/DB/DB***.class.php) /**
* returns enable list in supported dbms list
* will be written by classes/DB/DB***.class.php
* @var array
*/
var $supported_list = array();
var $cache_file = 'files/cache/queries/'; ///< location of query cache /**
* location of query cache
* @var string
*/
var $cache_file = 'files/cache/queries/';
var $db_type; ///< stores database type: 'mysql','cubrid','mssql' etc. or 'db' when database is not yet set /**
* stores database type: 'mysql','cubrid','mssql' etc. or 'db' when database is not yet set
* @var string
*/
var $db_type;
var $use_prepared_statements; ///< flag to decide if class prepared statements or not (when supported); can be changed from db.config.info /**
* flag to decide if class prepared statements or not (when supported); can be changed from db.config.info
* @var string
*/
var $use_prepared_statements;
/** /**
* @brief returns instance of certain db type * returns instance of certain db type
* @param[in] $db_type type of db * @param string $db_type type of db
* @return instance * @return DB return DB object instance
**/ */
function &getInstance($db_type = NULL) { function &getInstance($db_type = NULL) {
if(!$db_type) $db_type = Context::getDBType(); if(!$db_type) $db_type = Context::getDBType();
if(!$db_type && Context::isInstalled()) return new Object(-1, 'msg_db_not_setted'); if(!$db_type && Context::isInstalled()) return new Object(-1, 'msg_db_not_setted');
@ -108,32 +163,39 @@
return $GLOBALS['__DB__'][$db_type]; return $GLOBALS['__DB__'][$db_type];
} }
/**
* returns instance of db
* @return DB return DB object instance
*/
function create() { function create() {
return new DB; return new DB;
} }
/** /**
* @brief constructor * constructor
* @return none * @return void
**/ */
function DB() { function DB() {
$this->count_cache_path = _XE_PATH_.$this->count_cache_path; $this->count_cache_path = _XE_PATH_.$this->count_cache_path;
$this->cache_file = _XE_PATH_.$this->cache_file; $this->cache_file = _XE_PATH_.$this->cache_file;
} }
/** /**
* @brief returns list of supported db * returns list of supported dbms list
* @return list of supported db * this list return by directory list
**/ * check by instance can creatable
* @return array return supported DBMS list
*/
function getSupportedList() { function getSupportedList() {
$oDB = new DB(); $oDB = new DB();
return $oDB->_getSupportedList(); return $oDB->_getSupportedList();
} }
/** /**
* @brief returns list of enable in supported db * returns enable list in supported dbms list
* @return list of enable in supported db * this list return by child class
**/ * @return array return enable DBMS list in supported dbms list
*/
function getEnableList() function getEnableList()
{ {
if(!$this->supported_list) if(!$this->supported_list)
@ -152,9 +214,10 @@
} }
/** /**
* @brief returns list of disable in supported db * returns list of disable in supported dbms list
* @return list of disable in supported db * this list return by child class
**/ * @return array return disable DBMS list in supported dbms list
*/
function getDisableList() function getDisableList()
{ {
if(!$this->supported_list) if(!$this->supported_list)
@ -173,10 +236,17 @@
} }
/** /**
* @brief returns list of supported db * returns list of supported dbms list
* @return list of supported db * this method is private
**/ * @return array return supported DBMS list
*/
function _getSupportedList() { function _getSupportedList() {
static $get_supported_list = '';
if(is_array($get_supported_list)) {
$this->supported_list = $get_supported_list;
return $this->supported_list;
}
$get_supported_list = array();
$db_classes_path = _XE_PATH_."classes/db/"; $db_classes_path = _XE_PATH_."classes/db/";
$filter = "/^DB([^\.]+)\.class\.php/i"; $filter = "/^DB([^\.]+)\.class\.php/i";
$supported_list = FileHandler::readDir($db_classes_path, $filter, true); $supported_list = FileHandler::readDir($db_classes_path, $filter, true);
@ -203,34 +273,37 @@
$obj->db_type = $db_type; $obj->db_type = $db_type;
$obj->enable = $oDB->isSupported() ? true : false; $obj->enable = $oDB->isSupported() ? true : false;
$this->supported_list[] = $obj; $get_supported_list[] = $obj;
} }
$this->supported_list = $get_supported_list;
return $this->supported_list; return $this->supported_list;
} }
/** /**
* @brief check if the db_type is supported * Return dbms supportable status
* @param[in] $db_type type of db to check * The value is set in the child class
* @return true: is supported, false: is not supported * @return boolean true: is supported, false: is not supported
**/ */
function isSupported() { function isSupported() {
return FALSE; return FALSE;
} }
/** /**
* @brief check if is connected * Return connected status
* @return true: connected, false: not connected * @param string $type master or slave
**/ * @param int $indx key of server list
* @return boolean true: connected, false: not connected
*/
function isConnected($type = 'master', $indx = 0) { function isConnected($type = 'master', $indx = 0) {
if($type == 'master') return $this->master_db["is_connected"] ? true : false; if($type == 'master') return $this->master_db["is_connected"] ? true : false;
else return $this->slave_db[$indx]["is_connected"] ? true : false; else return $this->slave_db[$indx]["is_connected"] ? true : false;
} }
/** /**
* @brief start recording log * start recording log
* @return none * @param string $query query string
**/ * @return void
*/
function actStart($query) { function actStart($query) {
$this->setError(0, 'success'); $this->setError(0, 'success');
$this->query = $query; $this->query = $query;
@ -239,9 +312,9 @@
} }
/** /**
* @brief finish recording log * finish recording log
* @return none * @return void
**/ */
function actFinish() { function actFinish() {
if(!$this->query) return; if(!$this->query) return;
$this->act_finish = getMicroTime(); $this->act_finish = getMicroTime();
@ -297,41 +370,43 @@
} }
/** /**
* @brief set error * set error
* @param[in] $errno error code * @param int $errno error code
* @param[in] $errstr error message * @param string $errstr error message
* @return none * @return void
**/ */
function setError($errno = 0, $errstr = 'success') { function setError($errno = 0, $errstr = 'success') {
$this->errno = $errno; $this->errno = $errno;
$this->errstr = $errstr; $this->errstr = $errstr;
} }
/** /**
* @brief check if an error occured * Return error status
* @return true: error, false: no error * @return boolean true: error, false: no error
**/ */
function isError() { function isError() {
return $this->errno === 0 ? false : true; return $this->errno === 0 ? false : true;
} }
/** /**
* @brief returns object of error info * Returns object of error info
* @return object of error * @return object object of error
**/ */
function getError() { function getError() {
$this->errstr = Context::convertEncodingStr($this->errstr); $this->errstr = Context::convertEncodingStr($this->errstr);
return new Object($this->errno, $this->errstr); return new Object($this->errno, $this->errstr);
} }
/** /**
* @brief Run the result of the query xml file * Execute Query that result of the query xml file
* @param[in] $query_id query id (module.queryname * This function finds xml file or cache file of $query_id, compiles it and then execute it
* @param[in] $args arguments for query * @param string $query_id query id (module.queryname)
* @return result of query * @param array|object $args arguments for query
* @remarks this function finds xml file or cache file of $query_id, compiles it and then execute it * @param array $arg_columns column list. if you want get specific colums from executed result, add column list to $arg_columns
**/ * @return object result of query
*/
function executeQuery($query_id, $args = NULL, $arg_columns = NULL) { function executeQuery($query_id, $args = NULL, $arg_columns = NULL) {
static $cache_file = array();
if(!$query_id) return new Object(-1, 'msg_invalid_queryid'); if(!$query_id) return new Object(-1, 'msg_invalid_queryid');
if(!$this->db_type) return; if(!$this->db_type) return;
@ -339,49 +414,51 @@
$this->query_id = $query_id; $this->query_id = $query_id;
$id_args = explode('.', $query_id); if(!isset($cache_file[$query_id])) {
if(count($id_args) == 2) { $id_args = explode('.', $query_id);
$target = 'modules'; if(count($id_args) == 2) {
$module = $id_args[0]; $target = 'modules';
$id = $id_args[1]; $module = $id_args[0];
} elseif(count($id_args) == 3) { $id = $id_args[1];
$target = $id_args[0]; } elseif(count($id_args) == 3) {
if(!in_array($target, array('addons','widgets'))){ $target = $id_args[0];
$this->actDBClassFinish(); $typeList = array('addons'=>1, 'widgets'=>1);
return; if(!isset($typeList[$target])){
} $this->actDBClassFinish();
$module = $id_args[1]; return;
$id = $id_args[2]; }
} $module = $id_args[1];
if(!$target || !$module || !$id){ $id = $id_args[2];
$this->actDBClassFinish(); }
return new Object(-1, 'msg_invalid_queryid'); if(!$target || !$module || !$id){
} $this->actDBClassFinish();
return new Object(-1, 'msg_invalid_queryid');
}
$xml_file = sprintf('%s%s/%s/queries/%s.xml', _XE_PATH_, $target, $module, $id); $xml_file = sprintf('%s%s/%s/queries/%s.xml', _XE_PATH_, $target, $module, $id);
if(!file_exists($xml_file)){ if(!file_exists($xml_file)){
$this->actDBClassFinish(); $this->actDBClassFinish();
return new Object(-1, 'msg_invalid_queryid'); return new Object(-1, 'msg_invalid_queryid');
} }
// look for cache file // look for cache file
$cache_file = $this->checkQueryCacheFile($query_id, $xml_file); $cache_file[$query_id] = $this->checkQueryCacheFile($query_id, $xml_file);
$result = $this->_executeQuery($cache_file, $args, $query_id, $arg_columns); }
$result = $this->_executeQuery($cache_file[$query_id], $args, $query_id, $arg_columns);
$this->actDBClassFinish(); $this->actDBClassFinish();
// execute query // execute query
return $result; return $result;
} }
/** /**
* @brief look for cache file * Look for query cache file
* @param[in] $query_id query id for finding * @param string $query_id query id for finding
* @param[in] $xml_file original xml query file * @param string $xml_file original xml query file
* @return cache file * @return string cache file
**/ */
function checkQueryCacheFile($query_id,$xml_file){ function checkQueryCacheFile($query_id,$xml_file){
// first try finding cache file // first try finding cache file
$cache_file = sprintf('%s%s%s.%s.%s.cache.php', _XE_PATH_, $this->cache_file, $query_id, __ZBXE_VERSION__, $this->db_type); $cache_file = sprintf('%s%s%s.%s.%s.cache.php', _XE_PATH_, $this->cache_file, $query_id, __ZBXE_VERSION__, $this->db_type);
@ -400,12 +477,13 @@
/** /**
* @brief execute query and return the result * Execute query and return the result
* @param[in] $cache_file cache file of query * @param string $cache_file cache file of query
* @param[in] $source_args arguments for query * @param array|object $source_args arguments for query
* @param[in] $query_id query id * @param string $query_id query id
* @return result of query * @param array $arg_columns column list. if you want get specific colums from executed result, add column list to $arg_columns
**/ * @return object result of query
*/
function _executeQuery($cache_file, $source_args, $query_id, $arg_columns) { function _executeQuery($cache_file, $source_args, $query_id, $arg_columns) {
global $lang; global $lang;
@ -420,6 +498,7 @@
// execute appropriate query // execute appropriate query
switch($output->getAction()) { switch($output->getAction()) {
case 'insert' : case 'insert' :
case 'insert-select' :
$this->resetCountCache($output->tables); $this->resetCountCache($output->tables);
$output = $this->_executeInsertAct($output); $output = $this->_executeInsertAct($output);
break; break;
@ -449,11 +528,11 @@
/** /**
* @brief returns counter cache data * Returns counter cache data
* @param[in] $tables tables to get data * @param array|string $tables tables to get data
* @param[in] $condition condition to get data * @param string $condition condition to get data
* @return count of cache data * @return int count of cache data
**/ */
function getCountCache($tables, $condition) { function getCountCache($tables, $condition) {
return false; return false;
if(!$tables) return false; if(!$tables) return false;
@ -483,12 +562,12 @@
} }
/** /**
* @brief save counter cache data * Save counter cache data
* @param[in] $tables tables to save data * @param array|string $tables tables to save data
* @param[in] $condition condition to save data * @param string $condition condition to save data
* @param[in] $count count of cache data to save * @param int $count count of cache data to save
* @return none * @return void
**/ */
function putCountCache($tables, $condition, $count = 0) { function putCountCache($tables, $condition, $count = 0) {
return false; return false;
if(!$tables) return false; if(!$tables) return false;
@ -508,10 +587,10 @@
} }
/** /**
* @brief reset counter cache data * Reset counter cache data
* @param[in] $tables tables to reset cache data * @param array|string $tables tables to reset cache data
* @return true: success, false: failed * @return boolean true: success, false: failed
**/ */
function resetCountCache($tables) { function resetCountCache($tables) {
return false; return false;
if(!$tables) return false; if(!$tables) return false;
@ -528,9 +607,9 @@
} }
/** /**
* @brief returns supported database list * Returns supported database list
* @return list of supported database * @return array list of supported database
**/ */
function getSupportedDatabase(){ function getSupportedDatabase(){
$result = array(); $result = array();
@ -545,12 +624,23 @@
return $result; return $result;
} }
/**
* Drop tables
* @param string $table_name
* @return void
*/
function dropTable($table_name){ function dropTable($table_name){
if(!$table_name) return; if(!$table_name) return;
$query = sprintf("drop table %s%s", $this->prefix, $table_name); $query = sprintf("drop table %s%s", $this->prefix, $table_name);
$this->_query($query); $this->_query($query);
} }
/**
* Return select query string
* @param object $query
* @param boolean $with_values
* @return string
*/
function getSelectSql($query, $with_values = true){ function getSelectSql($query, $with_values = true){
$select = $query->getSelectString($with_values); $select = $query->getSelectString($with_values);
if($select == '') return new Object(-1, "Invalid query"); if($select == '') return new Object(-1, "Invalid query");
@ -585,6 +675,13 @@
return $select . ' ' . $from . ' ' . $where . ' ' . $index_hint_list . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; return $select . ' ' . $from . ' ' . $where . ' ' . $index_hint_list . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit;
} }
/**
* Return delete query string
* @param object $query
* @param boolean $with_values
* @param boolean $with_priority
* @return string
*/
function getDeleteSql($query, $with_values = true, $with_priority = false){ function getDeleteSql($query, $with_values = true, $with_priority = false){
$sql = 'DELETE '; $sql = 'DELETE ';
@ -603,6 +700,13 @@
return $sql; return $sql;
} }
/**
* Return update query string
* @param object $query
* @param boolean $with_values
* @param boolean $with_priority
* @return string
*/
function getUpdateSql($query, $with_values = true, $with_priority = false){ function getUpdateSql($query, $with_values = true, $with_priority = false){
$columnsList = $query->getUpdateString($with_values); $columnsList = $query->getUpdateString($with_values);
if($columnsList == '') return new Object(-1, "Invalid query"); if($columnsList == '') return new Object(-1, "Invalid query");
@ -618,6 +722,13 @@
return "UPDATE $priority $tables SET $columnsList ".$where; return "UPDATE $priority $tables SET $columnsList ".$where;
} }
/**
* Return insert query string
* @param object $query
* @param boolean $with_values
* @param boolean $with_priority
* @return string
*/
function getInsertSql($query, $with_values = true, $with_priority = false){ function getInsertSql($query, $with_values = true, $with_priority = false){
$tableName = $query->getFirstTableName(); $tableName = $query->getFirstTableName();
$values = $query->getInsertString($with_values); $values = $query->getInsertString($with_values);
@ -626,12 +737,22 @@
return "INSERT $priority INTO $tableName \n $values"; return "INSERT $priority INTO $tableName \n $values";
} }
/**
* Return index from slave server list
* @return int
*/
function _getSlaveConnectionStringIndex() { function _getSlaveConnectionStringIndex() {
$max = count($this->slave_db); $max = count($this->slave_db);
$indx = rand(0, $max - 1); $indx = rand(0, $max - 1);
return $indx; return $indx;
} }
/**
* Return connection resource
* @param string $type use 'master' or 'slave'. default value is 'master'
* @param int $indx if indx value is NULL, return rand number in slave server list
* @return resource
*/
function _getConnection($type = 'master', $indx = NULL){ function _getConnection($type = 'master', $indx = NULL){
if($type == 'master'){ if($type == 'master'){
if(!$this->master_db['is_connected']) if(!$this->master_db['is_connected'])
@ -650,6 +771,10 @@
return $this->slave_db[$indx]["resource"]; return $this->slave_db[$indx]["resource"];
} }
/**
* check db information exists
* @return boolean
*/
function _dbInfoExists() { function _dbInfoExists() {
if (!$this->master_db) if (!$this->master_db)
return false; return false;
@ -658,13 +783,22 @@
return true; return true;
} }
/**
* DB disconnection
* this method is protected
* @param resource $connection
* @return void
*/
function _close($connection){ function _close($connection){
} }
/** /**
* @brief DB disconnection * DB disconnection
* */ * @param string $type 'master' or 'slave'
* @param int $indx number in slave dbms server list
* @return void
*/
function close($type = 'master', $indx = 0) { function close($type = 'master', $indx = 0) {
if (!$this->isConnected($type, $indx)) if (!$this->isConnected($type, $indx))
return; return;
@ -679,12 +813,19 @@
$connection["is_connected"] = false; $connection["is_connected"] = false;
} }
/**
* DB transaction start
* this method is protected
* @return boolean
*/
function _begin(){ function _begin(){
return true; return true;
} }
/**
* @brief Begin transaction /**
* */ * DB transaction start
* @return void
*/
function begin() { function begin() {
if (!$this->isConnected() || $this->transaction_started) if (!$this->isConnected() || $this->transaction_started)
return; return;
@ -693,13 +834,19 @@
$this->transaction_started = true; $this->transaction_started = true;
} }
/**
* DB transaction rollback
* this method is protected
* @return boolean
*/
function _rollback(){ function _rollback(){
return true; return true;
} }
/** /**
* @brief Rollback * DB transaction rollback
* */ * @return void
*/
function rollback() { function rollback() {
if (!$this->isConnected() || !$this->transaction_started) if (!$this->isConnected() || !$this->transaction_started)
return; return;
@ -707,12 +854,20 @@
$this->transaction_started = false; $this->transaction_started = false;
} }
/**
* DB transaction commit
* this method is protected
* @return boolean
*/
function _commit(){ function _commit(){
return true; return true;
} }
/**
* @brief Commits /**
* */ * DB transaction commit
* @param boolean $force regardless transaction start status or connect status, forced to commit
* @return void
*/
function commit($force = false) { function commit($force = false) {
if (!$force && (!$this->isConnected() || !$this->transaction_started)) if (!$force && (!$this->isConnected() || !$this->transaction_started))
return; return;
@ -720,18 +875,24 @@
$this->transaction_started = false; $this->transaction_started = false;
} }
/**
* Execute the query
* this method is protected
* @param string $query
* @param resource $connection
* @return void
*/
function __query($query, $connection){ function __query($query, $connection){
} }
/**
* @brief : Run a query and fetch the result /**
* * Execute the query
* query: run a query and return the result \n * this method is protected
* fetch: NULL if no value is returned \n * @param string $query
* array object if rows are returned \n * @param resource $connection
* object if a row is returned \n * @return resource
* return\n */
* */
function _query($query, $connection = null) { function _query($query, $connection = null) {
if($connection == null) if($connection == null)
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
@ -747,9 +908,11 @@
return $result; return $result;
} }
/** /**
* @brief DB settings and connect/close * DB info settings
* */ * this method is protected
* @return void
*/
function _setDBInfo(){ function _setDBInfo(){
$db_info = Context::getDBInfo(); $db_info = Context::getDBInfo();
$this->master_db = $db_info->master_db; $this->master_db = $db_info->master_db;
@ -766,16 +929,33 @@
$this->use_prepared_statements = $db_info->use_prepared_statements; $this->use_prepared_statements = $db_info->use_prepared_statements;
} }
/**
* DB Connect
* this method is protected
* @param array $connection
* @return void
*/
function __connect($connection){ function __connect($connection){
} }
/**
* If have a task after connection, add a taks in this method
* this method is protected
* @param resource $connection
* @return void
*/
function _afterConnect($connection){ function _afterConnect($connection){
} }
/**
* @brief DB Connection /**
* */ * DB Connect
* this method is protected
* @param string $type 'master' or 'slave'
* @param int $indx number in slave dbms server list
* @return void
*/
function _connect($type = 'master', $indx = 0) { function _connect($type = 'master', $indx = 0) {
if ($this->isConnected($type, $indx)) if ($this->isConnected($type, $indx))
return; return;
@ -804,20 +984,21 @@
$this->_afterConnect($result); $this->_afterConnect($result);
} }
/**
* @brief start recording DBClass log /**
* @return none * Start recording DBClass log
**/ * @return void
*/
function actDBClassStart() { function actDBClassStart() {
$this->setError(0, 'success'); $this->setError(0, 'success');
$this->act_dbclass_start = getMicroTime(); $this->act_dbclass_start = getMicroTime();
$this->elapsed_dbclass_time = 0; $this->elapsed_dbclass_time = 0;
} }
/** /**
* @brief finish recording DBClass log * Finish recording DBClass log
* @return none * @return void
**/ */
function actDBClassFinish() { function actDBClassFinish() {
if(!$this->query) return; if(!$this->query) return;
$this->act_dbclass_finish = getMicroTime(); $this->act_dbclass_finish = getMicroTime();
@ -826,14 +1007,16 @@
$GLOBALS['__dbclass_elapsed_time__'] += $elapsed_dbclass_time; $GLOBALS['__dbclass_elapsed_time__'] += $elapsed_dbclass_time;
} }
/** /**
* Returns a database specific parser class * Returns a database specific parser instance
* used for escaping expressions and table/column identifiers * used for escaping expressions and table/column identifiers
* *
* Requires an implementation of the DB class (won't work if database is not set) * Requires an implementation of the DB class (won't work if database is not set)
* * this method is singleton
* @remarks singleton *
*/ * @param boolean $force force load DBParser instance
* @return DBParser
*/
function &getParser($force = false){ function &getParser($force = false){
static $dbParser = null; static $dbParser = null;
if(!$dbParser || $force) { if(!$dbParser || $force) {

View file

@ -1,28 +1,34 @@
<?php <?php
/** /**
* @class DBCubrid * - DB child class
* @author NHN (developers@xpressengine.com) * - Cubrid DBMS to use the class
* @brief Cubrid DBMS to use the class * - Works with CUBRID up to 8.4.1
* @version 1.0
* *
* Works with CUBRID up to 8.4.1 * @author NHN (developers@xpressengine.com)
**/ * @package /classes/db
* @version 0.1
*/
class DBCubrid extends DB class DBCubrid extends DB
{ {
/** /**
* @brief CUBRID DB connection information * prefix of XE tables(One more XE can be installed on a single DB)
**/ * @var string
var $prefix = 'xe_'; // / <prefix of XE tables(One more XE can be installed on a single DB) */
var $cutlen = 12000; // /< max size of constant in CUBRID(if string is larger than this, '...'+'...' should be used) var $prefix = 'xe_';
/**
* max size of constant in CUBRID(if string is larger than this, '...'+'...' should be used)
* @var int
*/
var $cutlen = 12000;
var $comment_syntax = '/* %s */'; var $comment_syntax = '/* %s */';
/** /**
* @brief column type used in CUBRID * column type used in CUBRID
* *
* column_type should be replaced for each DBMS's type * column_type should be replaced for each DBMS's type
* becasue it uses commonly defined type in the schema/query xml * becasue it uses commonly defined type in the schema/query xml
* @var array
**/ **/
var $column_type = array( var $column_type = array(
'bignumber' => 'numeric(20)', 'bignumber' => 'numeric(20)',
@ -37,8 +43,9 @@
); );
/** /**
* @brief constructor * constructor
**/ * @return void
*/
function DBCubrid() function DBCubrid()
{ {
$this->_setDBInfo(); $this->_setDBInfo();
@ -46,7 +53,8 @@
} }
/** /**
* @brief create an instance of this class * Create an instance of this class
* @return DBCubrid return DBCubrid object instance
*/ */
function create() function create()
{ {
@ -54,8 +62,10 @@
} }
/** /**
* @brief Return if installable * Return if supportable
**/ * Check 'cubrid_connect' function exists.
* @return boolean
*/
function isSupported() function isSupported()
{ {
if (!function_exists('cubrid_connect')) return false; if (!function_exists('cubrid_connect')) return false;
@ -63,8 +73,11 @@
} }
/** /**
* @brief DB Connection * DB Connect
**/ * this method is private
* @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password
* @return resource
*/
function __connect($connection) function __connect($connection)
{ {
// attempts to connect // attempts to connect
@ -90,8 +103,11 @@
} }
/** /**
* @brief DB disconnect * DB disconnection
**/ * this method is private
* @param resource $connection
* @return void
*/
function _close($connection) function _close($connection)
{ {
@cubrid_commit ($connection); @cubrid_commit ($connection);
@ -100,8 +116,10 @@
} }
/** /**
* @brief handles quatation of the string variables from the query * Handles quatation of the string variables from the query
**/ * @param string $string
* @return string
*/
function addQuotes($string) function addQuotes($string)
{ {
if (version_compare (PHP_VERSION, "5.9.0", "<") && if (version_compare (PHP_VERSION, "5.9.0", "<") &&
@ -126,8 +144,10 @@
} }
/** /**
* @brief Begin transaction * DB transaction start
**/ * this method is private
* @return boolean
*/
function _begin() function _begin()
{ {
if(__CUBRID_VERSION__ >= '8.4.0') if(__CUBRID_VERSION__ >= '8.4.0')
@ -139,8 +159,10 @@
} }
/** /**
* @brief Rollback * DB transaction rollback
**/ * this method is private
* @return boolean
*/
function _rollback() function _rollback()
{ {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
@ -149,8 +171,10 @@
} }
/** /**
* @brief Commit * DB transaction commit
**/ * this method is private
* @return boolean
*/
function _commit() function _commit()
{ {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
@ -159,14 +183,12 @@
} }
/** /**
* @brief : executing the query and fetching the result * Execute the query
* * this method is private
* query: run a query and return the result\n * @param string $query
* fetch: NULL if no value returned \n * @param resource $connection
* array object if rows returned \n * @return resource
* object if a row returned \n */
* return\n
**/
function __query($query, $connection) function __query($query, $connection)
{ {
if($this->use_prepared_statements == 'Y') if($this->use_prepared_statements == 'Y')
@ -232,8 +254,11 @@
} }
/** /**
* @brief Fetch the result * Fetch the result
**/ * @param resource $result
* @param int|NULL $arrayIndexEndValue
* @return array
*/
function _fetch($result, $arrayIndexEndValue = NULL) function _fetch($result, $arrayIndexEndValue = NULL)
{ {
$output = array(); $output = array();
@ -281,8 +306,10 @@
} }
/** /**
* @brief return the sequence value incremented by 1(auto_increment column only used in the CUBRID sequence table) * Return the sequence value incremented by 1
**/ * Auto_increment column only used in the CUBRID sequence table
* @return int
*/
function getNextSequence() function getNextSequence()
{ {
$this->_makeSequence(); $this->_makeSequence();
@ -295,8 +322,9 @@
} }
/** /**
* @brief return if the table already exists * if the table already exists, set the status to GLOBALS
**/ * @return void
*/
function _makeSequence() function _makeSequence()
{ {
if($_GLOBALS['XE_EXISTS_SEQUENCE']) return; if($_GLOBALS['XE_EXISTS_SEQUENCE']) return;
@ -337,8 +365,10 @@
/** /**
* brief return a table if exists * Check a table exists status
**/ * @param string $target_name
* @return boolean
*/
function isTableExists ($target_name) function isTableExists ($target_name)
{ {
if($target_name == 'sequence') { if($target_name == 'sequence') {
@ -362,8 +392,15 @@
} }
/** /**
* @brief add a column to the table * Add a column to the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @param string $type column type, default value is 'number'
* @param int $size column size
* @param string|int $default default value
* @param boolean $notnull not null status, default value is false
* @return void
*/
function addColumn($table_name, $column_name, $type = 'number', $size = '', $default = '', $notnull = false) function addColumn($table_name, $column_name, $type = 'number', $size = '', $default = '', $notnull = false)
{ {
$type = strtoupper($this->column_type[$type]); $type = strtoupper($this->column_type[$type]);
@ -397,8 +434,11 @@
} }
/** /**
* @brief drop a column from the table * Drop a column from the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return void
*/
function dropColumn ($table_name, $column_name) function dropColumn ($table_name, $column_name)
{ {
$query = sprintf ("alter class \"%s%s\" drop \"%s\" ", $this->prefix, $table_name, $column_name); $query = sprintf ("alter class \"%s%s\" drop \"%s\" ", $this->prefix, $table_name, $column_name);
@ -407,8 +447,11 @@
} }
/** /**
* @brief return column information of the table * Check column exist status of the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return boolean
*/
function isColumnExists ($table_name, $column_name) function isColumnExists ($table_name, $column_name)
{ {
$query = sprintf ("select \"attr_name\" from \"db_attribute\" where ". "\"attr_name\" ='%s' and \"class_name\" = '%s%s'", $column_name, $this->prefix, $table_name); $query = sprintf ("select \"attr_name\" from \"db_attribute\" where ". "\"attr_name\" ='%s' and \"class_name\" = '%s%s'", $column_name, $this->prefix, $table_name);
@ -423,10 +466,15 @@
} }
/** /**
* @brief add an index to the table * Add an index to the table
* $target_columns = array(col1, col2) * $target_columns = array(col1, col2)
* $is_unique? unique : none * $is_unique? unique : none
**/ * @param string $table_name table name
* @param string $index_name index name
* @param string|array $target_columns target column or columns
* @param boolean $is_unique
* @return void
*/
function addIndex ($table_name, $index_name, $target_columns, $is_unique = false) function addIndex ($table_name, $index_name, $target_columns, $is_unique = false)
{ {
if (!is_array ($target_columns)) { if (!is_array ($target_columns)) {
@ -439,8 +487,12 @@
} }
/** /**
* @brief drop an index from the table * Drop an index from the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @param boolean $is_unique
* @return void
*/
function dropIndex ($table_name, $index_name, $is_unique = false) function dropIndex ($table_name, $index_name, $is_unique = false)
{ {
$query = sprintf ("drop %s index \"%s\" on \"%s%s\"", $is_unique?'unique':'', $this->prefix .$index_name, $this->prefix, $table_name); $query = sprintf ("drop %s index \"%s\" on \"%s%s\"", $is_unique?'unique':'', $this->prefix .$index_name, $this->prefix, $table_name);
@ -449,8 +501,11 @@
} }
/** /**
* @brief return index information of the table * Check index status of the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @return boolean
*/
function isIndexExists ($table_name, $index_name) function isIndexExists ($table_name, $index_name)
{ {
$query = sprintf ("select \"index_name\" from \"db_index\" where ". "\"class_name\" = '%s%s' and \"index_name\" = '%s' ", $this->prefix, $table_name, $this->prefix .$index_name); $query = sprintf ("select \"index_name\" from \"db_index\" where ". "\"class_name\" = '%s%s' and \"index_name\" = '%s' ", $this->prefix, $table_name, $this->prefix .$index_name);
@ -464,6 +519,10 @@
return true; return true;
} }
/**
* Delete duplicated index of the table
* @return boolean
*/
function deleteDuplicateIndexes() function deleteDuplicateIndexes()
{ {
$query = sprintf(" $query = sprintf("
@ -507,16 +566,20 @@
} }
/** /**
* @brief creates a table by using xml file * Creates a table by using xml contents
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function createTableByXml ($xml_doc) function createTableByXml ($xml_doc)
{ {
return $this->_createTable ($xml_doc); return $this->_createTable ($xml_doc);
} }
/** /**
* @brief creates a table by using xml file * Creates a table by using xml file path
**/ * @param string $file_name xml schema file path
* @return void|object
*/
function createTableByXmlFile ($file_name) function createTableByXmlFile ($file_name)
{ {
if (!file_exists ($file_name)) return; if (!file_exists ($file_name)) return;
@ -526,12 +589,14 @@
} }
/** /**
* @brief create table by using the schema xml * Create table by using the schema xml
* *
* type : number, varchar, tinytext, text, bigtext, char, date, \n * type : number, varchar, tinytext, text, bigtext, char, date, \n
* opt : notnull, default, size\n * opt : notnull, default, size\n
* index : primary key, index, unique\n * index : primary key, index, unique\n
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function _createTable ($xml_doc) function _createTable ($xml_doc)
{ {
// xml parsing // xml parsing
@ -645,8 +710,11 @@
/** /**
* @brief handles insertAct * Handles insertAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeInsertAct($queryObject, $with_values = true) function _executeInsertAct($queryObject, $with_values = true)
{ {
if($this->use_prepared_statements == 'Y') if($this->use_prepared_statements == 'Y')
@ -668,8 +736,11 @@
} }
/** /**
* @brief handles updateAct * Handles updateAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeUpdateAct($queryObject, $with_values = true) function _executeUpdateAct($queryObject, $with_values = true)
{ {
if($this->use_prepared_statements == 'Y') if($this->use_prepared_statements == 'Y')
@ -689,8 +760,11 @@
/** /**
* @brief handles deleteAct * Handles deleteAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeDeleteAct($queryObject, $with_values = true) function _executeDeleteAct($queryObject, $with_values = true)
{ {
if($this->use_prepared_statements == 'Y') if($this->use_prepared_statements == 'Y')
@ -710,11 +784,14 @@
} }
/** /**
* @brief Handle selectAct * Handle selectAct
* * To get a specific page list easily in select statement,
* to get a specific page list easily in select statement,\n
* a method, navigation, is used * a method, navigation, is used
**/ * @param Object $queryObject
* @param resource $connection
* @param boolean $with_values
* @return Object
*/
function _executeSelectAct($queryObject, $connection = null, $with_values = true) { function _executeSelectAct($queryObject, $connection = null, $with_values = true) {
if ($this->use_prepared_statements == 'Y') { if ($this->use_prepared_statements == 'Y') {
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
@ -745,6 +822,11 @@
} }
} }
/**
* If have a error, return error object
* @param Object $queryObject
* @return Object
*/
function queryError($queryObject){ function queryError($queryObject){
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
if ($limit && $limit->isPageHandler()){ if ($limit && $limit->isPageHandler()){
@ -759,6 +841,13 @@
return; return;
} }
/**
* If select query execute, return page info
* @param Object $queryObject
* @param resource $connection
* @param boolean $with_values
* @return Object Object with page info containing
*/
function queryPageLimit($queryObject, $connection, $with_values){ function queryPageLimit($queryObject, $connection, $with_values){
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
// Total count // Total count
@ -834,11 +923,23 @@
return $buff; return $buff;
} }
function &getParser($force = FALSE){ /**
$dbParser = new DBParser('"', '"', $this->prefix); * Return the DBParser
return $dbParser; * @param boolean $force
* @return DBParser
*/
function getParser($force = FALSE){
return new DBParser('"', '"', $this->prefix);
} }
/**
* If select query execute, return paging sql
* @param object $query
* @param boolean $with_values
* @param int $start_count
* @param int $list_count
* @return string select paging sql
*/
function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) { function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) {
$select = $query->getSelectString($with_values); $select = $query->getSelectString($with_values);

View file

@ -1,27 +1,30 @@
<?php <?php
/** /**
* @class DBMSSQL * - DBMSSQL
* - Modified to use MSSQL driver by sol (sol@ngleader.com)
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief Modified to use MSSQL driver by sol (sol@ngleader.com) * @package /classes/db
* @version 0.1 * @version 0.1
**/ **/
class DBMssql extends DB { class DBMssql extends DB {
/** /**
* information to connect to DB * prefix of XE tables(One more XE can be installed on a single DB)
**/ * @var string
var $prefix = 'xe'; // / <prefix of XE tables(One more XE can be installed on a single DB) */
var $prefix = 'xe';
var $param = array(); var $param = array();
var $comment_syntax = '/* %s */'; var $comment_syntax = '/* %s */';
/** /**
* @brief column type used in mssql * column type used in mssql
* *
* column_type should be replaced for each DBMS's type * column_type should be replaced for each DBMS's type
* becasue it uses commonly defined type in the schema/query xml * becasue it uses commonly defined type in the schema/query xml
**/ * @var array
*/
var $column_type = array( var $column_type = array(
'bignumber' => 'bigint', 'bignumber' => 'bigint',
'number' => 'int', 'number' => 'int',
@ -34,32 +37,39 @@
); );
/** /**
* @brief constructor * Constructor
**/ * @return void
*/
function DBMssql() { function DBMssql() {
$this->_setDBInfo(); $this->_setDBInfo();
$this->_connect(); $this->_connect();
} }
/** /**
* @brief create an instance of this class * Create an instance of this class
* @return DBMssql return DBMssql object instance
*/ */
function create() function create()
{ {
return new DBMssql; return new DBMssql;
} }
/** /**
* @brief Return if installable * Return if supportable
**/ * Check 'sqlsrv' extension loaded.
* @return boolean
*/
function isSupported() { function isSupported() {
if (!extension_loaded("sqlsrv")) return false; if (!extension_loaded("sqlsrv")) return false;
return true; return true;
} }
/** /**
* @brief DB Connection * DB Connect
**/ * this method is private
* @param array $connection connection's value is db_hostname, db_database, db_userid, db_password
* @return resource
*/
function __connect($connection) { function __connect($connection) {
//sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); //sqlsrv_configure( 'WarningsReturnAsErrors', 0 );
//sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
@ -75,18 +85,23 @@
return $result; return $result;
} }
/** /**
* @brief DB disconnect * DB disconnection
**/ * this method is private
* @param resource $connection
* @return void
*/
function _close($connection) { function _close($connection) {
$this->commit(); $this->commit();
sqlsrv_close($connection); sqlsrv_close($connection);
} }
/** /**
* @brief handles quatation of the string variables from the query * Handles quatation of the string variables from the query
**/ * @todo See what to do about this
// TODO See what to do about this * @param string $string
* @return string
*/
function addQuotes($string) { function addQuotes($string) {
if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
//if(!is_numeric($string)) $string = str_replace("'","''",$string); //if(!is_numeric($string)) $string = str_replace("'","''",$string);
@ -94,42 +109,46 @@
return $string; return $string;
} }
/** /**
* @brief Begin transaction * DB transaction start
**/ * this method is private
* @return boolean
*/
function _begin() { function _begin() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
if(sqlsrv_begin_transaction($connection) === false) return; if(sqlsrv_begin_transaction($connection) === false) return;
return true; return true;
} }
/** /**
* @brief Rollback * DB transaction rollback
**/ * this method is private
* @return boolean
*/
function _rollback() { function _rollback() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
sqlsrv_rollback($connection); sqlsrv_rollback($connection);
return true; return true;
} }
/** /**
* @brief Commit * DB transaction commit
**/ * this method is private
* @return boolean
*/
function _commit() { function _commit() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
sqlsrv_commit($connection); sqlsrv_commit($connection);
return true; return true;
} }
/** /**
* @brief : executing the query and fetching the result * Execute the query
* * this method is private
* query: run a query and return the result\n * @param string $query
* fetch: NULL if no value returned \n * @param resource $connection
* array object if rows returned \n * @return resource|boolean Returns a statement resource on success and FALSE if an error occurred.
* object if a row returned \n */
* return\n
**/
function __query($query, $connection) { function __query($query, $connection) {
$_param = array(); $_param = array();
@ -183,6 +202,8 @@
* Parameters are sent as an array, where each parameter can be: * Parameters are sent as an array, where each parameter can be:
* - a PHP variable (by reference) * - a PHP variable (by reference)
* - a PHP array (containng param value, type and direction) -> also needs to be sent by reference * - a PHP array (containng param value, type and direction) -> also needs to be sent by reference
* @param array $_param
* @return array
*/ */
function _getParametersByReference($_param) function _getParametersByReference($_param)
{ {
@ -206,9 +227,12 @@
return $args; return $args;
} }
/** /**
* @brief Fetch results * Fetch results
**/ * @param resource $result
* @param int|NULL $arrayIndexEndValue
* @return array
*/
function _fetch($result, $arrayIndexEndValue = NULL) { function _fetch($result, $arrayIndexEndValue = NULL) {
$output = array(); $output = array();
if(!$this->isConnected() || $this->isError() || !$result) return $output; if(!$this->isConnected() || $this->isError() || !$result) return $output;
@ -234,9 +258,11 @@
} }
/** /**
* @brief Return sequence value incremented by 1(auto_increment is usd in the sequence table only) * Return the sequence value incremented by 1
**/ * Auto_increment column only used in the sequence table
* @return int
*/
function getNextSequence() { function getNextSequence() {
$query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix); $query = sprintf("insert into %ssequence (seq) values (ident_incr('%ssequence'))", $this->prefix, $this->prefix);
$this->_query($query); $this->_query($query);
@ -249,9 +275,11 @@
return $tmp->sequence; return $tmp->sequence;
} }
/** /**
* @brief Return if a table already exists * Check a table exists status
**/ * @param string $target_name
* @return boolean
*/
function isTableExists($target_name) { function isTableExists($target_name) {
$query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($target_name)); $query = sprintf("select name from sysobjects where name = '%s%s' and xtype='U'", $this->prefix, $this->addQuotes($target_name));
$result = $this->_query($query); $result = $this->_query($query);
@ -261,9 +289,16 @@
return true; return true;
} }
/** /**
* @brief Add a column to a table * Add a column to the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @param string $type column type, default value is 'number'
* @param int $size column size
* @param string|int $default default value
* @param boolean $notnull not null status, default value is false
* @return void
*/
function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) { function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) {
if($this->isColumnExists($table_name, $column_name)) return; if($this->isColumnExists($table_name, $column_name)) return;
$type = $this->column_type[$type]; $type = $this->column_type[$type];
@ -278,18 +313,24 @@
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Delete a column from a table * Drop a column from the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return void
*/
function dropColumn($table_name, $column_name) { function dropColumn($table_name, $column_name) {
if(!$this->isColumnExists($table_name, $column_name)) return; if(!$this->isColumnExists($table_name, $column_name)) return;
$query = sprintf("alter table %s%s drop %s ", $this->prefix, $table_name, $column_name); $query = sprintf("alter table %s%s drop %s ", $this->prefix, $table_name, $column_name);
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Return column information of a table * Check column exist status of the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return boolean
*/
function isColumnExists($table_name, $column_name) { function isColumnExists($table_name, $column_name) {
$query = sprintf("select syscolumns.name as name from syscolumns, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = syscolumns.id and syscolumns.name = '%s'", $this->prefix, $table_name, $column_name); $query = sprintf("select syscolumns.name as name from syscolumns, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = syscolumns.id and syscolumns.name = '%s'", $this->prefix, $table_name, $column_name);
$result = $this->_query($query); $result = $this->_query($query);
@ -299,11 +340,16 @@
return true; return true;
} }
/** /**
* @brief Add an index to a table * Add an index to the table
* $target_columns = array(col1, col2) * $target_columns = array(col1, col2)
* $is_unique? unique : none * $is_unique? unique : none
**/ * @param string $table_name table name
* @param string $index_name index name
* @param string|array $target_columns target column or columns
* @param boolean $is_unique
* @return void
*/
function addIndex($table_name, $index_name, $target_columns, $is_unique = false) { function addIndex($table_name, $index_name, $target_columns, $is_unique = false) {
if($this->isIndexExists($table_name, $index_name)) return; if($this->isIndexExists($table_name, $index_name)) return;
if(!is_array($target_columns)) $target_columns = array($target_columns); if(!is_array($target_columns)) $target_columns = array($target_columns);
@ -312,18 +358,25 @@
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Drop an index from a table * Drop an index from the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @param boolean $is_unique
* @return void
*/
function dropIndex($table_name, $index_name, $is_unique = false) { function dropIndex($table_name, $index_name, $is_unique = false) {
if(!$this->isIndexExists($table_name, $index_name)) return; if(!$this->isIndexExists($table_name, $index_name)) return;
$query = sprintf("drop index %s%s.%s", $this->prefix, $table_name, $index_name); $query = sprintf("drop index %s%s.%s", $this->prefix, $table_name, $index_name);
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Return index information of a table * Check index status of the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @return boolean
*/
function isIndexExists($table_name, $index_name) { function isIndexExists($table_name, $index_name) {
$query = sprintf("select sysindexes.name as name from sysindexes, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = sysindexes.id and sysindexes.name = '%s'", $this->prefix, $table_name, $index_name); $query = sprintf("select sysindexes.name as name from sysindexes, sysobjects where sysobjects.name = '%s%s' and sysobjects.id = sysindexes.id and sysindexes.name = '%s'", $this->prefix, $table_name, $index_name);
@ -335,16 +388,20 @@
return true; return true;
} }
/** /**
* @brief Create a table by using xml file * Creates a table by using xml contents
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function createTableByXml($xml_doc) { function createTableByXml($xml_doc) {
return $this->_createTable($xml_doc); return $this->_createTable($xml_doc);
} }
/** /**
* @brief Create a table by using xml file * Creates a table by using xml file path
**/ * @param string $file_name xml schema file path
* @return void|object
*/
function createTableByXmlFile($file_name) { function createTableByXmlFile($file_name) {
if(!file_exists($file_name)) return; if(!file_exists($file_name)) return;
// read xml file // read xml file
@ -352,13 +409,15 @@
return $this->_createTable($buff); return $this->_createTable($buff);
} }
/** /**
* @brief generate a query statement to create a table by using schema xml * Create table by using the schema xml
* *
* type : number, varchar, text, char, date, \n * type : number, varchar, tinytext, text, bigtext, char, date, \n
* opt : notnull, default, size\n * opt : notnull, default, size\n
* index : primary key, index, unique\n * index : primary key, index, unique\n
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function _createTable($xml_doc) { function _createTable($xml_doc) {
// xml parsing // xml parsing
$oXml = new XmlParser(); $oXml = new XmlParser();
@ -381,6 +440,7 @@
$unique_list = array(); $unique_list = array();
$index_list = array(); $index_list = array();
$typeList = array('number'=>1, 'text'=>1);
foreach($columns as $column) { foreach($columns as $column) {
$name = $column->attrs->name; $name = $column->attrs->name;
$type = $column->attrs->type; $type = $column->attrs->type;
@ -395,7 +455,7 @@
$column_schema[] = sprintf('[%s] %s%s %s %s %s', $column_schema[] = sprintf('[%s] %s%s %s %s %s',
$name, $name,
$this->column_type[$type], $this->column_type[$type],
!in_array($type,array('number','text'))&&$size?'('.$size.')':'', !isset($typeList[$type])&&$size?'('.$size.')':'',
isset($default)?"default '".$default."'":'', isset($default)?"default '".$default."'":'',
$notnull?'not null':'null', $notnull?'not null':'null',
$auto_increment?'identity(1,1)':'' $auto_increment?'identity(1,1)':''
@ -433,25 +493,37 @@
} }
/**
* @brief Handle the insertAct /**
**/ * Handles insertAct
// TODO Lookup _filterNumber against sql injection - see if it is still needed and how to integrate * @todo Lookup _filterNumber against sql injection - see if it is still needed and how to integrate
* @param Object $queryObject
* @return resource
*/
function _executeInsertAct($queryObject) { function _executeInsertAct($queryObject) {
$query = $this->getInsertSql($queryObject, false); $query = $this->getInsertSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
/** /**
* @brief Handle updateAct * Handles updateAct
**/ * @param Object $queryObject
* @return resource
*/
function _executeUpdateAct($queryObject) { function _executeUpdateAct($queryObject) {
$query = $this->getUpdateSql($queryObject, false); $query = $this->getUpdateSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
/**
* Return update query string
* @param object $query
* @param boolean $with_values
* @param boolean $with_priority
* @return string
*/
function getUpdateSql($query, $with_values = true, $with_priority = false){ function getUpdateSql($query, $with_values = true, $with_priority = false){
$columnsList = $query->getUpdateString($with_values); $columnsList = $query->getUpdateString($with_values);
if($columnsList == '') return new Object(-1, "Invalid query"); if($columnsList == '') return new Object(-1, "Invalid query");
@ -473,15 +545,23 @@
return "UPDATE $priority $alias_list SET $columnsList FROM ".$from.$where; return "UPDATE $priority $alias_list SET $columnsList FROM ".$from.$where;
} }
/** /**
* @brief Handle deleteAct * Handles deleteAct
**/ * @param Object $queryObject
* @return resource
*/
function _executeDeleteAct($queryObject) { function _executeDeleteAct($queryObject) {
$query = $this->getDeleteSql($queryObject, false); $query = $this->getDeleteSql($queryObject, false);
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
return $this->_query($query); return $this->_query($query);
} }
/**
* Return select query string
* @param object $query
* @param boolean $with_values
* @return string
*/
function getSelectSql($query, $with_values = TRUE){ function getSelectSql($query, $with_values = TRUE){
$with_values = false; $with_values = false;
@ -519,12 +599,14 @@
return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy;
} }
/** /**
* @brief Handle selectAct * Handle selectAct
* * In order to get a list of pages easily when selecting \n
* In order to get a list of pages easily when selecting \n * it supports a method as navigation
* it supports a method as navigation * @param Object $queryObject
**/ * @param resource $connection
* @return Object
*/
function _executeSelectAct($queryObject, $connection = null) { function _executeSelectAct($queryObject, $connection = null) {
$query = $this->getSelectSql($queryObject); $query = $this->getSelectSql($queryObject);
@ -540,11 +622,20 @@
else return $this->queryPageLimit($queryObject, $result, $connection); else return $this->queryPageLimit($queryObject, $result, $connection);
} }
function &getParser($force = FALSE){ /**
$dbParser = new DBParser("[", "]", $this->prefix); * Return the DBParser
return $dbParser; * @param boolean $force
* @return DBParser
*/
function getParser($force = FALSE){
return new DBParser("[", "]", $this->prefix);
} }
/**
* If have a error, return error object
* @param Object $queryObject
* @return Object
*/
function queryError($queryObject){ function queryError($queryObject){
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
if ($limit && $limit->isPageHandler()){ if ($limit && $limit->isPageHandler()){
@ -559,6 +650,13 @@
return; return;
} }
/**
* If select query execute, return page info
* @param Object $queryObject
* @param resource $result
* @param resource $connection
* @return Object Object with page info containing
*/
function queryPageLimit($queryObject, $result, $connection) { function queryPageLimit($queryObject, $result, $connection) {
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
if ($limit && $limit->isPageHandler()) { if ($limit && $limit->isPageHandler()) {
@ -615,7 +713,7 @@
$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count); $buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count);
return $buff; return $buff;
} }
$start_count = ($page - 1) * $list_count; $start_count = ($page - 1) * $list_count;
$this->param = $queryObject->getArguments(); $this->param = $queryObject->getArguments();
$virtual_no = $total_count - $start_count; $virtual_no = $total_count - $start_count;

View file

@ -1,29 +1,30 @@
<?php <?php
/** /**
* @class DBMysql * Class to use MySQL DBMS
* @author NHN (developers@xpressengine.com)
* @brief Class to use MySQL DBMS
* @version 0.1
*
* mysql handling class * mysql handling class
* *
* Does not use prepared statements, since mysql driver does not support them * Does not use prepared statements, since mysql driver does not support them
**/ *
* @author NHN (developers@xpressengine.com)
* @package /classes/db
* @version 0.1
*/
class DBMysql extends DB { class DBMysql extends DB {
/** /**
* @brief Connection information for Mysql DB * prefix of a tablename (One or more XEs can be installed in a single DB)
**/ * @var string
var $prefix = 'xe_'; // / <prefix of a tablename (One or more XEs can be installed in a single DB) */
var $prefix = 'xe_'; // / <
var $comment_syntax = '/* %s */'; var $comment_syntax = '/* %s */';
/** /**
* @brief Column type used in MySQL * Column type used in MySQL
* *
* Becasue a common column type in schema/query xml is used for colum_type, * Becasue a common column type in schema/query xml is used for colum_type,
* it should be replaced properly for each DBMS * it should be replaced properly for each DBMS
**/ * @var array
*/
var $column_type = array( var $column_type = array(
'bignumber' => 'bigint', 'bignumber' => 'bigint',
'number' => 'bigint', 'number' => 'bigint',
@ -36,28 +37,38 @@ class DBMysql extends DB {
); );
/** /**
* @brief constructor * Constructor
**/ * @return void
*/
function DBMysql() { function DBMysql() {
$this->_setDBInfo(); $this->_setDBInfo();
$this->_connect(); $this->_connect();
} }
/**
* Create an instance of this class
* @return DBMysql return DBMysql object instance
*/
function create() { function create() {
return new DBMysql; return new DBMysql;
} }
/** /**
* @brief Return if it is installable * Return if supportable
**/ * Check 'mysql_connect' function exists.
* @return boolean
*/
function isSupported() { function isSupported() {
if(!function_exists('mysql_connect')) return false; if(!function_exists('mysql_connect')) return false;
return true; return true;
} }
/** /**
* @brief DB Connection * DB Connect
**/ * this method is private
* @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password
* @return resource
*/
function __connect($connection) { function __connect($connection) {
// Ignore if no DB information exists // Ignore if no DB information exists
if (strpos($connection["db_hostname"], ':') === false && $connection["db_port"]) if (strpos($connection["db_hostname"], ':') === false && $connection["db_port"])
@ -85,57 +96,72 @@ class DBMysql extends DB {
return $result; return $result;
} }
/**
* If have a task after connection, add a taks in this method
* this method is private
* @param resource $connection
* @return void
*/
function _afterConnect($connection){ function _afterConnect($connection){
// Set utf8 if a database is MySQL // Set utf8 if a database is MySQL
$this->_query("set names 'utf8'", $connection); $this->_query("set names 'utf8'", $connection);
} }
/** /**
* @brief DB disconnection * DB disconnection
**/ * this method is private
* @param resource $connection
* @return void
*/
function _close($connection) { function _close($connection) {
@mysql_close($connection); @mysql_close($connection);
} }
/** /**
* @brief Add quotes on the string variables in a query * Handles quatation of the string variables from the query
**/ * @param string $string
* @return string
*/
function addQuotes($string) { function addQuotes($string) {
if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
if(!is_numeric($string)) $string = @mysql_real_escape_string($string); if(!is_numeric($string)) $string = @mysql_real_escape_string($string);
return $string; return $string;
} }
/** /**
* @brief Begin transaction * DB transaction start
**/ * this method is private
* @return boolean
*/
function _begin() { function _begin() {
return true; return true;
} }
/** /**
* @brief Rollback * DB transaction rollback
**/ * this method is private
* @return boolean
*/
function _rollback() { function _rollback() {
return true; return true;
} }
/** /**
* @brief Commits * DB transaction commit
**/ * this method is private
* @return boolean
*/
function _commit() { function _commit() {
return true; return true;
} }
/** /**
* @brief : Run a query and fetch the result * Execute the query
* * this method is private
* query: run a query and return the result \n * @param string $query
* fetch: NULL if no value is returned \n * @param resource $connection
* array object if rows are returned \n * @return resource
* object if a row is returned \n */
* return\n
**/
function __query($query, $connection) { function __query($query, $connection) {
// Run the query statement // Run the query statement
$result = mysql_query($query, $connection); $result = mysql_query($query, $connection);
@ -145,9 +171,12 @@ class DBMysql extends DB {
return $result; return $result;
} }
/** /**
* @brief Fetch results * Fetch the result
**/ * @param resource $result
* @param int|NULL $arrayIndexEndValue
* @return array
*/
function _fetch($result, $arrayIndexEndValue = NULL) { function _fetch($result, $arrayIndexEndValue = NULL) {
$output = array(); $output = array();
if(!$this->isConnected() || $this->isError() || !$result) return $output; if(!$this->isConnected() || $this->isError() || !$result) return $output;
@ -163,9 +192,11 @@ class DBMysql extends DB {
return $output; return $output;
} }
/** /**
* @brief Return sequence value incremented by 1(auto_increment is used in sequence table only in MySQL) * Return the sequence value incremented by 1
**/ * Auto_increment column only used in the sequence table
* @return int
*/
function getNextSequence() { function getNextSequence() {
$query = sprintf("insert into `%ssequence` (seq) values ('0')", $this->prefix); $query = sprintf("insert into `%ssequence` (seq) values ('0')", $this->prefix);
$this->_query($query); $this->_query($query);
@ -178,9 +209,12 @@ class DBMysql extends DB {
return $sequence; return $sequence;
} }
/** /**
* @brief Function to obtain mysql old password(mysql only) * Function to obtain mysql old password(mysql only)
**/ * @param string $password input password
* @param string $saved_password saved password in DBMS
* @return boolean
*/
function isValidOldPassword($password, $saved_password) { function isValidOldPassword($password, $saved_password) {
$query = sprintf("select password('%s') as password, old_password('%s') as old_password", $this->addQuotes($password), $this->addQuotes($password)); $query = sprintf("select password('%s') as password, old_password('%s') as old_password", $this->addQuotes($password), $this->addQuotes($password));
$result = $this->_query($query); $result = $this->_query($query);
@ -189,9 +223,11 @@ class DBMysql extends DB {
return false; return false;
} }
/** /**
* @brief Return if a table already exists * Check a table exists status
**/ * @param string $target_name
* @return boolean
*/
function isTableExists($target_name) { function isTableExists($target_name) {
$query = sprintf("show tables like '%s%s'", $this->prefix, $this->addQuotes($target_name)); $query = sprintf("show tables like '%s%s'", $this->prefix, $this->addQuotes($target_name));
$result = $this->_query($query); $result = $this->_query($query);
@ -200,9 +236,16 @@ class DBMysql extends DB {
return true; return true;
} }
/** /**
* @brief Add a column to a table * Add a column to the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @param string $type column type, default value is 'number'
* @param int $size column size
* @param string|int $default default value
* @param boolean $notnull not null status, default value is false
* @return void
*/
function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) { function addColumn($table_name, $column_name, $type='number', $size='', $default = '', $notnull=false) {
$type = $this->column_type[$type]; $type = $this->column_type[$type];
if(strtoupper($type)=='INTEGER') $size = ''; if(strtoupper($type)=='INTEGER') $size = '';
@ -216,17 +259,23 @@ class DBMysql extends DB {
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Delete a column from a table * Drop a column from the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return void
*/
function dropColumn($table_name, $column_name) { function dropColumn($table_name, $column_name) {
$query = sprintf("alter table `%s%s` drop `%s` ", $this->prefix, $table_name, $column_name); $query = sprintf("alter table `%s%s` drop `%s` ", $this->prefix, $table_name, $column_name);
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Return column information of a table * Check column exist status of the table
**/ * @param string $table_name table name
* @param string $column_name column name
* @return boolean
*/
function isColumnExists($table_name, $column_name) { function isColumnExists($table_name, $column_name) {
$query = sprintf("show fields from `%s%s`", $this->prefix, $table_name); $query = sprintf("show fields from `%s%s`", $this->prefix, $table_name);
$result = $this->_query($query); $result = $this->_query($query);
@ -242,11 +291,16 @@ class DBMysql extends DB {
return false; return false;
} }
/** /**
* @brief Add an index to a table * Add an index to the table
* $target_columns = array(col1, col2) * $target_columns = array(col1, col2)
* $is_unique? unique : none * $is_unique? unique : none
**/ * @param string $table_name table name
* @param string $index_name index name
* @param string|array $target_columns target column or columns
* @param boolean $is_unique
* @return void
*/
function addIndex($table_name, $index_name, $target_columns, $is_unique = false) { function addIndex($table_name, $index_name, $target_columns, $is_unique = false) {
if(!is_array($target_columns)) $target_columns = array($target_columns); if(!is_array($target_columns)) $target_columns = array($target_columns);
@ -254,18 +308,25 @@ class DBMysql extends DB {
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Drop an index from a table * Drop an index from the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @param boolean $is_unique
* @return void
*/
function dropIndex($table_name, $index_name, $is_unique = false) { function dropIndex($table_name, $index_name, $is_unique = false) {
$query = sprintf("alter table `%s%s` drop index `%s`", $this->prefix, $table_name, $index_name); $query = sprintf("alter table `%s%s` drop index `%s`", $this->prefix, $table_name, $index_name);
$this->_query($query); $this->_query($query);
} }
/** /**
* @brief Return index information of a table * Check index status of the table
**/ * @param string $table_name table name
* @param string $index_name index name
* @return boolean
*/
function isIndexExists($table_name, $index_name) { function isIndexExists($table_name, $index_name) {
//$query = sprintf("show indexes from %s%s where key_name = '%s' ", $this->prefix, $table_name, $index_name); //$query = sprintf("show indexes from %s%s where key_name = '%s' ", $this->prefix, $table_name, $index_name);
$query = sprintf("show indexes from `%s%s`", $this->prefix, $table_name); $query = sprintf("show indexes from `%s%s`", $this->prefix, $table_name);
@ -281,16 +342,20 @@ class DBMysql extends DB {
return false; return false;
} }
/** /**
* @brief Create a table by using xml file * Creates a table by using xml contents
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function createTableByXml($xml_doc) { function createTableByXml($xml_doc) {
return $this->_createTable($xml_doc); return $this->_createTable($xml_doc);
} }
/** /**
* @brief Create a table by using xml file * Creates a table by using xml file path
**/ * @param string $file_name xml schema file path
* @return void|object
*/
function createTableByXmlFile($file_name) { function createTableByXmlFile($file_name) {
if(!file_exists($file_name)) return; if(!file_exists($file_name)) return;
// read xml file // read xml file
@ -298,13 +363,15 @@ class DBMysql extends DB {
return $this->_createTable($buff); return $this->_createTable($buff);
} }
/** /**
* @brief generate a query statement to create a table by using schema xml * Create table by using the schema xml
* *
* type : number, varchar, text, char, date, \n * type : number, varchar, tinytext, text, bigtext, char, date, \n
* opt : notnull, default, size\n * opt : notnull, default, size\n
* index : primary key, index, unique\n * index : primary key, index, unique\n
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function _createTable($xml_doc) { function _createTable($xml_doc) {
// xml parsing // xml parsing
$oXml = new XmlParser(); $oXml = new XmlParser();
@ -368,39 +435,51 @@ class DBMysql extends DB {
if(!$output) return false; if(!$output) return false;
} }
/** /**
* @brief Handle the insertAct * Handles insertAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeInsertAct($queryObject, $with_values = true) { function _executeInsertAct($queryObject, $with_values = true) {
$query = $this->getInsertSql($queryObject, $with_values, true); $query = $this->getInsertSql($queryObject, $with_values, true);
if(is_a($query, 'Object')) return; if(is_a($query, 'Object')) return;
return $this->_query($query); return $this->_query($query);
} }
/** /**
* @brief Handle updateAct * Handles updateAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeUpdateAct($queryObject, $with_values = true) { function _executeUpdateAct($queryObject, $with_values = true) {
$query = $this->getUpdateSql($queryObject, $with_values, true); $query = $this->getUpdateSql($queryObject, $with_values, true);
if(is_a($query, 'Object')) return; if(is_a($query, 'Object')) return;
return $this->_query($query); return $this->_query($query);
} }
/** /**
* @brief Handle deleteAct * Handles deleteAct
**/ * @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeDeleteAct($queryObject, $with_values = true) { function _executeDeleteAct($queryObject, $with_values = true) {
$query = $this->getDeleteSql($queryObject, $with_values, true); $query = $this->getDeleteSql($queryObject, $with_values, true);
if(is_a($query, 'Object')) return; if(is_a($query, 'Object')) return;
return $this->_query($query); return $this->_query($query);
} }
/** /**
* @brief Handle selectAct * Handle selectAct
* * In order to get a list of pages easily when selecting \n
* In order to get a list of pages easily when selecting \n * it supports a method as navigation
* it supports a method as navigation * @param Object $queryObject
**/ * @param resource $connection
* @param boolean $with_values
* @return Object
*/
function _executeSelectAct($queryObject, $connection = null, $with_values = true) { function _executeSelectAct($queryObject, $connection = null, $with_values = true) {
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
$result = NULL; $result = NULL;
@ -423,26 +502,52 @@ class DBMysql extends DB {
} }
} }
/**
* Get the ID generated in the last query
* Return next sequence from sequence table
* This method use only mysql
* @return int
*/
function db_insert_id() function db_insert_id()
{ {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
return mysql_insert_id($connection); return mysql_insert_id($connection);
} }
/**
* Fetch a result row as an object
* @param resource $result
* @return object
*/
function db_fetch_object(&$result) function db_fetch_object(&$result)
{ {
return mysql_fetch_object($result); return mysql_fetch_object($result);
} }
/**
* Free result memory
* @param resource $result
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function db_free_result(&$result){ function db_free_result(&$result){
return mysql_free_result($result); return mysql_free_result($result);
} }
/**
* Return the DBParser
* @param boolean $force
* @return DBParser
*/
function &getParser($force = FALSE){ function &getParser($force = FALSE){
$dbParser = new DBParser('`', '`', $this->prefix); $dbParser = new DBParser('`', '`', $this->prefix);
return $dbParser; return $dbParser;
} }
/**
* If have a error, return error object
* @param Object $queryObject
* @return Object
*/
function queryError($queryObject){ function queryError($queryObject){
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
if ($limit && $limit->isPageHandler()){ if ($limit && $limit->isPageHandler()){
@ -457,6 +562,14 @@ class DBMysql extends DB {
return; return;
} }
/**
* If select query execute, return page info
* @param Object $queryObject
* @param resource $result
* @param resource $connection
* @param boolean $with_values
* @return Object Object with page info containing
*/
function queryPageLimit($queryObject, $result, $connection, $with_values = true){ function queryPageLimit($queryObject, $result, $connection, $with_values = true){
$limit = $queryObject->getLimit(); $limit = $queryObject->getLimit();
// Total count // Total count
@ -469,7 +582,7 @@ class DBMysql extends DB {
$uses_groupby = $queryObject->getGroupByString() != ''; $uses_groupby = $queryObject->getGroupByString() != '';
if($uses_distinct || $uses_groupby) { if($uses_distinct || $uses_groupby) {
$count_query = sprintf('select %s %s %s %s' $count_query = sprintf('select %s %s %s %s'
, $temp_select , $temp_select == '*' ? '1' : $temp_select
, 'FROM ' . $queryObject->getFromString($with_values) , 'FROM ' . $queryObject->getFromString($with_values)
, ($temp_where === '' ? '' : ' WHERE '. $temp_where) , ($temp_where === '' ? '' : ' WHERE '. $temp_where)
, ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '') , ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '')
@ -529,6 +642,14 @@ class DBMysql extends DB {
return $buff; return $buff;
} }
/**
* If select query execute, return paging sql
* @param object $query
* @param boolean $with_values
* @param int $start_count
* @param int $list_count
* @return string select paging sql
*/
function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) { function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) {
$select = $query->getSelectString($with_values); $select = $query->getSelectString($with_values);
if($select == '') return new Object(-1, "Invalid query"); if($select == '') return new Object(-1, "Invalid query");

View file

@ -1,79 +1,87 @@
<?php <?php
require_once('DBMysql.class.php'); require_once('DBMysql.class.php');
/** /**
* @class DBMysql_innodb * Class to use MySQL innoDB DBMS
* @author NHN (developers@xpressengine.com) * mysql innodb handling class
* @brief class to use MySQL DBMS *
* @version 0.1 * Does not use prepared statements, since mysql driver does not support them
* *
* mysql innodb handling class * @author NHN (developers@xpressengine.com)
* * @package /classes/db
* Does not use prepared statements since the mysql driver does not support them * @version 0.1
**/ **/
class DBMysql_innodb extends DBMysql { class DBMysql_innodb extends DBMysql {
/** /**
* @brief constructor * Constructor
**/ * @return void
**/
function DBMysql_innodb() { function DBMysql_innodb() {
$this->_setDBInfo(); $this->_setDBInfo();
$this->_connect(); $this->_connect();
} }
/** /**
* @brief create an instance of this class * Create an instance of this class
* @return DBMysql_innodb return DBMysql_innodb object instance
*/ */
function create() function create()
{ {
return new DBMysql_innodb; return new DBMysql_innodb;
} }
/** /**
* @brief DB disconnection * DB disconnection
**/ * this method is private
* @param resource $connection
* @return void
*/
function _close($connection) { function _close($connection) {
$this->_query("commit", $connection); $this->_query("commit", $connection);
@mysql_close($connection); @mysql_close($connection);
} }
/** /**
* @brief Begin transaction * DB transaction start
**/ * this method is private
* @return boolean
*/
function _begin() { function _begin() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
$this->_query("begin", $connection); $this->_query("begin", $connection);
return true; return true;
} }
/** /**
* @brief Rollback * DB transaction rollback
**/ * this method is private
* @return boolean
*/
function _rollback() { function _rollback() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
$this->_query("rollback", $connection); $this->_query("rollback", $connection);
return true; return true;
} }
/** /**
* @brief Commits * DB transaction commit
**/ * this method is private
* @return boolean
*/
function _commit() { function _commit() {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
$this->_query("commit", $connection); $this->_query("commit", $connection);
return true; return true;
} }
/** /**
* @brief : Run a query and fetch the result * Execute the query
* * this method is private
* query: run a query and return the result \n * @param string $query
* fetch: NULL if no value is returned \n * @param resource $connection
* array object if rows are returned \n * @return resource
* object if a row is returned \n */
* return\n
**/
function __query($query, $connection) { function __query($query, $connection) {
// Run the query statement // Run the query statement
$result = @mysql_query($query, $connection); $result = @mysql_query($query, $connection);
@ -83,13 +91,15 @@
return $result; return $result;
} }
/** /**
* @brief generate a query statement to create a table by using schema xml * Create table by using the schema xml
* *
* type : number, varchar, text, char, date, \n * type : number, varchar, tinytext, text, bigtext, char, date, \n
* opt : notnull, default, size\n * opt : notnull, default, size\n
* index : primary key, index, unique\n * index : primary key, index, unique\n
**/ * @param string $xml_doc xml schema contents
* @return void|object
*/
function _createTable($xml_doc) { function _createTable($xml_doc) {
// xml parsing // xml parsing
$oXml = new XmlParser(); $oXml = new XmlParser();

View file

@ -1,44 +1,52 @@
<?php <?php
require_once('DBMysql.class.php'); require_once('DBMysql.class.php');
/**
* @class DBMysqli
* @author NHN (developers@xpressengine.com)
* @brief Class to use MySQL DBMS as mysqli_*
* @version 0.1
*
* mysql handling class
**/
/**
* Class to use MySQLi DBMS as mysqli_*
* mysql handling class
*
* Does not use prepared statements, since mysql driver does not support them
*
* @author NHN (developers@xpressengine.com)
* @package /classes/db
* @version 0.1
**/
class DBMysqli extends DBMysql { class DBMysqli extends DBMysql {
/** /**
* @brief constructor * Constructor
**/ * @return void
**/
function DBMysqli() { function DBMysqli() {
$this->_setDBInfo(); $this->_setDBInfo();
$this->_connect(); $this->_connect();
} }
/** /**
* @brief Return if it is installable * Return if supportable
**/ * Check 'mysqli_connect' function exists.
* @return boolean
*/
function isSupported() { function isSupported() {
if(!function_exists('mysqli_connect')) return false; if(!function_exists('mysqli_connect')) return false;
return true; return true;
} }
/** /**
* @brief create an instance of this class * Create an instance of this class
* @return DBMysqli return DBMysqli object instance
*/ */
function create() function create()
{ {
return new DBMysqli; return new DBMysqli;
} }
/** /**
* @brief DB Connection * DB Connect
**/ * this method is private
* @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password
* @return resource
*/
function __connect($connection) { function __connect($connection) {
// Attempt to connect // Attempt to connect
if ($connection["db_port"]) { if ($connection["db_port"]) {
@ -62,16 +70,21 @@
return $result; return $result;
} }
/** /**
* @brief DB disconnection * DB disconnection
**/ * this method is private
* @param resource $connection
* @return void
*/
function _close($connection) { function _close($connection) {
mysqli_close($connection); mysqli_close($connection);
} }
/** /**
* @brief Add quotes on the string variables in a query * Handles quatation of the string variables from the query
**/ * @param string $string
* @return string
*/
function addQuotes($string) { function addQuotes($string) {
if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string));
if(!is_numeric($string)){ if(!is_numeric($string)){
@ -81,15 +94,13 @@
return $string; return $string;
} }
/** /**
* @brief : Run a query and fetch the result * Execute the query
* * this method is private
* query: run a query and return the result \n * @param string $query
* fetch: NULL if no value is returned \n * @param resource $connection
* array object if rows are returned \n * @return resource
* object if a row is returned \n */
* return\n
**/
function __query($query, $connection) { function __query($query, $connection) {
if($this->use_prepared_statements == 'Y') if($this->use_prepared_statements == 'Y')
{ {
@ -140,6 +151,13 @@
return $result; return $result;
} }
/**
* Before execute query, prepare statement
* this method is private
* @param string $types
* @param array $params
* @return void
*/
function _prepareQueryParameters(&$types, &$params){ function _prepareQueryParameters(&$types, &$params){
$types = ''; $types = '';
$params = array(); $params = array();
@ -182,9 +200,12 @@
} }
} }
/** /**
* @brief Fetch results * Fetch the result
**/ * @param resource $result
* @param int|NULL $arrayIndexEndValue
* @return array
*/
function _fetch($result, $arrayIndexEndValue = NULL) { function _fetch($result, $arrayIndexEndValue = NULL) {
if($this->use_prepared_statements != 'Y'){ if($this->use_prepared_statements != 'Y'){
return parent::_fetch($result, $arrayIndexEndValue); return parent::_fetch($result, $arrayIndexEndValue);
@ -247,6 +268,12 @@
return $output; return $output;
} }
/**
* Handles insertAct
* @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeInsertAct($queryObject, $with_values = false){ function _executeInsertAct($queryObject, $with_values = false){
if($this->use_prepared_statements != 'Y') if($this->use_prepared_statements != 'Y')
{ {
@ -258,6 +285,12 @@
return $result; return $result;
} }
/**
* Handles updateAct
* @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeUpdateAct($queryObject, $with_values = false) { function _executeUpdateAct($queryObject, $with_values = false) {
if($this->use_prepared_statements != 'Y') if($this->use_prepared_statements != 'Y')
{ {
@ -269,6 +302,12 @@
return $result; return $result;
} }
/**
* Handles deleteAct
* @param Object $queryObject
* @param boolean $with_values
* @return resource
*/
function _executeDeleteAct($queryObject, $with_values = false) { function _executeDeleteAct($queryObject, $with_values = false) {
if($this->use_prepared_statements != 'Y') if($this->use_prepared_statements != 'Y')
{ {
@ -280,6 +319,15 @@
return $result; return $result;
} }
/**
* Handle selectAct
* In order to get a list of pages easily when selecting \n
* it supports a method as navigation
* @param Object $queryObject
* @param resource $connection
* @param boolean $with_values
* @return Object
*/
function _executeSelectAct($queryObject, $connection = null, $with_values = false) { function _executeSelectAct($queryObject, $connection = null, $with_values = false) {
if($this->use_prepared_statements != 'Y') if($this->use_prepared_statements != 'Y')
{ {
@ -291,17 +339,33 @@
return $result; return $result;
} }
/**
* Get the ID generated in the last query
* Return next sequence from sequence table
* This method use only mysql
* @return int
*/
function db_insert_id() function db_insert_id()
{ {
$connection = $this->_getConnection('master'); $connection = $this->_getConnection('master');
return mysqli_insert_id($connection); return mysqli_insert_id($connection);
} }
/**
* Fetch a result row as an object
* @param resource $result
* @return object
*/
function db_fetch_object(&$result) function db_fetch_object(&$result)
{ {
return mysqli_fetch_object($result); return mysqli_fetch_object($result);
} }
/**
* Free result memory
* @param resource $result
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function db_free_result(&$result){ function db_free_result(&$result){
return mysqli_free_result($result); return mysqli_free_result($result);
} }

View file

@ -1,343 +1,497 @@
<?php <?php
/**
class Query extends Object { * @author NHN (developers@xpressengine.com)
var $queryID; * @package /classes/db/queryparts
var $action; * @version 0.1
var $priority; */
class Query extends Object {
var $columns; /**
var $tables; * Query id, defined in query xml file
var $conditions; * @var string
var $groups; */
var $orderby; var $queryID;
var $limit; /**
* DML type, ex) INSERT, DELETE, UPDATE, SELECT
var $arguments = null; * @var string
*/
var $columnList = null; var $action;
/**
var $_orderByString; * priority level ex)LOW_PRIORITY, HIGHT_PRIORITY
* @var string
function Query($queryID = null */
, $action = null var $priority;
, $columns = null
, $tables = null /**
, $conditions = null * column list
, $groups = null * @var string|array
, $orderby = null */
, $limit = null var $columns;
, $priority = null){ /**
$this->queryID = $queryID; * table list
$this->action = $action; * @var string|array
$this->priority = $priority; */
var $tables;
if(!isset($tables)) return; /**
$this->columns = $this->setColumns($columns); * condition list
$this->tables = $this->setTables($tables); * @var string|array
$this->conditions = $this->setConditions($conditions); */
$this->groups = $this->setGroups($groups); var $conditions;
$this->orderby = $this->setOrder($orderby); /**
$this->limit = $this->setLimit($limit); * group list
} * @var string|array
*/
function show(){ var $groups;
return true; /**
} * order list
* @var array
function setQueryId($queryID){ */
$this->queryID = $queryID; var $orderby;
} /**
* limit count
function setAction($action){ * @var int
$this->action = $action; */
} var $limit;
/**
* argument list
* @var array
*/
var $arguments = null;
/**
* column list
* @var array
*/
var $columnList = null;
/**
* order by text
* @var string
*/
var $_orderByString;
/**
* constructor
* @param string $queryID
* @param string $action
* @param string|array $columns
* @param string|array $tables
* @param string|array $conditions
* @param string|array $groups
* @param string|array $orderby
* @param int $limit
* @param string $priority
* @return void
*/
function Query($queryID = null
, $action = null
, $columns = null
, $tables = null
, $conditions = null
, $groups = null
, $orderby = null
, $limit = null
, $priority = null){
$this->queryID = $queryID;
$this->action = $action;
$this->priority = $priority;
if(!isset($tables)) return;
$this->columns = $this->setColumns($columns);
$this->tables = $this->setTables($tables);
$this->conditions = $this->setConditions($conditions);
$this->groups = $this->setGroups($groups);
$this->orderby = $this->setOrder($orderby);
$this->limit = $this->setLimit($limit);
}
function show(){
return true;
}
function setQueryId($queryID){
$this->queryID = $queryID;
}
function setAction($action){
$this->action = $action;
}
function setPriority($priority){
$this->priority = $priority;
}
function setColumnList($columnList){
$this->columnList = $columnList;
if(count($this->columnList) > 0) {
$selectColumns = array();
$dbParser = DB::getParser();
foreach($this->columnList as $columnName){
$columnName = $dbParser->escapeColumn($columnName);
$selectColumns[] = new SelectExpression($columnName);
}
unset($this->columns);
$this->columns = $selectColumns;
}
}
function setColumns($columns){
if(!isset($columns) || count($columns) === 0){
$this->columns = array(new StarExpression());
return;
}
if(!is_array($columns)) $columns = array($columns);
$this->columns = $columns;
}
function setTables($tables){
if(!isset($tables) || count($tables) === 0){
$this->setError(true);
$this->setMessage("You must provide at least one table for the query.");
return;
}
if(!is_array($tables)) $tables = array($tables);
$this->tables = $tables;
}
function setPriority($priority){ function setSubquery($subquery){
$this->priority = $priority; $this->subquery = $subquery;
} }
function setColumnList($columnList){ function setConditions($conditions){
$this->columnList = $columnList; $this->conditions = array();
if(count($this->columnList) > 0) { if(!isset($conditions) || count($conditions) === 0) return;
$selectColumns = array(); if(!is_array($conditions)) $conditions = array($conditions);
$dbParser = DB::getParser();
foreach($conditions as $conditionGroup){
foreach($this->columnList as $columnName){ if($conditionGroup->show()) $this->conditions[] = $conditionGroup;
$columnName = $dbParser->escapeColumn($columnName); }
$selectColumns[] = new SelectExpression($columnName); }
}
unset($this->columns); function setGroups($groups){
$this->columns = $selectColumns; if(!isset($groups) || count($groups) === 0) return;
} if(!is_array($groups)) $groups = array($groups);
}
$this->groups = $groups;
function setColumns($columns){ }
if(!isset($columns) || count($columns) === 0){
$this->columns = array(new StarExpression()); function setOrder($order){
return; if(!isset($order) || count($order) === 0) return;
} if(!is_array($order)) $order = array($order);
if(!is_array($columns)) $columns = array($columns); $this->orderby = $order;
}
$this->columns = $columns;
} function setLimit($limit = NULL){
if(!isset($limit)) return;
function setTables($tables){ $this->limit = $limit;
if(!isset($tables) || count($tables) === 0){ }
$this->setError(true);
$this->setMessage("You must provide at least one table for the query."); // START Fluent interface
return; /**
} * seleect set
* @param string|array $columns
if(!is_array($tables)) $tables = array($tables); * @return Query return Query instance
*/
$this->tables = $tables; function select($columns= null){
} $this->action = 'select';
$this->setColumns($columns);
function setConditions($conditions){ return $this;
$this->conditions = array(); }
if(!isset($conditions) || count($conditions) === 0) return;
if(!is_array($conditions)) $conditions = array($conditions); /**
* from set
foreach($conditions as $conditionGroup){ * @param string|array $tables
if($conditionGroup->show()) $this->conditions[] = $conditionGroup; * @return Query return Query instance
} */
} function from($tables){
$this->setTables($tables);
function setGroups($groups){ return $this;
if(!isset($groups) || count($groups) === 0) return; }
if(!is_array($groups)) $groups = array($groups);
/**
$this->groups = $groups; * where set
} * @param string|array $conditions
* @return Query return Query instance
function setOrder($order){ */
if(!isset($order) || count($order) === 0) return; function where($conditions){
if(!is_array($order)) $order = array($order); $this->setConditions($conditions);
return $this;
$this->orderby = $order; }
}
/**
function setLimit($limit = NULL){ * groupBy set
if(!isset($limit)) return; * @param string|array $groups
$this->limit = $limit; * @return Query return Query instance
} */
function groupBy($groups){
// START Fluent interface $this->setGroups($groups);
function select($columns= null){ return $this;
$this->action = 'select'; }
$this->setColumns($columns);
return $this; /**
} * orderBy set
* @param string|array $order
function from($tables){ * @return Query return Query instance
$this->setTables($tables); */
return $this; function orderBy($order){
} $this->setOrder($order);
return $this;
function where($conditions){ }
$this->setConditions($conditions);
return $this; /**
} * limit set
* @param int $limit
function groupBy($groups){ * @return Query return Query instance
$this->setGroups($groups); */
return $this; function limit($limit){
} $this->setLimit($limit);
return $this;
function orderBy($order){ }
$this->setOrder($order); // END Fluent interface
return $this;
} function getAction(){
return $this->action;
function limit($limit){ }
$this->setLimit($limit);
return $this; function getPriority(){
} return $this->priority?'LOW_PRIORITY':'';
// END Fluent interface }
function getAction(){ /**
return $this->action; * Return select sql
} * @param boolean $with_values
* @return string
function getPriority(){ */
return $this->priority?'LOW_PRIORITY':''; function getSelectString($with_values = true){
} foreach($this->columns as $column){
if($column->show())
function getSelectString($with_values = true){ if($column->isSubquery()){
foreach($this->columns as $column){ $select[] = $column->toString($with_values) . ' as '. $column->getAlias();
if($column->show()) }
if($column->isSubquery()){ else
$select[] = $column->toString($with_values) . ' as '. $column->getAlias(); $select[] = $column->getExpression($with_values);
} }
else return trim(implode($select, ', '));
$select[] = $column->getExpression($with_values); }
}
return trim(implode($select, ', ')); /**
} * Return update sql
* @param boolean $with_values
function getUpdateString($with_values = true){ * @return string
foreach($this->columns as $column){ */
if($column->show()) function getUpdateString($with_values = true){
$update[] = $column->getExpression($with_values); foreach($this->columns as $column){
} if($column->show())
return trim(implode($update, ', ')); $update[] = $column->getExpression($with_values);
} }
return trim(implode($update, ', '));
function getInsertString($with_values = true){ }
$columnsList = '';
$valuesList = ''; /**
foreach($this->columns as $column){ * Return insert sql
if($column->show()){ * @param boolean $with_values
$columnsList .= $column->getColumnName() . ', '; * @return string
$valuesList .= $column->getValue($with_values) . ', '; */
} function getInsertString($with_values = true){
} $columnsList = '';
$columnsList = substr($columnsList, 0, -2); if($this->subquery){ // means we have insert-select
$valuesList = substr($valuesList, 0, -2);
return "($columnsList) \n VALUES ($valuesList)";
}
function getTables(){
return $this->tables;
}
// from table_a
// from table_a inner join table_b on x=y
// from (select * from table a) as x
// from (select * from table t) as x inner join table y on y.x
function getFromString($with_values = true){
$from = '';
$simple_table_count = 0;
foreach($this->tables as $table){
if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString($with_values) . ' ';
else $from .= ', '.$table->toString($with_values) . ' ';
if(is_a($table, 'Subquery')) $from .= $table->getAlias() ? ' as ' . $table->getAlias() . ' ' : ' ';
$simple_table_count++;
}
if(trim($from) == '') return '';
return $from;
}
function getWhereString($with_values = true, $with_optimization = true){
$where = '';
$condition_count = 0;
foreach ($this->conditions as $conditionGroup) {
if ($condition_count === 0) {
$conditionGroup->setPipe("");
}
$condition_string = $conditionGroup->toString($with_values);
$where .= $condition_string;
$condition_count++;
}
if ($with_optimization &&
(strstr($this->getOrderByString(), 'list_order') || strstr($this->getOrderByString(), 'update_order'))) {
if ($condition_count !== 0)
$where = '(' . $where . ') ';
foreach ($this->orderby as $order) {
$colName = $order->getColumnName();
if (strstr($colName, 'list_order') || strstr($colName, 'update_order')) {
$opt_condition = new ConditionWithoutArgument($colName, 2100000000, 'less', 'and');
if ($condition_count === 0)
$opt_condition->setPipe("");
$where .= $opt_condition->toString($with_values) . ' ';
$condition_count++;
}
}
}
return trim($where);
}
function getGroupByString(){
$groupBy = '';
if($this->groups) if($this->groups[0] !== "")
$groupBy = implode(', ', $this->groups);
return $groupBy;
}
function getOrderByString(){
if(!$this->_orderByString){
if(count($this->orderby) === 0) return '';
$orderBy = '';
foreach($this->orderby as $order){
$orderBy .= $order->toString() .', ';
}
$orderBy = substr($orderBy, 0, -2);
$this->_orderByString = $orderBy;
}
return $this->_orderByString;
}
function getLimit(){
return $this->limit;
}
function getLimitString(){
$limit = '';
if(count($this->limit) > 0){
$limit = '';
$limit .= $this->limit->toString();
}
return $limit;
}
function getFirstTableName(){
return $this->tables[0]->getName();
}
function getArguments(){
if(!isset($this->arguments)){
$this->arguments = array();
// Join table arguments
if(count($this->tables) > 0)
{
foreach($this->tables as $table)
{
if($table->isJoinTable())
{
$args = $table->getArguments();
if($args) $this->arguments = array_merge($this->arguments, $args);
}
}
}
// Column arguments foreach($this->columns as $column){
if(count($this->columns) > 0){ // The if is for delete statements, all others must have columns $columnsList .= $column->getColumnName() . ', ';
foreach($this->columns as $column){
if($column->show()){
$args = $column->getArguments();
if($args) $this->arguments = array_merge($this->arguments, $args);
}
}
} }
$columnsList = substr($columnsList, 0, -2);
// Condition arguments
if(count($this->conditions) > 0) $selectStatement = $this->subquery->toString($with_values);
foreach($this->conditions as $conditionGroup){ $selectStatement = substr($selectStatement, 1, -1);
$args = $conditionGroup->getArguments();
if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args); return "($columnsList) \n $selectStatement";
}
// Navigation arguments
if(count($this->orderby) > 0)
foreach($this->orderby as $order){
$args = $order->getArguments();
if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args);
}
} }
return $this->arguments;
}
} $valuesList = '';
foreach($this->columns as $column){
if($column->show()){
$columnsList .= $column->getColumnName() . ', ';
?> $valuesList .= $column->getValue($with_values) . ', ';
}
}
$columnsList = substr($columnsList, 0, -2);
$valuesList = substr($valuesList, 0, -2);
return "($columnsList) \n VALUES ($valuesList)";
}
function getTables(){
return $this->tables;
}
/**
* from table_a
* from table_a inner join table_b on x=y
* from (select * from table a) as x
* from (select * from table t) as x inner join table y on y.x
* @param boolean $with_values
* @return string
*/
function getFromString($with_values = true){
$from = '';
$simple_table_count = 0;
foreach($this->tables as $table){
if($table->isJoinTable() || !$simple_table_count) $from .= $table->toString($with_values) . ' ';
else $from .= ', '.$table->toString($with_values) . ' ';
if(is_a($table, 'Subquery')) $from .= $table->getAlias() ? ' as ' . $table->getAlias() . ' ' : ' ';
$simple_table_count++;
}
if(trim($from) == '') return '';
return $from;
}
/**
* Return where sql
* @param boolean $with_values
* @param boolean $with_optimization
* @return string
*/
function getWhereString($with_values = true, $with_optimization = true){
$where = '';
$condition_count = 0;
foreach ($this->conditions as $conditionGroup) {
if ($condition_count === 0) {
$conditionGroup->setPipe("");
}
$condition_string = $conditionGroup->toString($with_values);
$where .= $condition_string;
$condition_count++;
}
if ($with_optimization &&
(strstr($this->getOrderByString(), 'list_order') || strstr($this->getOrderByString(), 'update_order'))) {
if ($condition_count !== 0)
$where = '(' . $where . ') ';
foreach ($this->orderby as $order) {
$colName = $order->getColumnName();
if (strstr($colName, 'list_order') || strstr($colName, 'update_order')) {
$opt_condition = new ConditionWithoutArgument($colName, 2100000000, 'less', 'and');
if ($condition_count === 0)
$opt_condition->setPipe("");
$where .= $opt_condition->toString($with_values) . ' ';
$condition_count++;
}
}
}
return trim($where);
}
/**
* Return groupby sql
* @return string
*/
function getGroupByString(){
$groupBy = '';
if($this->groups) if($this->groups[0] !== "")
$groupBy = implode(', ', $this->groups);
return $groupBy;
}
/**
* Return orderby sql
* @return string
*/
function getOrderByString(){
if(!$this->_orderByString){
if(count($this->orderby) === 0) return '';
$orderBy = '';
foreach($this->orderby as $order){
$orderBy .= $order->toString() .', ';
}
$orderBy = substr($orderBy, 0, -2);
$this->_orderByString = $orderBy;
}
return $this->_orderByString;
}
function getLimit(){
return $this->limit;
}
/**
* Return limit sql
* @return string
*/
function getLimitString(){
$limit = '';
if(count($this->limit) > 0){
$limit = '';
$limit .= $this->limit->toString();
}
return $limit;
}
function getFirstTableName(){
return $this->tables[0]->getName();
}
/**
* Return argument list
* @return array
*/
function getArguments(){
if(!isset($this->arguments)){
$this->arguments = array();
// Join table arguments
if(count($this->tables) > 0)
{
foreach($this->tables as $table)
{
if($table->isJoinTable() || is_a($table, 'Subquery'))
{
$args = $table->getArguments();
if($args) $this->arguments = array_merge($this->arguments, $args);
}
}
}
// Column arguments
if(count($this->columns) > 0){ // The if is for delete statements, all others must have columns
foreach($this->columns as $column){
if($column->show()){
$args = $column->getArguments();
if($args) $this->arguments = array_merge($this->arguments, $args);
}
}
}
// Condition arguments
if(count($this->conditions) > 0)
foreach($this->conditions as $conditionGroup){
$args = $conditionGroup->getArguments();
if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args);
}
// Navigation arguments
if(count($this->orderby) > 0)
foreach($this->orderby as $order){
$args = $order->getArguments();
if(count($args) > 0) $this->arguments = array_merge($this->arguments, $args);
}
}
return $this->arguments;
}
}
?>

View file

@ -1,9 +1,33 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts
* @version 0.1
*/
class Subquery extends Query { class Subquery extends Query {
/**
* table alias
* @var string
*/
var $alias; var $alias;
/**
* join type
* @var string
*/
var $join_type; var $join_type;
/**
* constructor
* @param string $alias
* @param string|array $columns
* @param string|array $tables
* @param string|array $conditions
* @param string|array $groups
* @param string|array $orderby
* @param int $limit
* @param string $join_type
* @return void
*/
function Subquery($alias, $columns, $tables, $conditions, $groups, $orderby, $limit, $join_type = null){ function Subquery($alias, $columns, $tables, $conditions, $groups, $orderby, $limit, $join_type = null){
$this->alias = $alias; $this->alias = $alias;

View file

@ -1,9 +1,27 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/condition
* @version 0.1
*/
class Condition { class Condition {
/**
* column name
* @var string
*/
var $column_name; var $column_name;
var $argument; var $argument;
/**
* operation can use 'equal', 'more', 'excess', 'less', 'below', 'like_tail', 'like_prefix', 'like', 'notlike_tail',
* 'notlike_prefix', 'notlike', 'in', 'notin', 'not_in', 'and', 'or', 'xor', 'not', 'notequal', 'between'
* 'null', 'notnull'
* @var string
*/
var $operation; var $operation;
/**
* pipe can use 'and', 'or'...
* @var string
*/
var $pipe; var $pipe;
var $_value; var $_value;
@ -11,6 +29,14 @@
var $_show; var $_show;
var $_value_to_string; var $_value_to_string;
/**
* constructor
* @param string $column_name
* @param mixed $argument
* @param string $operation
* @param string $pipe
* @return void
*/
function Condition($column_name, $argument, $operation, $pipe){ function Condition($column_name, $argument, $operation, $pipe){
$this->column_name = $column_name; $this->column_name = $column_name;
$this->argument = $argument; $this->argument = $argument;
@ -23,6 +49,11 @@
return null; return null;
} }
/**
* value to string
* @param boolean $withValue
* @return string
*/
function toString($withValue = true){ function toString($withValue = true){
if (!isset($this->_value_to_string)) { if (!isset($this->_value_to_string)) {
if (!$this->show()) if (!$this->show())
@ -41,10 +72,18 @@
return $this->_value_to_string; return $this->_value_to_string;
} }
/**
* change string without value
* @return string
*/
function toStringWithoutValue(){ function toStringWithoutValue(){
return $this->pipe . ' ' . $this->getConditionPart($this->_value); return $this->pipe . ' ' . $this->getConditionPart($this->_value);
} }
/**
* change string with value
* @return string
*/
function toStringWithValue(){ function toStringWithValue(){
return $this->pipe . ' ' . $this->getConditionPart($this->_value); return $this->pipe . ' ' . $this->getConditionPart($this->_value);
} }
@ -53,6 +92,9 @@
$this->pipe = $pipe; $this->pipe = $pipe;
} }
/**
* @return boolean
*/
function show(){ function show(){
if(!isset($this->_show)){ if(!isset($this->_show)){
if(is_array($this->_value) && count($this->_value) === 1 && $this->_value[0] === '') { if(is_array($this->_value) && count($this->_value) === 1 && $this->_value[0] === '') {
@ -74,6 +116,7 @@
case 'notlike' : case 'notlike' :
case 'in' : case 'in' :
case 'notin' : case 'notin' :
case 'not_in' :
case 'and': case 'and':
case 'or': case 'or':
case 'xor': case 'xor':
@ -82,17 +125,32 @@
// if variable is not set or is not string or number, return // if variable is not set or is not string or number, return
if(!isset($this->_value)) { $this->_show = false; break;} if(!isset($this->_value)) { $this->_show = false; break;}
if($this->_value === '') { $this->_show = false; break; } if($this->_value === '') { $this->_show = false; break; }
if(!in_array(gettype($this->_value), array('string', 'integer'))) {$this->_show = false; break; } $tmpArray = array('string'=>1, 'integer'=>1);
if(!isset($tmpArray[gettype($this->_value)]))
{
$this->_show = false; break;
}
break; break;
case 'between' : case 'between' :
if(!is_array($this->_value)) { $this->_show = false; break;} if(!is_array($this->_value)) { $this->_show = false; break;}
if(count($this->_value)!=2) {$this->_show = false; break;} if(count($this->_value)!=2) {$this->_show = false; break;}
case 'null':
case 'notnull':
break;
default:
// If operation is not one of the above, means the condition is invalid
$this->_show = false;
} }
} }
} }
return $this->_show; return $this->_show;
} }
/**
* Return condition string
* @param int|string|array $value
* @return string
*/
function getConditionPart($value) { function getConditionPart($value) {
$name = $this->column_name; $name = $this->column_name;
$operation = $this->operation; $operation = $this->operation;
@ -131,6 +189,7 @@
return $name.' in '.$value; return $name.' in '.$value;
break; break;
case 'notin' : case 'notin' :
case 'not_in' :
return $name.' not in '.$value; return $name.' not in '.$value;
break; break;
case 'notequal' : case 'notequal' :

View file

@ -1,12 +1,30 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/condition
* @version 0.1
*/
class ConditionGroup { class ConditionGroup {
/**
* condition list
* @var array
*/
var $conditions; var $conditions;
/**
* pipe can use 'and', 'or'...
* @var string
*/
var $pipe; var $pipe;
var $_group; var $_group;
var $_show; var $_show;
/**
* constructor
* @param array $conditions
* @param string $pipe
* @return void
*/
function ConditionGroup($conditions, $pipe = "") { function ConditionGroup($conditions, $pipe = "") {
$this->conditions = array(); $this->conditions = array();
foreach($conditions as $condition){ foreach($conditions as $condition){
@ -28,6 +46,11 @@
$this->pipe = $pipe; $this->pipe = $pipe;
} }
/**
* value to string
* @param boolean $with_value
* @return string
*/
function toString($with_value = true){ function toString($with_value = true){
if(!isset($this->_group)){ if(!isset($this->_group)){
$cond_indx = 0; $cond_indx = 0;
@ -48,6 +71,10 @@
return $this->_group; return $this->_group;
} }
/**
* return argument list
* @return array
*/
function getArguments(){ function getArguments(){
$args = array(); $args = array();
foreach($this->conditions as $condition){ foreach($this->conditions as $condition){
@ -57,4 +84,4 @@
return $args; return $args;
} }
} }
?> ?>

View file

@ -1,7 +1,19 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/condition
* @version 0.1
*/
class ConditionSubquery extends Condition { class ConditionSubquery extends Condition {
/**
* constructor
* @param string $column_name
* @param mixed $argument
* @param string $operation
* @param string $pipe
* @return void
*/
function ConditionSubquery($column_name, $argument, $operation, $pipe = ""){ function ConditionSubquery($column_name, $argument, $operation, $pipe = ""){
parent::Condition($column_name, $argument, $operation, $pipe); parent::Condition($column_name, $argument, $operation, $pipe);
$this->_value = $this->argument->toString(); $this->_value = $this->argument->toString();

View file

@ -1,7 +1,19 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/condition
* @version 0.1
*/
class ConditionWithArgument extends Condition { class ConditionWithArgument extends Condition {
/**
* constructor
* @param string $column_name
* @param mixed $argument
* @param string $operation
* @param string $pipe
* @return void
*/
function ConditionWithArgument($column_name, $argument, $operation, $pipe = ""){ function ConditionWithArgument($column_name, $argument, $operation, $pipe = ""){
if($argument === null) { $this->_show = false; return; } if($argument === null) { $this->_show = false; return; }
parent::Condition($column_name, $argument, $operation, $pipe); parent::Condition($column_name, $argument, $operation, $pipe);
@ -13,6 +25,10 @@
return $this->argument; return $this->argument;
} }
/**
* change string without value
* @return string
*/
function toStringWithoutValue(){ function toStringWithoutValue(){
$value = $this->argument->getUnescapedValue(); $value = $this->argument->getUnescapedValue();
@ -37,6 +53,9 @@
return $this->pipe . ' ' . $this->getConditionPart($q); return $this->pipe . ' ' . $this->getConditionPart($q);
} }
/**
* @return boolean
*/
function show(){ function show(){
if(!isset($this->_show)){ if(!isset($this->_show)){
if(!$this->argument->isValid()) $this->_show = false; if(!$this->argument->isValid()) $this->_show = false;

View file

@ -1,9 +1,22 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/condition
* @version 0.1
*/
class ConditionWithoutArgument extends Condition { class ConditionWithoutArgument extends Condition {
/**
* constructor
* @param string $column_name
* @param mixed $argument
* @param string $operation
* @param string $pipe
* @return void
*/
function ConditionWithoutArgument($column_name, $argument, $operation, $pipe = ""){ function ConditionWithoutArgument($column_name, $argument, $operation, $pipe = ""){
parent::Condition($column_name, $argument, $operation, $pipe); parent::Condition($column_name, $argument, $operation, $pipe);
if(in_array($operation, array('in', 'notin'))){ $tmpArray = array('in'=>1, 'notin'=>1, 'not_in'=>1);
if(isset($tmpArray[$operation])){
if(is_array($argument)) $argument = implode($argument, ','); if(is_array($argument)) $argument = implode($argument, ',');
$this->_value = '('. $argument .')'; $this->_value = '('. $argument .')';
} }

View file

@ -1,15 +1,24 @@
<?php <?php
/** /**
* @class ClickCountExpression * ClickCountExpression
* @author Arnia Software * @author Arnia Software
* @brief * @package /classes/db/queryparts/expression
* * @version 0.1
*/ */
class ClickCountExpression extends SelectExpression { class ClickCountExpression extends SelectExpression {
/**
* click count
* @var bool
*/
var $click_count; var $click_count;
/**
* constructor
* @param string $column_name
* @param string $alias
* @param bool $click_count
* @return void
*/
function ClickCountExpression($column_name, $alias = NULL, $click_count = false){ function ClickCountExpression($column_name, $alias = NULL, $click_count = false){
parent::SelectExpression($column_name, $alias); parent::SelectExpression($column_name, $alias);
@ -25,9 +34,13 @@
return $this->click_count; return $this->click_count;
} }
/**
* Return column expression, ex) column = column + 1
* @return string
*/
function getExpression(){ function getExpression(){
return "$this->column_name = $this->column_name + 1"; return "$this->column_name = $this->column_name + 1";
} }
} }
?> ?>

View file

@ -1,20 +1,35 @@
<?php <?php
/** /**
* @class DeleteExpression * DeleteExpression
* @author Arnia Software
* @brief
* *
* @author Arnia Software
* @package /classes/db/queryparts/expression
* @version 0.1
* @todo Fix this class
*/ */
// TODO Fix this class
class DeleteExpression extends Expression { class DeleteExpression extends Expression {
/**
* column value
* @var mixed
*/
var $value; var $value;
/**
* constructor
* @param string $column_name
* @param mixed $value
* @return void
*/
function DeleteExpression($column_name, $value){ function DeleteExpression($column_name, $value){
parent::Expression($column_name); parent::Expression($column_name);
$this->value = $value; $this->value = $value;
} }
/**
* Return column expression, ex) column = value
* @return string
*/
function getExpression(){ function getExpression(){
return "$this->column_name = $this->value"; return "$this->column_name = $this->value";
} }
@ -32,4 +47,4 @@
} }
?> ?>

View file

@ -1,18 +1,28 @@
<?php <?php
/** /**
* @class Expression * Expression
* @author Corina * Represents an expression used in select/update/insert/delete statements
* @brief Represents an expression used in select/update/insert/delete statements
* *
* Examples (expressions are inside double square brackets): * Examples (expressions are inside double square brackets):
* select [[columnA]], [[columnB as aliasB]] from tableA * select [[columnA]], [[columnB as aliasB]] from tableA
* update tableA set [[columnA = valueA]] where columnB = something * update tableA set [[columnA = valueA]] where columnB = something
* *
* @author Corina
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class Expression { class Expression {
/**
* column name
* @var string
*/
var $column_name; var $column_name;
/**
* constructor
* @param string $column_name
* @return void
*/
function Expression($column_name){ function Expression($column_name){
$this->column_name = $column_name; $this->column_name = $column_name;
} }
@ -25,6 +35,10 @@
return false; return false;
} }
/**
* Return column expression, ex) column as alias
* @return string
*/
function getExpression() { function getExpression() {
} }
} }

View file

@ -1,15 +1,24 @@
<?php <?php
/** /**
* @class InsertExpression * InsertExpression
* @author Arnia Software
* @brief
* *
* @author Arnia Software
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class InsertExpression extends Expression { class InsertExpression extends Expression {
/**
* argument
* @var object
*/
var $argument; var $argument;
/**
* constructor
* @param string $column_name
* @param object $argument
* @return void
*/
function InsertExpression($column_name, $argument){ function InsertExpression($column_name, $argument){
parent::Expression($column_name); parent::Expression($column_name);
$this->argument = $argument; $this->argument = $argument;

View file

@ -1,26 +1,40 @@
<?php <?php
/** /**
* @class SelectExpression * SelectExpression
* @author Arnia Software * Represents an expresion that appears in the select clause
* @brief Represents an expresion that appears in the select clause
* *
* @remarks
* $column_name can be: * $column_name can be:
* - a table column name * - a table column name
* - an sql function - like count(*) * - an sql function - like count(*)
* - an sql expression - substr(column_name, 1, 8) or score1 + score2 * - an sql expression - substr(column_name, 1, 8) or score1 + score2
* $column_name is already escaped * $column_name is already escaped
*
* @author Arnia Software
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class SelectExpression extends Expression { class SelectExpression extends Expression {
/**
* column alias name
* @var string
*/
var $column_alias; var $column_alias;
/**
* constructor
* @param string $column_name
* @param string $alias
* @return void
*/
function SelectExpression($column_name, $alias = NULL){ function SelectExpression($column_name, $alias = NULL){
parent::Expression($column_name); parent::Expression($column_name);
$this->column_alias = $alias; $this->column_alias = $alias;
} }
/**
* Return column expression, ex) column as alias
* @return string
*/
function getExpression() { function getExpression() {
return sprintf("%s%s", $this->column_name, $this->column_alias ? " as ".$this->column_alias : ""); return sprintf("%s%s", $this->column_name, $this->column_alias ? " as ".$this->column_alias : "");
} }

View file

@ -1,14 +1,17 @@
<?php <?php
/** /**
* @class StarExpression * StarExpression
* @author Corina * Represents the * in 'select * from ...' statements
* @brief Represents the * in 'select * from ...' statements
* *
* @author Corina
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class StarExpression extends SelectExpression { class StarExpression extends SelectExpression {
/**
* constructor, set the column to asterisk
* @return void
*/
function StarExpression(){ function StarExpression(){
parent::SelectExpression("*"); parent::SelectExpression("*");
} }

View file

@ -1,25 +1,43 @@
<?php <?php
/** /**
* @class UpdateExpression * UpdateExpression
* @author Arnia Software
* @brief
* *
* @author Arnia Software
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class UpdateExpression extends Expression { class UpdateExpression extends Expression {
/**
* argument
* @var object
*/
var $argument; var $argument;
/**
* constructor
* @param string $column_name
* @param object $argument
* @return void
*/
function UpdateExpression($column_name, $argument){ function UpdateExpression($column_name, $argument){
parent::Expression($column_name); parent::Expression($column_name);
$this->argument = $argument; $this->argument = $argument;
} }
/**
* Return column expression, ex) column = value
* @return string
*/
function getExpression($with_value = true){ function getExpression($with_value = true){
if($with_value) if($with_value)
return $this->getExpressionWithValue(); return $this->getExpressionWithValue();
return $this->getExpressionWithoutValue(); return $this->getExpressionWithoutValue();
} }
/**
* Return column expression, ex) column = value
* @return string
*/
function getExpressionWithValue(){ function getExpressionWithValue(){
$value = $this->argument->getValue(); $value = $this->argument->getValue();
$operation = $this->argument->getColumnOperation(); $operation = $this->argument->getColumnOperation();
@ -28,6 +46,11 @@
return "$this->column_name = $value"; return "$this->column_name = $value";
} }
/**
* Return column expression, ex) column = ?
* Can use prepare statement
* @return string
*/
function getExpressionWithoutValue(){ function getExpressionWithoutValue(){
$operation = $this->argument->getColumnOperation(); $operation = $this->argument->getColumnOperation();
if(isset($operation)) if(isset($operation))

View file

@ -1,14 +1,24 @@
<?php <?php
/** /**
* @class UpdateExpression * UpdateExpression
* @author Arnia Software
* @brief
* *
* @author Arnia Software
* @package /classes/db/queryparts/expression
* @version 0.1
*/ */
class UpdateExpressionWithoutArgument extends UpdateExpression { class UpdateExpressionWithoutArgument extends UpdateExpression {
/**
* argument
* @var object
*/
var $argument; var $argument;
/**
* constructor
* @param string $column_name
* @param object $argument
* @return void
*/
function UpdateExpressionWithoutArgument($column_name, $argument){ function UpdateExpressionWithoutArgument($column_name, $argument){
parent::Expression($column_name); parent::Expression($column_name);
$this->argument = $argument; $this->argument = $argument;
@ -35,11 +45,11 @@
function getArgument(){ function getArgument(){
return null; return null;
} }
function getArguments(){ function getArguments(){
return array(); return array();
} }
} }
?> ?>

View file

@ -1,10 +1,38 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/limit
* @version 0.1
*/
class Limit { class Limit {
/**
* start number
* @var int
*/
var $start; var $start;
/**
* list count
* @var int
*/
var $list_count; var $list_count;
/**
* page count
* @var int
*/
var $page_count; var $page_count;
/**
* current page
* @var int
*/
var $page; var $page;
/**
* constructor
* @param int $list_count
* @param int $page
* @param int $page_count
* @return void
*/
function Limit($list_count, $page= NULL, $page_count= NULL){ function Limit($list_count, $page= NULL, $page_count= NULL){
$this->list_count = $list_count; $this->list_count = $list_count;
if ($page){ if ($page){
@ -16,7 +44,11 @@
} }
} }
function isPageHandler(){//in case you choose to use query limit in other cases than page select /**
* In case you choose to use query limit in other cases than page select
* @return boolean
*/
function isPageHandler(){
if ($this->page)return true; if ($this->page)return true;
else return false; else return false;
} }
@ -34,4 +66,4 @@
else return $this->list_count->getValue(); else return $this->list_count->getValue();
} }
} }
?> ?>

View file

@ -1,8 +1,27 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/order
* @version 0.1
*/
class OrderByColumn { class OrderByColumn {
/**
* column name
* @var string
*/
var $column_name; var $column_name;
/**
* sort order
* @var string
*/
var $sort_order; var $sort_order;
/**
* constructor
* @param string $column_name
* @param string $sort_order
* @return void
*/
function OrderByColumn($column_name, $sort_order){ function OrderByColumn($column_name, $sort_order){
$this->column_name = $column_name; $this->column_name = $column_name;
$this->sort_order = $sort_order; $this->sort_order = $sort_order;
@ -28,4 +47,4 @@
} }
} }
?> ?>

View file

@ -1,15 +1,42 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/table
* @version 0.1
*/
class CubridTableWithHint extends Table { class CubridTableWithHint extends Table {
/**
* table name
* @var string
*/
var $name; var $name;
/**
* table alias
* @var string
*/
var $alias; var $alias;
/**
* index hint list
* @var array
*/
var $index_hints_list; var $index_hints_list;
/**
* constructor
* @param string $name
* @param string $alias
* @param array $index_hints_list
* @return void
*/
function CubridTableWithHint($name, $alias = NULL, $index_hints_list){ function CubridTableWithHint($name, $alias = NULL, $index_hints_list){
parent::Table($name, $alias); parent::Table($name, $alias);
$this->index_hints_list = $index_hints_list; $this->index_hints_list = $index_hints_list;
} }
/**
* Return index hint string
* @return string
*/
function getIndexHintString(){ function getIndexHintString(){
$result = ''; $result = '';
@ -32,4 +59,4 @@
} }
} }
?> ?>

View file

@ -1,9 +1,27 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/table
* @version 0.1
*/
class IndexHint { class IndexHint {
/**
* index name
* @var string
*/
var $index_name; var $index_name;
/**
* index hint type, ex) IGNORE, FORCE, USE...
* @var string
*/
var $index_hint_type; var $index_hint_type;
/**
* constructor
* @param string $index_name
* @param string $index_hint_type
* @return void
*/
function IndexHint($index_name, $index_hint_type){ function IndexHint($index_name, $index_hint_type){
$this->index_name = $index_name; $this->index_name = $index_name;
$this->index_hint_type = $index_hint_type; $this->index_hint_type = $index_hint_type;
@ -18,4 +36,4 @@
} }
} }
?> ?>

View file

@ -1,19 +1,32 @@
<?php <?php
/** /**
* @class JoinTable * class JoinTable
* @author Arnia Software
* @brief
*
* @remarks
* $conditions in an array of Condition objects * $conditions in an array of Condition objects
* *
* @author Arnia Software
* @package /classes/db/queryparts/table
* @version 0.1
*/ */
class JoinTable extends Table { class JoinTable extends Table {
/**
* join type
* @var string
*/
var $join_type; var $join_type;
/**
* condition list
* @var array
*/
var $conditions; var $conditions;
/**
* constructor
* @param string $name
* @param string $alias
* @param string $join_type
* @param array $conditions
* @return void
*/
function JoinTable($name, $alias, $join_type, $conditions){ function JoinTable($name, $alias, $join_type, $conditions){
parent::Table($name, $alias); parent::Table($name, $alias);
$this->join_type = $join_type; $this->join_type = $join_type;
@ -43,4 +56,4 @@
} }
?> ?>

View file

@ -1,10 +1,33 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/table
* @version 0.1
*/
class MssqlTableWithHint extends Table { class MssqlTableWithHint extends Table {
/**
* table name
* @var string
*/
var $name; var $name;
/**
* table alias
* @var string
*/
var $alias; var $alias;
/**
* index hint type, ex) IGNORE, FORCE, USE...
* @var array
*/
var $index_hints_list; var $index_hints_list;
/**
* constructor
* @param string $name
* @param string $alias
* @param string $index_hints_list
* @return void
*/
function MssqlTableWithHint($name, $alias = NULL, $index_hints_list){ function MssqlTableWithHint($name, $alias = NULL, $index_hints_list){
parent::Table($name, $alias); parent::Table($name, $alias);
$this->index_hints_list = $index_hints_list; $this->index_hints_list = $index_hints_list;
@ -14,9 +37,10 @@
$result = parent::toString(); $result = parent::toString();
$index_hint_string = ''; $index_hint_string = '';
$indexTypeList = array('USE'=>1, 'FORCE'=>1);
foreach($this->index_hints_list as $index_hint){ foreach($this->index_hints_list as $index_hint){
$index_hint_type = $index_hint->getIndexHintType(); $index_hint_type = $index_hint->getIndexHintType();
if(in_array($index_hint_type, array('USE', 'FORCE'))) if(isset($indexTypeList[$index_hint_type]))
$index_hint_string .= 'INDEX(' . $index_hint->getIndexName() . '), '; $index_hint_string .= 'INDEX(' . $index_hint->getIndexName() . '), ';
} }
if($index_hint_string != ''){ if($index_hint_string != ''){
@ -26,4 +50,4 @@
} }
} }
?> ?>

View file

@ -1,10 +1,33 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/table
* @version 0.1
*/
class MysqlTableWithHint extends Table { class MysqlTableWithHint extends Table {
/**
* table name
* @var string
*/
var $name; var $name;
/**
* table alias
* @var string
*/
var $alias; var $alias;
/**
* index hint type, ex) IGNORE, FORCE, USE...
* @var array
*/
var $index_hints_list; var $index_hints_list;
/**
* constructor
* @param string $name
* @param string $alias
* @param string $index_hints_list
* @return void
*/
function MysqlTableWithHint($name, $alias = NULL, $index_hints_list){ function MysqlTableWithHint($name, $alias = NULL, $index_hints_list){
parent::Table($name, $alias); parent::Table($name, $alias);
$this->index_hints_list = $index_hints_list; $this->index_hints_list = $index_hints_list;
@ -33,4 +56,4 @@
} }
} }
?> ?>

View file

@ -1,9 +1,27 @@
<?php <?php
/**
* @author NHN (developers@xpressengine.com)
* @package /classes/db/queryparts/table
* @version 0.1
*/
class Table { class Table {
/**
* table name
* @var string
*/
var $name; var $name;
/**
* table alias
* @var string
*/
var $alias; var $alias;
/**
* constructor
* @param string $name
* @param string $alias
* @return void
*/
function Table($name, $alias = NULL){ function Table($name, $alias = NULL){
$this->name = $name; $this->name = $name;
$this->alias = $alias; $this->alias = $alias;
@ -27,4 +45,4 @@
} }
} }
?> ?>

View file

@ -2,7 +2,7 @@
/** /**
* @class DisplayHandler * @class DisplayHandler
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief DisplayHandler is responsible for displaying the execution result. \n * DisplayHandler is responsible for displaying the execution result. \n
* Depending on the request type, it can display either HTML or XML content.\n * Depending on the request type, it can display either HTML or XML content.\n
* Xml content is simple xml presentation of variables in oModule while html content * Xml content is simple xml presentation of variables in oModule while html content
* is the combination of the variables of oModue and template files/. * is the combination of the variables of oModue and template files/.
@ -16,11 +16,11 @@
var $handler = null; var $handler = null;
/** /**
* @brief print either html or xml content given oModule object * print either html or xml content given oModule object
* @remark addon execution and the trigger execution are included within this method, which * @remark addon execution and the trigger execution are included within this method, which might create inflexibility for the fine grained caching
* might create inflexibility for the fine grained caching * @param ModuleObject $oModule the module object
* @param[in] $oModule the module object * @return void
**/ **/
function printContent(&$oModule) { function printContent(&$oModule) {
// Check if the gzip encoding supported // Check if the gzip encoding supported
if( if(
@ -82,9 +82,10 @@
/** /**
* @brief Print debugging message to designated output source depending on the value set to __DEBUG_OUTPUT_. \n * Print debugging message to designated output source depending on the value set to __DEBUG_OUTPUT_. \n
* This method only functions when __DEBUG__ variable is set to 1. * This method only functions when __DEBUG__ variable is set to 1.
* __DEBUG_OUTPUT__ == 0, messages are written in ./files/_debug_message.php * __DEBUG_OUTPUT__ == 0, messages are written in ./files/_debug_message.php
* @return void
**/ **/
function _debugOutput() { function _debugOutput() {
if(!__DEBUG__) return; if(!__DEBUG__) return;
@ -221,7 +222,8 @@
} }
/** /**
* @brief print a HTTP HEADER for XML, which is encoded in UTF-8 * print a HTTP HEADER for XML, which is encoded in UTF-8
* @return void
**/ **/
function _printXMLHeader() { function _printXMLHeader() {
header("Content-Type: text/xml; charset=UTF-8"); header("Content-Type: text/xml; charset=UTF-8");
@ -234,7 +236,8 @@
/** /**
* @brief print a HTTP HEADER for HTML, which is encoded in UTF-8 * print a HTTP HEADER for HTML, which is encoded in UTF-8
* @return void
**/ **/
function _printHTMLHeader() { function _printHTMLHeader() {
header("Content-Type: text/html; charset=UTF-8"); header("Content-Type: text/html; charset=UTF-8");
@ -247,7 +250,8 @@
/** /**
* @brief print a HTTP HEADER for JSON, which is encoded in UTF-8 * print a HTTP HEADER for JSON, which is encoded in UTF-8
* @return void
**/ **/
function _printJSONHeader() { function _printJSONHeader() {
header("Content-Type: text/html; charset=UTF-8"); header("Content-Type: text/html; charset=UTF-8");
@ -260,7 +264,8 @@
/** /**
* @brief print a HTTP HEADER for HTML, which is encoded in UTF-8 * print a HTTP HEADER for HTML, which is encoded in UTF-8
* @return void
**/ **/
function _printHttpStatusCode($code) { function _printHttpStatusCode($code) {
$statusMessage = Context::get('http_status_message'); $statusMessage = Context::get('http_status_message');

View file

@ -2,8 +2,9 @@
class HTMLDisplayHandler { class HTMLDisplayHandler {
/** /**
* @brief Produce HTML compliant content given a module object.\n * Produce HTML compliant content given a module object.\n
* @param[in] $oModule the module object * @param ModuleObject $oModule the module object
* @return string compiled template string
**/ **/
function toDoc(&$oModule) function toDoc(&$oModule)
{ {
@ -79,6 +80,11 @@ class HTMLDisplayHandler {
return $output; return $output;
} }
/**
* when display mode is HTML, prepare code before print.
* @param string $output compiled template string
* @return void
**/
function prepareToPrint(&$output) { function prepareToPrint(&$output) {
if(Context::getResponseMethod() != 'HTML') return; if(Context::getResponseMethod() != 'HTML') return;
@ -151,6 +157,11 @@ class HTMLDisplayHandler {
$oModuleController->replaceDefinedLangCode($output); $oModuleController->replaceDefinedLangCode($output);
} }
/**
* when display mode is HTML, prepare code before print about <input> tag value.
* @param array $match input value.
* @return string input value.
**/
function _preserveValue($match) function _preserveValue($match)
{ {
$INPUT_ERROR = Context::get('INPUT_ERROR'); $INPUT_ERROR = Context::get('INPUT_ERROR');
@ -164,7 +175,7 @@ class HTMLDisplayHandler {
switch($type){ switch($type){
case 'text': case 'text':
case 'hidden': case 'hidden':
$str = preg_replace('@\svalue="[^"]*?"@', ' ', $str).' value="'.htmlspecialchars($INPUT_ERROR[$match[3]]).'"'; $str = preg_replace('@\svalue="[^"]*?"@', ' ', $str).' value="'.@htmlspecialchars($INPUT_ERROR[$match[3]]).'"';
break; break;
case 'password': case 'password':
$str = preg_replace('@\svalue="[^"]*?"@', ' ', $str); $str = preg_replace('@\svalue="[^"]*?"@', ' ', $str);
@ -172,7 +183,7 @@ class HTMLDisplayHandler {
case 'radio': case 'radio':
case 'checkbox': case 'checkbox':
$str = preg_replace('@\schecked(="[^"]*?")?@', ' ', $str); $str = preg_replace('@\schecked(="[^"]*?")?@', ' ', $str);
if(preg_match('@\s(?i:value)="'.$INPUT_ERROR[$match[3]].'"@', $str)) { if(@preg_match('@\s(?i:value)="'.$INPUT_ERROR[$match[3]].'"@', $str)) {
$str .= ' checked="checked"'; $str .= ' checked="checked"';
} }
break; break;
@ -181,6 +192,11 @@ class HTMLDisplayHandler {
return $str.' />'; return $str.' />';
} }
/**
* when display mode is HTML, prepare code before print about <select> tag value.
* @param array $matches select tag.
* @return string select tag.
**/
function _preserveSelectValue($matches) function _preserveSelectValue($matches)
{ {
$INPUT_ERROR = Context::get('INPUT_ERROR'); $INPUT_ERROR = Context::get('INPUT_ERROR');
@ -200,6 +216,11 @@ class HTMLDisplayHandler {
return $mm[0].implode('', $m[0]).'</select>'; return $mm[0].implode('', $m[0]).'</select>';
} }
/**
* when display mode is HTML, prepare code before print about <textarea> tag value.
* @param array $matches textarea tag information.
* @return string textarea tag
**/
function _preserveTextAreaValue($matches) function _preserveTextAreaValue($matches)
{ {
$INPUT_ERROR = Context::get('INPUT_ERROR'); $INPUT_ERROR = Context::get('INPUT_ERROR');
@ -208,23 +229,29 @@ class HTMLDisplayHandler {
} }
/** /**
* @brief add html style code extracted from html body to Context, which will be * add html style code extracted from html body to Context, which will be
* printed inside <header></header> later. * printed inside <header></header> later.
* @param[in] $oModule the module object * @param array $matches
* @return void
**/ **/
function _moveStyleToHeader($matches) { function _moveStyleToHeader($matches) {
Context::addHtmlHeader($matches[0]); Context::addHtmlHeader($matches[0]);
} }
/** /**
* @brief add given .css or .js file names in widget code to Context * add given .css or .js file names in widget code to Context
* @param[in] $oModule the module object * @param array $matches
* @return void
**/ **/
function _transMeta($matches) { function _transMeta($matches) {
if($matches[1]) return ''; if($matches[1]) return '';
Context::loadFile($matches[2]); Context::loadFile($matches[2]);
} }
/**
* import basic .js files.
* @return void
**/
function _loadJSCSS() function _loadJSCSS()
{ {
$oContext =& Context::getInstance(); $oContext =& Context::getInstance();
@ -260,6 +287,10 @@ class HTMLDisplayHandler {
} }
} }
/**
* add meta tag.
* @return void
**/
function _addMetaTag() function _addMetaTag()
{ {
$oContext =& Context::getInstance(); $oContext =& Context::getInstance();

View file

@ -1,6 +1,11 @@
<?php <?php
class JSONDisplayHandler { class JSONDisplayHandler {
/**
* Produce JSON compliant content given a module object.\n
* @param ModuleObject $oModule the module object
* @return string
**/
function toDoc(&$oModule) function toDoc(&$oModule)
{ {
$variables = $oModule->getVariables(); $variables = $oModule->getVariables();

View file

@ -2,8 +2,9 @@
class VirtualXMLDisplayHandler { class VirtualXMLDisplayHandler {
/** /**
* @brief Produce virtualXML compliant content given a module object.\n * Produce virtualXML compliant content given a module object.\n
* @param[in] $oModule the module object * @param ModuleObject $oModule the module object
* @return string
**/ **/
function toDoc(&$oModule) function toDoc(&$oModule)

View file

@ -2,8 +2,9 @@
class XMLDisplayHandler { class XMLDisplayHandler {
/** /**
* @brief Produce XML compliant content given a module object.\n * Produce XML compliant content given a module object.\n
* @param[in] $oModule the module object * @param ModuleObject $oModule the module object
* @return string
**/ **/
function toDoc(&$oModule) function toDoc(&$oModule)
{ {
@ -21,8 +22,9 @@ class XMLDisplayHandler {
} }
/** /**
* @brief produce XML code given variable object\n * produce XML code given variable object\n
* @param[in] $oModule the module object * @param object $obj
* @return string
**/ **/
function _makeXmlDoc($obj) { function _makeXmlDoc($obj) {
if(!count($obj)) return; if(!count($obj)) return;

View file

@ -10,7 +10,9 @@
class EditorHandler extends Object { class EditorHandler extends Object {
/** /**
* @brief set the xml and other information of the component * set the xml and other information of the component
* @param object $info editor information
* @return void
**/ **/
function setInfo($info) { function setInfo($info) {
Context::set('component_info', $info); Context::set('component_info', $info);

View file

@ -1,32 +1,48 @@
<?php <?php
/** /**
* @class ExtraVar * A class to handle extra variables used in posts, member and others
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief a class to handle extra variables used in posts, member and others
*
**/ **/
class ExtraVar { class ExtraVar {
/**
* sequence of module
* @var int
*/
var $module_srl = null; var $module_srl = null;
/**
* Current module's Set of ExtraItem
* @var ExtraItem[]
*/
var $keys = null; var $keys = null;
/** /**
* @brief constructor * Get instance of ExtraVar (singleton)
*
* @param int $module_srl Sequence of module
* @return ExtraVar
**/ **/
function &getInstance($module_srl) { function &getInstance($module_srl) {
return new ExtraVar($module_srl); return new ExtraVar($module_srl);
} }
/** /**
* @brief constructor * Constructor
*
* @param int $module_srl Sequence of module
* @return void
**/ **/
function ExtraVar($module_srl) { function ExtraVar($module_srl) {
$this->module_srl = $module_srl; $this->module_srl = $module_srl;
} }
/** /**
* @brief register a key of extra variable * Register a key of extra variable
* @param module_srl, idx, name, type, default, desc, is_required, search, value *
* @param object[] $extra_keys Array of extra variable. A value of array is object that contains module_srl, idx, name, default, desc, is_required, search, value, eid.
* @return void
**/ **/
function setExtraVarKeys($extra_keys) { function setExtraVarKeys($extra_keys) {
if(!is_array($extra_keys) || !count($extra_keys)) return; if(!is_array($extra_keys) || !count($extra_keys)) return;
@ -38,7 +54,9 @@
} }
/** /**
* @brief Return an array of extra vars * Returns an array of ExtraItem
*
* @return ExtraItem[]
**/ **/
function getExtraVars() { function getExtraVars() {
return $this->keys; return $this->keys;
@ -46,24 +64,84 @@
} }
/** /**
* @class ExtraItem * Each value of the extra vars
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief each value of the extra vars
**/ **/
class ExtraItem { class ExtraItem {
/**
* Sequence of module
* @var int
*/
var $module_srl = 0; var $module_srl = 0;
/**
* Index of extra variable
* @var int
*/
var $idx = 0; var $idx = 0;
/**
* Name of extra variable
* @var string
*/
var $name = 0; var $name = 0;
/**
* Type of extra variable
* @var string text, homepage, email_address, tel, textarea, checkbox, date, select, radio, kr_zip
*/
var $type = 'text'; var $type = 'text';
/**
* Default values
* @var string[]
*/
var $default = null; var $default = null;
/**
* Description
* @var string
*/
var $desc = ''; var $desc = '';
/**
* Whether required or not requred this extra variable
* @var string Y, N
*/
var $is_required = 'N'; var $is_required = 'N';
/**
* Whether can or can not search this extra variable
* @var string Y, N
*/
var $search = 'N'; var $search = 'N';
/**
* Value
* @var string
*/
var $value = null; var $value = null;
/**
* Unique id of extra variable in module
* @var string
*/
var $eid = ''; var $eid = '';
/** /**
* @brief constructor * Constructor
*
* @param int $module_srl Sequence of module
* @param int $idx Index of extra variable
* @param string $type Type of extra variable. text, homepage, email_address, tel, textarea, checkbox, date, sleect, radio, kr_zip
* @param string[] $default Default values
* @param string $desc Description
* @param string $is_required Whether required or not requred this extra variable. Y, N
* @param string $search Whether can or can not search this extra variable
* @param string $value Value
* @param string $eid Unique id of extra variable in module
* @return void
**/ **/
function ExtraItem($module_srl, $idx, $name, $type = 'text', $default = null, $desc = '', $is_required = 'N', $search = 'N', $value = null, $eid = '') { function ExtraItem($module_srl, $idx, $name, $type = 'text', $default = null, $desc = '', $is_required = 'N', $search = 'N', $value = null, $eid = '') {
if(!$idx) return; if(!$idx) return;
@ -80,14 +158,21 @@
} }
/** /**
* @brief Values * Sets Value
*
* @param string $value The value to set
* @return void
**/ **/
function setValue($value) { function setValue($value) {
$this->value = $value; $this->value = $value;
} }
/** /**
* @brief return a given value converted based on its type * Returns a given value converted based on its type
*
* @param string $type Type of variable
* @param string $value Value
* @return string Returns a converted value
**/ **/
function _getTypeValue($type, $value) { function _getTypeValue($type, $value) {
$value = trim($value); $value = trim($value);
@ -134,8 +219,9 @@
} }
/** /**
* @brief Return value * Returns a value for HTML
* return the original values for HTML result *
* @return string Returns a value expressed in HTML.
**/ **/
function getValueHTML() { function getValueHTML() {
$value = $this->_getTypeValue($this->type, $this->value); $value = $this->_getTypeValue($this->type, $this->value);
@ -174,7 +260,9 @@
} }
/** /**
* @brief return a form based on its type * Returns a form based on its type
*
* @return string Returns a form html.
**/ **/
function getFormHTML() { function getFormHTML() {
static $id_num = 1000; static $id_num = 1000;

View file

@ -1,15 +1,15 @@
<?php <?php
/** /**
* @class FileHandler * Contains methods for accessing file system
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief contains methods for accessing file system
**/ **/
class FileHandler { class FileHandler {
/** /**
* @brief changes path of target file, directory into absolute path * Changes path of target file, directory into absolute path
* @param[in] $source path *
* @return absolute path * @param string $source path to change into absolute path
* @return string Absolute path
**/ **/
function getRealPath($source) { function getRealPath($source) {
$temp = explode('/', $source); $temp = explode('/', $source);
@ -18,13 +18,15 @@ class FileHandler {
} }
/** /**
* @brief copy a directory to target * Copy a directory to target
* @param[in] $source_dir path of source directory *
* @param[in] $target_dir path of target dir * If target directory does not exist, this function creates it
* @param[in] $filter *
* @param[in] $type * @param string $source_dir Path of source directory
* @remarks if target directory does not exist, this function creates it * @param string $target_dir Path of target dir
* @return none * @param string $filter Regex to filter files. If file matches this regex, the file is not copied.
* @param string $type If set as 'force'. Even if the file exists in target, the file is copied.
* @return void
**/ **/
function copyDir($source_dir, $target_dir, $filter=null,$type=null){ function copyDir($source_dir, $target_dir, $filter=null,$type=null){
$source_dir = FileHandler::getRealPath($source_dir); $source_dir = FileHandler::getRealPath($source_dir);
@ -53,11 +55,12 @@ class FileHandler {
} }
/** /**
* @brief copy a file to target * Copy a file to target
* @param[in] $source path of source file *
* @param[in] $target path of target file * @param string $source Path of source file
* @param[in] $force Y: overwrite * @param string $target Path of target file
* @return none * @param string $force Y: overwrite
* @return void
**/ **/
function copyFile($source, $target, $force='Y'){ function copyFile($source, $target, $force='Y'){
setlocale(LC_CTYPE, 'en_US.UTF8', 'ko_KR.UTF8'); setlocale(LC_CTYPE, 'en_US.UTF8', 'ko_KR.UTF8');
@ -70,9 +73,10 @@ class FileHandler {
} }
/** /**
* @brief returns the content of the file * Returns the content of the file
* @param[in] $file_name path of target file *
* @return the content of the file. if target file does not exist, this function returns nothing. * @param string $file_name Path of target file
* @return string The content of the file. If target file does not exist, this function returns nothing.
**/ **/
function readFile($file_name) { function readFile($file_name) {
$file_name = FileHandler::getRealPath($file_name); $file_name = FileHandler::getRealPath($file_name);
@ -96,11 +100,12 @@ class FileHandler {
} }
/** /**
* @brief write $buff into the specified file * Write $buff into the specified file
* @param[in] $file_name path of target file *
* @param[in] $buff content to be writeen * @param string $file_name Path of target file
* @param[in] $mode a(append) / w(write) * @param string $buff Content to be writeen
* @return none * @param string $mode a(append) / w(write)
* @return void
**/ **/
function writeFile($file_name, $buff, $mode = "w") { function writeFile($file_name, $buff, $mode = "w") {
$file_name = FileHandler::getRealPath($file_name); $file_name = FileHandler::getRealPath($file_name);
@ -118,9 +123,10 @@ class FileHandler {
} }
/** /**
* @brief remove a file * Remove a file
* @param[in] $file_name path of target file *
* @return returns true on success or false on failure. * @param string $file_name path of target file
* @return bool Returns true on success or false on failure.
**/ **/
function removeFile($file_name) { function removeFile($file_name) {
$file_name = FileHandler::getRealPath($file_name); $file_name = FileHandler::getRealPath($file_name);
@ -128,11 +134,13 @@ class FileHandler {
} }
/** /**
* @brief rename a file * Rename a file
* @param[in] $source path of source file *
* @param[in] $target path of target file * In order to move a file, use this function.
* @remarks In order to move a file, use this function. *
* @return returns true on success or false on failure. * @param string $source Path of source file
* @param string $target Path of target file
* @return bool Returns true on success or false on failure.
**/ **/
function rename($source, $target) { function rename($source, $target) {
$source = FileHandler::getRealPath($source); $source = FileHandler::getRealPath($source);
@ -141,10 +149,11 @@ class FileHandler {
} }
/** /**
* @brief Move a file * Move a file
* @param[in] $source path of source file *
* @param[in] $target path of target file * @param string $source Path of source file
* @return returns true on success or false on failure. * @param string $target Path of target file
* @return bool Returns true on success or false on failure.
*/ */
function moveFile($source, $target) { function moveFile($source, $target) {
$source = FileHandler::getRealPath($source); $source = FileHandler::getRealPath($source);
@ -157,24 +166,28 @@ class FileHandler {
} }
/** /**
* @brief move a directory * Move a directory
* @param[in] $source_dir path of source directory *
* @param[in] $target_dir path of target directory * This function just wraps rename function.
* @remarks this function just wraps rename function. *
* @return none * @param string $source_dir Path of source directory
* @param string $target_dir Path of target directory
* @return void
**/ **/
function moveDir($source_dir, $target_dir) { function moveDir($source_dir, $target_dir) {
FileHandler::rename($source_dir, $target_dir); FileHandler::rename($source_dir, $target_dir);
} }
/** /**
* @brief return list of the files in the path * Return list of the files in the path
* @param[in] $path path of target directory *
* @param[in] $filter if specified, return only files matching with the filter * The array does not contain files, such as '.', '..', and files starting with '.'
* @param[in] $to_lower if true, file names will be changed into lower case. *
* @param[in] $concat_prefix if true, return file name as absolute path * @param string $path Path of target directory
* @remarks the array does not contain files, such as '.', '..', and files starting with '.' * @param string $filter If specified, return only files matching with the filter
* @return array of the filenames in the path * @param bool $to_lower If true, file names will be changed into lower case.
* @param bool $concat_prefix If true, return file name as absolute path
* @return string[] Array of the filenames in the path
**/ **/
function readDir($path, $filter = '', $to_lower = false, $concat_prefix = false) { function readDir($path, $filter = '', $to_lower = false, $concat_prefix = false) {
$path = FileHandler::getRealPath($path); $path = FileHandler::getRealPath($path);
@ -205,10 +218,12 @@ class FileHandler {
} }
/** /**
* @brief creates a directory * Creates a directory
* @param[in] $path_string path of target directory *
* @return true if success. it might return nothing when ftp is used and connection to the ftp address failed. * This function creates directories recursively, which means that if ancestors of the target directory does not exist, they will be created too.
* @remarks This function creates directories recursively, which means that if ancestors of the target directory does not exist, they will be created too. *
* @param string $path_string Path of target directory
* @return bool true if success. It might return nothing when ftp is used and connection to the ftp address failed.
**/ **/
function makeDir($path_string) { function makeDir($path_string) {
static $oFtp = null; static $oFtp = null;
@ -256,9 +271,10 @@ class FileHandler {
} }
/** /**
* @brief remove all files under the path * Remove all files under the path
* @param[in] $path path of the target directory *
* @return none * @param string $path Path of the target directory
* @return void
**/ **/
function removeDir($path) { function removeDir($path) {
$path = FileHandler::getRealPath($path); $path = FileHandler::getRealPath($path);
@ -278,9 +294,10 @@ class FileHandler {
} }
/** /**
* @brief remove a directory only if it is empty * Remove a directory only if it is empty
* @param[in] $path path of the target directory *
* @return none * @param string $path Path of the target directory
* @return void
**/ **/
function removeBlankDir($path) { function removeBlankDir($path) {
$item_cnt = 0; $item_cnt = 0;
@ -299,10 +316,12 @@ class FileHandler {
/** /**
* @biref remove files in the target directory. * Remove files in the target directory
* @param[in] $path path of the target directory *
* @remarks This function keeps the directory structure. * This function keeps the directory structure.
* @return none *
* @param string $path Path of the target directory
* @return void
**/ **/
function removeFilesInDir($path) { function removeFilesInDir($path) {
$path = FileHandler::getRealPath($path); $path = FileHandler::getRealPath($path);
@ -321,9 +340,11 @@ class FileHandler {
} }
/** /**
* @brief makes file size byte into KB, MB according to the size * Makes file size byte into KB, MB according to the size
* @param[in] $size number of the size *
* @return file size string * @see FileHandler::returnBytes()
* @param int $size Number of the size
* @return string File size string
**/ **/
function filesize($size) { function filesize($size) {
if(!$size) return '0Byte'; if(!$size) return '0Byte';
@ -334,17 +355,19 @@ class FileHandler {
} }
/** /**
* @brief return remote file's content via HTTP * Return remote file's content via HTTP
* @param[in] $url the address of the target file *
* @param[in] $body HTTP request body * If the target is moved (when return code is 300~399), this function follows the location specified response header.
* @param[in] $timeout connection timeout *
* @param[in] $method GET/POST * @param string $url The address of the target file
* @param[in] $content_type content type header of HTTP request * @param string $body HTTP request body
* @param[in] $headers headers key vaule array. * @param int $timeout Connection timeout
* @param[in] $cookies cookies key value array. * @param string $method GET/POST
* @param[in] $post_data request arguments array for POST method * @param string $content_type Content type header of HTTP request
* @return if success, the content of the target file. otherwise: none * @param string[] $headers Headers key vaule array.
* @remarks if the target is moved (when return code is 300~399), this function follows the location specified response header. * @param string[] $cookies Cookies key value array.
* @param string $post_data Request arguments array for POST method
* @return string If success, the content of the target file. Otherwise: none
**/ **/
function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array()) { function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array()) {
requirePear(); requirePear();
@ -402,15 +425,16 @@ class FileHandler {
} }
/** /**
* @brief retrieves remote file, then stores it into target path. * Retrieves remote file, then stores it into target path.
* @param[in] $url the address of the target file *
* @param[in] $target_file the location to store * @param string $url The address of the target file
* @param[in] $body HTTP request body * @param string $target_filename The location to store
* @param[in] $timeout connection timeout * @param string $body HTTP request body
* @param[in] $method GET/POST * @param string $timeout Connection timeout
* @param[in] $content_type content type header of HTTP request * @param string $method GET/POST
* @param[in] $headers headers key vaule array. * @param string $content_type Content type header of HTTP request
* @return true: success, false: failed * @param string[] $headers Headers key vaule array.
* @return bool true: success, false: failed
**/ **/
function getRemoteFile($url, $target_filename, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array()) { function getRemoteFile($url, $target_filename, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array()) {
$body = FileHandler::getRemoteResource($url, $body, $timeout, $method, $content_type, $headers); $body = FileHandler::getRemoteResource($url, $body, $timeout, $method, $content_type, $headers);
@ -421,9 +445,11 @@ class FileHandler {
} }
/** /**
* @brief convert size in string into numeric value * Convert size in string into numeric value
* @param[in] $val size in string (ex., 10, 10K, 10M, 10G ) *
* @return converted size * @see FileHandler::filesize()
* @param $val Size in string (ex., 10, 10K, 10M, 10G )
* @return int converted size
*/ */
function returnBytes($val) function returnBytes($val)
{ {
@ -438,9 +464,10 @@ class FileHandler {
} }
/** /**
* @brief check available memory to load image file * Check available memory to load image file
* @param[in] $imageInfo image info retrieved by getimagesize function *
* @return true: it's ok, false: otherwise * @param array $imageInfo Image info retrieved by getimagesize function
* @return bool true: it's ok, false: otherwise
*/ */
function checkMemoryLoadImage(&$imageInfo) function checkMemoryLoadImage(&$imageInfo)
{ {
@ -456,14 +483,15 @@ class FileHandler {
} }
/** /**
* @brief moves an image file (resizing is possible) * Moves an image file (resizing is possible)
* @param[in] $source_file path of the source file *
* @param[in] $target_file path of the target file * @param string $source_file Path of the source file
* @param[in] $resize_width width to resize * @param string $target_file Path of the target file
* @param[in] $resize_height height to resize * @param int $resize_width Width to resize
* @param[in] $target_type if $target_type is set (gif, jpg, png, bmp), result image will be saved as target type * @param int $resize_height Height to resize
* @param[in] $thumbnail_type thumbnail type(crop, ratio) * @param string $target_type If $target_type is set (gif, jpg, png, bmp), result image will be saved as target type
* @return true: success, false: failed * @param string $thumbnail_type Thumbnail type(crop, ratio)
* @return bool true: success, false: failed
**/ **/
function createImageFile($source_file, $target_file, $resize_width = 0, $resize_height = 0, $target_type = '', $thumbnail_type = 'crop') { function createImageFile($source_file, $target_file, $resize_width = 0, $resize_height = 0, $target_type = '', $thumbnail_type = 'crop') {
$source_file = FileHandler::getRealPath($source_file); $source_file = FileHandler::getRealPath($source_file);
@ -610,9 +638,11 @@ class FileHandler {
} }
/** /**
* @brief reads ini file, and puts result into array * Reads ini file, and puts result into array
* @param[in] $filename path of the ini file *
* @return ini array (if the target file does not exist, it returns false) * @see FileHandler::writeIniFile()
* @param string $filename Path of the ini file
* @return array ini array (if the target file does not exist, it returns false)
**/ **/
function readIniFile($filename){ function readIniFile($filename){
$filename = FileHandler::getRealPath($filename); $filename = FileHandler::getRealPath($filename);
@ -624,10 +654,18 @@ class FileHandler {
/** /**
* @brief write array into ini file * Write array into ini file
* @param[in] $filename target ini file name *
* @param[in] $arr array * $ini['key1'] = 'value1';<br/>
* @return if array contains nothing it returns false, otherwise true * $ini['key2'] = 'value2';<br/>
* $ini['section']['key1_in_section'] = 'value1_in_section';<br/>
* $ini['section']['key2_in_section'] = 'value2_in_section';<br/>
* FileHandler::writeIniFile('exmple.ini', $ini);
*
* @see FileHandler::readIniFile()
* @param string $filename Target ini file name
* @param array $arr Array
* @return bool if array contains nothing it returns false, otherwise true
**/ **/
function writeIniFile($filename, $arr){ function writeIniFile($filename, $arr){
if(count($arr)==0) return false; if(count($arr)==0) return false;
@ -635,6 +673,12 @@ class FileHandler {
return true; return true;
} }
/**
* Make array to ini string
*
* @param array $arr Array
* @return string
*/
function _makeIniBuff($arr){ function _makeIniBuff($arr){
$return = ''; $return = '';
foreach($arr as $key => $val){ foreach($arr as $key => $val){
@ -653,11 +697,13 @@ class FileHandler {
} }
/** /**
* @brief return file object * Returns a file object
* @param[in] $filename target file name *
* @param[in] $mode file mode for fopen * If the directory of the file does not exist, create it.
* @remarks if the directory of the file does not exist, create it. *
* @return file object * @param string $filename Target file name
* @param string $mode File mode for fopen
* @return FileObject File object
**/ **/
function openFile($filename, $mode) function openFile($filename, $mode)
{ {
@ -671,9 +717,10 @@ class FileHandler {
} }
/** /**
* @brief check whether the given file has the content. * Check whether the given file has the content.
* @param[in] $file_name target file name *
* @return return true if the file exists and contains something. * @param string $filename Target file name
* @return bool Returns true if the file exists and contains something.
*/ */
function hasContent($filename) function hasContent($filename)
{ {

View file

@ -1,21 +1,35 @@
<?php <?php
/** /**
* @class FileObject * File abstraction class
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief file abstraction class
**/ **/
class FileObject extends Object class FileObject extends Object
{ {
var $fp = null; ///< file descriptor /**
var $path = null; ///< file path * File descriptor
var $mode = "r"; ///< file open mode * @var resource
*/
var $fp = null;
/** /**
* @brief constructor * File path
* @param[in] $path path of target file * @var string
* @param[in] $mode file open mode */
* @return file object var $path = null;
/**
* File open mode
* @var string
*/
var $mode = "r";
/**
* Constructor
*
* @param string $path Path of target file
* @param string $mode File open mode
* @return void
**/ **/
function FileObject($path, $mode) function FileObject($path, $mode)
{ {
@ -23,9 +37,10 @@ class FileObject extends Object
} }
/** /**
* @brief append target file's content to current file * Append target file's content to current file
* @param[in] $file_name path of target file *
* @return none * @param string $file_name Path of target file
* @return void
**/ **/
function append($file_name) function append($file_name)
{ {
@ -39,8 +54,9 @@ class FileObject extends Object
} }
/** /**
* @brief check current file meets eof * Check current file meets eof
* @return true: if eof. false: otherwise *
* @return bool true: if eof. false: otherwise
**/ **/
function feof() function feof()
{ {
@ -48,9 +64,10 @@ class FileObject extends Object
} }
/** /**
* @brief read from current file * Read from current file
* @param[in] $size size to read *
* @return read bytes * @param int $size Size to read
* @return string Returns the read string or false on failure.
**/ **/
function read($size = 1024) function read($size = 1024)
{ {
@ -59,9 +76,10 @@ class FileObject extends Object
/** /**
* @brief write string to current file * Write string to current file
* @param[in] $str string to write *
* @return written bytes. if failed, it returns false * @param string $str String to write
* @return int Returns the number of bytes written, or false on error.
**/ **/
function write($str) function write($str)
{ {
@ -73,11 +91,13 @@ class FileObject extends Object
} }
/** /**
* @brief open a file * Open a file
* @param[in] $path path of target file *
* @param[in] $mode file open mode * If file is opened, close it and open the new path
* @remarks if file is opened, close it and open the new path *
* @return true if succeed, false otherwise. * @param string $path Path of target file
* @param string $mode File open mode (http://php.net/manual/en/function.fopen.php)
* @return bool true if succeed, false otherwise.
*/ */
function open($path, $mode) function open($path, $mode)
{ {
@ -96,8 +116,9 @@ class FileObject extends Object
} }
/** /**
* @brief return current file's path * Return current file's path
* @return file path *
* @return string Returns the path of current file.
**/ **/
function getPath() function getPath()
{ {
@ -112,8 +133,9 @@ class FileObject extends Object
} }
/** /**
* @brief close file * Close file
* @return none *
* @return void
**/ **/
function close() function close()
{ {

View file

@ -1,18 +1,51 @@
<?php <?php
/** /**
* @class FrontEndFileHandler * Handle front end files
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
**/ **/
class FrontEndFileHandler extends Handler class FrontEndFileHandler extends Handler
{ {
/**
* Map for css
* @var array
*/
var $cssMap = array(); var $cssMap = array();
/**
* Map for Javascript at head
* @var array
*/
var $jsHeadMap = array(); var $jsHeadMap = array();
/**
* Map for Javascript at body
* @var array
*/
var $jsBodyMap = array(); var $jsBodyMap = array();
/**
* Index for css
* @var array
*/
var $cssMapIndex = array(); var $cssMapIndex = array();
/**
* Index for javascript at head
* @var array
*/
var $jsHeadMapIndex = array(); var $jsHeadMapIndex = array();
/**
* Index for javascript at body
* @var array
*/
var $jsBodyMapIndex = array(); var $jsBodyMapIndex = array();
/**
* Check SSL
*
* @return bool If using ssl returns true, otherwise returns false.
*/
function isSsl() function isSsl()
{ {
if ($GLOBAL['__XE_IS_SSL__']) return $GLOBAL['__XE_IS_SSL__']; if ($GLOBAL['__XE_IS_SSL__']) return $GLOBAL['__XE_IS_SSL__'];
@ -27,8 +60,11 @@
} }
/** /**
* @brief load front end file * Load front end file
* @params $args array *
* The $args is use as below. File type(js, css) is detected by file extension.
*
* <pre>
* case js * case js
* $args[0]: file name * $args[0]: file name
* $args[1]: type (head | body) * $args[1]: type (head | body)
@ -39,6 +75,22 @@
* $args[1]: media * $args[1]: media
* $args[2]: target IE * $args[2]: target IE
* $args[3]: index * $args[3]: index
* </pre>
*
* If $useCdn set true, use CDN instead local file.
* CDN path = $cdnPrefix . $cdnVersion . $args[0]<br />
*<br />
* i.e.<br />
* $cdnPrefix = 'http://static.xpressengine.com/core/';<br />
* $cdnVersion = 'ardent1';<br />
* $args[0] = './common/js/xe.js';<br />
* The CDN path is http://static.xprssengine.com/core/ardent1/common/js/xe.js.<br />
*
* @param array $args Arguments
* @param bool $useCdn If set true, use cdn instead local file
* @param string $cdnPrefix CDN url prefix. (http://static.xpressengine.com/core/)
* @param string $cdnVersion CDN version string (ardent1)
* @return void
**/ **/
function loadFile($args, $useCdn = false, $cdnPrefix = '', $cdnVersion = '') function loadFile($args, $useCdn = false, $cdnPrefix = '', $cdnVersion = '')
{ {
@ -57,8 +109,8 @@
$file->cdnVersion = $cdnVersion; $file->cdnVersion = $cdnVersion;
} }
$availableExtension = array('css', 'js'); $availableExtension = array('css'=>1, 'js'=>1);
if (!in_array($file->fileExtension, $availableExtension)) return; if (!isset($availableExtension[$file->fileExtension])) return;
$file->targetIe = $args[2]; $file->targetIe = $args[2];
$file->index = (int)$args[3]; $file->index = (int)$args[3];
@ -70,6 +122,8 @@
$map = &$this->cssMap; $map = &$this->cssMap;
$mapIndex = &$this->cssMapIndex; $mapIndex = &$this->cssMapIndex;
$key = $file->filePath . $file->fileName . "\t" . $file->targetIe . "\t" . $file->media; $key = $file->filePath . $file->fileName . "\t" . $file->targetIe . "\t" . $file->media;
$this->_arrangeCssIndex($pathInfo['dirname'], $file);
} }
else if ($file->fileExtension == 'js') else if ($file->fileExtension == 'js')
{ {
@ -95,6 +149,14 @@
} }
} }
/**
* Unload front end file
*
* @param string $fileName The file name to unload
* @param string $targetIe Target IE of file to unload
* @param string $media Media of file to unload. Only use when file is css.
* @return void
*/
function unloadFile($fileName, $targetIe = '', $media = 'all') function unloadFile($fileName, $targetIe = '', $media = 'all')
{ {
$pathInfo = pathinfo($fileName); $pathInfo = pathinfo($fileName);
@ -105,6 +167,11 @@
if ($fileExtension == 'css') if ($fileExtension == 'css')
{ {
if(empty($media))
{
$media = 'all';
}
$key .= "\t" . $media; $key .= "\t" . $media;
if (isset($this->cssMapIndex[$key])) if (isset($this->cssMapIndex[$key]))
{ {
@ -130,6 +197,12 @@
} }
} }
/**
* Unload all front end file
*
* @param string $type Type to unload. all, css, js
* @return void
*/
function unloadAllFiles($type = 'all') function unloadAllFiles($type = 'all')
{ {
if ($type == 'css' || $type == 'all') if ($type == 'css' || $type == 'all')
@ -147,6 +220,11 @@
} }
} }
/**
* Get css file list
*
* @return array Returns css file list. Array contains file, media, targetie.
*/
function getCssFileList() function getCssFileList()
{ {
$map = &$this->cssMap; $map = &$this->cssMap;
@ -177,6 +255,12 @@
return $result; return $result;
} }
/**
* Get javascript file list
*
* @param string $type Type of javascript. head, body
* @return array Returns javascript file list. Array contains file, targetie.
*/
function getJsFileList($type = 'head') function getJsFileList($type = 'head')
{ {
if ($type == 'head') if ($type == 'head')
@ -216,11 +300,24 @@
return $result; return $result;
} }
/**
* Sort a map
*
* @param array $map Array to sort
* @param array $index Not used
* @return void
*/
function _sortMap(&$map, &$index) function _sortMap(&$map, &$index)
{ {
ksort($map); ksort($map);
} }
/**
* Normalize File path
*
* @param string $path Path to normalize
* @return string Normalized path
*/
function _normalizeFilePath($path) function _normalizeFilePath($path)
{ {
if (strpos($path, '://') === false && $path{0} != '/' && $path{0} != '.') if (strpos($path, '://') === false && $path{0} != '/' && $path{0} != '.')
@ -238,6 +335,12 @@
return $path; return $path;
} }
/**
* Get absolute file url
*
* @param string $path Path to get absolute url
* @return string Absolute url
*/
function _getAbsFileUrl($path) function _getAbsFileUrl($path)
{ {
$path = $this->_normalizeFilePath($path); $path = $this->_normalizeFilePath($path);
@ -260,4 +363,28 @@
return $path; return $path;
} }
/**
* Arrage css index
*
* @param string $dirName First directory name of css path
* @param array $file file info.
* @return void
*/
function _arrangeCssIndex($dirName, &$file)
{
if($file->index !== 0)
{
return;
}
$dirName = str_replace('./', '', $dirName);
$tmp = explode('/', $dirName);
$cssSortList = array('common'=>-100000, 'layouts'=>-90000, 'modules'=>-80000, 'widgets'=>-70000, 'addons'=>-60000);
$file->index = $cssSortList[$tmp[0]];
}
} }
/* End of file FrontEndFileHandler.class.php */
/* Location: ./classes/frontendfile/FrontEndFileHandler.class.php */

View file

@ -1,8 +1,8 @@
<?php <?php
/** /**
* @class Handler * An abstract class of (*)Handler
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief an abstract class of (*)Handler
**/ **/
class Handler { class Handler {

View file

@ -1,21 +1,32 @@
<?php <?php
/** /**
* @class HttpRequest * - HttpRequest class
* - a class that is designed to be used for sending out HTTP request to an external server and retrieving response
* - Connection: keep-alive is not supported
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @package /classes/httprequest
* @version 0.1 * @version 0.1
* @brief a class that is designed to be used for sending out HTTP request to an external server and retrieving response
* @remarks Connection: keep-alive is not supported
*/ */
class XEHttpRequest { class XEHttpRequest {
/// target host /**
* target host
* @var string
*/
var $m_host; var $m_host;
/// target Port /**
* target Port
* @var int
*/
var $m_port; var $m_port;
/// header array /**
* target header
* @var array
*/
var $m_headers; var $m_headers;
/** /**
* @brief Constructor * constructor
* @return void
*/ */
function XEHttpRequest($host, $port) function XEHttpRequest($host, $port)
{ {
@ -25,9 +36,10 @@ class XEHttpRequest {
} }
/** /**
* @brief mether to add key/value pair to the HTTP request header * Mether to add key/value pair to the HTTP request header
* @param[in] key HTTP header element * @param int|string $key HTTP header element
* @param[in] value value string for HTTP header element * @param string $value value string for HTTP header element
* @return void
*/ */
function addToHeader($key, $value) function addToHeader($key, $value)
{ {
@ -35,12 +47,12 @@ class XEHttpRequest {
} }
/** /**
* @brief send HTTP message to the host * Send HTTP message to the host
* @param[in] target ip or url of the external server * @param string $target ip or url of the external server
* @param[in] method HTTP method such as GET and POST * @param string $method HTTP method such as GET and POST
* @param[in] timeout time out value for HTTP request expiration * @param int $timeout time out value for HTTP request expiration
* @param[in] post variables to send * @param array $post_vars variables to send
* @return Returns an object containing HTTP Response body and HTTP response code * @return object Returns an object containing HTTP Response body and HTTP response code
*/ */
function send($target='/', $method='GET', $timeout=3, $post_vars=null) function send($target='/', $method='GET', $timeout=3, $post_vars=null)
{ {
@ -67,8 +79,12 @@ class XEHttpRequest {
} }
/** /**
* @brief Send a request with the file socket * Send a request with the file socket
* @private * @param string $target ip or url of the external server
* @param string $method HTTP method such as GET and POST
* @param int $timeout time out value for HTTP request expiration
* @param array $post_vars variables to send
* @return object Returns an object containing HTTP Response body and HTTP response code
*/ */
function sendWithSock($target, $method, $timeout, $post_vars) function sendWithSock($target, $method, $timeout, $post_vars)
{ {
@ -131,8 +147,12 @@ class XEHttpRequest {
} }
/** /**
* @brief Send a request with the curl library * Send a request with the curl library
* @private * @param string $target ip or url of the external server
* @param string $method HTTP method such as GET and POST
* @param int $timeout time out value for HTTP request expiration
* @param array $post_vars variables to send
* @return object Returns an object containing HTTP Response body and HTTP response code
*/ */
function sendWithCurl($target, $method, $timeout, $post_vars) function sendWithCurl($target, $method, $timeout, $post_vars)
{ {

View file

@ -9,36 +9,128 @@ else
} }
/** /**
* @brief Mailing class for XpressEngine * Mailing class for XpressEngine
*
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @developer NHN (developers@xpressengine.com)
*/ */
class Mail extends PHPMailer class Mail extends PHPMailer
{ {
/**
* Sender name
* @var string
*/
var $sender_name = ''; var $sender_name = '';
/**
* Sender email address
* @var string
*/
var $sender_email = ''; var $sender_email = '';
/**
* Receiptor name
* @var string
*/
var $receiptor_name = ''; var $receiptor_name = '';
/**
* Receiptor email address
* @var string
*/
var $receiptor_email = ''; var $receiptor_email = '';
/**
* Title of email
* @var string
*/
var $title = ''; var $title = '';
/**
* Content of email
* @var string
*/
var $content = ''; var $content = '';
/**
* Content type
* @var string
*/
var $content_type = 'html'; var $content_type = 'html';
/**
* Message id
* @var string
*/
var $messageId = NULL; var $messageId = NULL;
/**
* Reply to
* @var string
*/
var $replyTo = NULL; var $replyTo = NULL;
/**
* BCC (Blind carbon copy)
* @var string
*/
var $bcc = NULL; var $bcc = NULL;
/**
* Attachments
* @var array
*/
var $attachments = array(); var $attachments = array();
/**
* Content attachements
* @var array
*/
var $cidAttachments = array(); var $cidAttachments = array();
/**
* ???
* @var ???
*/
var $mainMailPart = NULL; var $mainMailPart = NULL;
/**
* Raw body
* @var string
*/
var $body = ''; var $body = '';
/**
* Raw header
* @var string
*/
var $header = ''; var $header = '';
/**
* End of line
* @var string
*/
var $eol = ''; var $eol = '';
/**
* Reference
* @var string
*/
var $references = ''; var $references = '';
/**
* Additional parameters
* @var string
*/
var $additional_params = NULL; var $additional_params = NULL;
/**
* Whether use or not use stmp
* @var bool
*/
var $use_smtp = FALSE; var $use_smtp = FALSE;
/** /**
* @brief Constructor function * Constructor function
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return void * @return void
*/ */
@ -48,13 +140,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set parameters for using Gmail * Set parameters for using Gmail
* @access public
* @developer NHN (developers@xpressengine.com)
*
* @param $account_name password
* @param $account_passwd secure method ('ssl','tls')
* *
* @param string $account_name Password
* @param string $account_passwd Secure method ('ssl','tls')
* @return void * @return void
*/ */
function useGmailAccount($account_name, $account_passwd) function useGmailAccount($account_name, $account_passwd)
@ -76,18 +165,16 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set parameters for using SMTP protocol * Set parameters for using SMTP protocol
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $auth SMTP authentication * @param bool $auth SMTP authentication
* @param $host * @param string $host SMTP host address
* @param $user * @param string $user SMTP user id
* @param $password * @param string $pass STMP user password
* @param $secure method ('ssl','tls') * @param string $secure method ('ssl','tls')
* @param $port * @param int $port STMP port
* *
* @return boolean TRUE if SMTP is set correct, otherwise return FALSE * @return bool TRUE if SMTP is set correct, otherwise return FALSE
*/ */
function useSMTP($auth = NULL, $host = NULL, $user = NULL, $pass = NULL, $secure = NULL, $port = 25) function useSMTP($auth = NULL, $host = NULL, $user = NULL, $pass = NULL, $secure = NULL, $port = 25)
{ {
@ -116,11 +203,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set additional parameters * Set additional parameters
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $additional_params * @param string $additional_params Additional parameters
* @return void * @return void
*/ */
function setAdditionalParams($additional_params) function setAdditionalParams($additional_params)
@ -129,12 +214,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Add file attachment * Add file attachment
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $filename * @param string $filename File name to attach
* @param $orgfilename (real path to file) * @param string $orgfilename Real path of file to attach
* @return void * @return void
*/ */
function addAttachment($filename, $orgfilename) function addAttachment($filename, $orgfilename)
@ -143,12 +226,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Add content attachment * Add content attachment
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $filename * @param string $filename Real path of file to attach
* @param $cid * @param string $cid Content-CID
* @return void * @return void
*/ */
function addCidAttachment($filename, $cid) function addCidAttachment($filename, $cid)
@ -157,12 +238,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set Sender (From:) * Set Sender (From:)
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $name * @param string $name Sender name
* @param $email * @param string $email Sender email address
* @return void * @return void
*/ */
function setSender($name, $email) function setSender($name, $email)
@ -179,9 +258,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Get Sender (From:) * Get Sender (From:)
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return string * @return string
*/ */
@ -195,12 +272,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set Receiptor (TO:) * Set Receiptor (TO:)
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $name * @param string $name Receiptor name
* @param $email * @param string $email Receiptor email address
* @return void * @return void
*/ */
function setReceiptor($name, $email) function setReceiptor($name, $email)
@ -217,9 +292,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Get Receiptor (TO:) * Get Receiptor (TO:)
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return string * @return string
*/ */
@ -233,11 +306,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set Email's Title * Set Email's Title
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $title * @param string $title Title to set
* @return void * @return void
*/ */
function setTitle($title) function setTitle($title)
@ -253,9 +324,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Get Email's Title * Get Email's Title
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return string * @return string
*/ */
@ -265,11 +334,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set BCC * Set BCC
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $bcc * @param string $bcc
* @return void * @return void
*/ */
function setBCC($bcc) function setBCC($bcc)
@ -285,11 +352,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set Message ID * Set Message ID
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $messageId * @param string $messageId
* @return void * @return void
*/ */
function setMessageID($messageId) function setMessageID($messageId)
@ -298,11 +363,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set references * Set references
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $references * @param string $references
* @return void * @return void
*/ */
function setReferences($references) function setReferences($references)
@ -311,11 +374,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set ReplyTo param * Set ReplyTo param
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $replyTo * @param string $replyTo
* @return void * @return void
*/ */
function setReplyTo($replyTo) function setReplyTo($replyTo)
@ -331,11 +392,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set message content * Set message content
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $content * @param string $content Content
* @return void * @return void
*/ */
function setContent($content) function setContent($content)
@ -352,12 +411,10 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Replace resourse path of the files * Replace resourse path of the files
* @access public
* @developer NHN (developers@xpressengine.com)
*
* @param $matches
* *
* @see Mail::setContent()
* @param array $matches Match info.
* @return string * @return string
*/ */
function replaceResourceRealPath($matches) function replaceResourceRealPath($matches)
@ -366,9 +423,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Get the Plain content of body message * Get the Plain content of body message
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return string * @return string
*/ */
@ -378,9 +433,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Get the HTML content of body message * Get the HTML content of body message
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return string * @return string
*/ */
@ -390,11 +443,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Set the type of body's content * Set the type of body's content
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @param $mode * @param string $mode
* @return void * @return void
*/ */
function setContentType($mode = 'html') function setContentType($mode = 'html')
@ -403,9 +454,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Process the images from attachments * Process the images from attachments
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return void * @return void
*/ */
@ -460,9 +509,7 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Process the images from body content. This functions is used if Mailer is set as mail not as SMTP * Process the images from body content. This functions is used if Mailer is set as mail not as SMTP
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return void * @return void
*/ */
@ -505,11 +552,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Send email * Send email
* @access public
* @developer NHN (developers@xpressengine.com)
* *
* @return boolean TRUE in case of success, FALSE if sending fails * @return bool TRUE in case of success, FALSE if sending fails
*/ */
function send() function send()
{ {
@ -567,12 +612,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Check if DNS of param is real or fake * Check if DNS of param is real or fake
* @access public
* @developer NHN (developers@xpressengine.com)
*
* @param $email_address
* *
* @param string $email_address Email address
* @return boolean TRUE if param is valid DNS otherwise FALSE * @return boolean TRUE if param is valid DNS otherwise FALSE
*/ */
function checkMailMX($email_address) function checkMailMX($email_address)
@ -597,12 +639,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Check if param is a valid email or not * Check if param is a valid email or not
* @access public
* @developer NHN (developers@xpressengine.com)
*
* @param $email_address
* *
* @param string $email_address Email address
* @return string email address if param is valid email address otherwise blank string * @return string email address if param is valid email address otherwise blank string
*/ */
function isVaildMailAddress($email_address) function isVaildMailAddress($email_address)
@ -618,12 +657,9 @@ class Mail extends PHPMailer
} }
/** /**
* @brief Gets the MIME type of param * Gets the MIME type of param
* @access public
* @developer NHN (developers@xpressengine.com)
*
* @param $filename filename
* *
* @param string $filename filename
* @return string MIME type of ext * @return string MIME type of ext
*/ */
function returnMIMEType($filename) function returnMIMEType($filename)

View file

@ -1,19 +1,43 @@
<?php <?php
/**
* Mobile class
*
* @author NHN (developers@xpressengine.com)
*/
class Mobile { class Mobile {
/**
* Whether mobile or not mobile mode
* @var bool
*/
var $ismobile = null; var $ismobile = null;
/**
* Get instance of Mobile class(for singleton)
*
* @return Mobile
*/
function &getInstance() { function &getInstance() {
static $theInstance; static $theInstance;
if(!isset($theInstance)) $theInstance = new Mobile(); if(!isset($theInstance)) $theInstance = new Mobile();
return $theInstance; return $theInstance;
} }
/**
* Get current mobile mode
*
* @return bool If mobile mode returns true or false
*/
function isFromMobilePhone() { function isFromMobilePhone() {
$oMobile =& Mobile::getInstance(); $oMobile =& Mobile::getInstance();
return $oMobile->_isFromMobilePhone(); return $oMobile->_isFromMobilePhone();
} }
/**
* Get current mobile mode
*
* @return bool
*/
function _isFromMobilePhone() { function _isFromMobilePhone() {
if($this->ismobile !== null) return $this->ismobile; if($this->ismobile !== null) return $this->ismobile;
@ -94,6 +118,11 @@ class Mobile {
return $this->ismobile; return $this->ismobile;
} }
/**
* Detect mobile device by user agent
*
* @return bool Returns true on mobile device or false.
*/
function isMobileCheckByAgent() function isMobileCheckByAgent()
{ {
static $UACheck; static $UACheck;
@ -123,10 +152,11 @@ class Mobile {
return FALSE; return FALSE;
} }
/* /**
* @ brief check if user-agent is a tablet PC as iPad or Andoid tablet. * Check if user-agent is a tablet PC as iPad or Andoid tablet.
* @ return TRUE for tablet, and FALSE for else. *
*/ * @return bool TRUE for tablet, and FALSE for else.
*/
function isMobilePadCheckByAgent() function isMobilePadCheckByAgent()
{ {
static $UACheck; static $UACheck;
@ -167,6 +197,12 @@ class Mobile {
return FALSE; return FALSE;
} }
/**
* Set mobile mode
*
* @param bool $ismobile
* @return void
*/
function setMobile($ismobile) function setMobile($ismobile)
{ {
$oMobile =& Mobile::getInstance(); $oMobile =& Mobile::getInstance();

View file

@ -2,7 +2,7 @@
/** /**
* @class ModuleHandler * @class ModuleHandler
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief Handling modules * Handling modules
* *
* @remarks This class is to excute actions of modules. * @remarks This class is to excute actions of modules.
* Constructing an instance without any parameterconstructor, it finds the target module based on Context. * Constructing an instance without any parameterconstructor, it finds the target module based on Context.
@ -23,8 +23,13 @@
var $httpStatusCode = NULL; ///< http status code. var $httpStatusCode = NULL; ///< http status code.
/** /**
* @brief constructor * prepares variables to use in moduleHandler
* @remarks it prepares variables to use in moduleHandler * @param string $module name of module
* @param string $act name of action
* @param int $mid
* @param int $document_srl
* @param int $module_srl
* @return void
**/ **/
function ModuleHandler($module = '', $act = '', $mid = '', $document_srl = '', $module_srl = '') { function ModuleHandler($module = '', $act = '', $mid = '', $document_srl = '', $module_srl = '') {
// If XE has not installed yet, set module as install // If XE has not installed yet, set module as install
@ -63,8 +68,8 @@
} }
/** /**
* @brief Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action * Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action
* @return true: OK, false: redirected * @return boolean true: OK, false: redirected
**/ **/
function init() { function init() {
$oModuleModel = &getModel('module'); $oModuleModel = &getModel('module');
@ -172,8 +177,8 @@
} }
/** /**
* @brief get a module instance and execute an action * get a module instance and execute an action
* @return executed module instance * @return ModuleObject executed module instance
**/ **/
function procModule() { function procModule() {
$oModuleModel = &getModel('module'); $oModuleModel = &getModel('module');
@ -207,7 +212,17 @@
if(!$this->act) { if(!$this->act) {
$this->error = 'msg_module_is_not_exists'; $this->error = 'msg_module_is_not_exists';
$this->httpStatusCode = '404'; $this->httpStatusCode = '404';
return;
$type = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
$oMessageObject = &ModuleHandler::getModuleInstance('message',$type);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
if($this->httpStatusCode)
{
$oMessageObject->setHttpStatusCode($this->httpStatusCode);
}
return $oMessageObject;
} }
// get type, kind // get type, kind
@ -266,9 +281,16 @@
} }
if(!is_object($oModule)) { if(!is_object($oModule)) {
$this->error = 'msg_module_is_not_exists'; $type = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
$this->httpStatusCode = '404'; $oMessageObject = &ModuleHandler::getModuleInstance('message',$type);
return; $oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
if($this->httpStatusCode)
{
$oMessageObject->setHttpStatusCode($this->httpStatusCode);
}
return $oMessageObject;
} }
// If there is no such action in the module object // If there is no such action in the module object
@ -278,7 +300,15 @@
if(!Context::isInstalled()) if(!Context::isInstalled())
{ {
$this->error = 'msg_invalid_request'; $this->error = 'msg_invalid_request';
return; $oMessageObject = &ModuleHandler::getModuleInstance('message',$type);
$oMessageObject->setError(-1);
$oMessageObject->setMessage($this->error);
$oMessageObject->dispMessage();
if($this->httpStatusCode)
{
$oMessageObject->setHttpStatusCode($this->httpStatusCode);
}
return $oMessageObject;
} }
$forward = null; $forward = null;
@ -364,7 +394,9 @@
else else
{ {
$this->error = 'msg_invalid_request'; $this->error = 'msg_invalid_request';
return; $oModule->setError(-1);
$oModule->setMessage($this->error);
return $oModule;
} }
} }
@ -425,7 +457,8 @@
$procResult = $oModule->proc(); $procResult = $oModule->proc();
if(!in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) $methodList = array('XMLRPC'=>1, 'JSON'=>1);
if(!$oModule->stop_proc && !isset($methodList[Context::getRequestMethod()]))
{ {
$error = $oModule->getError(); $error = $oModule->getError();
$message = $oModule->getMessage(); $message = $oModule->getMessage();
@ -458,6 +491,10 @@
return $oModule; return $oModule;
} }
/**
* set error message to Session.
* @return void
**/
function _setInputErrorToContext() function _setInputErrorToContext()
{ {
if($_SESSION['XE_VALIDATOR_ERROR'] && !Context::get('XE_VALIDATOR_ERROR')) Context::set('XE_VALIDATOR_ERROR', $_SESSION['XE_VALIDATOR_ERROR']); if($_SESSION['XE_VALIDATOR_ERROR'] && !Context::get('XE_VALIDATOR_ERROR')) Context::set('XE_VALIDATOR_ERROR', $_SESSION['XE_VALIDATOR_ERROR']);
@ -468,6 +505,10 @@
$this->_clearErrorSession(); $this->_clearErrorSession();
} }
/**
* clear error message to Session.
* @return void
**/
function _clearErrorSession() function _clearErrorSession()
{ {
$_SESSION['XE_VALIDATOR_ERROR'] = ''; $_SESSION['XE_VALIDATOR_ERROR'] = '';
@ -476,6 +517,10 @@
$_SESSION['XE_VALIDATOR_RETURN_URL'] = ''; $_SESSION['XE_VALIDATOR_RETURN_URL'] = '';
} }
/**
* occured error when, set input values to session.
* @return void
**/
function _setInputValueToSession() function _setInputValueToSession()
{ {
$requestVars = Context::getRequestVars(); $requestVars = Context::getRequestVars();
@ -484,9 +529,9 @@
} }
/** /**
* @brief display contents from executed module * display contents from executed module
* @param[in] $oModule module instance * @param ModuleObject $oModule module instance
* @return none * @return void
**/ **/
function displayContent($oModule = NULL) { function displayContent($oModule = NULL) {
// If the module is not set or not an object, set error // If the module is not set or not an object, set error
@ -505,7 +550,8 @@
if(!$output->toBool()) $this->error = $output->getMessage(); if(!$output->toBool()) $this->error = $output->getMessage();
// Use message view object, if HTML call // Use message view object, if HTML call
if(!in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) { $methodList = array('XMLRPC'=>1, 'JSON'=>1);
if(!isset($methodList[Context::getRequestMethod()])) {
if($_SESSION['XE_VALIDATOR_RETURN_URL']) if($_SESSION['XE_VALIDATOR_RETURN_URL'])
{ {
@ -594,20 +640,20 @@
} }
/** /**
* @brief returns module's path * returns module's path
* @param[in] $module module name * @param string $module module name
* @return path of the module * @return string path of the module
**/ **/
function getModulePath($module) { function getModulePath($module) {
return sprintf('./modules/%s/', $module); return sprintf('./modules/%s/', $module);
} }
/** /**
* @brief It creates a module instance * It creates a module instance
* @param[in] $module module name * @param string $module module name
* @param[in] $type instance type, (e.g., view, controller, model) * @param string $type instance type, (e.g., view, controller, model)
* @param[in] $kind admin or svc * @param string $kind admin or svc
* @return module instance (if failed it returns null) * @return ModuleObject module instance (if failed it returns null)
* @remarks if there exists a module instance created before, returns it. * @remarks if there exists a module instance created before, returns it.
**/ **/
function &getModuleInstance($module, $type = 'view', $kind = '') { function &getModuleInstance($module, $type = 'view', $kind = '') {
@ -617,19 +663,19 @@
$kind = strtolower($kind); $kind = strtolower($kind);
$type = strtolower($type); $type = strtolower($type);
$kinds = explode(' ', 'svc admin'); $kinds = array('svc'=>1, 'admin'=>1);
if(!in_array($kind, $kinds)) $kind = $kinds[0]; if(!isset($kinds[$kind])) $kind = 'svc';
$key = $module.'.'.($kind!='admin'?'':'admin').'.'.$type; $key = $module.'.'.($kind!='admin'?'':'admin').'.'.$type;
if(is_array($GLOBALS['__MODULE_EXTEND__']) && array_key_exists($key, $GLOBALS['__MODULE_EXTEND__'])) { if(is_array($GLOBALS['__MODULE_EXTEND__']) && array_key_exists($key, $GLOBALS['__MODULE_EXTEND__']))
{
$module = $extend_module = $GLOBALS['__MODULE_EXTEND__'][$key]; $module = $extend_module = $GLOBALS['__MODULE_EXTEND__'][$key];
}else{
unset($parent_module);
} }
// if there is no instance of the module in global variable, create a new one // if there is no instance of the module in global variable, create a new one
if(!$GLOBALS['_loaded_module'][$module][$type][$kind]) { if(!isset($GLOBALS['_loaded_module'][$module][$type][$kind]))
{
$parent_module = $module; $parent_module = $module;
$class_path = ModuleHandler::getModulePath($module); $class_path = ModuleHandler::getModulePath($module);
@ -696,10 +742,10 @@
} }
/** /**
* @brief call a trigger * call a trigger
* @param[in] $trigger_name trigger's name to call * @param string $trigger_name trigger's name to call
* @param[in] $called_position called position * @param string $called_position called position
* @param[in] $obj an object as a parameter to trigger * @param object $obj an object as a parameter to trigger
* @return Object * @return Object
**/ **/
function triggerCall($trigger_name, $called_position, &$obj) { function triggerCall($trigger_name, $called_position, &$obj) {
@ -728,7 +774,9 @@
} }
/** /**
* @brief get http status message by http status code * get http status message by http status code
* @param string $code
* @return string
**/ **/
function _setHttpStatusMessage($code) { function _setHttpStatusMessage($code) {
$statusMessageList = array( $statusMessageList = array(

View file

@ -2,7 +2,7 @@
/** /**
* @class ModuleObject * @class ModuleObject
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief base class of ModuleHandler * base class of ModuleHandler
**/ **/
class ModuleObject extends Object { class ModuleObject extends Object {
@ -28,18 +28,21 @@
var $stop_proc = false; ///< a flag to indicating whether to stop the execution of code. var $stop_proc = false; ///< a flag to indicating whether to stop the execution of code.
var $module_config = NULL; var $module_config = NULL;
var $ajaxRequestMethod = array('XMLRPC', 'JSON');
/** /**
* @brief setter to set the name of module * setter to set the name of module
* @param name of module * @param string $module name of module
* @return void
**/ **/
function setModule($module) { function setModule($module) {
$this->module = $module; $this->module = $module;
} }
/** /**
* @brief setter to set the name of module path * setter to set the name of module path
* @param the directory path to a module directory * @param string $path the directory path to a module directory
* @return void
**/ **/
function setModulePath($path) { function setModulePath($path) {
if(substr($path,-1)!='/') $path.='/'; if(substr($path,-1)!='/') $path.='/';
@ -47,25 +50,37 @@
} }
/** /**
* @brief setter to set an url for redirection * setter to set an url for redirection
* @param $url url for redirection * @param string $url url for redirection
* @remark redirect_url is used only for ajax requests * @remark redirect_url is used only for ajax requests
* @return void
**/ **/
function setRedirectUrl($url='./') { function setRedirectUrl($url='./', $output = NULL) {
$this->add('redirect_url', $url); $ajaxRequestMethod = array_flip($this->ajaxRequestMethod);
if(!isset($ajaxRequestMethod[Context::getRequestMethod()]))
{
$this->add('redirect_url', $url);
}
if($output !== NULL && is_object($output))
{
return $output;
}
} }
/** /**
* @brief get url for redirection * get url for redirection
* @return string redirect_url
**/ **/
function getRedirectUrl(){ function getRedirectUrl(){
return $this->get('redirect_url'); return $this->get('redirect_url');
} }
/** /**
* @brief set message * set message
* @param $message a message string * @param string $message a message string
* @param $type type of message (error, info, update) * @param string $type type of message (error, info, update)
* @return void
**/ **/
function setMessage($message, $type = null){ function setMessage($message, $type = null){
parent::setMessage($message); parent::setMessage($message);
@ -73,28 +88,32 @@
} }
/** /**
* @brief set type of message * set type of message
* @param $type type of message (error, info, update) * @param string $type type of message (error, info, update)
* @return void
**/ **/
function setMessageType($type){ function setMessageType($type){
$this->add('message_type', $type); $this->add('message_type', $type);
} }
/** /**
* @brief get type of message * get type of message
* @return string $type
**/ **/
function getMessageType(){ function getMessageType(){
$type = $this->get('message_type'); $type = $this->get('message_type');
if (!in_array($type, array('error', 'info', 'update'))){ $typeList = array('error'=>1, 'info'=>1, 'update'=>1);
if (!isset($typeList[$type])){
$type = $this->getError()?'error':'info'; $type = $this->getError()?'error':'info';
} }
return $type; return $type;
} }
/** /**
* @brief sett to set the template path for refresh.html * sett to set the template path for refresh.html
* @remark refresh.html is executed as a result of method execution * refresh.html is executed as a result of method execution
* Tpl as the common run of the refresh.html .. * Tpl as the common run of the refresh.html ..
* @return void
**/ **/
function setRefreshPage() { function setRefreshPage() {
$this->setTemplatePath('./common/tpl'); $this->setTemplatePath('./common/tpl');
@ -103,16 +122,19 @@
/** /**
* @brief sett to set the action name * sett to set the action name
* @param string $act
* @return void
**/ **/
function setAct($act) { function setAct($act) {
$this->act = $act; $this->act = $act;
} }
/** /**
* @brief sett to set module information * sett to set module information
* @param[in] $module_info object containing module information * @param object $module_info object containing module information
* @param[in] $xml_info object containing module description * @param object $xml_info object containing module description
* @return void
**/ **/
function setModuleInfo($module_info, $xml_info) { function setModuleInfo($module_info, $xml_info) {
// The default variable settings // The default variable settings
@ -129,7 +151,7 @@
$oModuleModel = &getModel('module'); $oModuleModel = &getModel('module');
// permission settings. access, manager(== is_admin) are fixed and privilege name in XE // permission settings. access, manager(== is_admin) are fixed and privilege name in XE
$module_srl = Context::get('module_srl'); $module_srl = Context::get('module_srl');
if(!$module_info->mid && preg_match('/^([0-9]+)$/',$module_srl)) { if(!$module_info->mid && !is_array($module_srl) && preg_match('/^([0-9]+)$/',$module_srl)) {
$request_module = $oModuleModel->getModuleInfoByModuleSrl($module_srl); $request_module = $oModuleModel->getModuleInfoByModuleSrl($module_srl);
if($request_module->module_srl == $module_srl) { if($request_module->module_srl == $module_srl) {
$grant = $oModuleModel->getGrant($request_module, $logged_info); $grant = $oModuleModel->getGrant($request_module, $logged_info);
@ -151,13 +173,15 @@
// Check permissions // Check permissions
switch($permission_target) { switch($permission_target) {
case 'root' : case 'root' :
$this->stop('msg_not_permitted_act'); case 'manager' :
break; $this->stop('msg_not_permitted_act');
case 'manager' : return;
if(!$grant->manager) $this->stop('msg_not_permitted_act');
break;
case 'member' : case 'member' :
if(!$is_logged) $this->stop('msg_not_permitted_act'); if(!$is_logged)
{
$this->stop('msg_not_permitted_act');
return;
}
break; break;
} }
} }
@ -172,8 +196,9 @@
} }
/** /**
* @brief set the stop_proc and approprate message for msg_code * set the stop_proc and approprate message for msg_code
* @param $msg_code an error code * @param string $msg_code an error code
* @return ModuleObject $this
**/ **/
function stop($msg_code) { function stop($msg_code) {
// flag setting to stop the proc processing // flag setting to stop the proc processing
@ -195,7 +220,9 @@
} }
/** /**
* @brief set the file name of the template file * set the file name of the template file
* @param string name of file
* @return void
**/ **/
function setTemplateFile($filename) { function setTemplateFile($filename) {
if(substr($filename,-5)!='.html') $filename .= '.html'; if(substr($filename,-5)!='.html') $filename .= '.html';
@ -203,14 +230,17 @@
} }
/** /**
* @brief retrieve the directory path of the template directory * retrieve the directory path of the template directory
* @return string
**/ **/
function getTemplateFile() { function getTemplateFile() {
return $this->template_file; return $this->template_file;
} }
/** /**
* @brief set the directory path of the template directory * set the directory path of the template directory
* @param string path of template directory.
* @return void
**/ **/
function setTemplatePath($path) { function setTemplatePath($path) {
if(substr($path,0,1)!='/' && substr($path,0,2)!='./') $path = './'.$path; if(substr($path,0,1)!='/' && substr($path,0,2)!='./') $path = './'.$path;
@ -219,15 +249,17 @@
} }
/** /**
* retrieve the directory path of the template directory
* @brief retrieve the directory path of the template directory * @return string
**/ **/
function getTemplatePath() { function getTemplatePath() {
return $this->template_path; return $this->template_path;
} }
/** /**
* @brief set the file name of the temporarily modified by admin * set the file name of the temporarily modified by admin
* @param string name of file
* @return void
**/ **/
function setEditedLayoutFile($filename) { function setEditedLayoutFile($filename) {
if(substr($filename,-5)!='.html') $filename .= '.html'; if(substr($filename,-5)!='.html') $filename .= '.html';
@ -235,14 +267,17 @@
} }
/** /**
* @brief retreived the file name of edited_layout_file * retreived the file name of edited_layout_file
* @return string
**/ **/
function getEditedLayoutFile() { function getEditedLayoutFile() {
return $this->edited_layout_file; return $this->edited_layout_file;
} }
/** /**
* @brief set the file name of the layout file * set the file name of the layout file
* @param string name of file
* @return void
**/ **/
function setLayoutFile($filename) { function setLayoutFile($filename) {
if(substr($filename,-5)!='.html') $filename .= '.html'; if(substr($filename,-5)!='.html') $filename .= '.html';
@ -250,14 +285,16 @@
} }
/** /**
* @brief get the file name of the layout file * get the file name of the layout file
* @return string
**/ **/
function getLayoutFile() { function getLayoutFile() {
return $this->layout_file; return $this->layout_file;
} }
/** /**
* @brief set the directory path of the layout directory * set the directory path of the layout directory
* @param string path of layout directory.
**/ **/
function setLayoutPath($path) { function setLayoutPath($path) {
if(substr($path,0,1)!='/' && substr($path,0,2)!='./') $path = './'.$path; if(substr($path,0,1)!='/' && substr($path,0,2)!='./') $path = './'.$path;
@ -266,15 +303,16 @@
} }
/** /**
* @brief set the directory path of the layout directory * set the directory path of the layout directory
* @return string
**/ **/
function getLayoutPath() { function getLayoutPath() {
return $this->layout_path; return $this->layout_path;
} }
/** /**
* @brief excute the member method specified by $act variable * excute the member method specified by $act variable
* * @return boolean true : success false : fail
**/ **/
function proc() { function proc() {
// pass if stop_proc is true // pass if stop_proc is true
@ -297,7 +335,8 @@
if(isset($this->xml_info->action->{$this->act}) && method_exists($this, $this->act)) { if(isset($this->xml_info->action->{$this->act}) && method_exists($this, $this->act)) {
// Check permissions // Check permissions
if(!$this->grant->access){ if(!$this->grant->access){
return $this->stop("msg_not_permitted_act"); $this->stop("msg_not_permitted_act");
return FALSE;
} }
// integrate skin information of the module(change to sync skin info with the target module only by seperating its table) // integrate skin information of the module(change to sync skin info with the target module only by seperating its table)
$oModuleModel = &getModel('module'); $oModuleModel = &getModel('module');

View file

@ -1,105 +1,159 @@
<?php <?php
/** /**
* @class Object * Every modules inherits from Object class. It includes error, message, and other variables for communicatin purpose.
* @author NHN (developers@xpressengine.com)
* @brief Base class design to pass the Object instance between XE Modules
* *
* @remark Every modules inherits from Object class. It includes error, message, and other variables for communicatin purpose * @author NHN (developers@xpressengine.com)
**/ */
class Object { class Object {
var $error = 0; // / "Error code (if 0, it is not an error)
var $message = 'success'; // / "Error message (if success, it is not an error)
var $variables = array(); // /< an additional variable
var $httpStatusCode = NULL; ///< http status code.
/** /**
* @brief constructor * Error code. If `0`, it is not an error.
**/ * @var int
*/
var $error = 0;
/**
* Error message. If `success`, it is not an error.
* @var string
*/
var $message = 'success';
/**
* An additional variable
* @var array
*/
var $variables = array();
/**
* http status code.
* @var int
*/
var $httpStatusCode = NULL;
/**
* Constructor
*
* @param int $error Error code
* @param string $message Error message
* @return void
*/
function Object($error = 0, $message = 'success') { function Object($error = 0, $message = 'success') {
$this->setError($error); $this->setError($error);
$this->setMessage($message); $this->setMessage($message);
} }
/** /**
* @brief Setter to set error code * Setter to set error code
* @param[in] $error error code *
**/ * @param int $error error code
* @return void
*/
function setError($error = 0) { function setError($error = 0) {
$this->error = $error; $this->error = $error;
} }
/** /**
* @brief Getter to retrieve error code * Getter to retrieve error code
**/ *
* @return int Returns an error code
*/
function getError() { function getError() {
return $this->error; return $this->error;
} }
/**
* Setter to set HTTP status code
*
* @param int $code HTTP status code. Default value is `200` that means successful
* @return void
*/
function setHttpStatusCode($code = '200') function setHttpStatusCode($code = '200')
{ {
$this->httpStatusCode = $code; $this->httpStatusCode = $code;
} }
/**
* Getter to retrieve HTTP status code
*
* @return int Returns HTTP status code
*/
function getHttpStatusCode() function getHttpStatusCode()
{ {
return $this->httpStatusCode; return $this->httpStatusCode;
} }
/** /**
* @brief Setter to set set the error message * Setter to set set the error message
* @param[in] $message a messge string *
* @return return True * @param string $message Error message
* @remark this method always returns True. We'd better remove it * @return bool Alaways returns true.
**/ */
function setMessage($message = 'success') { function setMessage($message = 'success') {
if(Context::getLang($message)) $message = Context::getLang($message); if(Context::getLang($message)) $message = Context::getLang($message);
$this->message = $message; $this->message = $message;
// TODO This method always returns True. We'd better remove it
return true; return true;
} }
/** /**
* @brief getter to retrieve an error message * Getter to retrieve an error message
**/ *
* @return string Returns message
*/
function getMessage() { function getMessage() {
return $this->message; return $this->message;
} }
/** /**
* @brief setter to set a key/value pair as an additional variable * Setter to set a key/value pair as an additional variable
* @param[in] $key a variable name *
* @param[in] $val a value for the variable * @param string $key A variable name
**/ * @param mixed $val A value for the variable
* @return void
*/
function add($key, $val) { function add($key, $val) {
$this->variables[$key] = $val; $this->variables[$key] = $val;
} }
/** /**
* @brief method to set multiple key/value pairs as an additional variables * Method to set multiple key/value pairs as an additional variables
* @param[in] $object either object or array containg key/value pairs to be added *
**/ * @param Object|array $object Either object or array containg key/value pairs to be added
function adds($object) { * @return void
if(is_object($object)) { */
$vars = get_object_vars($object); function adds($object)
foreach($vars as $key => $val) $this->add($key, $val); {
} elseif(is_array($object)) { if(is_object($object))
foreach($object as $key => $val) $this->add($key, $val); {
$object = get_object_vars($object);
}
if(is_array($object))
{
foreach($object as $key => $val) $this->variables[$key] = $val;
} }
} }
/** /**
* @brief method to retrieve a corresponding value to a given key * Method to retrieve a corresponding value to a given key
**/ *
* @param string $key
* @return string Returns value to a given key
*/
function get($key) { function get($key) {
return $this->variables[$key]; return $this->variables[$key];
} }
/** /**
* @brief method to retrieve an object containing a key/value paris * Method to retrieve an object containing a key/value paris
* @return Returns an object containing key/value pairs *
**/ * @return Object Returns an object containing key/value pairs
*/
function gets() { function gets() {
$num_args = func_num_args(); $num_args = func_num_args();
$args_list = func_get_args(); $args_list = func_get_args();
@ -111,35 +165,40 @@ class Object {
} }
/** /**
* @brief method to retrieve an array of key/value pairs * Method to retrieve an array of key/value pairs
* @return Return a list of key/value pairs *
**/ * @return array
*/
function getVariables() { function getVariables() {
return $this->variables; return $this->variables;
} }
/** /**
* @brief method to retrieve an object of key/value pairs * Method to retrieve an object of key/value pairs
* @return Return an object of key/value pairs *
**/ * @return Object
*/
function getObjectVars() { function getObjectVars() {
foreach($this->variables as $key => $val) $output->{$key} = $val; foreach($this->variables as $key => $val) $output->{$key} = $val;
return $output; return $output;
} }
/** /**
* @brief method to return either true or false depnding on the value in a 'error' variable * Method to return either true or false depnding on the value in a 'error' variable
* @remark this method is misleading in that it returns true if error is 0, which should be true in *
* boolean representation. * @return bool Retruns true : error isn't 0 or false : otherwise.
**/ */
function toBool() { function toBool() {
// TODO This method is misleading in that it returns true if error is 0, which should be true in boolean representation.
return $this->error==0?true:false; return $this->error==0?true:false;
} }
/** /**
* @brief method to return either true or false depnding on the value in a 'error' variable * Method to return either true or false depnding on the value in a 'error' variable
**/ *
* @return bool
*/
function toBoolean() { function toBoolean() {
return $this->toBool(); return $this->toBool();
} }

View file

@ -2,7 +2,7 @@
/** /**
* @class PageHandler * @class PageHandler
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief handles page navigation * handles page navigation
* @version 0.1 * @version 0.1
* *
* @remarks Getting total counts, number of pages, current page number, number of items per page, * @remarks Getting total counts, number of pages, current page number, number of items per page,
@ -20,11 +20,12 @@
var $point = 0; ///< increments per getNextPage() var $point = 0; ///< increments per getNextPage()
/** /**
* @brief constructor * constructor
* @param[in] $total_count number of total items * @param int $total_count number of total items
* @param[in] $total_page number of total pages * @param int $total_page number of total pages
* @param[in] $cur_page current page number * @param int $cur_page current page number
* @param[in] $page_count number of page links displayed at one time * @param int $page_count number of page links displayed at one time
* @return void
**/ **/
function PageHandler($total_count, $total_page, $cur_page, $page_count = 10) { function PageHandler($total_count, $total_page, $cur_page, $page_count = 10) {
$this->total_count = $total_count; $this->total_count = $total_count;
@ -45,8 +46,8 @@
} }
/** /**
* @brief request next page * request next page
* @return next page number * @return int next page number
**/ **/
function getNextPage() { function getNextPage() {
$page = $this->first_page+$this->point++; $page = $this->first_page+$this->point++;
@ -54,6 +55,11 @@
return $page; return $page;
} }
/**
* return number of page that added offset.
* @param int $offset
* @return int
**/
function getPage($offset) function getPage($offset)
{ {
return max(min($this->cur_page + $offset, $this->total_page), ''); return max(min($this->cur_page + $offset, $this->total_page), '');

View file

@ -1,20 +1,23 @@
<?php <?php
/** /**
* @class Security * - Security class
* @brief This class helps to solve security problems. * - This class helps to solve security problems.
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
**/ * @package /classes/security
* @version 0.1
*/
class Security class Security
{ {
/** /**
* @brief Action target variable. If this value is null, the method will use Context variables * Action target variable. If this value is null, the method will use Context variables
* @protected * @var mixed
**/ **/
var $_targetVar = null; var $_targetVar = null;
/** /**
* @constructor * @constructor
* @param $var Target context * @param mixed $var Target context
* @return void
*/ */
function Security($var = null) function Security($var = null)
{ {
@ -22,13 +25,11 @@ class Security
} }
/** /**
* @brief Convert special characters to HTML entities for the target variables. * - Convert special characters to HTML entities for the target variables.
* The results of conversion are equivalent to the results of htmlspecialchars() which is a native function of PHP. * - The results of conversion are equivalent to the results of htmlspecialchars() which is a native function of PHP.
* @params string $varName * @params string $varName. A variable's name to convert to process properties of an object or elements of an array,
* A variable's name to convert * separate the owner(object or array) and the item(property or element) using a dot(.)
* To process properties of an object or elements of an array, * @return mixed
* separate the owner(object or array) and the item(property or element) using a dot(.)
* @public
*/ */
function encodeHTML(/*, $varName1, $varName2, ... */) function encodeHTML(/*, $varName1, $varName2, ... */)
{ {
@ -70,7 +71,10 @@ class Security
} }
/** /**
* @protected * Convert special characters to HTML entities for the target variables.
* @param mixed $var
* @param array $name
* @return mixed
*/ */
function _encodeHTML($var, $name=array()) function _encodeHTML($var, $name=array())
{ {

View file

@ -2,7 +2,7 @@
/** /**
* @class TemplateHandler * @class TemplateHandler
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief template compiler * template compiler
* @version 0.1 * @version 0.1
* @remarks It compiles template file by using regular expression into php * @remarks It compiles template file by using regular expression into php
* code, and XE caches compiled code for further uses * code, and XE caches compiled code for further uses
@ -22,6 +22,10 @@ class TemplateHandler {
var $handler_mtime = 0; var $handler_mtime = 0;
/**
* constructor
* @return void
**/
function TemplateHandler() function TemplateHandler()
{ {
// TODO: replace this with static variable in PHP5 // TODO: replace this with static variable in PHP5
@ -33,7 +37,7 @@ class TemplateHandler {
} }
/** /**
* @brief returns TemplateHandler's singleton object * returns TemplateHandler's singleton object
* @return TemplateHandler instance * @return TemplateHandler instance
**/ **/
function &getInstance() function &getInstance()
@ -51,7 +55,11 @@ class TemplateHandler {
} }
/** /**
* @brief set variables for template compile * set variables for template compile
* @param string $tpl_path
* @param string $tpl_filename
* @param string $tpl_file
* @return void
**/ **/
function init($tpl_path, $tpl_filename, $tpl_file='') function init($tpl_path, $tpl_filename, $tpl_file='')
{ {
@ -80,11 +88,11 @@ class TemplateHandler {
} }
/** /**
* @brief compiles specified tpl file and execution result in Context into resultant content * compiles specified tpl file and execution result in Context into resultant content
* @param[in] $tpl_path path of the directory containing target template file * @param string $tpl_path path of the directory containing target template file
* @param[in] $tpl_filename target template file's name * @param string $tpl_filename target template file's name
* @param[in] $tpl_file if specified use it as template file's full path * @param string $tpl_file if specified use it as template file's full path
* @return Returns compiled result in case of success, NULL otherwise * @return string Returns compiled result in case of success, NULL otherwise
*/ */
function compile($tpl_path, $tpl_filename, $tpl_file='') { function compile($tpl_path, $tpl_filename, $tpl_file='') {
global $__templatehandler_root_tpl; global $__templatehandler_root_tpl;
@ -140,10 +148,10 @@ class TemplateHandler {
} }
/** /**
* @brief compile specified file and immediately return * compile specified file and immediately return
* @param[in] $tpl_path path of the directory containing target template file * @param string $tpl_path path of the directory containing target template file
* @param[in] $tpl_filename target template file's name * @param string $tpl_filename target template file's name
* @return Returns compiled content in case of success or NULL in case of failure * @return string Returns compiled content in case of success or NULL in case of failure
**/ **/
function compileDirect($tpl_path, $tpl_filename) { function compileDirect($tpl_path, $tpl_filename) {
$this->init($tpl_path, $tpl_filename, null); $this->init($tpl_path, $tpl_filename, null);
@ -158,11 +166,9 @@ class TemplateHandler {
} }
/** /**
* @brief compile a template file specified in $tpl_file and * parse syntax.
* @pre files specified by $tpl_file exists. * @param string $buff template file
* @param[in] $tpl_file path of tpl file * @return string compiled result in case of success or NULL in case of error
* @param[in] $compiled_tpl_file if specified, write compiled result into the file
* @return compiled result in case of success or NULL in case of error
**/ **/
function parse($buff=null) { function parse($buff=null) {
if(is_null($buff)) { if(is_null($buff)) {
@ -189,8 +195,8 @@ class TemplateHandler {
// include, unload/load, import // include, unload/load, import
$buff = preg_replace_callback('/{(@[\s\S]+?|(?=\$\w+|_{1,2}[A-Z]+|[!\(+-]|\w+(?:\(|::)|\d+|[\'"].*?[\'"]).+?)}|<(!--[#%])?(include|import|(un)?load(?(4)|(?:_js_plugin)?))(?(2)\(["\']([^"\']+)["\'])(.*?)(?(2)\)--|\/)>|<!--(@[a-z@]*)([\s\S]*?)-->(\s*)/', array($this, '_parseResource'), $buff); $buff = preg_replace_callback('/{(@[\s\S]+?|(?=\$\w+|_{1,2}[A-Z]+|[!\(+-]|\w+(?:\(|::)|\d+|[\'"].*?[\'"]).+?)}|<(!--[#%])?(include|import|(un)?load(?(4)|(?:_js_plugin)?))(?(2)\(["\']([^"\']+)["\'])(.*?)(?(2)\)--|\/)>|<!--(@[a-z@]*)([\s\S]*?)-->(\s*)/', array($this, '_parseResource'), $buff);
// remove block which is a virtual tag and remove comments // remove block which is a virtual tag
$buff = preg_replace('@</?block\s*>|\s?<!--//(.*?)-->@is','',$buff); $buff = preg_replace('@</?block\s*>@is','',$buff);
// form auto generation // form auto generation
$buff = preg_replace_callback('/(<form(?:<\?php.+?\?>|[^<>]+)*?>)(.*?)(<\/form>)/is', array($this, '_compileFormAuthGeneration'), $buff); $buff = preg_replace_callback('/(<form(?:<\?php.+?\?>|[^<>]+)*?>)(.*?)(<\/form>)/is', array($this, '_compileFormAuthGeneration'), $buff);
@ -198,14 +204,20 @@ class TemplateHandler {
// prevent from calling directly before writing into file // prevent from calling directly before writing into file
$buff = '<?php if(!defined("__XE__"))exit;?>'.$buff; $buff = '<?php if(!defined("__XE__"))exit;?>'.$buff;
// remove php script reopening
$buff = preg_replace(array('/(\n|\r\n)+/','/(;)?( )*\?\>\<\?php([\n\t ]+)?/'),array("\n",";\n"),$buff);
return $buff; return $buff;
} }
/** /**
* @brief 1. remove ruleset from form tag * preg_replace_callback handler
* 1. remove ruleset from form tag
* 2. add hidden tag with ruleset value * 2. add hidden tag with ruleset value
* 3. if empty default hidden tag, generate hidden tag (ex:mid, vid, act...) * 3. if empty default hidden tag, generate hidden tag (ex:mid, vid, act...)
* 4. generate return url, return url use in server side validator * 4. generate return url, return url use in server side validator
* @param array $matches
* @return string
**/ **/
function _compileFormAuthGeneration($matches) function _compileFormAuthGeneration($matches)
{ {
@ -260,7 +272,7 @@ class TemplateHandler {
if(!preg_match('/no-error-return-url="true"/i', $matches[1])) if(!preg_match('/no-error-return-url="true"/i', $matches[1]))
{ {
preg_match('/<input[^>]*name="error_return_url"[^>]*>/is', $matches[2], $m3); preg_match('/<input[^>]*name="error_return_url"[^>]*>/is', $matches[2], $m3);
if(!$m3[0]) $matches[2] = '<input type="hidden" name="error_return_url" value="<?php echo getRequestUriByServerEnviroment() ?>" />'.$matches[2]; if(!$m3[0]) $matches[2] = '<input type="hidden" name="error_return_url" value="<?php echo htmlspecialchars(getRequestUriByServerEnviroment()) ?>" />'.$matches[2];
} }
else else
{ {
@ -272,11 +284,9 @@ class TemplateHandler {
} }
/** /**
* @brief fetch using ob_* function * fetch using ob_* function
* @param[in] $compiled_tpl_file path of compiled template file * @param string $buff if buff is not null, eval it instead of including compiled template file
* @param[in] $buff if buff is not null, eval it instead of including compiled template file * @return string
* @param[in] $tpl_path set context's tpl path
* @return result string
**/ **/
function _fetch($buff) { function _fetch($buff) {
if(!$buff) return; if(!$buff) return;
@ -300,10 +310,12 @@ class TemplateHandler {
} }
/** /**
* @brief change image path * preg_replace_callback hanlder
* @pre $matches is an array containg three elements *
* @param[in] $matches match * replace image path
* @return changed result * @param array $match
*
* @return string changed result
**/ **/
function _replacePath($match) function _replacePath($match)
{ {
@ -320,6 +332,11 @@ class TemplateHandler {
return substr($match[0],0,-strlen($match[1])-6)."src=\"{$src}\""; return substr($match[0],0,-strlen($match[1])-6)."src=\"{$src}\"";
} }
/**
* replace loop and cond template syntax
* @param string $buff
* @return string changed result
**/
function _parseInline($buff) function _parseInline($buff)
{ {
if(preg_match_all('/<([a-zA-Z]+\d?)(?>(?!<[a-z]+\d?[\s>]).)*?(?:[ \|]cond| loop)="/s', $buff, $match) === false) return $buff; if(preg_match_all('/<([a-zA-Z]+\d?)(?>(?!<[a-z]+\d?[\s>]).)*?(?:[ \|]cond| loop)="/s', $buff, $match) === false) return $buff;
@ -334,7 +351,7 @@ class TemplateHandler {
$nodes = preg_split($split_regex, $buff, -1, PREG_SPLIT_DELIM_CAPTURE); $nodes = preg_split($split_regex, $buff, -1, PREG_SPLIT_DELIM_CAPTURE);
// list of self closing tags // list of self closing tags
$self_closing = explode(',', 'area,base,basefont,br,hr,input,img,link,meta,param,frame,col'); $self_closing = array('area'=>1,'base'=>1,'basefont'=>1,'br'=>1,'hr'=>1,'input'=>1,'img'=>1,'link'=>1,'meta'=>1,'param'=>1,'frame'=>1,'col'=>1);
for($idx=1,$node_len=count($nodes); $idx < $node_len; $idx+=2) { for($idx=1,$node_len=count($nodes); $idx < $node_len; $idx+=2) {
if(!($node=$nodes[$idx])) continue; if(!($node=$nodes[$idx])) continue;
@ -375,7 +392,7 @@ class TemplateHandler {
// find closing tag // find closing tag
$close_php = '<?php '.str_repeat('}', $closing).' ?>'; $close_php = '<?php '.str_repeat('}', $closing).' ?>';
if($node{1} == '!' || substr($node,-2,1) == '/' || in_array($tag, $self_closing)) { // self closing tag if($node{1} == '!' || substr($node,-2,1) == '/' || isset($self_closing[$tag])) { // self closing tag
$nodes[$idx+1] = $close_php.$nodes[$idx+1]; $nodes[$idx+1] = $close_php.$nodes[$idx+1];
} else { } else {
$depth = 1; $depth = 1;
@ -396,7 +413,7 @@ class TemplateHandler {
} }
if(strpos($node, '|cond="') !== false) { if(strpos($node, '|cond="') !== false) {
$node = preg_replace('@(\s[\w:\-]+="[^"]+?")\|cond="(.+?)"@s', '<?php if($2){ ?>$1<?php } ?>', $node); $node = preg_replace('@(\s[-\w:]+="[^"]+?")\|cond="(.+?)"@s', '<?php if($2){ ?>$1<?php } ?>', $node);
$node = $this->_replaceVar($node); $node = $this->_replaceVar($node);
} }
@ -408,6 +425,12 @@ class TemplateHandler {
return $buff; return $buff;
} }
/**
* preg_replace_callback hanlder
* replace php code.
* @param array $m
* @return string changed result
**/
function _parseResource($m) function _parseResource($m)
{ {
// {@ ... } or {$var} or {func(...)} // {@ ... } or {$var} or {func(...)}
@ -545,6 +568,11 @@ class TemplateHandler {
return $m[0]; return $m[0];
} }
/**
* change relative path
* @param string $path
* @return string
**/
function _getRelativeDir($path) function _getRelativeDir($path)
{ {
$_path = $path; $_path = $path;
@ -573,7 +601,9 @@ class TemplateHandler {
} }
/** /**
* @brief replace PHP variables of $ character * replace PHP variables of $ character
* @param string $php
* @return string $__Context->varname
**/ **/
function _replaceVar($php) { function _replaceVar($php) {
if(!strlen($php)) return ''; if(!strlen($php)) return '';

View file

@ -2,25 +2,66 @@
/** /**
* Validator class * Validator class
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @package /classes/validator
* @version 0.1
*/ */
class Validator class Validator
{ {
/**
* cache directory
* @var string
*/
var $_cache_dir = ''; var $_cache_dir = '';
/**
* last error
* @var array
*/
var $_last_error; var $_last_error;
/**
* xml ruleset object
* @var Xml_Node_ object
*/
var $_xml_ruleset = null; var $_xml_ruleset = null;
/**
* rule list
* @var array
*/
var $_rules; var $_rules;
/**
* filter list
* @var array
*/
var $_filters; var $_filters;
/**
* Can usable status for multibyte string function
* @var boolean
*/
var $_has_mb_func; var $_has_mb_func;
/**
* validator version
* @var string
*/
var $_version = '1.0'; var $_version = '1.0';
/**
* ruleset xml file path
* @var string
*/
var $_xml_path = ''; var $_xml_path = '';
/** /**
* @constructor * @constructor
* @param string $xml_path
* @return void
*/ */
function Validator($xml_path='') { function Validator($xml_path='') {
$this->__construct($xml_path); $this->__construct($xml_path);
} }
/**
* @constructor
* @param string $xml_path
* @return void
*/
function __construct($xml_path='') { function __construct($xml_path='') {
$this->_rules = array(); $this->_rules = array();
$this->_filters = array(); $this->_filters = array();
@ -42,6 +83,10 @@ class Validator
$this->setCacheDir('./files/cache'); $this->setCacheDir('./files/cache');
} }
/**
* @destructor
* @return void
*/
function __destruct() { function __destruct() {
$this->_rules = null; $this->_rules = null;
$this->_filters = null; $this->_filters = null;
@ -49,7 +94,8 @@ class Validator
/** /**
* Load a xml file * Load a xml file
* @param[in] string $xml_path A file name to be loaded * @param string $xml_path A file name to be loaded
* @return boolean
*/ */
function load($xml_path) { function load($xml_path) {
$this->_xml_ruleset = null; $this->_xml_ruleset = null;
@ -116,7 +162,8 @@ class Validator
/** /**
* Set root cache directory * Set root cache directory
* @param[in] string $cache_dir Root cache directory * @param string $cache_dir Root cache directory
* @return void
*/ */
function setCacheDir($cache_dir){ function setCacheDir($cache_dir){
if(is_dir($cache_dir)) { if(is_dir($cache_dir)) {
@ -126,8 +173,8 @@ class Validator
/** /**
* Validate the fields. If the fields aren't passed, validation will be execute on the Context variables. * Validate the fields. If the fields aren't passed, validation will be execute on the Context variables.
* @param[in] (optional) array $fields Target fields. The keys of the array represents field's name, its values represents field's value. * @param array $fields Target fields. The keys of the array represents field's name, its values represents field's value.
* @return bool True if it is valid, FALSE otherwise. * @return boolean TRUE if it is valid, FALSE otherwise.
*/ */
function validate($fields_=null) { function validate($fields_=null) {
if(is_array($fields_)) { if(is_array($fields_)) {
@ -245,6 +292,8 @@ class Validator
/** /**
* apply trim recursive * apply trim recursive
* @param string|array $array
* @return string|array
*/ */
function arrayTrim($array) function arrayTrim($array)
{ {
@ -260,8 +309,8 @@ class Validator
/** /**
* Log an error * Log an error
* @param[in] $msg error message * @param $msg error message
* @return always false * @return boolean always false
*/ */
function error($field, $msg){ function error($field, $msg){
$lang_filter = Context::getLang('filter'); $lang_filter = Context::getLang('filter');
@ -283,8 +332,9 @@ class Validator
/** /**
* Add a new rule * Add a new rule
* @param[in] string $name rule name * @param string $name rule name
* @param[in] mixed $rule * @param mixed $rule
* @return void
*/ */
function addRule($name, $rule=''){ function addRule($name, $rule=''){
if(is_array($name)) $args = $name; if(is_array($name)) $args = $name;
@ -305,12 +355,19 @@ class Validator
/** /**
* Remove a rule * Remove a rule
* @param[in] string $name rule name * @param string $name rule name
* @return void
*/ */
function removeRule($name){ function removeRule($name){
unset($this->_rules[$name]); unset($this->_rules[$name]);
} }
/**
* add filter to filter list
* @param string $name rule name
* @param string $filter filter
* @return void
*/
function addFilter($name, $filter='') { function addFilter($name, $filter='') {
if(is_array($name)) $args = $name; if(is_array($name)) $args = $name;
else $args = array($name=>$filter); else $args = array($name=>$filter);
@ -331,15 +388,20 @@ class Validator
} }
} }
/**
* remove filter from filter list
* @param string $name rule name
* @return void
*/
function removeFilter($name) { function removeFilter($name) {
unset($this->_filters[$name]); unset($this->_filters[$name]);
} }
/** /**
* Find whether the field is valid with the rule * Find whether the field is valid with the rule
* @param[in] string $name rule name * @param string $name rule name
* @param[in] string $value a value to be validated * @param string $value a value to be validated
* @return bool TRUE if the field is valid, FALSE otherwise. * @return boolean TRUE if the field is valid, FALSE otherwise.
*/ */
function applyRule($name, $value){ function applyRule($name, $value){
$rule = $this->_rules[$name]; $rule = $this->_rules[$name];
@ -356,7 +418,7 @@ class Validator
return in_array($value, $rule['test']); return in_array($value, $rule['test']);
case 'expr': case 'expr':
if(!$rule['func_test']) { if(!$rule['func_test']) {
$rule['func_test'] = create_function('$a', 'return ('.preg_replace('/\$\$/', '$a', $rule['test']).');'); $rule['func_test'] = create_function('$a', 'return ('.preg_replace('/\$\$/', '$a', html_entity_decode($rule['test'])).');');
} }
return $rule['func_test']($value); return $rule['func_test']($value);
} }
@ -365,7 +427,9 @@ class Validator
} }
/** /**
* Return * if not supported 'mb_strlen' function, this method can use.
* @param string $str
* @return int
*/ */
function mbStrLen($str){ function mbStrLen($str){
$arr = count_chars($str); $arr = count_chars($str);
@ -411,7 +475,7 @@ class Validator
/** /**
* Compile a ruleset to a javascript file * Compile a ruleset to a javascript file
* @private * @return string
*/ */
function _compile2js() { function _compile2js() {
global $lang; global $lang;

View file

@ -1,18 +1,23 @@
<?php <?php
/** /**
* @class GeneralXmlParser * GeneralXmlParser class
* @author NHN (developers@xpressengine.com) * Generic XML parser for XE
* @brief Generic XML parser for XE * @author NHN (developers@xpressengine.com)
* @version 0.1 * @package /classes/xml
*/ * @version 0.1
class GeneralXmlParser { */
class GeneralXmlParser {
/**
* result of parse
* @var array
*/
var $output = array(); var $output = array();
/** /**
* @brief parse a given input to product a object containing parse values. * Parse a given input to product a object containing parse values.
* @param[in] $input data to be parsed * @param string $input data to be parsed
* @return Returns an object containing parsed values or NULL in case of failure * @return array|NULL Returns an object containing parsed values or NULL in case of failure
*/ */
function parse($input = '') { function parse($input = '') {
$oParser = xml_parser_create('UTF-8'); $oParser = xml_parser_create('UTF-8');
xml_set_object($oParser, $this); xml_set_object($oParser, $this);
@ -28,12 +33,13 @@
return $this->output; return $this->output;
} }
/** /**
* @brief start element handler * Start element handler
* @param[in] $parse an instance of parser * @param resource $parser an instance of parser
* @param[in] $node_name a name of node * @param string $node_name a name of node
* @param[in] $attrs attributes to be set * @param array $attrs attributes to be set
*/ * @return void
*/
function _tagOpen($parser, $node_name, $attrs) { function _tagOpen($parser, $node_name, $attrs) {
$obj->node_name = strtolower($node_name); $obj->node_name = strtolower($node_name);
$obj->attrs = $attrs; $obj->attrs = $attrs;
@ -42,23 +48,25 @@
array_push($this->output, $obj); array_push($this->output, $obj);
} }
/** /**
* @brief character data handler * Character data handler
* variable in the last element of this->output * Variable in the last element of this->output
* @param[in] $parse an instance of parser * @param resource $parse an instance of parser
* @param[in] $body a data to be added * @param string $body a data to be added
*/ * @return void
*/
function _tagBody($parser, $body) { function _tagBody($parser, $body) {
//if(!trim($body)) return; //if(!trim($body)) return;
$this->output[count($this->output)-1]->body .= $body; $this->output[count($this->output)-1]->body .= $body;
} }
/** /**
* @brief end element handler * End element handler
* @param[in] $parse an instance of parser * @param resource $parse an instance of parser
* @param[in] $node_name name of xml node * @param string $node_name name of xml node
*/ * @return void
*/
function _tagClosed($parser, $node_name) { function _tagClosed($parser, $node_name) {
$node_name = strtolower($node_name); $node_name = strtolower($node_name);
$cur_obj = array_pop($this->output); $cur_obj = array_pop($this->output);
@ -79,5 +87,5 @@
} }
} }
} }
?> ?>

View file

@ -1,7 +1,16 @@
<?php <?php
/**
* XmlGenerator class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml
* @version 0.1
*/
class XmlGenerator{ class XmlGenerator{
/**
* object change to xml
* @param object $xml
* @return string
*/
function obj2xml($xml){ function obj2xml($xml){
$buff = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; $buff = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
@ -11,6 +20,11 @@ class XmlGenerator{
return $buff; return $buff;
} }
/**
* object change to xml
* @param object $node node in xml object
* @return string
*/
function _makexml($node){ function _makexml($node){
$body = ''; $body = '';
foreach($node as $key => $value){ foreach($node as $key => $value){

View file

@ -1,13 +1,10 @@
<?php <?php
/** /**
* @class XmlJsFilter * filter class traslate xml content into javascript code
* @author NHN (developers@xpressengine.com)
* @brief filter class traslate xml content into javascript code
* @version 0.2
* *
* it convert xml code into js file and save the result as a cache file * it convert xml code into js file and save the result as a cache file
* @code * @code
* { * <pre>{
* <filter name="name of javascript funcion" act="action name" confirm_msg_code="message string to be prompted when submitting the form" > * <filter name="name of javascript funcion" act="action name" confirm_msg_code="message string to be prompted when submitting the form" >
* <form> <-- code to validate data in the form * <form> <-- code to validate data in the form
* <node target="name" required="true" minlength="1" maxlength="5" filter="email,userid,alpha,number" equalto="target" /> * <node target="name" required="true" minlength="1" maxlength="5" filter="email,userid,alpha,number" equalto="target" />
@ -19,9 +16,10 @@
* <tag name="error" /> <- get the result of error name * <tag name="error" /> <- get the result of error name
* </response> * </response>
* </filter> * </filter>
* } * }</pre>
* *
* @detail { * @detail
* <pre>{
* - syntax description of <form> node * - syntax description of <form> node
* target = name of for element * target = name of for element
* required = flag indicating whether a field is mandatory or not * required = flag indicating whether a field is mandatory or not
@ -40,18 +38,40 @@
* *
* - response * - response
* tag = key : name of variable that will contain the result of the execution * tag = key : name of variable that will contain the result of the execution
* } * }</pre>
**/ * @class XmlJsFilter
* @author NHN (developers@xpressengine.com)
* @package /classes/xml
* @version 0.2
*/
class XmlJsFilter extends XmlParser { class XmlJsFilter extends XmlParser {
/**
* version
* @var string
*/
var $version = '0.2.5'; var $version = '0.2.5';
/**
* compiled javascript cache path
* @var string
*/
var $compiled_path = './files/cache/js_filter_compiled/'; // / directory path for compiled cache file var $compiled_path = './files/cache/js_filter_compiled/'; // / directory path for compiled cache file
var $xml_file = NULL; // / Target xml file /**
var $js_file = NULL; // / Compiled js file * Target xml file
* @var string
*/
var $xml_file = NULL;
/**
* Compiled js file
* @var string
*/
var $js_file = NULL; // /
/** /**
* @brief constructor * constructor
**/ * @param string $path
* @param string $xml_file
* @return void
*/
function XmlJsFilter($path, $xml_file) { function XmlJsFilter($path, $xml_file) {
if(substr($path,-1)!=='/') $path .= '/'; if(substr($path,-1)!=='/') $path .= '/';
$this->xml_file = sprintf("%s%s",$path, $xml_file); $this->xml_file = sprintf("%s%s",$path, $xml_file);
@ -59,9 +79,9 @@
} }
/** /**
* @brief compile a xml_file only when a corresponding js file does not exists or is outdated * Compile a xml_file only when a corresponding js file does not exists or is outdated
* @return Returns NULL regardless of the success of failure of the operation * @return void Returns NULL regardless of the success of failure of the operation
**/ */
function compile() { function compile() {
if(!file_exists($this->xml_file)) return; if(!file_exists($this->xml_file)) return;
if(!file_exists($this->js_file)) $this->_compile(); if(!file_exists($this->js_file)) $this->_compile();
@ -70,8 +90,9 @@
} }
/** /**
* @brief compile a xml_file into js_file * compile a xml_file into js_file
**/ * @return void
*/
function _compile() { function _compile() {
global $lang; global $lang;
@ -283,7 +304,9 @@
} }
/** /**
* @brief return a file name of js file corresponding to the xml file * return a file name of js file corresponding to the xml file
* @param string $xml_file
* @return string
**/ **/
function _getCompiledFileName($xml_file) { function _getCompiledFileName($xml_file) {
return sprintf('%s%s.%s.compiled.js',$this->compiled_path, md5($this->version.$xml_file),Context::getLangType()); return sprintf('%s%s.%s.compiled.js',$this->compiled_path, md5($this->version.$xml_file),Context::getLangType());

View file

@ -1,22 +1,50 @@
<?php <?php
/** /**
* @class XmlLangParser * XmlLangParser class
* Change to lang php file from xml.
* @author NHN (developers@xpressengine.com) * @author NHN (developers@xpressengine.com)
* @brief change to lang php file from xml. * @package /classes/xml
* @version 0.1 * @version 0.1
**/ **/
class XmlLangParser extends XmlParser { class XmlLangParser extends XmlParser {
/**
* compiled language cache path
* @var string
*/
var $compiled_path = './files/cache/lang/'; // / directory path for compiled cache file var $compiled_path = './files/cache/lang/'; // / directory path for compiled cache file
var $xml_file = NULL; // / Target xml file /**
var $php_file = NULL; // / Target php file * Target xml file
* @var string
*/
var $xml_file = NULL;
/**
* Target php file
* @var string
*/
var $php_file = NULL;
/**
* result source code
* @var string
*/
var $code; var $code;
/**
* language list, for example ko, en...
* @var array
*/
var $lang_types; var $lang_types;
/**
* language type
* @see _XE_PATH_.'/common/lang/lang.info'
* @var string
*/
var $lang_type; var $lang_type;
/** /**
* @brief constructor * constructor
**/ * @param string $xml_file
* @param string $lang_type
* @return void
*/
function XmlLangParser($xml_file, $lang_type) { function XmlLangParser($xml_file, $lang_type) {
$this->lang_type = $lang_type; $this->lang_type = $lang_type;
$this->xml_file = $xml_file; $this->xml_file = $xml_file;
@ -24,9 +52,9 @@
} }
/** /**
* @brief compile a xml_file only when a corresponding php lang file does not exists or is outdated * compile a xml_file only when a corresponding php lang file does not exists or is outdated
* @return Returns compiled php file. * @return string|bool Returns compiled php file.
**/ */
function compile() { function compile() {
if(!file_exists($this->xml_file)) return false; if(!file_exists($this->xml_file)) return false;
if(!file_exists($this->php_file)){ if(!file_exists($this->php_file)){
@ -36,9 +64,13 @@
else return $this->php_file; else return $this->php_file;
} }
return $this->_writefile() ? $this->php_file : false; return $this->_writeFile() ? $this->php_file : false;
} }
/**
* Return compiled content
* @return string Returns compiled lang source code
*/
function getCompileContent() { function getCompileContent() {
if(!file_exists($this->xml_file)) return false; if(!file_exists($this->xml_file)) return false;
$this->_compile(); $this->_compile();
@ -47,8 +79,9 @@
} }
/** /**
* @brief compile a xml_file * Compile a xml_file
**/ * @return void
*/
function _compile() { function _compile() {
$lang_selected = Context::loadLangSelected(); $lang_selected = Context::loadLangSelected();
$this->lang_types = array_keys($lang_selected); $this->lang_types = array_keys($lang_selected);
@ -68,8 +101,9 @@
} }
/** /**
* @brief writing cache file * Writing cache file
**/ * @return void|bool
*/
function _writeFile(){ function _writeFile(){
if(!$this->code) return; if(!$this->code) return;
FileHandler::writeFile($this->php_file, "<?php\n".$this->code); FileHandler::writeFile($this->php_file, "<?php\n".$this->code);
@ -77,8 +111,11 @@
} }
/** /**
* @brief Parsing item node * Parsing item node, set content to '$this->code'
**/ * @param object $item
* @param string $var
* @return void
*/
function _parseItem($item, $var){ function _parseItem($item, $var){
$name = $item->attrs->name; $name = $item->attrs->name;
$value = $item->value; $value = $item->value;
@ -108,8 +145,11 @@
} }
/** /**
* @brief Parsing value nodes * Parsing value nodes
**/ * @param array $nodes
* @param string $var
* @return array|string
*/
function _parseValues($nodes, $var) { function _parseValues($nodes, $var) {
if(!is_array($nodes)) $nodes = array($nodes); if(!is_array($nodes)) $nodes = array($nodes);
@ -132,8 +172,11 @@
} }
/** /**
* @brief Parsing value node * Parsing value node
**/ * @param object $node
* @param string $var
* @return array|bool
*/
function _parseValue($node, $var) { function _parseValue($node, $var) {
$lang_type = $node->attrs->xml_lang; $lang_type = $node->attrs->xml_lang;
$value = $node->body; $value = $node->body;
@ -144,8 +187,11 @@
} }
/** /**
* @brief get cache file name * Get cache file name
**/ * @param string $lang_type
* @param string $type
* @return string
*/
function _getCompiledFileName($lang_type, $type='php') { function _getCompiledFileName($lang_type, $type='php') {
return sprintf('%s%s.%s.php',$this->compiled_path, md5($this->xml_file), $lang_type); return sprintf('%s%s.%s.php',$this->compiled_path, md5($this->xml_file), $lang_type);
} }

View file

@ -1,6 +1,11 @@
<?php <?php
/**
/* Element node or attribute node. */ * Xml_Node_ class
* Element node or attribute node.
* @author NHN (developers@xpressengine.com)
* @package /classes/xml
* @version 0.1
*/
class Xml_Node_ class Xml_Node_
{ {
/** In PHP5 this will silence E_STRICT warnings /** In PHP5 this will silence E_STRICT warnings
@ -13,33 +18,46 @@
} }
} }
/** /**
* @class XmlParser * XmlParser class
* @author NHN (developers@xpressengine.com) * Class parsing a given xmlrpc request and creating a data object
* @brief class parsing a given xmlrpc request and creating a data object * @remarks <pre>{
* @version 0.1 * This class may drops unsupported xml lanuage attributes when multiple language attributes are given.
* * For example, if 'xml:lang='ko, en, ch, jp..' is given in a xml file, only ko will be left ignoring all other language
* @remarks { * attributes when kor is only supported language. It seems to work fine now but we did not scrutinze any potential side effects,
* This class may drops unsupported xml lanuage attributes when multiple language attributes are given. * }</pre>
* For example, if 'xml:lang='ko, en, ch, jp..' is given in a xml file, only ko will be left ignoring all other language *
* attributes when kor is only supported language. It seems to work fine now but we did not scrutinze any potential side effects, * @author NHN (developers@xpressengine.com)
* } * @package /classes/xml
**/ * @version 0.1
*/
class XmlParser { class XmlParser {
/**
* Xml parser
* @var resource
*/
var $oParser = NULL;
/**
* Input xml
* @var string
*/
var $input = NULL;
/**
* Output object in array
* @var array
*/
var $output = array();
/**
* The default language type
* @var string
*/
var $lang = "en";
var $oParser = NULL; ///< xml parser /**
* Load a xml file specified by a filename and parse it to Return the resultant data object
var $input = NULL; ///< input xml * @param string $filename a file path of file
var $output = array(); ///< output object * @return array Returns a data object containing data extracted from a xml file or NULL if a specified file does not exist
*/
var $lang = "en"; // /< The default language type
/**
* @brief load a xml file specified by a filename and parse it to Return the resultant data object
* @param[in] $filename a file path of file
* @return Returns a data object containing data extracted from a xml file or NULL if a specified file does not exist
**/
function loadXmlFile($filename) { function loadXmlFile($filename) {
if(!file_exists($filename)) return; if(!file_exists($filename)) return;
$buff = FileHandler::readFile($filename); $buff = FileHandler::readFile($filename);
@ -48,11 +66,13 @@
return $oXmlParser->parse($buff); return $oXmlParser->parse($buff);
} }
/** /**
* @brief parse xml data to extract values from it and construct data object * Parse xml data to extract values from it and construct data object
* @param[in] a data buffer containing xml data * @param string $input a data buffer containing xml data
* @return Returns a resultant data object or NULL in case of error * @param mixed $arg1 ???
**/ * @param mixed $arg2 ???
* @return array Returns a resultant data object or NULL in case of error
*/
function parse($input = '', $arg1 = NULL, $arg2 = NULL) { function parse($input = '', $arg1 = NULL, $arg2 = NULL) {
// Save the compile starting time for debugging // Save the compile starting time for debugging
if(__DEBUG__==3) $start = getMicroTime(); if(__DEBUG__==3) $start = getMicroTime();
@ -67,9 +87,10 @@
// extracts the supported lanuage when xml:lang is used // extracts the supported lanuage when xml:lang is used
if(count($matches[1]) && $supported_lang = array_unique($matches[1])) { if(count($matches[1]) && $supported_lang = array_unique($matches[1])) {
$tmpLangList = array_flip($supported_lang);
// if lang of the first log-in user doesn't exist, apply en by default if exists. Otherwise apply the first lang. // if lang of the first log-in user doesn't exist, apply en by default if exists. Otherwise apply the first lang.
if(!in_array($this->lang, $supported_lang)) { if(!isset($tmpLangList[$this->lang])) {
if(in_array('en', $supported_lang)) { if(isset($tmpLangList['en'])) {
$this->lang = 'en'; $this->lang = 'en';
} else { } else {
$this->lang = array_shift($supported_lang); $this->lang = array_shift($supported_lang);
@ -99,12 +120,13 @@
} }
/** /**
* @brief start element handler. * Start element handler.
* @param[in] $parse an instance of parser * @param resource $parse an instance of parser
* @param[in] $node_name a name of node * @param string $node_name a name of node
* @param[in] $attrs attributes to be set * @param array $attrs attributes to be set
*/ * @return array
*/
function _tagOpen($parser, $node_name, $attrs) { function _tagOpen($parser, $node_name, $attrs) {
$obj = new Xml_Node_(); $obj = new Xml_Node_();
$obj->node_name = strtolower($node_name); $obj->node_name = strtolower($node_name);
@ -114,23 +136,24 @@
} }
/** /**
* @brief character data handler * Character data handler
* variable in the last element of this->output * Variable in the last element of this->output
* @param[in] $parse an instance of parser * @param resource $parse an instance of parser
* @param[in] $body a data to be added * @param string $body a data to be added
* @remark the first parameter, $parser ought to be remove since it is not used. * @return void
*/ */
function _tagBody($parser, $body) { function _tagBody($parser, $body) {
//if(!trim($body)) return; //if(!trim($body)) return;
$this->output[count($this->output)-1]->body .= $body; $this->output[count($this->output)-1]->body .= $body;
} }
/** /**
* @brief end element handler * End element handler
* @param[in] $parse an instance of parser * @param resource $parse an instance of parser
* @param[in] $node_name name of xml node * @param string $node_name name of xml node
*/ * @return void
*/
function _tagClosed($parser, $node_name) { function _tagClosed($parser, $node_name) {
$node_name = strtolower($node_name); $node_name = strtolower($node_name);
$cur_obj = array_pop($this->output); $cur_obj = array_pop($this->output);
@ -155,10 +178,11 @@
} }
} }
/** /**
* @brief method to transfer values in an array to a data object * Method to transfer values in an array to a data object
* @param[in] $arr data array * @param array $arr data array
**/ * @return Xml_Node_ object
**/
function _arrToAttrsObj($arr) { function _arrToAttrsObj($arr) {
$output = new Xml_Node_(); $output = new Xml_Node_();
foreach($arr as $key => $val) { foreach($arr as $key => $val) {

View file

@ -1,14 +1,4 @@
<?php <?php
/**
* @class NewXmlQueryParser
* @author NHN (developers@xpressengine.com)
* @brief case to parse XE xml query
* @version 0.1
*
* @todo need to support extend query such as subquery, union
* @todo include info about column types for parsing user input
**/
if(!defined('__XE_LOADED_XML_CLASS__')){ if(!defined('__XE_LOADED_XML_CLASS__')){
define('__XE_LOADED_XML_CLASS__', 1); define('__XE_LOADED_XML_CLASS__', 1);
@ -21,6 +11,7 @@
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/ColumnTag.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnTag.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnTag.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnTagWithoutArgument.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/UpdateColumnTag.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/SelectColumnsTag.class.php');
require(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/tags/column/InsertColumnsTag.class.php');
@ -43,12 +34,27 @@
require(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php'); require(_XE_PATH_.'classes/xml/xmlquery/queryargument/DefaultValue.class.php');
} }
/**
* New XmlQueryParser class
* @author NHN (developers@xpressengine.com)
* @brief case to parse XE xml query
* @version 0.1
*
* @todo need to support extend query such as subquery, union
* @todo include info about column types for parsing user input
*/
class XmlQueryParser extends XmlParser { class XmlQueryParser extends XmlParser {
/**
* constructor
* @return void
*/
function XmlQueryParser(){ function XmlQueryParser(){
} }
/**
* Create XmlQueryParser instance for Singleton
* @return XmlQueryParser object
*/
function &getInstance(){ function &getInstance(){
static $theInstance = null; static $theInstance = null;
if(!isset($theInstance)){ if(!isset($theInstance)){
@ -57,6 +63,12 @@
return $theInstance; return $theInstance;
} }
/**
* 1. Read xml file<br />
* 2. Check the action<br />
* 3. Parsing and write a cache file<br />
* @return QueryParser object
*/
function &parse_xml_query($query_id, $xml_file, $cache_file) function &parse_xml_query($query_id, $xml_file, $cache_file)
{ {
// Read xml file // Read xml file
@ -73,11 +85,19 @@
return $parser; return $parser;
} }
/**
* Query XML file parsing
* @return QueryParser object
*/
function parse($query_id = NULL, $xml_file = NULL, $cache_file = NULL) function parse($query_id = NULL, $xml_file = NULL, $cache_file = NULL)
{ {
$query_parser = &$this->parse_xml_query($query_id, $xml_file, $cache_file); $this->parse_xml_query($query_id, $xml_file, $cache_file);
} }
/**
* Return XML file content
* @return array|NULL Returns a resultant data object or NULL in case of error
*/
function getXmlFileContent($xml_file){ function getXmlFileContent($xml_file){
$buff = FileHandler::readFile($xml_file); $buff = FileHandler::readFile($xml_file);
$xml_obj = parent::parse($buff); $xml_obj = parent::parse($buff);

View file

@ -1,13 +1,12 @@
<?php <?php
/** /**
* @class XmlQueryParser * XmlQueryParser
* @author NHN (developers@xpressengine.com) * Case to parse XE xml query
* @brief case to parse XE xml query
* @version 0.1
* *
* @author NHN (developers@xpressengine.com)
* @version 0.1
* @todo need to support extend query such as subquery, union * @todo need to support extend query such as subquery, union
**/ */
class XmlQueryParser extends XmlParser { class XmlQueryParser extends XmlParser {
var $default_list = array(); var $default_list = array();
@ -15,13 +14,13 @@
var $filter_list = array(); var $filter_list = array();
/** /**
* @brief parse a xml query file and save the result as a new file specified by cache_file * Parse a xml query file and save the result as a new file specified by cache_file
* @param[in] $query_id name of query * {there should be a way to report an error}
* @param[in] $xml_file file path of a xml query file to be loaded * @param string $query_id name of query
* @param[in] $cache_file file path of a cache file to store resultant php code after parsing xml query * @param string $xml_file file path of a xml query file to be loaded
* @return Nothing is requred. * @param string $cache_file file path of a cache file to store resultant php code after parsing xml query
* @remarks {there should be a way to report an error} * @return void Nothing is requred.
**/ */
function parse($query_id, $xml_file, $cache_file) { function parse($query_id, $xml_file, $cache_file) {
// query xml 파일을 찾아서 파싱, 결과가 없으면 return // query xml 파일을 찾아서 파싱, 결과가 없으면 return
$buff = FileHandler::readFile($xml_file); $buff = FileHandler::readFile($xml_file);
@ -36,7 +35,8 @@
$id = $id_args[1]; $id = $id_args[1];
} elseif(count($id_args)==3) { } elseif(count($id_args)==3) {
$target = $id_args[0]; $target = $id_args[0];
if(!in_array($target, array('modules','addons','widgets'))) return; $typeList = array('modules'=>1, 'addons'=>1, 'widgets'=>1);
if(!isset($typeList[$target])) return;
$module = $id_args[1]; $module = $id_args[1];
$id = $id_args[2]; $id = $id_args[2];
} }
@ -53,6 +53,7 @@
if(!$tables) return; if(!$tables) return;
if(!is_array($tables)) $tables = array($tables); if(!is_array($tables)) $tables = array($tables);
$joinList = array('left join'=>1, 'left outer join'=>1, 'right join'=>1, 'right outer join'=>1);
foreach($tables as $key => $val) { foreach($tables as $key => $val) {
// 테이블과 alias의 이름을 구함 // 테이블과 alias의 이름을 구함
@ -62,7 +63,7 @@
$output->tables[$alias] = $table_name; $output->tables[$alias] = $table_name;
if(in_array($val->attrs->type,array('left join','left outer join','right join','right outer join')) && count($val->conditions)){ if(isset($joinList[$val->attrs->type]) && count($val->conditions)){
$output->left_tables[$alias] = $val->attrs->type; $output->left_tables[$alias] = $val->attrs->type;
$left_conditions[$alias] = $val->conditions; $left_conditions[$alias] = $val->conditions;
} }
@ -260,11 +261,10 @@
} }
/** /**
* @brief transfer given column information to object->columns * Transfer given column information to object->columns
* @param[in] column information * @param array $columns column information
* @result Returns $object * @return object
*/ */
function _setColumn($columns){ function _setColumn($columns){
if(!$columns) { if(!$columns) {
$output->column[] = array("*" => "*"); $output->column[] = array("*" => "*");
@ -296,9 +296,9 @@
} }
/** /**
* @brief transfer condition information to $object->conditions * Transfer condition information to $object->conditions
* @param[in] SQL condition information * @param object @condition SQL condition information
* @result Returns $output * @retrun object
*/ */
function _setConditions($conditions){ function _setConditions($conditions){
// 조건절 정리 // 조건절 정리
@ -339,9 +339,9 @@
} }
/** /**
* @brief transfer condition information to $object->groups * Transfer condition information to $object->groups
* @param[in] SQL group information * @param array $group_list SQL group information
* @result Returns $output * @return object
*/ */
function _setGroup($group_list){ function _setGroup($group_list){
// group 정리 // group 정리
@ -361,9 +361,9 @@
/** /**
* @brief transfer pagnation information to $output * Transfer pagnation information to $output
* @param[in] $xml_obj xml object containing Navigation information * @param object $xml_obj xml object containing Navigation information
* @result Returns $output * @return object
*/ */
function _setNavigation($xml_obj){ function _setNavigation($xml_obj){
$navigation = $xml_obj->query->navigation; $navigation = $xml_obj->query->navigation;
@ -389,10 +389,10 @@
} }
/** /**
* @brief retrieve column information from $output->colums to generate corresponding php code * Retrieve column information from $output->colums to generate corresponding php code <br />
* @param[in] $column * The name of this method is misleading.
* @remarks the name of this method is misleading. * @param array $columns
* @result Returns string buffer containing php code * @return string buffer containing php code
*/ */
function _getColumn($columns){ function _getColumn($columns){
$buff = ''; $buff = '';
@ -439,10 +439,10 @@
} }
/** /**
* @brief retrieve condition information from $output->condition to generate corresponding php code * Retrieve condition information from $output->condition to generate corresponding php code
* @param[in] $conditions array containing Query conditions * The name of this method is misleading.
* @remarks the name of this method is misleading. * @param array $conditions array containing Query conditions
* @return Returns string buffer containing php code * @return string buffer containing php code
*/ */
function _getConditions($conditions){ function _getConditions($conditions){
$buff = ''; $buff = '';
@ -472,21 +472,30 @@
return $buff; return $buff;
} }
/**
* Add argument to $this->args
* @param mixed $args_name argument value
* @return void
*/
function addArguments($args_name) function addArguments($args_name)
{ {
$this->args[] = $args_name; $this->args[] = $args_name;
} }
/**
* Get argument from $this->args
* @return mixed
*/
function getArguments() function getArguments()
{ {
return $this->args; return $this->args;
} }
/** /**
* @brief returns predefined default values correspoding to given parameters * Returns predefined default values correspoding to given parameters
* @param[in] $name * @param string $name
* @param[in] $value * @param mixed $value
* @return Returns a default value for specified field * @return mixed Returns a default value for specified field
*/ */
function getDefault($name, $value) { function getDefault($name, $value) {
$db_info = Context::getDBInfo (); $db_info = Context::getDBInfo ();

View file

@ -1,9 +1,34 @@
<?php <?php
/**
* DBParser class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery
* @version 0.1
*/
class DBParser { class DBParser {
/**
* Character for escape target value on the left
* @var string
*/
var $escape_char_left; var $escape_char_left;
/**
* Character for escape target value on the right
* @var string
*/
var $escape_char_right; var $escape_char_right;
/**
* Table prefix string
* @var string
*/
var $table_prefix; var $table_prefix;
/**
* constructor
* @param string $escape_char_left
* @param string $escape_char_right
* @param string $table_prefix
* @return void
*/
function DBParser($escape_char_left, $escape_char_right = "", $table_prefix = "xe_"){ function DBParser($escape_char_left, $escape_char_right = "", $table_prefix = "xe_"){
$this->escape_char_left = $escape_char_left; $this->escape_char_left = $escape_char_left;
if ($escape_char_right !== "")$this->escape_char_right = $escape_char_right; if ($escape_char_right !== "")$this->escape_char_right = $escape_char_right;
@ -11,33 +36,68 @@
$this->table_prefix = $table_prefix; $this->table_prefix = $table_prefix;
} }
/**
* Get escape character
* @param string $leftOrRight left or right
* @return string
*/
function getEscapeChar($leftOrRight){ function getEscapeChar($leftOrRight){
if ($leftOrRight === 'left')return $this->escape_char_left; if ($leftOrRight === 'left')return $this->escape_char_left;
else return $this->escape_char_right; else return $this->escape_char_right;
} }
/**
* escape the value
* @param mixed $name
* @return string
*/
function escape($name){ function escape($name){
return $this->escape_char_left . $name . $this->escape_char_right; return $this->escape_char_left . $name . $this->escape_char_right;
} }
/**
* escape the string value
* @param string $name
* @return string
*/
function escapeString($name){ function escapeString($name){
return "'".$this->escapeStringValue($name)."'"; return "'".$this->escapeStringValue($name)."'";
} }
/**
* escape the string value
* @param string $value
* @return string
*/
function escapeStringValue($value){ function escapeStringValue($value){
if($value == "*") return $value; if($value == "*") return $value;
if (is_string($value)) return $value = str_replace("'","''",$value); if (is_string($value)) return $value = str_replace("'","''",$value);
return $value; return $value;
} }
/**
* Return table full name
* @param string $name table name without table prefix
* @return string table full name with table prefix
*/
function parseTableName($name){ function parseTableName($name){
return $this->table_prefix . $name; return $this->table_prefix . $name;
} }
/**
* Return colmun name after escape
* @param string $name column name before escape
* @return string column name after escape
*/
function parseColumnName($name){ function parseColumnName($name){
return $this->escapeColumn($name); return $this->escapeColumn($name);
} }
/**
* Escape column
* @param string $column_name
* @return string column name with db name
*/
function escapeColumn($column_name){ function escapeColumn($column_name){
if($this->isUnqualifiedColumnName($column_name)) if($this->isUnqualifiedColumnName($column_name))
return $this->escape($column_name); return $this->escape($column_name);
@ -49,11 +109,21 @@
} }
} }
/**
* Column name is suitable for use in checking
* @param string $column_name
* @return bool
*/
function isUnqualifiedColumnName($column_name){ function isUnqualifiedColumnName($column_name){
if(strpos($column_name,'.')===false && strpos($column_name,'(')===false) return true; if(strpos($column_name,'.')===false && strpos($column_name,'(')===false) return true;
return false; return false;
} }
/**
* Column name is suitable for use in checking
* @param string $column_name
* @return bool
*/
function isQualifiedColumnName($column_name){ function isQualifiedColumnName($column_name){
if(strpos($column_name,'.')!==false && strpos($column_name,'(')===false) return true; if(strpos($column_name,'.')!==false && strpos($column_name,'(')===false) return true;
return false; return false;
@ -84,6 +154,11 @@
return implode('', $functions); return implode('', $functions);
} }
/*
* Checks argument is asterisk
* @param string $column_name
* @return bool
*/
function isStar($column_name){ function isStar($column_name){
if(substr($column_name,-1) == '*') return true; if(substr($column_name,-1) == '*') return true;
return false; return false;
@ -92,12 +167,19 @@
/* /*
* Checks to see if expression is an aggregate star function * Checks to see if expression is an aggregate star function
* like count(*) * like count(*)
* @param string $column_name
* @return bool
*/ */
function isStarFunction($column_name){ function isStarFunction($column_name){
if(strpos($column_name, "(*)")!==false) return true; if(strpos($column_name, "(*)")!==false) return true;
return false; return false;
} }
/*
* Return column name after escape
* @param string $column_name
* @return string
*/
function escapeColumnExpression($column_name){ function escapeColumnExpression($column_name){
if($this->isStar($column_name)) return $column_name; if($this->isStar($column_name)) return $column_name;
if($this->isStarFunction($column_name)){ if($this->isStarFunction($column_name)){
@ -108,4 +190,4 @@
} }
} }

View file

@ -1,14 +1,34 @@
<?php <?php
/**
* QueryParser class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery
* @version 0.1
*/
class QueryParser { class QueryParser {
/**
* QueryTag object
* @var QueryTag object
*/
var $queryTag; var $queryTag;
/**
* constructor
* @param object $query
* @param bool $isSubQuery
* @return void
*/
function QueryParser($query = NULL, $isSubQuery = false) { function QueryParser($query = NULL, $isSubQuery = false) {
if ($query) if ($query)
$this->queryTag = new QueryTag($query, $isSubQuery); $this->queryTag = new QueryTag($query, $isSubQuery);
} }
/**
* Return table information
* @param object $query_id
* @param bool $table_name
* @return array
*/
function getTableInfo($query_id, $table_name) { function getTableInfo($query_id, $table_name) {
$column_type = array(); $column_type = array();
$module = ''; $module = '';
@ -20,7 +40,8 @@
$id = $id_args[1]; $id = $id_args[1];
} elseif (count($id_args) == 3) { } elseif (count($id_args) == 3) {
$target = $id_args[0]; $target = $id_args[0];
if (!in_array($target, array('modules', 'addons', 'widgets'))) $targetList = array('modules'=>1, 'addons'=>1, 'widgets'=>1);
if (!isset($targetList[$target]))
return; return;
$module = $id_args[1]; $module = $id_args[1];
$id = $id_args[2]; $id = $id_args[2];
@ -56,6 +77,10 @@
return $column_type; return $column_type;
} }
/**
* Change code string from queryTag object
* @return string
*/
function toString() { function toString() {
return "<?php if(!defined('__ZBXE__')) exit();\n" return "<?php if(!defined('__ZBXE__')) exit();\n"
. $this->queryTag->toString() . $this->queryTag->toString()

View file

@ -1,17 +1,57 @@
<?php <?php
/**
* Argument class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/argument
* @version 0.1
*/
class Argument { class Argument {
/**
* argument value
* @var mixed
*/
var $value; var $value;
/**
* argument name
* @var string
*/
var $name; var $name;
/**
* argument type
* @var string
*/
var $type; var $type;
/**
* result of argument type check
* @var bool
*/
var $isValid; var $isValid;
/**
* error message
* @var Object
*/
var $errorMessage; var $errorMessage;
/**
* column operation
*/
var $column_operation; var $column_operation;
/**
var $uses_default_value; // Check if arg value is user submnitted or default * Check if arg value is user submnitted or default
var $_value; // Caches escaped and toString value so that the parsing won't happen multiple times; * @var mixed
*/
var $uses_default_value;
/**
* Caches escaped and toString value so that the parsing won't happen multiple times
* @var mixed
*/
var $_value; //
/**
* constructor
* @param string $name
* @param mixed $value
* @return void
*/
function Argument($name, $value) { function Argument($name, $value) {
$this->value = $value; $this->value = $value;
$this->name = $name; $this->name = $name;
@ -60,6 +100,11 @@ class Argument {
return $this->value; return $this->value;
} }
/**
* mixed value to string
* @param mixed $value
* @return string
*/
function toString($value) { function toString($value) {
if (is_array($value)) { if (is_array($value)) {
if (count($value) === 0) if (count($value) === 0)
@ -71,6 +116,11 @@ class Argument {
return $value; return $value;
} }
/**
* escape value
* @param mixed $value
* @return mixed
*/
function escapeValue($value) { function escapeValue($value) {
$column_type = $this->getType(); $column_type = $this->getType();
if ($column_type == 'column_name') { if ($column_type == 'column_name') {
@ -80,7 +130,8 @@ class Argument {
if (!isset($value)) if (!isset($value))
return null; return null;
if (in_array($column_type, array('date', 'varchar', 'char', 'text', 'bigtext'))) { $columnTypeList = array('date'=>1, 'varchar'=>1, 'char'=>1, 'text'=>1, 'bigtext'=>1);
if (isset($columnTypeList[$column_type])) {
if (!is_array($value)) if (!is_array($value))
$value = $this->_escapeStringValue($value); $value = $this->_escapeStringValue($value);
else { else {
@ -106,6 +157,11 @@ class Argument {
return $value; return $value;
} }
/**
* escape string value
* @param string $value
* @return string
*/
function _escapeStringValue($value) { function _escapeStringValue($value) {
$db = &DB::getInstance(); $db = &DB::getInstance();
$value = $db->addQuotes($value); $value = $db->addQuotes($value);
@ -135,6 +191,11 @@ class Argument {
} }
} }
/**
* check filter by filter type
* @param string $filter_type
* @return void
*/
function checkFilter($filter_type) { function checkFilter($filter_type) {
if (isset($this->value) && $this->value != '') { if (isset($this->value) && $this->value != '') {
global $lang; global $lang;

View file

@ -1,11 +1,28 @@
<?php <?php
/**
* ConditionArgument class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/argument
* @version 0.1
*/
class ConditionArgument extends Argument { class ConditionArgument extends Argument {
/**
* Operator keyword. for example 'in', 'notint', 'between'
* @var string
*/
var $operation; var $operation;
/**
* constructor
* @param string $name
* @param mixed $value
* @param string $operation
* @return void
*/
function ConditionArgument($name, $value, $operation){ function ConditionArgument($name, $value, $operation){
if(isset($value) && in_array($operation, array('in', 'notin', 'between')) && !is_array($value) && $value != ''){ $operationList = array('in'=>1, 'notin'=>1, 'not_in'=>1, 'between'=>1);
if(isset($value) && isset($operationList[$operation]) && !is_array($value) && $value != ''){
$value = str_replace(' ', '', $value); $value = str_replace(' ', '', $value);
$value = str_replace('\'', '', $value); $value = str_replace('\'', '', $value);
$value = explode(',', $value); $value = explode(',', $value);
@ -14,6 +31,10 @@
$this->operation = $operation; $this->operation = $operation;
} }
/**
* create condition value. set $this->value
* @return void
*/
function createConditionValue(){ function createConditionValue(){
if(!isset($this->value)) return; if(!isset($this->value)) return;
@ -57,22 +78,23 @@
if(!is_array($value)) $this->value = array($value); if(!is_array($value)) $this->value = array($value);
break; break;
case 'notin': case 'notin':
case 'not_in':
if(!is_array($value)) $this->value = array($value); if(!is_array($value)) $this->value = array($value);
break; break;
} }
} }
/** /**
* Since ConditionArgument is used in WHERE clause, * Since ConditionArgument is used in WHERE clause,
* where the argument value is compared to a table column, * where the argument value is compared to a table column,
* it is assumed that all arguments have type. There are cases though * it is assumed that all arguments have type. There are cases though
* where the column does not have any type - if it was removed from * where the column does not have any type - if it was removed from
* the XML schema for example - see the is_secret column in xe_documents table. * the XML schema for example - see the is_secret column in xe_documents table.
* In this case, the column type is retrieved according to argument * In this case, the column type is retrieved according to argument
* value type (using the PHP function is_numeric). * value type (using the PHP function is_numeric).
* *
* @return type string * @return type string
*/ */
function getType(){ function getType(){
if($this->type) if($this->type)
{ {

View file

@ -1,5 +1,10 @@
<?php <?php
/**
* SortArgument class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/argument
* @version 0.1
*/
class SortArgument extends Argument { class SortArgument extends Argument {
function getValue(){ function getValue(){

View file

@ -1,15 +1,53 @@
<?php <?php
/**
* DefaultValue class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/queryargument
* @version 0.1
*/
class DefaultValue { class DefaultValue {
/**
* Column name
* @var string
*/
var $column_name; var $column_name;
/**
* Value
* @var mixed
*/
var $value; var $value;
/**
* sequnence status
* @var bool
*/
var $is_sequence = false; var $is_sequence = false;
/**
* operation status
* @var bool
*/
var $is_operation = false; var $is_operation = false;
/**
* operation
* @var string
*/
var $operation = ''; var $operation = '';
/**
* Checks if value is plain string or name of XE function (ipaddress, plus, etc).
* @var bool
*/
var $_is_string = false;
/**
* Checks if value is string resulted from evaluating a piece of PHP code (see $_SERVER[REMOTE_ADDR])
* @var bool
*/
var $_is_string_from_function = false;
var $_is_string = false; ///< Checks if value is plain string or name of XE function (ipaddress, plus, etc). /**
var $_is_string_from_function = false; //< Checks if value is string resulted from evaluating a piece of PHP code (see $_SERVER[REMOTE_ADDR]) * constructor
* @param string $column_name column name
* @param mixed $value value
* @return void
*/
function DefaultValue($column_name, $value){ function DefaultValue($column_name, $value){
$dbParser = &DB::getParser(); $dbParser = &DB::getParser();
$this->column_name = $dbParser->parseColumnName($column_name); $this->column_name = $dbParser->parseColumnName($column_name);

View file

@ -1,15 +1,53 @@
<?php <?php
/**
* QueryArgument class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/queryargument
* @version 0.1
*/
class QueryArgument { class QueryArgument {
/**
* Argument name
* @var string
*/
var $argument_name; var $argument_name;
/**
* Variable name
* @var string
*/
var $variable_name; var $variable_name;
/**
* Argument validator
* @var QueryArgumentValidator
*/
var $argument_validator; var $argument_validator;
/**
* Column name
* @var string
*/
var $column_name; var $column_name;
/**
* Table name
* @var string
*/
var $table_name; var $table_name;
/**
* Operation
* @var string
*/
var $operation; var $operation;
/**
* Ignore value
* @var bool
*/
var $ignore_value; var $ignore_value;
/**
* constructor
* @param object $tag tag object
* @param bool $ignore_value
* @return void
*/
function QueryArgument($tag, $ignore_value = false) { function QueryArgument($tag, $ignore_value = false) {
static $number_of_arguments = 0; static $number_of_arguments = 0;
@ -64,6 +102,10 @@ class QueryArgument {
return false; return false;
} }
/**
* Change QueryArgument object to string
* @return string
*/
function toString() { function toString() {
if ($this->isConditionArgument()) { if ($this->isConditionArgument()) {
// Instantiation // Instantiation

View file

@ -1,6 +1,15 @@
<?php <?php
/**
* SortQueryArgument class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/queryargument
* @version 0.1
*/
class SortQueryArgument extends QueryArgument{ class SortQueryArgument extends QueryArgument{
/**
* Change SortQueryArgument object to string
* @return string
*/
function toString(){ function toString(){
$arg = sprintf("\n" . '${\'%s_argument\'} = new SortArgument(\'%s\', %s);' . "\n" $arg = sprintf("\n" . '${\'%s_argument\'} = new SortArgument(\'%s\', %s);' . "\n"
, $this->argument_name , $this->argument_name

View file

@ -1,16 +1,56 @@
<?php <?php
/**
* QueryArgumentValidator class
* @author NHN (developers@xpressengine.com)
* @package /classes/xml/xmlquery/queryargument/validator
* @version 0.1
*/
class QueryArgumentValidator { class QueryArgumentValidator {
/**
* Argument name
* @var string
*/
var $argument_name; var $argument_name;
/**
* Default value
* @var string
*/
var $default_value; var $default_value;
/**
* Notnull status setting, if value should be not null, this value is 'notnull'
* @var string
*/
var $notnull; var $notnull;
/**
* Filter for value type, for example number
* @var string
*/
var $filter; var $filter;
/**
* Minimum length for value
* @var int
*/
var $min_length; var $min_length;
/**
* Maximum length for value
* @var int
*/
var $max_length; var $max_length;
var $validator_string; var $validator_string;
/**
* Query argument for validate
* @var QueryArgument object
*/
var $argument; var $argument;
/**
* constructor
* @param Xml_Node_ $tag tag object by Query xml file parse
* @param QueryArgument $argument
* @return void
*/
function QueryArgumentValidator($tag, $argument){ function QueryArgumentValidator($tag, $argument){
$this->argument = $argument; $this->argument = $argument;
$this->argument_name = $this->argument->getArgumentName(); $this->argument_name = $this->argument->getArgumentName();

View file

@ -1,19 +1,28 @@
<?php <?php
/** /**
* @class ColumnTag * ColumnTag class
* @author Arnia Software * Models the <column> tag inside an XML Query file
* @brief Models the <column> tag inside an XML Query file * Since the <column> tag supports different attributes depending on
* * the type of query (select, update, insert, delete) this is only
* Since the <column> tag supports different attributes depending on * the base class for the classes that will model each type <column> tag.
* the type of query (select, update, insert, delete) this is only
* the base class for the classes that will model each type <column> tag.
* *
**/ * @author Arnia Software
* @package /classes/xml/xmlquery/tags/column
* @version 0.1
*/
class ColumnTag { class ColumnTag {
/**
* Column name
* @var string
*/
var $name; var $name;
/**
* constructor
* @param string $name
* @return void
*/
function ColumnTag($name){ function ColumnTag($name){
$this->name = $name; $this->name = $name;
} }
} }

View file

@ -1,15 +1,24 @@
<?php <?php
/** /**
* @class InsertColumnTag * InsertColumnTag
* @author Arnia Software * Models the <column> tag inside an XML Query file whose action is 'insert'
* @brief Models the <column> tag inside an XML Query file whose action is 'insert' *
* * @author Arnia Software
**/ * @package /classes/xml/xmlquery/tags/column
* @version 0.1
*/
class InsertColumnTag extends ColumnTag { class InsertColumnTag extends ColumnTag {
/**
* argument
* @var QueryArgument object
*/
var $argument; var $argument;
/**
* constructor
* @param object $column
* @return void
*/
function InsertColumnTag($column) { function InsertColumnTag($column) {
parent::ColumnTag($column->attrs->name); parent::ColumnTag($column->attrs->name);
$dbParser = DB::getParser(); $dbParser = DB::getParser();

View file

@ -0,0 +1,31 @@
<?php
/**
* InsertColumnTagWithoutArgument
* Models the <column> tag inside an XML Query file whose action is 'insert-select'
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/column
* @version 0.1
*/
class InsertColumnTagWithoutArgument extends ColumnTag {
/**
* constructor
* @param object $column
* @return void
*/
function InsertColumnTagWithoutArgument($column) {
parent::ColumnTag($column->attrs->name);
$dbParser = DB::getParser();
$this->name = $dbParser->parseColumnName($this->name);
}
function getExpressionString(){
return sprintf('new Expression(\'%s\')', $this->name);
}
function getArgument(){
return null;
}
}
?>

View file

@ -1,14 +1,24 @@
<?php <?php
/** /**
* @class InsertColumnsTag * InsertColumnsTag class
* @author Arnia Software * Models the <column> tag inside an XML Query file whose action is 'insert'
* @brief Models the <column> tag inside an XML Query file whose action is 'insert' *
* * @author Arnia Software
**/ * @package /classes/xml/xmlquery/tags/column
* @version 0.1
*/
class InsertColumnsTag{ class InsertColumnsTag{
/**
* Column list
* @var array value is InsertColumnTag object
*/
var $columns; var $columns;
/**
* constructor
* @param array|string $xml_columns
* @return void
*/
function InsertColumnsTag($xml_columns) { function InsertColumnsTag($xml_columns) {
$this->columns = array(); $this->columns = array();
@ -19,10 +29,15 @@
foreach($xml_columns as $column){ foreach($xml_columns as $column){
if($column->name === 'query') $this->columns[] = new QueryTag($column, true); if($column->name === 'query') $this->columns[] = new QueryTag($column, true);
else if(!isset($column->attrs->var) && !isset($column->attrs->default)) $this->columns[] = new InsertColumnTagWithoutArgument($column);
else $this->columns[] = new InsertColumnTag($column); else $this->columns[] = new InsertColumnTag($column);
} }
} }
/**
* InsertColumnTag object to string
* @return string
*/
function toString(){ function toString(){
$output_columns = 'array(' . PHP_EOL; $output_columns = 'array(' . PHP_EOL;
foreach($this->columns as $column){ foreach($this->columns as $column){
@ -33,6 +48,10 @@
return $output_columns; return $output_columns;
} }
/**
* Return argument list
* @return array
*/
function getArguments(){ function getArguments(){
$arguments = array(); $arguments = array();
foreach($this->columns as $column){ foreach($this->columns as $column){
@ -43,4 +62,4 @@
} }
?> ?>

View file

@ -1,16 +1,29 @@
<?php <?php
/**
/** * SelectColumnTag
* @class SelectColumnTag * Models the <column> tag inside an XML Query file whose action is 'select'
* @author Arnia Software *
* @brief Models the <column> tag inside an XML Query file whose action is 'select' * @author Arnia Software
* * @package /classes/xml/xmlquery/tags/column
**/ * @version 0.1
*/
class SelectColumnTag extends ColumnTag{ class SelectColumnTag extends ColumnTag{
/**
* alias
* @var string
*/
var $alias; var $alias;
/**
* click count status
* @var bool
*/
var $click_count; var $click_count;
/**
* constructor
* @param string|object $column
* @return void
*/
function SelectColumnTag($column){ function SelectColumnTag($column){
if ($column == "*" || $column->attrs->name == '*') if ($column == "*" || $column->attrs->name == '*')
{ {
@ -32,6 +45,8 @@
if($this->name == '*') return "new StarExpression()"; if($this->name == '*') return "new StarExpression()";
if($this->click_count) if($this->click_count)
return sprintf('new ClickCountExpression(%s, %s, $args->%s)', $this->name, $this->alias,$this->click_count); return sprintf('new ClickCountExpression(%s, %s, $args->%s)', $this->name, $this->alias,$this->click_count);
if(strpos($this->name, '$') === 0)
return sprintf('new SelectExpression($args->%s)', substr($this->name, 1));
$dbParser = DB::getParser(); $dbParser = DB::getParser();
return sprintf('new SelectExpression(\'%s\'%s)', $this->name, $this->alias ? ', \''.$dbParser->escape($this->alias) .'\'': ''); return sprintf('new SelectExpression(\'%s\'%s)', $this->name, $this->alias ? ', \''.$dbParser->escape($this->alias) .'\'': '');
} }

View file

@ -1,8 +1,23 @@
<?php <?php
/**
* SelectColumnTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/column
* @version 0.1
*/
class SelectColumnsTag { class SelectColumnsTag {
/**
* Column list
* @var array value is SelectColumnTag object
*/
var $columns; var $columns;
/**
* constructor
* @param Xml_Node_ $xml_columns
* @return void
*/
function SelectColumnsTag($xml_columns_tag){ function SelectColumnsTag($xml_columns_tag){
if (!$xml_columns_tag) if (!$xml_columns_tag)
$xml_columns_tag = new Xml_Node_(); $xml_columns_tag = new Xml_Node_();
@ -35,6 +50,10 @@
} }
} }
/**
* SelectColumnTag object to string
* @return string
*/
function toString(){ function toString(){
$output_columns = 'array(' . PHP_EOL; $output_columns = 'array(' . PHP_EOL;
foreach($this->columns as $column){ foreach($this->columns as $column){
@ -48,6 +67,10 @@
return $output_columns; return $output_columns;
} }
/**
* Return argument list
* @return array
*/
function getArguments(){ function getArguments(){
$arguments = array(); $arguments = array();
foreach($this->columns as $column){ foreach($this->columns as $column){

View file

@ -1,18 +1,29 @@
<?php <?php
/**
/** * UpdateColumnTag
* @class UpdateColumnTag * Models the <column> tag inside an XML Query file whose action is 'update'
* @author Arnia Software *
* @brief Models the <column> tag inside an XML Query file whose action is 'update' * @author Arnia Software
* * @package /classes/xml/xmlquery/tags/column
**/ * @version 0.1
*/
class UpdateColumnTag extends ColumnTag { class UpdateColumnTag extends ColumnTag {
/**
* argument
* @var QueryArgument object
*/
var $argument; var $argument;
/**
* default value
* @var string
*/
var $default_value; var $default_value;
/**
* constructor
* @param object $column
* @return void
*/
function UpdateColumnTag($column) { function UpdateColumnTag($column) {
parent::ColumnTag($column->attrs->name); parent::ColumnTag($column->attrs->name);
$dbParser = DB::getParser(); $dbParser = DB::getParser();

View file

@ -1,15 +1,24 @@
<?php <?php
/**
/** * UpdateColumnsTag
* @class UpdateColumnsTag * Models the <column> tag inside an XML Query file whose action is 'update'
* @author Arnia Software *
* @brief Models the <column> tag inside an XML Query file whose action is 'update' * @author Arnia Software
* * @package /classes/xml/xmlquery/tags/column
**/ * @version 0.1
*/
class UpdateColumnsTag{ class UpdateColumnsTag{
/**
* Column list
* @var array value is UpdateColumnTag object
*/
var $columns; var $columns;
/**
* constructor
* @param array|string $xml_columns
* @return void
*/
function UpdateColumnsTag($xml_columns) { function UpdateColumnsTag($xml_columns) {
$this->columns = array(); $this->columns = array();
@ -21,6 +30,10 @@
} }
} }
/**
* UpdateColumnTag object to string
* @return string
*/
function toString(){ function toString(){
$output_columns = 'array(' . PHP_EOL; $output_columns = 'array(' . PHP_EOL;
foreach($this->columns as $column){ foreach($this->columns as $column){
@ -31,6 +44,10 @@
return $output_columns; return $output_columns;
} }
/**
* Return argument list
* @return array
*/
function getArguments(){ function getArguments(){
$arguments = array(); $arguments = array();
foreach($this->columns as $column){ foreach($this->columns as $column){
@ -41,4 +58,4 @@
} }
?> ?>

View file

@ -1,9 +1,29 @@
<?php <?php
/**
* ConditionGroupTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/condition
* @version 0.1
*/
class ConditionGroupTag { class ConditionGroupTag {
/**
* condition list
* @var string|array value is ConditionTag object
*/
var $conditions; var $conditions;
/**
* pipe
* @var string
*/
var $pipe; var $pipe;
/**
* constructor
* @param string|array $conditions
* @param string $pipe
* @return void
*/
function ConditionGroupTag($conditions, $pipe = ""){ function ConditionGroupTag($conditions, $pipe = ""){
$this->pipe = $pipe; $this->pipe = $pipe;
@ -19,6 +39,10 @@
return $this->conditions; return $this->conditions;
} }
/**
* ConditionTag object to string
* @return string
*/
function getConditionGroupString(){ function getConditionGroupString(){
$conditions_string = 'array('.PHP_EOL; $conditions_string = 'array('.PHP_EOL;
foreach($this->conditions as $condition){ foreach($this->conditions as $condition){
@ -39,4 +63,4 @@
} }
} }
?> ?>

View file

@ -1,22 +1,54 @@
<?php <?php
/** /**
* @class ConditionTag * ConditionTag
* @author Corina * Models the <condition> tag inside an XML Query file. Base class.
* @brief Models the <condition> tag inside an XML Query file. Base class.
* *
* @author Corina
* @package /classes/xml/xmlquery/tags/condition
* @version 0.1
*/ */
class ConditionTag { class ConditionTag {
/**
* operation for example 'in', 'between', 'not in'...
* @var string
*/
var $operation; var $operation;
/**
* Column name
* @var string
*/
var $column_name; var $column_name;
/**
* Pipe
* @var string
*/
var $pipe; var $pipe;
/**
* Argument name
* @var string
*/
var $argument_name; var $argument_name;
/**
* QueryArgument object
* @var QueryArgument
*/
var $argument; var $argument;
/**
* Default column
* @var string
*/
var $default_column; var $default_column;
/**
* QueryTag object
* @var QueryTag
*/
var $query; var $query;
/**
* constructor
* @param object $condition
* @return void
*/
function ConditionTag($condition){ function ConditionTag($condition){
$this->operation = $condition->attrs->operation; $this->operation = $condition->attrs->operation;
$this->pipe = $condition->attrs->pipe; $this->pipe = $condition->attrs->pipe;
@ -38,7 +70,8 @@
} }
else { else {
if(isset($condition->attrs->default)){ if(isset($condition->attrs->default)){
if(in_array($this->operation, array('in', 'between', 'not in'))){ $operationList = array('in'=>1, 'between'=>1, 'not in'=>1);
if(isset($operationList[$this->operation])){
$default_value = $condition->attrs->default; $default_value = $condition->attrs->default;
if(strpos($default_value, "'") !== false) if(strpos($default_value, "'") !== false)
$default_value = "\"" . $default_value . "\""; $default_value = "\"" . $default_value . "\"";

View file

@ -1,7 +1,23 @@
<?php <?php
/**
* ConditionsTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/condition
* @version 0.1
*/
class ConditionsTag { class ConditionsTag {
/**
* ConditionGroupTag list
* @var array value is ConditionGroupTag object
*/
var $condition_groups; var $condition_groups;
/**
* constructor
* @param object $xml_conditions
* @return void
*/
function ConditionsTag($xml_conditions){ function ConditionsTag($xml_conditions){
$this->condition_groups = array(); $this->condition_groups = array();
if (!$xml_conditions) if (!$xml_conditions)
@ -29,6 +45,10 @@
} }
} }
/**
* ConditionGroupTag object to string
* @return string
*/
function toString(){ function toString(){
$output_conditions = 'array(' . PHP_EOL; $output_conditions = 'array(' . PHP_EOL;
foreach($this->condition_groups as $condition){ foreach($this->condition_groups as $condition){

View file

@ -1,11 +1,21 @@
<?php <?php
/**
* JoinConditionsTag class
*
* @author Corina
* @package /classes/xml/xmlquery/tags/condition
* @version 0.1
*/
class JoinConditionsTag extends ConditionsTag { class JoinConditionsTag extends ConditionsTag {
/**
* constructor
* @param object $xml_conditions
* @return void
*/
function JoinConditionsTag($xml_conditions){ function JoinConditionsTag($xml_conditions){
parent::ConditionsTag($xml_conditions); parent::ConditionsTag($xml_conditions);
$this->condition_groups[0]->conditions[0]->setPipe(""); $this->condition_groups[0]->conditions[0]->setPipe("");
} }
} }
?> ?>

View file

@ -1,8 +1,23 @@
<?php <?php
/**
* GroupsTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/group
* @version 0.1
*/
class GroupsTag { class GroupsTag {
/**
* column list
* @var array
*/
var $groups; var $groups;
/**
* constructor
* @param array|string $xml_groups
* @return void
*/
function GroupsTag($xml_groups){ function GroupsTag($xml_groups){
$this->groups = array(); $this->groups = array();

View file

@ -1,12 +1,43 @@
<?php <?php
/**
* IndexTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/navigation
* @version 0.1
*/
class IndexTag { class IndexTag {
/**
* argument name
* @var string
*/
var $argument_name; var $argument_name;
/**
* QueryArgument object
* @var QueryArgument
*/
var $argument; var $argument;
/**
* Default value
* @var string
*/
var $default; var $default;
/**
* Sort order
* @var string
*/
var $sort_order; var $sort_order;
/**
* Sort order argument
* @var SortQueryArgument object
*/
var $sort_order_argument; var $sort_order_argument;
/**
* constructor
* @param object $index
* @return void
*/
function IndexTag($index){ function IndexTag($index){
$this->argument_name = $index->attrs->var; $this->argument_name = $index->attrs->var;
@ -18,7 +49,8 @@
// Sort order - asc / desc // Sort order - asc / desc
$this->sort_order = $index->attrs->order; $this->sort_order = $index->attrs->order;
if(!in_array($this->sort_order, array("asc", "desc"))){ $sortList = array('asc'=>1, 'desc'=>1);
if(!isset($sortList[$this->sort_order])){
$arg = new Xml_Node_(); $arg = new Xml_Node_();
$arg->attrs = new Xml_Node_(); $arg->attrs = new Xml_Node_();
$arg->attrs->var = $this->sort_order; $arg->attrs->var = $this->sort_order;

View file

@ -1,11 +1,38 @@
<?php <?php
/**
* LimitTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/navigation
* @version 0.1
*/
class LimitTag { class LimitTag {
/**
* Value is relate to limit query
* @var array
*/
var $arguments; var $arguments;
/**
* QueryArgument object
* @var QueryArgument
*/
var $page; var $page;
/**
* QueryArgument object
* @var QueryArgument
*/
var $page_count; var $page_count;
/**
* QueryArgument object
* @var QueryArgument
*/
var $list_count; var $list_count;
/**
* constructor
* @param object $index
* @return void
*/
function LimitTag($index){ function LimitTag($index){
if($index->page && $index->page->attrs && $index->page_count && $index->page_count->attrs){ if($index->page && $index->page->attrs && $index->page_count && $index->page_count->attrs){
$this->page = new QueryArgument($index->page); $this->page = new QueryArgument($index->page);

View file

@ -1,11 +1,43 @@
<?php <?php
/**
* NavigationTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/navigation
* @version 0.1
*/
class NavigationTag { class NavigationTag {
/**
* Order
* @var array
*/
var $order; var $order;
/**
* List count
* @var int
*/
var $list_count; var $list_count;
/**
* Page count
* @var int
*/
var $page_count; var $page_count;
/**
* Page
* @var int
*/
var $page; var $page;
/**
* Limit
* @var LimitTag object
*/
var $limit; var $limit;
/**
* constructor
* @param object $xml_navigation
* @return void
*/
function NavigationTag($xml_navigation){ function NavigationTag($xml_navigation){
$this->order = array(); $this->order = array();
if($xml_navigation) { if($xml_navigation) {
@ -31,6 +63,10 @@
} }
} }
/**
* NavigationTag object to string
* @return string
*/
function getOrderByString(){ function getOrderByString(){
$output = 'array(' . PHP_EOL; $output = 'array(' . PHP_EOL;
foreach($this->order as $order){ foreach($this->order as $order){
@ -41,6 +77,10 @@
return $output; return $output;
} }
/**
* LimitTag object to string
* @return string
*/
function getLimitString(){ function getLimitString(){
if ($this->limit) return $this->limit->toString(); if ($this->limit) return $this->limit->toString();
else return ""; else return "";

View file

@ -1,25 +1,104 @@
<?php <?php
/**
* QueryTag class
*
* @author Arnia Software
* @package /classes/xml/xmlquery/tags/query
* @version 0.1
*/
class QueryTag { class QueryTag {
/**
* Action for example, 'select', 'insert', 'delete'...
* @var string
*/
var $action; var $action;
/**
* Query id
* @var string
*/
var $query_id; var $query_id;
/**
* Priority
* @var string
*/
var $priority; var $priority;
/**
* column type list
* @var array
*/
var $column_type; var $column_type;
/**
* Query stdClass object
* @var object
*/
var $query; var $query;
//xml tags /**
* Columns in xml tags
* @var object
*/
var $columns; var $columns;
/**
* Tables in xml tags
* @var object
*/
var $tables; var $tables;
/**
* Subquery in xml tags
* @var object
*/
var $subquery;
/**
* Conditions in xml tags
* @var object
*/
var $conditions; var $conditions;
/**
* Groups in xml tags
* @var object
*/
var $groups; var $groups;
/**
* Navigation in xml tags
* @var object
*/
var $navigation; var $navigation;
/**
* Arguments in xml tags
* @var object
*/
var $arguments; var $arguments;
/**
* PreBuff
* @var string
*/
var $preBuff; var $preBuff;
/**
* Buff
* @var string
*/
var $buff; var $buff;
/**
* Subquery status
* @var bool
*/
var $isSubQuery; var $isSubQuery;
/**
* Join type
* @var string
*/
var $join_type; var $join_type;
/**
* alias
* @var string
*/
var $alias; var $alias;
/**
* constructor
* @param object $query
* @param bool $isSubQuery
* @return void
*/
function QueryTag($query, $isSubQuery = false) { function QueryTag($query, $isSubQuery = false) {
$this->action = $query->attrs->action; $this->action = $query->attrs->action;
$this->query_id = $query->attrs->id; $this->query_id = $query->attrs->id;
@ -37,9 +116,12 @@ class QueryTag {
$this->getColumns(); $this->getColumns();
$tables = $this->getTables(); $tables = $this->getTables();
$this->setTableColumnTypes($tables); $this->setTableColumnTypes($tables);
$this->getSubquery(); // Used for insert-select
$this->getConditions(); $this->getConditions();
$this->getGroups(); $this->getGroups();
$this->getNavigation(); $this->getNavigation();
$this->getPrebuff(); $this->getPrebuff();
$this->getBuff(); $this->getBuff();
} }
@ -77,19 +159,20 @@ class QueryTag {
} }
} }
function getColumns() { function getColumns(){
if ($this->action == 'select') { if($this->action == 'select'){
return $this->columns = new SelectColumnsTag($this->query->columns); return $this->columns = new SelectColumnsTag($this->query->columns);
} else if ($this->action == 'insert') { }else if($this->action == 'insert' || $this->action == 'insert-select'){
return $this->columns = new InsertColumnsTag($this->query->columns->column); return $this->columns = new InsertColumnsTag($this->query->columns->column);
} else if ($this->action == 'update') { }else if($this->action == 'update') {
return $this->columns = new UpdateColumnsTag($this->query->columns->column); return $this->columns = new UpdateColumnsTag($this->query->columns->column);
} else if ($this->action == 'delete') { }else if($this->action == 'delete') {
return $this->columns = null; return $this->columns = null;
} }
} }
function getPrebuff() { function getPrebuff() {
if($this->isSubQuery) return;
// TODO Check if this work with arguments in join clause // TODO Check if this work with arguments in join clause
$arguments = $this->getArguments(); $arguments = $this->getArguments();
@ -159,11 +242,13 @@ class QueryTag {
if ($this->columns) if ($this->columns)
$buff .= '$query->setColumns(' . $this->columns->toString() . ');' . PHP_EOL; $buff .= '$query->setColumns(' . $this->columns->toString() . ');' . PHP_EOL;
$buff .= '$query->setTables(' . $this->tables->toString() . ');' . PHP_EOL; $buff .= '$query->setTables(' . $this->tables->toString() .');'.PHP_EOL;
$buff .= '$query->setConditions(' . $this->conditions->toString() . ');' . PHP_EOL; if($this->action == 'insert-select')
$buff .= '$query->setGroups(' . $this->groups->toString() . ');' . PHP_EOL; $buff .= '$query->setSubquery(' . $this->subquery->toString() .');'.PHP_EOL;
$buff .= '$query->setOrder(' . $this->navigation->getOrderByString() . ');' . PHP_EOL; $buff .= '$query->setConditions('.$this->conditions->toString() .');'.PHP_EOL;
$buff .= '$query->setLimit(' . $this->navigation->getLimitString() . ');' . PHP_EOL; $buff .= '$query->setGroups(' . $this->groups->toString() . ');'.PHP_EOL;
$buff .= '$query->setOrder(' . $this->navigation->getOrderByString() .');'.PHP_EOL;
$buff .= '$query->setLimit(' . $this->navigation->getLimitString() .');'.PHP_EOL;
$this->buff = $buff; $this->buff = $buff;
return $this->buff; return $this->buff;
@ -176,7 +261,13 @@ class QueryTag {
return $this->tables = new TablesTag($this->query->tables); return $this->tables = new TablesTag($this->query->tables);
} }
function getConditions() { function getSubquery(){
if($this->query->query){
$this->subquery = new QueryTag($this->query->query, true);
}
}
function getConditions(){
return $this->conditions = new ConditionsTag($this->query->conditions); return $this->conditions = new ConditionsTag($this->query->conditions);
} }
@ -207,11 +298,13 @@ class QueryTag {
return $this->buff; return $this->buff;
} }
function getArguments() { function getArguments(){
$arguments = array(); $arguments = array();
if ($this->columns) if ($this->columns)
$arguments = array_merge($arguments, $this->columns->getArguments()); $arguments = array_merge($arguments, $this->columns->getArguments());
$arguments = array_merge($arguments, $this->tables->getArguments()); if($this->action =='insert-select')
$arguments = array_merge($arguments, $this->subquery->getArguments());
$arguments = array_merge($arguments, $this->tables->getArguments());
$arguments = array_merge($arguments, $this->conditions->getArguments()); $arguments = array_merge($arguments, $this->conditions->getArguments());
$arguments = array_merge($arguments, $this->navigation->getArguments()); $arguments = array_merge($arguments, $this->navigation->getArguments());
return $arguments; return $arguments;

View file

@ -1,20 +1,26 @@
<?php <?php
/** /**
* @class HintTableTag * HintTableTag
* @author Arnia Sowftare * Models the <table> tag inside an XML Query file and the corresponding <index_hint> tag
* @brief Models the <table> tag inside an XML Query file
* and the corresponding <index_hint> tag
* *
* @author Arnia Sowftare
* @package /classes/xml/xmlquery/tags/table
* @version 0.1
*/ */
class HintTableTag extends TableTag { class HintTableTag extends TableTag {
/**
* Action for example, 'select', 'insert', 'delete'...
* @var array
*/
var $index; var $index;
/** /**
* @brief Initialises Table Tag properties * constructor
* @param XML <table> tag $table * Initialises Table Tag properties
*/ * @param object $table XML <table> tag
* @param array $index
* @return void
*/
function HintTableTag($table, $index){ function HintTableTag($table, $index){
parent::TableTag($table); parent::TableTag($table);
$this->index = $index; $this->index = $index;

View file

@ -1,34 +1,62 @@
<?php <?php
/** /**
* @class TableTag * TableTag
* @author Arnia Sowftare * Models the <table> tag inside an XML Query file
* @brief Models the <table> tag inside an XML Query file * @abstract
* Example
* <table name="modules" />
* <table name="documents" alias="doc" />
* Attributes
* name - name of the table - table prefix will be automatically added
* alias - table alias. If no value is specified, the table name will be set as default alias
* join_type - in case the table is part of a join clause, this specifies the type of join: left, right etc.
* - permitted values: 'left join','left outer join','right join','right outer join'
* Children
* Can have children of type <conditions>
* *
* @abstract * @author Arnia Sowftare
* Example * @package /classes/xml/xmlquery/tags/table
* <table name="modules" /> * @version 0.1
* <table name="documents" alias="doc" />
* Attributes
* name - name of the table - table prefix will be automatically added
* alias - table alias. If no value is specified, the table name will be set as default alias
* join_type - in case the table is part of a join clause, this specifies the type of join: left, right etc.
* - permitted values: 'left join','left outer join','right join','right outer join'
* Children
* Can have children of type <conditions>
*/ */
class TableTag { class TableTag {
/**
* Unescaped name
* @var string
*/
var $unescaped_name; var $unescaped_name;
/**
* name
* @var string
*/
var $name; var $name;
/**
* alias
* @var string
*/
var $alias; var $alias;
/**
* Join type
* @example 'left join', 'left outer join', 'right join', 'right outer join'
* @var string
*/
var $join_type; var $join_type;
/**
* Condition object
* @var object
*/
var $conditions; var $conditions;
/**
* JoinConditionsTag
* @var JoinConditionsTag object
*/
var $conditionsTag; var $conditionsTag;
/**
* @brief Initialises Table Tag properties /**
* @param XML <table> tag $table * constructor
*/ * Initialises Table Tag properties
* @param object $table XML <table> tag
* @return void
*/
function TableTag($table){ function TableTag($table){
$dbParser = DB::getParser(); $dbParser = DB::getParser();
@ -47,7 +75,8 @@
} }
function isJoinTable(){ function isJoinTable(){
if(in_array($this->join_type,array('left join','left outer join','right join','right outer join')) $joinList = array('left join'=>1, 'left outer join'=>1, 'right join'=>1, 'right outer join'=>1);
if(isset($joinList[$this->join_type])
&& count($this->conditions)) return true; && count($this->conditions)) return true;
return false; return false;
} }
@ -60,12 +89,12 @@
return $this->unescaped_name; return $this->unescaped_name;
} }
/** /**
* @brief Returns string for printing in PHP query cache file * Returns string for printing in PHP query cache file
* The string contains code for instantiation of either * The string contains code for instantiation of either
* a Table or a JoinTable object * a Table or a JoinTable object
* @return string * @return string
*/ */
function getTableString(){ function getTableString(){
$dbParser = DB::getParser(); $dbParser = DB::getParser();

View file

@ -1,24 +1,34 @@
<?php <?php
/** /**
* @class TablesTag * TablesTag class
* @author Arnia Sowftare * Models the <tables> tag inside an XML Query file
* @brief Models the <tables> tag inside an XML Query file * @abstract
* Example
* <tables>
* <table name="documents" alias="doc" />
* </tables>
* Attributes
* None.
* Children
* Can have children of type <table> or <query>
* *
* @abstract * @author Arnia Sowftare
* Example * @package /classes/xml/xmlquery/tags/table
* <tables> * @version 0.1
* <table name="documents" alias="doc" />
* </tables>
* Attributes
* None.
* Children
* Can have children of type <table> or <query>
*/ */
class TablesTag { class TablesTag {
/**
* Table list
* @var array
*/
var $tables; var $tables;
/**
* constructor
* @param object $xml_tables_tag
* @param object $xml_index_hints_tag
* @return void
*/
function TablesTag($xml_tables_tag, $xml_index_hints_tag = NULL){ function TablesTag($xml_tables_tag, $xml_index_hints_tag = NULL){
$this->tables = array(); $this->tables = array();
@ -42,7 +52,7 @@
$this->tables[] = new QueryTag($tag, true); $this->tables[] = new QueryTag($tag, true);
} }
else { else {
if(isset($indexes) && $indexes && isset($indexes[$tag->attrs->name])) if(isset($indexes[$tag->attrs->name]) && $indexes[$tag->attrs->name])
$this->tables[] = new HintTableTag($tag, $indexes[$tag->attrs->name]); $this->tables[] = new HintTableTag($tag, $indexes[$tag->attrs->name]);
else else
$this->tables[] = new TableTag($tag); $this->tables[] = new TableTag($tag);

View file

@ -2,15 +2,15 @@
/* NHN (developers@xpressengine.com) */ /* NHN (developers@xpressengine.com) */
/* Element Reset */ /* Element Reset */
body,table,input,textarea,select,button{font-family:Tahoma,Geneva,sans-serif;font-size:12px} body,table,input,textarea,select,button{font-family:Tahoma,Geneva,sans-serif;font-size:12px}
img{border:0} body{word-wrap:break-word}
.xe_content{word-break:break-all;word-wrap:break-word} a img{border:0}
.xe_content img{max-width:100%;height:auto} .xe_content img{max-width:100%;height:auto}
@media \0screen{.xe_content img{max-width:none}} @media \0screen{.xe_content img{max-width:none}}
/* Button Area */ /* Button Area */
.btnArea{margin:1em 0;text-align:right;zoom:1;clear:both} .btnArea{margin:1em 0;text-align:right;zoom:1;clear:both}
.btnArea:after{content:"";display:block;clear:both} .btnArea:after{content:"";display:block;clear:both}
.btnArea .etc{float:left} .btnArea .etc{float:left}
/* Button */ /* Button - Legacy Code (Don't use it. It will be removed as soon as possible.) */
.btn{position:relative;display:inline-block;vertical-align:middle} .btn{position:relative;display:inline-block;vertical-align:middle}
.btn *{display:inline-block;padding:0 8px;font-size:12px;height:24px;line-height:22px;margin:0;font-weight:bold !important;color:#fff;text-decoration:none !important;border:1px solid;cursor:pointer;overflow:visible;border-radius:3px;box-shadow:inset 0 0 1px #fff;background-color:#666;text-shadow:0 -1px 0 #333;zoom:1} .btn *{display:inline-block;padding:0 8px;font-size:12px;height:24px;line-height:22px;margin:0;font-weight:bold !important;color:#fff;text-decoration:none !important;border:1px solid;cursor:pointer;overflow:visible;border-radius:3px;box-shadow:inset 0 0 1px #fff;background-color:#666;text-shadow:0 -1px 0 #333;zoom:1}
.btn *[disabled=disabled]{opacity:.5;*filter:alpha(opacity=50)} .btn *[disabled=disabled]{opacity:.5;*filter:alpha(opacity=50)}

Some files were not shown because too many files have changed in this diff Show more