issue 2662 coding convention

git-svn-id: http://xe-core.googlecode.com/svn/branches/maserati@12220 201d5d3c-b55e-5fd7-737f-ddc643e51545
This commit is contained in:
ovclas 2012-11-14 09:59:39 +00:00
parent f9ca200edf
commit 15fa10dc39
11 changed files with 697 additions and 522 deletions

View file

@ -1,11 +1,11 @@
<?php
/**
* An abstract class of (*)Handler
*
* @author NHN (developers@xpressengine.com)
**/
class Handler {
}
?>
/**
* An abstract class of (*)Handler
*
* @author NHN (developers@xpressengine.com)
*/
class Handler
{
}
/* End of file Handler.class.php */
/* Location: ./classes/handler/Handler.class.php */

View file

@ -7,7 +7,8 @@
* @package /classes/httprequest
* @version 0.1
*/
class XEHttpRequest {
class XEHttpRequest
{
/**
* target host
* @var string
@ -30,9 +31,9 @@ class XEHttpRequest {
*/
function XEHttpRequest($host, $port)
{
$this->m_host = $host;
$this->m_port = $port;
$this->m_headers = array();
$this->m_host = $host;
$this->m_port = $port;
$this->m_headers = array();
}
/**
@ -43,7 +44,7 @@ class XEHttpRequest {
*/
function addToHeader($key, $value)
{
$this->m_headers[$key] = $value;
$this->m_headers[$key] = $value;
}
/**
@ -71,9 +72,12 @@ class XEHttpRequest {
// list of post variables
if(!is_array($post_vars)) $post_vars = array();
if(false && is_callable('curl_init')) {
if(false && is_callable('curl_init'))
{
return $this->sendWithCurl($target, $method, $timeout, $post_vars);
} else {
}
else
{
return $this->sendWithSock($target, $method, $timeout, $post_vars);
}
}
@ -91,7 +95,8 @@ class XEHttpRequest {
static $crlf = "\r\n";
$sock = @fsockopen($this->m_host, $this->m_port, $errno, $errstr, $timeout);
if(!$sock) {
if(!$sock)
{
return new Object(-1, 'socket_connect_failed');
}
@ -100,8 +105,10 @@ class XEHttpRequest {
// post body
$post_body = '';
if($method == 'POST' && count($post_vars)) {
foreach($post_vars as $key=>$value) {
if($method == 'POST' && count($post_vars))
{
foreach($post_vars as $key=>$value)
{
$post_body .= urlencode($key).'='.urlencode($value).'&';
}
$post_body = substr($post_body, 0, -1);
@ -111,7 +118,8 @@ class XEHttpRequest {
}
$request = "$method $target HTTP/1.1$crlf";
foreach($headers as $equiv=>$content) {
foreach($headers as $equiv=>$content)
{
$request .= "$equiv: $content$crlf";
}
$request .= $crlf.$post_body;
@ -121,19 +129,25 @@ class XEHttpRequest {
// read response headers
$is_chunked = false;
while(strlen(trim($line = fgets($sock)))) {
while(strlen(trim($line = fgets($sock))))
{
list($equiv, $content) = preg_split('/ *: */', rtrim($line), 1);
if(!strcasecmp($equiv, 'Transfer-Encoding') && $content == 'chunked') {
if(!strcasecmp($equiv, 'Transfer-Encoding') && $content == 'chunked')
{
$is_chunked = true;
}
}
$body = '';
while(!feof($sock)) {
if ($is_chunked) {
while(!feof($sock))
{
if($is_chunked)
{
$chunk_size = hexdec(fgets($sock));
if($chunk_size) $body .= fread($sock, $chunk_size);
} else {
}
else
{
$body .= fgets($sock, 512);
}
}
@ -171,9 +185,10 @@ class XEHttpRequest {
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
switch($method) {
case 'GET': curl_setopt($ch, CURLOPT_HTTPGET, true); break;
case 'PUT': curl_setopt($ch, CURLOPT_PUT, true); break;
switch($method)
{
case 'GET': curl_setopt($ch, CURLOPT_HTTPGET, true); break;
case 'PUT': curl_setopt($ch, CURLOPT_PUT, true); break;
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars);
@ -181,14 +196,16 @@ class XEHttpRequest {
}
$arr_headers = array();
foreach($headers as $key=>$value){
foreach($headers as $key=>$value)
{
$arr_headers[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_headers);
$body = curl_exec($ch);
if(curl_errno($ch)) {
if(curl_errno($ch))
{
return new Object(-1, 'socket_connect_failed');
}
@ -201,4 +218,5 @@ class XEHttpRequest {
return $ret;
}
}
?>
/* End of file XEHttpRequest.class.php */
/* Location: ./classes/httprequest/XEHttpRequest.class.php */

View file

@ -9,10 +9,10 @@ else
}
/**
* Mailing class for XpressEngine
*
* @author NHN (developers@xpressengine.com)
*/
* Mailing class for XpressEngine
*
* @author NHN (developers@xpressengine.com)
*/
class Mail extends PHPMailer
{
/**
@ -130,22 +130,21 @@ class Mail extends PHPMailer
var $use_smtp = FALSE;
/**
* Constructor function
*
* @return void
*/
* Constructor function
*
* @return void
*/
function Mail()
{
}
/**
* Set parameters for using Gmail
*
* @param string $account_name Password
* @param string $account_passwd Secure method ('ssl','tls')
* @return void
*/
* Set parameters for using Gmail
*
* @param string $account_name Password
* @param string $account_passwd Secure method ('ssl','tls')
* @return void
*/
function useGmailAccount($account_name, $account_passwd)
{
$this->SMTPAuth = TRUE;
@ -165,17 +164,17 @@ class Mail extends PHPMailer
}
/**
* Set parameters for using SMTP protocol
*
* @param bool $auth SMTP authentication
* @param string $host SMTP host address
* @param string $user SMTP user id
* @param string $pass STMP user password
* @param string $secure method ('ssl','tls')
* @param int $port STMP port
*
* @return bool TRUE if SMTP is set correct, otherwise return FALSE
*/
* Set parameters for using SMTP protocol
*
* @param bool $auth SMTP authentication
* @param string $host SMTP host address
* @param string $user SMTP user id
* @param string $pass STMP user password
* @param string $secure method ('ssl','tls')
* @param int $port STMP port
*
* @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)
{
$this->SMTPAuth = $auth;
@ -203,47 +202,47 @@ class Mail extends PHPMailer
}
/**
* Set additional parameters
*
* @param string $additional_params Additional parameters
* @return void
*/
* Set additional parameters
*
* @param string $additional_params Additional parameters
* @return void
*/
function setAdditionalParams($additional_params)
{
$this->additional_params = $additional_params;
}
/**
* Add file attachment
*
* @param string $filename File name to attach
* @param string $orgfilename Real path of file to attach
* @return void
*/
* Add file attachment
*
* @param string $filename File name to attach
* @param string $orgfilename Real path of file to attach
* @return void
*/
function addAttachment($filename, $orgfilename)
{
$this->attachments[$orgfilename] = $filename;
}
/**
* Add content attachment
*
* @param string $filename Real path of file to attach
* @param string $cid Content-CID
* @return void
*/
* Add content attachment
*
* @param string $filename Real path of file to attach
* @param string $cid Content-CID
* @return void
*/
function addCidAttachment($filename, $cid)
{
$this->cidAttachments[$cid] = $filename;
}
/**
* Set Sender (From:)
*
* @param string $name Sender name
* @param string $email Sender email address
* @return void
*/
* Set Sender (From:)
*
* @param string $name Sender name
* @param string $email Sender email address
* @return void
*/
function setSender($name, $email)
{
if($this->Mailer == "mail")
@ -258,10 +257,10 @@ class Mail extends PHPMailer
}
/**
* Get Sender (From:)
*
* @return string
*/
* Get Sender (From:)
*
* @return string
*/
function getSender()
{
if(!stristr(PHP_OS, 'win') && $this->sender_name)
@ -272,12 +271,12 @@ class Mail extends PHPMailer
}
/**
* Set Receiptor (TO:)
*
* @param string $name Receiptor name
* @param string $email Receiptor email address
* @return void
*/
* Set Receiptor (TO:)
*
* @param string $name Receiptor name
* @param string $email Receiptor email address
* @return void
*/
function setReceiptor($name, $email)
{
if($this->Mailer == "mail")
@ -292,10 +291,10 @@ class Mail extends PHPMailer
}
/**
* Get Receiptor (TO:)
*
* @return string
*/
* Get Receiptor (TO:)
*
* @return string
*/
function getReceiptor()
{
if(!stristr(PHP_OS, 'win') && $this->receiptor_name && $this->receiptor_name != $this->receiptor_email)
@ -306,11 +305,11 @@ class Mail extends PHPMailer
}
/**
* Set Email's Title
*
* @param string $title Title to set
* @return void
*/
* Set Email's Title
*
* @param string $title Title to set
* @return void
*/
function setTitle($title)
{
if($this->Mailer == "mail")
@ -324,21 +323,21 @@ class Mail extends PHPMailer
}
/**
* Get Email's Title
*
* @return string
*/
* Get Email's Title
*
* @return string
*/
function getTitle()
{
return '=?utf-8?b?' . base64_encode($this->title) . '?=';
}
/**
* Set BCC
*
* @param string $bcc
* @return void
*/
* Set BCC
*
* @param string $bcc
* @return void
*/
function setBCC($bcc)
{
if($this->Mailer == "mail")
@ -352,33 +351,33 @@ class Mail extends PHPMailer
}
/**
* Set Message ID
*
* @param string $messageId
* @return void
*/
* Set Message ID
*
* @param string $messageId
* @return void
*/
function setMessageID($messageId)
{
$this->messageId = $messageId;
}
/**
* Set references
*
* @param string $references
* @return void
*/
* Set references
*
* @param string $references
* @return void
*/
function setReferences($references)
{
$this->references = $references;
}
/**
* Set ReplyTo param
*
* @param string $replyTo
* @return void
*/
* Set ReplyTo param
*
* @param string $replyTo
* @return void
*/
function setReplyTo($replyTo)
{
if($this->Mailer == "mail")
@ -392,11 +391,11 @@ class Mail extends PHPMailer
}
/**
* Set message content
*
* @param string $content Content
* @return void
*/
* Set message content
*
* @param string $content Content
* @return void
*/
function setContent($content)
{
$content = preg_replace_callback('/<img([^>]+)>/i', array($this, 'replaceResourceRealPath'), $content);
@ -411,53 +410,53 @@ class Mail extends PHPMailer
}
/**
* Replace resourse path of the files
*
* @see Mail::setContent()
* @param array $matches Match info.
* @return string
*/
* Replace resourse path of the files
*
* @see Mail::setContent()
* @param array $matches Match info.
* @return string
*/
function replaceResourceRealPath($matches)
{
return preg_replace('/src=(["\']?)files/i', 'src=$1' . Context::getRequestUri() . 'files', $matches[0]);
}
/**
* Get the Plain content of body message
*
* @return string
*/
* Get the Plain content of body message
*
* @return string
*/
function getPlainContent()
{
return chunk_split(base64_encode(str_replace(array("<", ">", "&"), array("&lt;", "&gt;", "&amp;"), $this->content)));
}
/**
* Get the HTML content of body message
*
* @return string
*/
* Get the HTML content of body message
*
* @return string
*/
function getHTMLContent()
{
return chunk_split(base64_encode($this->content_type != 'html' ? nl2br($this->content):$this->content));
}
/**
* Set the type of body's content
*
* @param string $mode
* @return void
*/
* Set the type of body's content
*
* @param string $mode
* @return void
*/
function setContentType($mode = 'html')
{
$this->content_type = $mode == 'html' ? 'html':'';
}
/**
* Process the images from attachments
*
* @return void
*/
* Process the images from attachments
*
* @return void
*/
function procAttachments()
{
if($this->Mailer == "mail")
@ -477,19 +476,19 @@ class Mail extends PHPMailer
$file_str = $file_handler->readFile($attachment);
$chunks = chunk_split(base64_encode($file_str));
$tempBody = sprintf(
"--" . $boundary . $this->eol .
"Content-Type: %s;" . $this->eol .
"\tname=\"%s\"" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Description: %s" . $this->eol .
"Content-Disposition: attachment;" . $this->eol .
"\tfilename=\"%s\"" . $this->eol . $this->eol .
"%s" . $this->eol . $this->eol,
$type,
$filename,
$filename,
$filename,
$chunks);
"--" . $boundary . $this->eol .
"Content-Type: %s;" . $this->eol .
"\tname=\"%s\"" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Description: %s" . $this->eol .
"Content-Disposition: attachment;" . $this->eol .
"\tfilename=\"%s\"" . $this->eol . $this->eol .
"%s" . $this->eol . $this->eol,
$type,
$filename,
$filename,
$filename,
$chunks);
$res[] = $tempBody;
}
$this->body = implode("", $res);
@ -509,10 +508,10 @@ class Mail extends PHPMailer
}
/**
* Process the images from body content. This functions is used if Mailer is set as mail not as SMTP
*
* @return void
*/
* Process the images from body content. This functions is used if Mailer is set as mail not as SMTP
*
* @return void
*/
function procCidAttachments()
{
if(count($this->cidAttachments) > 0)
@ -530,20 +529,20 @@ class Mail extends PHPMailer
$file_str = FileHandler::readFile($attachment);
$chunks = chunk_split(base64_encode($file_str));
$tempBody = sprintf(
"--" . $boundary . $this->eol .
"Content-Type: %s;" . $this->eol .
"\tname=\"%s\"" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-ID: <%s>" . $this->eol .
"Content-Description: %s" . $this->eol .
"Content-Location: %s" . $this->eol . $this->eol .
"%s" . $this->eol . $this->eol,
$type,
$filename,
$cid,
$filename,
$filename,
$chunks);
"--" . $boundary . $this->eol .
"Content-Type: %s;" . $this->eol .
"\tname=\"%s\"" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-ID: <%s>" . $this->eol .
"Content-Description: %s" . $this->eol .
"Content-Location: %s" . $this->eol . $this->eol .
"%s" . $this->eol . $this->eol,
$type,
$filename,
$cid,
$filename,
$filename,
$chunks);
$res[] = $tempBody;
}
$this->body = implode("", $res);
@ -552,10 +551,10 @@ class Mail extends PHPMailer
}
/**
* Send email
*
* @return bool TRUE in case of success, FALSE if sending fails
*/
* Send email
*
* @return bool TRUE in case of success, FALSE if sending fails
*/
function send()
{
if($this->Mailer == "mail")
@ -564,39 +563,39 @@ class Mail extends PHPMailer
$this->eol = $GLOBALS['_qmail_compatibility'] == "Y" ? "\n" : "\r\n";
$this->header = "Content-Type: multipart/alternative;" . $this->eol . "\tboundary=\"" . $boundary . "\"" . $this->eol . $this->eol;
$this->body = sprintf(
"--%s" . $this->eol .
"Content-Type: text/plain; charset=utf-8; format=flowed" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Disposition: inline" . $this->eol . $this->eol .
"%s" .
"--%s" . $this->eol .
"Content-Type: text/html; charset=utf-8" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Disposition: inline" . $this->eol . $this->eol .
"%s" .
"--%s--" .
"",
$boundary,
$this->getPlainContent(),
$boundary,
$this->getHTMLContent(),
$boundary
);
"--%s" . $this->eol .
"Content-Type: text/plain; charset=utf-8; format=flowed" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Disposition: inline" . $this->eol . $this->eol .
"%s" .
"--%s" . $this->eol .
"Content-Type: text/html; charset=utf-8" . $this->eol .
"Content-Transfer-Encoding: base64" . $this->eol .
"Content-Disposition: inline" . $this->eol . $this->eol .
"%s" .
"--%s--" .
"",
$boundary,
$this->getPlainContent(),
$boundary,
$this->getHTMLContent(),
$boundary
);
$this->procCidAttachments();
$this->procAttachments();
$headers = sprintf(
"From: %s" . $this->eol .
"%s" .
"%s" .
"%s" .
"%s" .
"MIME-Version: 1.0" . $this->eol . "",
$this->getSender(),
$this->messageId ? ("Message-ID: <" . $this->messageId . ">" . $this->eol):"",
$this->replyTo ? ("Reply-To: <" . $this->replyTo . ">" . $this->eol):"",
$this->bcc ? ("Bcc: " . $this->bcc . $this->eol):"",
$this->references ? ("References: <" . $this->references . ">" . $this->eol . "In-Reply-To: <" . $this->references . ">" . $this->eol):""
);
"From: %s" . $this->eol .
"%s" .
"%s" .
"%s" .
"%s" .
"MIME-Version: 1.0" . $this->eol . "",
$this->getSender(),
$this->messageId ? ("Message-ID: <" . $this->messageId . ">" . $this->eol):"",
$this->replyTo ? ("Reply-To: <" . $this->replyTo . ">" . $this->eol):"",
$this->bcc ? ("Bcc: " . $this->bcc . $this->eol):"",
$this->references ? ("References: <" . $this->references . ">" . $this->eol . "In-Reply-To: <" . $this->references . ">" . $this->eol):""
);
$headers .= $this->header;
if($this->additional_params)
{
@ -612,11 +611,11 @@ class Mail extends PHPMailer
}
/**
* Check if DNS of param is real or fake
*
* @param string $email_address Email address
* @return boolean TRUE if param is valid DNS otherwise FALSE
*/
* Check if DNS of param is real or fake
*
* @param string $email_address Email address
* @return boolean TRUE if param is valid DNS otherwise FALSE
*/
function checkMailMX($email_address)
{
if(!Mail::isVaildMailAddress($email_address))
@ -639,11 +638,11 @@ class Mail extends PHPMailer
}
/**
* Check if param is a valid email or not
*
* @param string $email_address Email address
* @return string email address if param is valid email address otherwise blank string
*/
* Check if param is a valid email or not
*
* @param string $email_address Email address
* @return string email address if param is valid email address otherwise blank string
*/
function isVaildMailAddress($email_address)
{
if(preg_match("/([a-z0-9\_\-\.]+)@([a-z0-9\_\-\.]+)/i", $email_address))
@ -657,11 +656,11 @@ class Mail extends PHPMailer
}
/**
* Gets the MIME type of param
*
* @param string $filename filename
* @return string MIME type of ext
*/
* Gets the MIME type of param
*
* @param string $filename filename
* @return string MIME type of ext
*/
function returnMIMEType($filename)
{
preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);

View file

@ -4,9 +4,8 @@
*
* @author NHN (developers@xpressengine.com)
*/
class Object {
class Object
{
/**
* Error code. If `0`, it is not an error.
* @var int
@ -39,7 +38,8 @@ class Object {
* @param string $message Error message
* @return void
*/
function Object($error = 0, $message = 'success') {
function Object($error = 0, $message = 'success')
{
$this->setError($error);
$this->setMessage($message);
}
@ -51,7 +51,8 @@ class Object {
* @param int $error error code
* @return void
*/
function setError($error = 0) {
function setError($error = 0)
{
$this->error = $error;
}
@ -60,7 +61,8 @@ class Object {
*
* @return int Returns an error code
*/
function getError() {
function getError()
{
return $this->error;
}
@ -91,7 +93,8 @@ class Object {
* @param string $message Error message
* @return bool Alaways returns true.
*/
function setMessage($message = 'success') {
function setMessage($message = 'success')
{
if(Context::getLang($message)) $message = Context::getLang($message);
$this->message = $message;
@ -104,7 +107,8 @@ class Object {
*
* @return string Returns message
*/
function getMessage() {
function getMessage()
{
return $this->message;
}
@ -115,7 +119,8 @@ class Object {
* @param mixed $val A value for the variable
* @return void
*/
function add($key, $val) {
function add($key, $val)
{
$this->variables[$key] = $val;
}
@ -144,7 +149,8 @@ class Object {
* @param string $key
* @return string Returns value to a given key
*/
function get($key) {
function get($key)
{
return $this->variables[$key];
}
@ -154,10 +160,12 @@ class Object {
*
* @return Object Returns an object containing key/value pairs
*/
function gets() {
function gets()
{
$num_args = func_num_args();
$args_list = func_get_args();
for($i=0;$i<$num_args;$i++) {
for($i=0;$i<$num_args;$i++)
{
$key = $args_list[$i];
$output->{$key} = $this->get($key);
}
@ -169,7 +177,8 @@ class Object {
*
* @return array
*/
function getVariables() {
function getVariables()
{
return $this->variables;
}
@ -178,7 +187,8 @@ class Object {
*
* @return Object
*/
function getObjectVars() {
function getObjectVars()
{
foreach($this->variables as $key => $val) $output->{$key} = $val;
return $output;
}
@ -188,7 +198,8 @@ class Object {
*
* @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;
}
@ -199,8 +210,9 @@ class Object {
*
* @return bool
*/
function toBoolean() {
return $this->toBool();
function toBoolean()
{
return $this->toBool();
}
}

View file

@ -1,74 +1,76 @@
<?php
/**
* @class PageHandler
* @author NHN (developers@xpressengine.com)
* handles page navigation
* @version 0.1
*
* @remarks Getting total counts, number of pages, current page number, number of items per page,
* this class implements methods and contains variables for page navigation
**/
/**
* @class PageHandler
* @author NHN (developers@xpressengine.com)
* handles page navigation
* @version 0.1
*
* @remarks Getting total counts, number of pages, current page number, number of items per page,
* this class implements methods and contains variables for page navigation
*/
class PageHandler extends Handler
{
var $total_count = 0; ///< number of total items
var $total_page = 0; ///< number of total pages
var $cur_page = 0; ///< current page number
var $page_count = 10; ///< number of page links displayed at one time
var $first_page = 1; ///< first page number
var $last_page = 1; ///< last page number
var $point = 0; ///< increments per getNextPage()
class PageHandler extends Handler {
/**
* constructor
* @param int $total_count number of total items
* @param int $total_page number of total pages
* @param int $cur_page current page number
* @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)
{
$this->total_count = $total_count;
$this->total_page = $total_page;
$this->cur_page = $cur_page;
$this->page_count = $page_count;
$this->point = 0;
var $total_count = 0; ///< number of total items
var $total_page = 0; ///< number of total pages
var $cur_page = 0; ///< current page number
var $page_count = 10; ///< number of page links displayed at one time
var $first_page = 1; ///< first page number
var $last_page = 1; ///< last page number
var $point = 0; ///< increments per getNextPage()
$first_page = $cur_page - (int)($page_count/2);
if($first_page<1) $first_page = 1;
/**
* constructor
* @param int $total_count number of total items
* @param int $total_page number of total pages
* @param int $cur_page current page number
* @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) {
$this->total_count = $total_count;
$this->total_page = $total_page;
$this->cur_page = $cur_page;
$this->page_count = $page_count;
$this->point = 0;
$first_page = $cur_page - (int)($page_count/2);
if($first_page<1) $first_page = 1;
if($total_page > $page_count && $first_page + $page_count - 1 > $total_page)
{
$first_page -= $first_page + $page_count - 1 - $total_page;
}
$last_page = $total_page;
if($last_page>$total_page) $last_page = $total_page;
$this->first_page = $first_page;
$this->last_page = $last_page;
if($total_page < $this->page_count) $this->page_count = $total_page;
}
/**
* request next page
* @return int next page number
**/
function getNextPage() {
$page = $this->first_page+$this->point++;
if($this->point > $this->page_count || $page > $this->last_page) $page = 0;
return $page;
}
/**
* return number of page that added offset.
* @param int $offset
* @return int
**/
function getPage($offset)
if($total_page > $page_count && $first_page + $page_count - 1 > $total_page)
{
return max(min($this->cur_page + $offset, $this->total_page), '');
$first_page -= $first_page + $page_count - 1 - $total_page;
}
}
?>
$last_page = $total_page;
if($last_page>$total_page) $last_page = $total_page;
$this->first_page = $first_page;
$this->last_page = $last_page;
if($total_page < $this->page_count) $this->page_count = $total_page;
}
/**
* request next page
* @return int next page number
*/
function getNextPage()
{
$page = $this->first_page+$this->point++;
if($this->point > $this->page_count || $page > $this->last_page) $page = 0;
return $page;
}
/**
* return number of page that added offset.
* @param int $offset
* @return int
*/
function getPage($offset)
{
return max(min($this->cur_page + $offset, $this->total_page), '');
}
}
/* End of file PageHandler.class.php */
/* Location: ./classes/page/PageHandler.class.php */

View file

@ -609,3 +609,4 @@ class EmbedFilter
}
}
/* End of file : EmbedFilter.class.php */
/* Location: ./classes/security/EmbedFilter.class.php */

View file

@ -131,14 +131,14 @@ class Purifier
$whiteIframeUrlList = $oEmbedFilter->getWhiteIframeUrlList();
$whiteDomainRegex = '%^(';
if(is_array($whiteIframeUrlList))
{
foreach($whiteIframeUrlList AS $key=>$value)
{
if(is_array($whiteIframeUrlList))
{
foreach($whiteIframeUrlList AS $key=>$value)
{
$whiteDomainRegex .= $value;
}
}
$whiteDomainRegex .= ')%';
}
}
$whiteDomainRegex .= ')%';
return $whiteDomainRegex;
}
@ -163,3 +163,4 @@ class Purifier
}
/* End of file : Purifier.class.php */
/* Location: ./classes/security/Purifier.class.php */

View file

@ -11,7 +11,7 @@ class Security
/**
* Action target variable. If this value is null, the method will use Context variables
* @var mixed
**/
*/
var $_targetVar = null;
/**
@ -37,32 +37,44 @@ class Security
if(count($varNames) < 0) return false;
$use_context = is_null($this->_targetVar);
if(!$use_context) {
if(!$use_context)
{
if(!count($varNames) || (!is_object($this->_targetVar) && !is_array($this->_targetVar)) ) return $this->_encodeHTML($this->_targetVar);
$is_object = is_object($this->_targetVar);
}
foreach($varNames as $varName) {
foreach($varNames as $varName)
{
$varName = explode('.', $varName);
$varName0 = array_shift($varName);
if($use_context) {
if($use_context)
{
$var = Context::get($varName0);
} elseif($varName0) {
}
elseif($varName0)
{
$var = $is_object ? $this->_targetVar->{$varName0} : $this->_targetVar[$varName0];
} else {
}
else
{
$var = $this->_targetVar;
}
$var = $this->_encodeHTML($var, $varName);
if($var === false) continue;
if($use_context) {
if($use_context)
{
Context::set($varName0, $var);
} elseif($varName0) {
}
elseif($varName0)
{
if($is_object) $this->_targetVar->{$varName0} = $var;
else $this->_targetVar[$varName0] = $var;
} else {
}
else
{
$this->_targetVar = $var;
}
}
@ -78,7 +90,8 @@ class Security
*/
function _encodeHTML($var, $name=array())
{
if(is_string($var)) {
if(is_string($var))
{
if (!preg_match('/^\$user_lang->/', $var)) $var = htmlspecialchars($var);
return $var;
}
@ -88,7 +101,8 @@ class Security
$is_object = is_object($var);
$name0 = array_shift($name);
if(strlen($name0)) {
if(strlen($name0))
{
$target = $is_object ? $var->{$name0} : $var[$name0];
$target = $this->_encodeHTML($target, $name);
@ -100,7 +114,8 @@ class Security
return $var;
}
foreach($var as $key=>$target) {
foreach($var as $key=>$target)
{
$cloned_name = array_slice($name, 0);
$target = $this->_encodeHTML($target, $name);
$name = $cloned_name;
@ -116,3 +131,4 @@ class Security
}
/* End of file : Security.class.php */
/* Location: ./classes/security/Security.class.php */

View file

@ -6,12 +6,10 @@
* @version 0.1
* @remarks It compiles template file by using regular expression into php
* code, and XE caches compiled code for further uses
**/
class TemplateHandler {
*/
class TemplateHandler
{
var $compiled_path = './files/cache/template_compiled/'; ///< path of compiled caches files
var $path = null; ///< target directory
var $filename = null; ///< target filename
var $file = null; ///< target file (fullpath)
@ -19,13 +17,12 @@ class TemplateHandler {
var $web_path = null; ///< tpl file web path
var $compiled_file = null; ///< tpl file web path
var $skipTags = null;
var $handler_mtime = 0;
/**
* constructor
* @return void
**/
*/
function TemplateHandler()
{
// TODO: replace this with static variable in PHP5
@ -39,12 +36,13 @@ class TemplateHandler {
/**
* returns TemplateHandler's singleton object
* @return TemplateHandler instance
**/
*/
function &getInstance()
{
static $oTemplate = null;
if(__DEBUG__==3 ) {
if(__DEBUG__==3 )
{
if(!isset($GLOBALS['__TemplateHandlerCalled__'])) $GLOBALS['__TemplateHandlerCalled__']=1;
else $GLOBALS['__TemplateHandlerCalled__']++;
}
@ -60,7 +58,7 @@ class TemplateHandler {
* @param string $tpl_filename
* @param string $tpl_file
* @return void
**/
*/
function init($tpl_path, $tpl_filename, $tpl_file='')
{
// verify arguments
@ -94,7 +92,8 @@ class TemplateHandler {
* @param string $tpl_file if specified use it as template file's full path
* @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;
$buff = '';
@ -109,7 +108,8 @@ class TemplateHandler {
if(!$this->file || !file_exists($this->file)) return "Err : '{$this->file}' template file does not exists.";
// for backward compatibility
if(is_null($__templatehandler_root_tpl)) {
if(is_null($__templatehandler_root_tpl))
{
$__templatehandler_root_tpl = $this->file;
}
@ -120,16 +120,21 @@ class TemplateHandler {
$oCacheHandler = &CacheHandler::getInstance('template');
// get cached buff
if($oCacheHandler->isSupport()){
if($oCacheHandler->isSupport())
{
$cache_key = 'template:'.$this->file;
$buff = $oCacheHandler->get($cache_key, $latest_mtime);
} else {
if(is_readable($this->compiled_file) && filemtime($this->compiled_file)>$latest_mtime && filesize($this->compiled_file)) {
}
else
{
if(is_readable($this->compiled_file) && filemtime($this->compiled_file)>$latest_mtime && filesize($this->compiled_file))
{
$buff = 'file://'.$this->compiled_file;
}
}
if(!$buff) {
if(!$buff)
{
$buff = $this->parse();
if($oCacheHandler->isSupport()) $oCacheHandler->put($cache_key, $buff);
else FileHandler::writeFile($this->compiled_file, $buff);
@ -137,7 +142,8 @@ class TemplateHandler {
$output = $this->_fetch($buff);
if($__templatehandler_root_tpl == $this->file) {
if($__templatehandler_root_tpl == $this->file)
{
$__templatehandler_root_tpl = null;
}
@ -152,12 +158,14 @@ class TemplateHandler {
* @param string $tpl_path path of the directory containing target template file
* @param string $tpl_filename target template file's name
* @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);
// if target file does not exist exit
if(!$this->file || !file_exists($this->file)) {
if(!$this->file || !file_exists($this->file))
{
Context::close();
exit("Cannot find the template file: '{$this->file}'");
}
@ -169,9 +177,11 @@ class TemplateHandler {
* parse syntax.
* @param string $buff template file
* @return string compiled result in case of success or NULL in case of error
**/
function parse($buff=null) {
if(is_null($buff)) {
*/
function parse($buff=null)
{
if(is_null($buff))
{
if(!is_readable($this->file)) return;
// read tpl file
@ -179,7 +189,8 @@ class TemplateHandler {
}
// HTML tags to skip
if(is_null($this->skipTags)) {
if(is_null($this->skipTags))
{
$this->skipTags = array('marquee');
}
@ -222,7 +233,7 @@ class TemplateHandler {
* 4. generate return url, return url use in server side validator
* @param array $matches
* @return string
**/
*/
function _compileFormAuthGeneration($matches)
{
@ -234,10 +245,13 @@ class TemplateHandler {
{
$matches[1] = preg_replace('/'.addcslashes($m[0], '?$').'/i', '', $matches[1]);
if (strpos($m[1],'@') !== false){
if (strpos($m[1],'@') !== false)
{
$path = str_replace('@', '', $m[1]);
$path = './files/ruleset/'.$path.'.xml';
}else if(strpos($m[1],'#') !== false){
}
else if(strpos($m[1],'#') !== false)
{
$fileName = str_replace('#', '', $m[1]);
$fileName = str_replace('<?php echo ', '', $fileName);
$fileName = str_replace(' ?>', '', $fileName);
@ -248,7 +262,9 @@ class TemplateHandler {
list($rulsetFile) = explode('.', $fileName);
$autoPath = $module_path.'/ruleset/'.$rulsetFile.'.xml';
$m[1] = $rulsetFile;
}else if(preg_match('@(?:^|\.?/)(modules/[\w-]+)@', $this->path, $mm)) {
}
else if(preg_match('@(?:^|\.?/)(modules/[\w-]+)@', $this->path, $mm))
{
$module_path = $mm[1];
$path = $module_path.'/ruleset/'.$m[1].'.xml';
}
@ -292,21 +308,26 @@ class TemplateHandler {
* fetch using ob_* function
* @param string $buff if buff is not null, eval it instead of including compiled template file
* @return string
**/
function _fetch($buff) {
*/
function _fetch($buff)
{
if(!$buff) return;
$__Context = &$GLOBALS['__Context__'];
$__Context->tpl_path = $this->path;
if($_SESSION['is_logged']) {
if($_SESSION['is_logged'])
{
$__Context->logged_info = Context::get('logged_info');
}
ob_start();
if(substr($buff, 0, 7) == 'file://') {
if(substr($buff, 0, 7) == 'file://')
{
include(substr($buff, 7));
} else {
}
else
{
$eval_str = "?>".$buff;
eval($eval_str);
}
@ -321,7 +342,7 @@ class TemplateHandler {
* @param array $match
*
* @return string changed result
**/
*/
function _replacePath($match)
{
//return origin conde when src value started '${'.
@ -353,7 +374,7 @@ class TemplateHandler {
* replace loop and cond template syntax
* @param string $buff
* @return string changed result
**/
*/
function _parseInline($buff)
{
if(preg_match_all('/<([a-zA-Z]+\d?)(?>(?!<[a-z]+\d?[\s>]).)*?(?:[ \|]cond| loop)="/s', $buff, $match) === false) return $buff;
@ -370,10 +391,12 @@ class TemplateHandler {
// list of self closing tags
$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(preg_match_all('@\s(loop|cond)="([^"]+)"@', $node, $matches)) {
if(preg_match_all('@\s(loop|cond)="([^"]+)"@', $node, $matches))
{
// this tag
$tag = substr($node, 1, strpos($node, ' ')-1);
@ -381,45 +404,61 @@ class TemplateHandler {
$closing = 0;
// process opening tag
foreach($matches[1] as $n=>$stmt) {
foreach($matches[1] as $n=>$stmt)
{
$expr = $matches[2][$n];
$expr = $this->_replaceVar($expr);
$closing++;
switch($stmt) {
case 'cond':
$nodes[$idx-1] .= "<?php if({$expr}){ ?>";
break;
case 'loop':
if(!preg_match('@^(?:(.+?)=>(.+?)(?:,(.+?))?|(.*?;.*?;.*?)|(.+?)\s*=\s*(.+?))$@', $expr, $expr_m)) break;
if($expr_m[1]) {
$expr_m[1] = trim($expr_m[1]);
$expr_m[2] = trim($expr_m[2]);
if($expr_m[3]) $expr_m[2] .= '=>'.trim($expr_m[3]);
$nodes[$idx-1] .= "<?php if({$expr_m[1]}&&count({$expr_m[1]}))foreach({$expr_m[1]} as {$expr_m[2]}){ ?>";
}elseif($expr_m[4]) {
$nodes[$idx-1] .= "<?php for({$expr_m[4]}){ ?>";
}elseif($expr_m[5]) {
$nodes[$idx-1] .= "<?php while({$expr_m[5]}={$expr_m[6]}){ ?>";
}
break;
switch($stmt)
{
case 'cond':
$nodes[$idx-1] .= "<?php if({$expr}){ ?>";
break;
case 'loop':
if(!preg_match('@^(?:(.+?)=>(.+?)(?:,(.+?))?|(.*?;.*?;.*?)|(.+?)\s*=\s*(.+?))$@', $expr, $expr_m)) break;
if($expr_m[1])
{
$expr_m[1] = trim($expr_m[1]);
$expr_m[2] = trim($expr_m[2]);
if($expr_m[3]) $expr_m[2] .= '=>'.trim($expr_m[3]);
$nodes[$idx-1] .= "<?php if({$expr_m[1]}&&count({$expr_m[1]}))foreach({$expr_m[1]} as {$expr_m[2]}){ ?>";
}
elseif($expr_m[4])
{
$nodes[$idx-1] .= "<?php for({$expr_m[4]}){ ?>";
}
elseif($expr_m[5])
{
$nodes[$idx-1] .= "<?php while({$expr_m[5]}={$expr_m[6]}){ ?>";
}
break;
}
}
$node = preg_replace('@\s(loop|cond)="([^"]+)"@', '', $node);
// find closing tag
$close_php = '<?php '.str_repeat('}', $closing).' ?>';
if($node{1} == '!' || substr($node,-2,1) == '/' || isset($self_closing[$tag])) { // self closing tag
// self closing tag
if($node{1} == '!' || substr($node,-2,1) == '/' || isset($self_closing[$tag]))
{
$nodes[$idx+1] = $close_php.$nodes[$idx+1];
} else {
}
else
{
$depth = 1;
for($i=$idx+2; $i < $node_len; $i+=2) {
for($i=$idx+2; $i < $node_len; $i+=2)
{
$nd = $nodes[$i];
if(strpos($nd, $tag) === 1) {
if(strpos($nd, $tag) === 1)
{
$depth++;
} elseif(strpos($nd, '/'.$tag) === 1) {
}
elseif(strpos($nd, '/'.$tag) === 1)
{
$depth--;
if(!$depth) {
if(!$depth)
{
$nodes[$i-1] .= $nodes[$i].$close_php;
$nodes[$i] = '';
break;
@ -429,7 +468,8 @@ 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 = $this->_replaceVar($node);
}
@ -447,7 +487,7 @@ class TemplateHandler {
* replace php code.
* @param array $m
* @return string changed result
**/
*/
function _parseResource($m)
{
// {@ ... } or {$var} or {func(...)}
@ -456,7 +496,8 @@ class TemplateHandler {
if(preg_match('@^(\w+)\(@', $m[1], $mm) && !function_exists($mm[1])) return $m[0];
$echo = 'echo ';
if($m[1]{0} == '@') {
if($m[1]{0} == '@')
{
$echo = '';
$m[1] = substr($m[1], 1);
}
@ -466,16 +507,22 @@ class TemplateHandler {
if($m[3])
{
$attr = array();
if($m[5]) {
if(preg_match_all('@,(\w+)="([^"]+)"@', $m[6], $mm)) {
foreach($mm[1] as $idx=>$name) {
if($m[5])
{
if(preg_match_all('@,(\w+)="([^"]+)"@', $m[6], $mm))
{
foreach($mm[1] as $idx=>$name)
{
$attr[$name] = $mm[2][$idx];
}
}
$attr['target'] = $m[5];
} else {
}
else
{
if(!preg_match_all('@ (\w+)="([^"]+)"@', $m[6], $mm)) return $m[0];
foreach($mm[1] as $idx=>$name) {
foreach($mm[1] as $idx=>$name)
{
$attr[$name] = $mm[2][$idx];
}
}
@ -492,14 +539,12 @@ class TemplateHandler {
if(!$fileDir) return '';
return "<?php \$__tpl=TemplateHandler::getInstance();echo \$__tpl->compile('{$fileDir}','{$pathinfo['basename']}') ?>";
// <!--%load_js_plugin-->
case 'load_js_plugin':
$plugin = $this->_replaceVar($m[5]);
if(strpos($plugin, '$__Context') === false) $plugin = "'{$plugin}'";
return "<?php Context::loadJavascriptPlugin({$plugin}); ?>";
// <load ...> or <unload ...> or <!--%import ...--> or <!--%unload ...-->
case 'import':
case 'load':
@ -509,9 +554,11 @@ class TemplateHandler {
$doUnload = ($m[3] === 'unload');
$isRemote = !!preg_match('@^https?://@i', $attr['target']);
if(!$isRemote) {
if(!$isRemote)
{
if(!preg_match('@^\.?/@',$attr['target'])) $attr['target'] = './'.$attr['target'];
if(substr($attr['target'], -5) == '/lang') {
if(substr($attr['target'], -5) == '/lang')
{
$pathinfo['dirname'] .= '/lang';
$pathinfo['basename'] = '';
$pathinfo['extension'] = 'xml';
@ -527,24 +574,33 @@ class TemplateHandler {
case 'xml':
if($isRemote || $doUnload) return '';
// language file?
if($pathinfo['basename'] == 'lang.xml' || substr($pathinfo['dirname'],-5) == '/lang') {
if($pathinfo['basename'] == 'lang.xml' || substr($pathinfo['dirname'],-5) == '/lang')
{
$result = "Context::loadLang('{$relativeDir}');";
} else {
}
else
{
$result = "require_once('./classes/xml/XmlJsFilter.class.php');\$__xmlFilter=new XmlJsFilter('{$relativeDir}','{$pathinfo['basename']}');\$__xmlFilter->compile();";
}
break;
case 'js':
if($doUnload) {
if($doUnload)
{
$result = "Context::unloadFile('{$attr['target']}','{$attr['targetie']}');";
} else {
}
else
{
$metafile = $attr['target'];
$result = "\$__tmp=array('{$attr['target']}','{$attr['type']}','{$attr['targetie']}','{$attr['index']}');Context::loadFile(\$__tmp,'{$attr['usecdn']}','{$attr['cdnprefix']}','{$attr['cdnversion']}');unset(\$__tmp);";
}
break;
case 'css':
if($doUnload) {
if($doUnload)
{
$result = "Context::unloadFile('{$attr['target']}','{$attr['targetie']}','{$attr['media']}');";
} else {
}
else
{
$metafile = $attr['target'];
$result = "\$__tmp=array('{$attr['target']}','{$attr['media']}','{$attr['targetie']}','{$attr['index']}');Context::loadFile(\$__tmp,'{$attr['usecdn']}','{$attr['cdnprefix']}','{$attr['cdnversion']}');unset(\$__tmp);";
}
@ -564,13 +620,17 @@ class TemplateHandler {
$m[7] = substr($m[7],1);
if(!$m[7]) return '<?php '.$this->_replaceVar($m[8]).'{ ?>'.$m[9];
if(!preg_match('/^(?:((?:end)?(?:if|switch|for(?:each)?|while)|end)|(else(?:if)?)|(break@)?(case|default)|(break))$/', $m[7], $mm)) return '';
if($mm[1]) {
if($mm[1])
{
if($mm[1]{0} == 'e') return '<?php } ?>'.$m[9];
$precheck = '';
if($mm[1] == 'switch') {
if($mm[1] == 'switch')
{
$m[9] = '';
} elseif($mm[1] == 'foreach') {
}
elseif($mm[1] == 'foreach')
{
$var = preg_replace('/^\s*\(\s*(.+?) .*$/', '$1', $m[8]);
$precheck = "if({$var}&&count({$var}))";
}
@ -581,7 +641,6 @@ class TemplateHandler {
if($mm[5]) return "<?php break; ?>";
return '';
}
return $m[0];
}
@ -589,7 +648,7 @@ class TemplateHandler {
* change relative path
* @param string $path
* @return string
**/
*/
function _getRelativeDir($path)
{
$_path = $path;
@ -598,13 +657,16 @@ class TemplateHandler {
if($path{0} != '/') $path = strtr(realpath($fileDir.'/'.$path),'\\','/');
// for backward compatibility
if(!$path) {
if(!$path)
{
$dirs = explode('/', $fileDir);
$paths = explode('/', $_path);
$idx = array_search($paths[0], $dirs);
if($idx !== false) {
while($dirs[$idx] && $dirs[$idx] === $paths[0]) {
if($idx !== false)
{
while($dirs[$idx] && $dirs[$idx] === $paths[0])
{
array_splice($dirs, $idx, 1);
array_shift($paths);
}
@ -621,11 +683,12 @@ class TemplateHandler {
* replace PHP variables of $ character
* @param string $php
* @return string $__Context->varname
**/
function _replaceVar($php) {
*/
function _replaceVar($php)
{
if(!strlen($php)) return '';
return preg_replace('@(?<!::|\\\\|(?<!eval\()\')\$([a-z]|_[a-z0-9])@i', '\$__Context->$1', $php);
}
}
/* End of File: TemplateHandler.class.php */
/* Location: ./classes/template/TemplateHandler.class.php */

View file

@ -53,7 +53,8 @@ class Validator
* @param string $xml_path
* @return void
*/
function Validator($xml_path='') {
function Validator($xml_path='')
{
$this->__construct($xml_path);
}
@ -62,7 +63,8 @@ class Validator
* @param string $xml_path
* @return void
*/
function __construct($xml_path='') {
function __construct($xml_path='')
{
$this->_rules = array();
$this->_filters = array();
$this->_xml_ruleset = null;
@ -71,13 +73,13 @@ class Validator
// predefined rules
$this->addRule(array(
'email' => '/^[\w-]+((?:\.|\+|\~)[\w-]+)*@[\w-]+(\.[\w-]+)+$/',
'userid' => '/^[a-z]+[\w-]*[a-z0-9_]+$/i',
'url' => '/^(https?|ftp|mms):\/\/[0-9a-z-]+(\.[_0-9a-z-]+)+(:\d+)?/',
'alpha' => '/^[a-z]*$/i',
'alpha_number' => '/^[a-z][a-z0-9_]*$/i',
'number' => '/^(?:[1-9]\\d*|0)$/'
));
'email' => '/^[\w-]+((?:\.|\+|\~)[\w-]+)*@[\w-]+(\.[\w-]+)+$/',
'userid' => '/^[a-z]+[\w-]*[a-z0-9_]+$/i',
'url' => '/^(https?|ftp|mms):\/\/[0-9a-z-]+(\.[_0-9a-z-]+)+(:\d+)?/',
'alpha' => '/^[a-z]*$/i',
'alpha_number' => '/^[a-z][a-z0-9_]*$/i',
'number' => '/^(?:[1-9]\\d*|0)$/'
));
$this->_has_mb_func = is_callable('mb_strlen');
$this->setCacheDir('./files/cache');
@ -87,7 +89,8 @@ class Validator
* @destructor
* @return void
*/
function __destruct() {
function __destruct()
{
$this->_rules = null;
$this->_filters = null;
}
@ -97,7 +100,8 @@ class Validator
* @param string $xml_path A file name to be loaded
* @return boolean
*/
function load($xml_path) {
function load($xml_path)
{
$this->_xml_ruleset = null;
$xml_path = realpath($xml_path);
@ -108,12 +112,14 @@ class Validator
if(!isset($xml->ruleset) || !isset($xml->ruleset->fields) || !isset($xml->ruleset->fields->field)) return false;
// custom rules
if(isset($xml->ruleset->customrules) && isset($xml->ruleset->customrules->rule)) {
if(isset($xml->ruleset->customrules) && isset($xml->ruleset->customrules->rule))
{
$customrules = $xml->ruleset->customrules->rule;
if(!is_array($customrules)) $customrules = array($customrules);
$rules = array();
foreach($customrules as $rule) {
foreach($customrules as $rule)
{
if(!isset($rule->attrs) || !isset($rule->attrs->name)) continue;
$rule = (array)$rule->attrs;
@ -130,7 +136,8 @@ class Validator
if(!is_array($fields)) $fields = array($fields);
$filters = array();
foreach($fields as $field) {
foreach($fields as $field)
{
$name = '';
$filter = array();
@ -141,10 +148,12 @@ class Validator
unset($filter['name']);
// conditional statement
if(isset($field->if)) {
if(isset($field->if))
{
$if = $field->if;
if(!is_array($if)) $if = array($if);
foreach($if as $idx=>$cond) {
foreach($if as $idx=>$cond)
{
$if[$idx] = (array)$cond->attrs;
}
$filter['if'] = $if;
@ -165,8 +174,10 @@ class Validator
* @param string $cache_dir Root cache directory
* @return void
*/
function setCacheDir($cache_dir){
if(is_dir($cache_dir)) {
function setCacheDir($cache_dir)
{
if(is_dir($cache_dir))
{
$this->_cache_dir = preg_replace('@/$@', '', $cache_dir);
}
}
@ -176,10 +187,14 @@ class Validator
* @param array $fields Target fields. The keys of the array represents field's name, its values represents field's value.
* @return boolean TRUE if it is valid, FALSE otherwise.
*/
function validate($fields_=null) {
if(is_array($fields_)) {
function validate($fields_=null)
{
if(is_array($fields_))
{
$fields = $fields_;
} else {
}
else
{
$args = array_keys($this->_filters);
$fields = (array)Context::getRequestVars();
}
@ -187,14 +202,14 @@ class Validator
if(!is_array($fields)) return true;
$filter_default = array(
'required' => 'false',
'default' => '',
'modifiers' => array(),
'length' => 0,
'equalto' => 0,
'rule' => 0,
'if' => array()
);
'required' => 'false',
'default' => '',
'modifiers' => array(),
'length' => 0,
'equalto' => 0,
'rule' => 0,
'if' => array()
);
$fields = array_map(array($this, 'arrayTrim'), $fields);
$field_names = array_keys($fields);
@ -202,11 +217,15 @@ class Validator
$filters = array();
// get field names matching patterns
foreach($this->_filters as $key=>$filter) {
foreach($this->_filters as $key=>$filter)
{
$names = array();
if($key{0} == '^') {
if($key{0} == '^')
{
$names = preg_grep('/^'.preg_quote(substr($key,1)).'/', $field_names);
}elseif(substr($key,-2) == '[]'){
}
elseif(substr($key,-2) == '[]')
{
$filters[substr($key,0,-2)] = $filter;
unset($filters[$key]);
}
@ -217,14 +236,15 @@ class Validator
if(!count($names)) continue;
foreach($names as $name) {
foreach($names as $name)
{
$filters[$name] = $filter;
}
unset($filters[$key]);
}
foreach($filters as $key=>$filter) {
foreach($filters as $key=>$filter)
{
$fname = preg_replace('/\[\]$/', '', $key);
$filter = array_merge($filter_default, $filter);
@ -239,16 +259,21 @@ class Validator
$value = $exists ? $fields[$fname] : null;
}
if(is_array($value)) {
if(!isset($value[tmp_name])){
$value = implode('', $value);
}else{
$value = $value['name'];
}
}
if(is_array($value))
{
if(!isset($value[tmp_name]))
{
$value = implode('', $value);
}
else
{
$value = $value['name'];
}
}
// conditional statement
foreach($filter['if'] as $cond) {
foreach($filter['if'] as $cond)
{
if(!isset($cond['test']) || !isset($cond['attr'])) continue;
$func_body = preg_replace('/\\$(\w+)/', '$c[\'$1\']', $cond['test']);
@ -258,7 +283,8 @@ class Validator
}
// attr : default
if(!$value && strlen($default=trim($filter['default']))) {
if(!$value && strlen($default=trim($filter['default'])))
{
$value = $default;
if(is_null($fields_)) Context::set($fname, $value);
else $fields_[$fname] = $value;
@ -275,14 +301,16 @@ class Validator
if(!$exists && !$value_len) continue;
// attr : length
if($length=$filter['length']){
if($length=$filter['length'])
{
list($min, $max) = explode(':', trim($length));
$is_min_b = (substr($min, -1) === 'b');
$is_max_b = (substr($max, -1) === 'b');
list($min, $max) = array((int)$min, (int)$max);
$strbytes = strlen($value);
if(!$is_min_b || !$is_max_b) {
if(!$is_min_b || !$is_max_b)
{
$strlength = $this->_has_mb_func?mb_strlen($value,'utf-8'):$this->mbStrLen($value);
}
@ -290,14 +318,17 @@ class Validator
}
// equalto
if($equalto=$filter['equalto']){
if($equalto=$filter['equalto'])
{
if(!array_key_exists($equalto, $fields) || trim($fields[$equalto]) !== $value) return $this->error($key, 'equalto');
}
// rules
if($rules=$filter['rule']){
if($rules=$filter['rule'])
{
$rules = explode(',', $rules);
foreach($rules as $rule) {
foreach($rules as $rule)
{
$result = $this->applyRule($rule, $value);
// apply the 'not' modifier
if(in_array('not', $modifiers)) $result = !$result;
@ -316,7 +347,7 @@ class Validator
*/
function arrayTrim($array)
{
if (!is_array($array)) return trim($array);
if(!is_array($array)) return trim($array);
foreach($array as $key => $value)
{
@ -331,7 +362,8 @@ class Validator
* @param $msg error message
* @return boolean always false
*/
function error($field, $msg){
function error($field, $msg)
{
$lang_filter = Context::getLang('filter');
$msg = isset($lang_filter->{$msg})?$lang_filter->{$msg}:$lang_filter->invalid;
$msg = sprintf($msg, Context::getLang($field));
@ -345,7 +377,8 @@ class Validator
* Returns the last error infomation including a field name and an error message.
* @return array The last error infomation
*/
function getLastError(){
function getLastError()
{
return $this->_last_error;
}
@ -355,15 +388,18 @@ class Validator
* @param mixed $rule
* @return void
*/
function addRule($name, $rule=''){
function addRule($name, $rule='')
{
if(is_array($name)) $args = $name;
else $args = array($name=>$rule);
foreach($args as $name=>$rule){
foreach($args as $name=>$rule)
{
if(!$rule) continue;
if(is_string($rule)) $rule = array('type'=>'regex', 'test'=>$rule);
if($rule['type'] == 'enum') {
if($rule['type'] == 'enum')
{
$delim = isset($rule['delim'])?$rule['delim']:',';
$rule['test'] = explode($delim, $rule['test']);
}
@ -377,7 +413,8 @@ class Validator
* @param string $name rule name
* @return void
*/
function removeRule($name){
function removeRule($name)
{
unset($this->_rules[$name]);
}
@ -387,18 +424,24 @@ class Validator
* @param string $filter filter
* @return void
*/
function addFilter($name, $filter='') {
function addFilter($name, $filter='')
{
if(is_array($name)) $args = $name;
else $args = array($name=>$filter);
foreach($args as $name=>$filter) {
foreach($args as $name=>$filter)
{
if(!$filter) continue;
if(isset($filter['if'])) {
if(is_array($filter['if']) && count($filter['if'])) {
if(isset($filter['if']))
{
if(is_array($filter['if']) && count($filter['if']))
{
$key = key($filter['if']);
if(!is_int($key)) $filter['if'] = array($filter['if']);
} else {
}
else
{
unset($filter['if']);
}
}
@ -412,7 +455,8 @@ class Validator
* @param string $name rule name
* @return void
*/
function removeFilter($name) {
function removeFilter($name)
{
unset($this->_filters[$name]);
}
@ -422,7 +466,8 @@ class Validator
* @param string $value a value to be validated
* @return boolean TRUE if the field is valid, FALSE otherwise.
*/
function applyRule($name, $value){
function applyRule($name, $value)
{
$rule = $this->_rules[$name];
if (is_array($value) && isset($value['tmp_name']))
@ -430,13 +475,15 @@ class Validator
$value = $value['name'];
}
switch($rule['type']) {
switch($rule['type'])
{
case 'regex':
return (preg_match($rule['test'], $value) > 0);
case 'enum':
return in_array($value, $rule['test']);
case 'expr':
if(!$rule['func_test']) {
if(!$rule['func_test'])
{
$rule['func_test'] = create_function('$a', 'return ('.preg_replace('/\$\$/', '$a', html_entity_decode($rule['test'])).');');
}
return $rule['func_test']($value);
@ -450,9 +497,11 @@ class Validator
* @param string $str
* @return int
*/
function mbStrLen($str){
function mbStrLen($str)
{
$arr = count_chars($str);
for($i=0x80; $i < 0xc0; $i++) {
for($i=0x80; $i < 0xc0; $i++)
{
unset($arr[$i]);
}
return array_sum($arr);
@ -462,7 +511,8 @@ class Validator
* Returns compiled javascript file path. The path begins from XE root directory.
* @return string Compiled JavaScript file path
*/
function getJsPath(){
function getJsPath()
{
if(!$this->_cache_dir) return false;
$dir = $this->_cache_dir.'/ruleset';
@ -479,11 +529,15 @@ class Validator
$content = $this->_compile2js();
if($content === false) return false;
if(is_callable('file_put_contents')) {
if(is_callable('file_put_contents'))
{
@file_put_contents($filepath, $content);
} else {
}
else
{
$fp = @fopen($filepath, 'w');
if(is_resource($fp)) {
if(is_resource($fp))
{
fwrite($fp, $content);
fclose($fp);
}
@ -496,7 +550,8 @@ class Validator
* Compile a ruleset to a javascript file
* @return string
*/
function _compile2js() {
function _compile2js()
{
global $lang;
$ruleset = basename($this->_xml_path,'.xml');
@ -511,9 +566,11 @@ class Validator
// custom rulesets
$addrules = array();
foreach($this->_rules as $name=>$rule) {
foreach($this->_rules as $name=>$rule)
{
if(strpos('email,userid,url,alpha,alpha_number,number,', $name.',') !== false) continue;
switch($rule['type']) {
switch($rule['type'])
{
case 'regex':
$content[] = "v.cast('ADD_RULE', ['{$name}', {$rule['test']}]);";
break;
@ -531,11 +588,13 @@ class Validator
// filters
$content = array();
$messages = array();
foreach($this->_filters as $name=>$filter) {
foreach($this->_filters as $name=>$filter)
{
$field = array();
// form filed name
if(isset($lang->{$name})) {
if(isset($lang->{$name}))
{
$field_lang = addslashes($lang->{$name});
$messages[] = "v.cast('ADD_MESSAGE',['{$name}','{$field_lang}']);";
}
@ -544,20 +603,24 @@ class Validator
if($filter['rule']) $field[] = "rule:'{$filter['rule']}'";
if($filter['default']) $field[] = "default:'{$filter['default']}'";
if($filter['modifier']) $field[] = "modifier:'{$filter['modifier']}'";
if($filter['length']) {
if($filter['length'])
{
list($min, $max) = explode(':', $filter['length']);
if($min) $field[] = "minlength:'{$min}'";
if($max) $field[] = "maxlength:'{$max}'";
}
if($filter['if']) {
if($filter['if'])
{
$ifs = array();
if(!isset($filter['if'][0])) $filter['if'] = array($filter['if']);
foreach($filter['if'] as $if) {
foreach($filter['if'] as $if)
{
$ifs[] = "{test:'".addslashes($if['test'])."', attr:'{$if['attr']}', value:'".addslashes($if['value'])."'}";
}
$field[] = "'if':[".implode(',', $ifs)."]";
}
if(count($field)) {
if(count($field))
{
$field = '{'.implode(',', $field).'}';
$content[] = "'{$name}':{$field}";
}
@ -566,8 +629,10 @@ class Validator
if(!$content) return '/* Error : empty ruleset */';
// error messages
foreach($lang->filter as $key=>$text) {
if($text) {
foreach($lang->filter as $key=>$text)
{
if($text)
{
$text = preg_replace('@\r?\n@', '\\n', addslashes($text));
$messages[] = "v.cast('ADD_MESSAGE',['{$key}','{$text}']);";
}
@ -579,6 +644,5 @@ class Validator
return "(function($,v){\nv=xe.getApp('validator')[0];if(!v)return;\n{$addrules}\nv.cast('ADD_FILTER',['{$ruleset}', {{$content}}]);\n{$messages}\n})(jQuery);";
}
}
/* End of file Validator.class.php */
/* Location: ./classes/validator/Validator.class.php */

View file

@ -1,14 +1,13 @@
<?php
/**
* @class WidgetHandler
* @author NHN (developers@xpressengine.com)
* @brief Handler class for widget execution
* @remark it is empty for now, it would be removed in the future
**/
class WidgetHandler {
var $widget_path = '';
}
?>
/**
* @class WidgetHandler
* @author NHN (developers@xpressengine.com)
* @brief Handler class for widget execution
* @remark it is empty for now, it would be removed in the future
*/
class WidgetHandler
{
var $widget_path = '';
}
/* End of file WidgetHandler.class.php */
/* Location: ./classes/widget/WidgetHandler.class.php */