[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Phpgroupware-cvs] api/core_functions.inc.php, 1.1.1.1.2.21
From: |
nomail |
Subject: |
[Phpgroupware-cvs] api/core_functions.inc.php, 1.1.1.1.2.21 |
Date: |
Thu, 20 May 2004 14:47:32 -0000 |
Update of /api
Modified Files:
Branch: proposal-branch
core_functions.inc.php
date: 2004/04/16 20:59:49; author: seek3r; state: Exp; lines: +698 -424
Log Message:
bringing savannah cvs back up to date with what we were doing on our private
cvs server. We will not be doing dev from this cvs tree
=====================================================================
No syntax errors detected in -
=====================================================================
Index: api/core_functions.inc.php
diff -u api/core_functions.inc.php:1.1.1.1.2.20
api/core_functions.inc.php:1.1.1.1.2.21
--- api/core_functions.inc.php:1.1.1.1.2.20 Sat Feb 28 06:34:10 2004
+++ api/core_functions.inc.php Fri Apr 16 20:59:49 2004
@@ -33,6 +33,32 @@
@abstract Direct functions which are not part of the API classes
because they are required to be available at the lowest level.
*/
+ function phpgw_exit()
+ {
+ if(!defined('PHPGW_FINISHED') && is_object($GLOBALS['phpgw']))
+ {
+ $GLOBALS['phpgw']->finish();
+ }
+ }
+
+ function phpgw_checkoutput($curbuffer)
+ {
+ if(!defined('PHPGW_FINISHED') && is_object($GLOBALS['phpgw']))
+ {
+ define('MISBEHAVEDAPP',true);
+
$GLOBALS['phpgw_xmldoc']->add_node($curbuffer,'APPHTML');
+ $_GET['fxsl'] = 2;
+ return
$GLOBALS['phpgw']->finish(array('sendoutput'=>false));
+ }
+ return $curbuffer;
+ }
+
+ /* Will use phpgw_shutdown to handle things */
+ register_shutdown_function('phpgw_exit');
+ /* Now start catching all output. */
+ ob_start('phpgw_checkoutput');
+ //ob_start();
+
class performance_timer
{
var $data = Array();
@@ -65,12 +91,12 @@
function calc_times()
{
- foreach($this->data as $key=>$val)
+ foreach($this->data as $key=>$val)
{
if(isset($val['start']) && isset($val['stop']))
{
$this->data[$key]['duration'] =
number_format ($val['stop'] - $val['start'], 5);
- }
+ }
}
}
@@ -78,30 +104,27 @@
{
if($this->filename == '')
{
-
if(isset($GLOBALS['phpgw_data']['server']['performance_file']))
- {
- $this->filename =
$GLOBALS['phpgw_data']['server']['performance_file'];
- }
- else
+
if(!isset($GLOBALS['phpgw_data']['server']['performance_file']))
{
return;
}
+ $this->filename =
$GLOBALS['phpgw_data']['server']['performance_file'];
}
$this->calc_times();
$contents = '';
- foreach($this->data as $key=>$val)
+ foreach($this->data as $key=>$val)
{
if(isset($val['duration']))
{
$total += $val['duration'];
- $contents .= $key.":
".$val['duration']."\n";
+ $contents .= $key.':
'.$val['duration']."\n";
}
}
$contents .= "______________________\n";
- $contents .= "Total: $total\n";
+ $contents .= 'Total: '.$total."\n";
- if (file_exists($this->filename) &&
!is_writable($this->filename))
+ if (!file_exists($this->filename) ||
!is_writable($this->filename))
{
return;
}
@@ -109,7 +132,6 @@
{
return;
}
-
if (!fwrite($handle, $contents))
{
return;
@@ -122,225 +144,224 @@
$GLOBALS['performance_timer'] = new performance_timer();
$GLOBALS['performance_timer']->start('phpgw');
- function phpgw_error_trap ($errno, $errstr, $errfile = '', $errline =
'')
+ function __autoload($class)
{
- switch ($errno)
+ if(!validate($class,'alphanumeric'))
{
- case E_COMPILE_ERROR:
- case E_PARSE:
- $type = 'fatal';
- break;
- case E_CORE_ERROR:
- case E_COMPILE_ERROR:
- case E_USER_ERROR:
- case E_ERROR:
- $type = 'error';
- break;
- case E_WARNING:
- break;
- case E_CORE_WARNING:
- case E_USER_WARNING:
- $type = 'warning';
- break;
- case E_NOTICE:
- break;
- case E_USER_NOTICE:
- $type = 'notice';
- break;
- default:
- $type = 'unknown';
+ return;
}
- if(isset($type))
+ list($appname,$classname) = explode('_',$class,2);
+
+ if(!(validate($appname,'alphanumeric') &&
validate($classname,'alphanumeric')))
+ {
+ return;
+ }
+
+ if (class_exists($class))
{
- if(is_object($GLOBALS['msgbox']))
+ return TRUE;
+ }
+
+ $filename =
PHPGW_ROOT.SEP.$appname.SEP.'class.'.$classname.'.php';
+ if(!file_exists($filename))
+ {
+ return;
+ }
+
+ include_once($filename);
+
+ return class_exists($class);
+ }
+
+ function createObject()
+ {
+ $args = new safe_args();
+ $args->set('class',REQUIRED);
+ $args->set('inputs',NOTSET);
+ $args->set('silent',false);
+ extract($args->get(func_get_args()));
+
+ if(__autoload($class))
+ {
+ if(!isset($inputs))
{
- $GLOBALS['msgbox']->add(strtoupper($type).':
['.$errno.'] '.$errstr,$errline,$errfile, $type);
+ return new $class;
}
- else
+ return new $class($inputs);
+ }
+ if(!$silent)
+ {
+ $msg = 'does not exist';
+ if(function_exists('lang'))
{
- echo "<b>".strtoupper($type)."</b>: [$errno]
$errstr<br />\n";
- if($type == 'fatal')
- {
- echo "Error in line $errline of file
$errfile<br />\n";
- exit(1);
- }
+ $msg = lang($msg,NULL,'api');
}
+ trigger_error($class.' '.$msg,E_USER_WARNING);
}
+ /* If method didnt exist */
+ return '##NOMETHOD##';
}
- set_error_handler('phpgw_error_trap');
-
- function createobject($class, $inputs='##NOTSET##', $silent = False)
+ function saveObject(&$obj, $var_name = NULL)
{
- if(sanitize($class,'alphanumeric'))
+ if(round(phpversion(), 1) > 4.2)
{
- $pos = strpos($class,'_');
- $appname = substr($class,0,$pos);
- $classname = substr($class,($pos + 1));
-
- if(sanitize($appname,'alphanumeric') &&
sanitize($classname,'alphanumeric'))
+ if(is_object($obj))
{
- $filename =
PHPGW_ROOT.SEP.$appname.SEP.'class.'.$classname.'.php';
- if(file_exists($filename))
+ if(!isset($var_name))
{
- include_once($filename);
- if(class_exists($class))
- {
- if($inputs == '##NOTSET##')
- {
- return new $class;
- }
- else
- {
- return new
$class($inputs);
- }
- }
- elseif(!$silent)
- {
- $msg = 'does not exist';
- if(function_exists('lang'))
- {
- $msg = lang($msg,
'##NOTSET##', 'api');
- }
-
$GLOBALS['msgbox']->add($class.' '.$msg,__LINE__,__FILE__, 'warning');
- }
- /* If method didnt exist */
- return '##NOMETHOD##';
+ $var_name = get_class($obj);
}
+
$_SESSION['phpgw_session']['serialized_classes'][$var_name] = &$obj;
}
}
}
- function saveobject($obj, $var_name = '##NOTSET##')
+ function recoverObject()
{
- if(is_object($obj) && method_exists($obj,'pre_serialize'))
+ $args = new safe_args();
+ $args->set('var_name',REQUIRED);
+ $args->set('class',REQUIRED);
+ $args->set('inputs',NOTSET);
+ $args->set('silent',false);
+ extract($args->get(func_get_args()));
+
+ if (__autoload($class) &&
isset($_SESSION['phpgw_session']['serialized_classes'][$var_name]))
{
- /* This would clean up anything it didnt need. */
- $obj->pre_serialize();
- if($var_name == '##NOTSET##')
+ $obj =
$_SESSION['phpgw_session']['serialized_classes'][$var_name];
+ if(is_object($obj))
{
- $var_name = get_class($obj);
+ return $obj;
}
-
$GLOBALS['phpgw_session']['serialized_classes'][$var_name] = serialize($obj);
}
+ return createObject($class, $inputs, $silent);
}
- function recoverobject($var_name, $class, $inputs='##NOTSET##', $silent
= False)
+ function execMethod()
{
- $pos = strpos($class,'_');
- $appname = substr($class,0,$pos);
- $classname = substr($class,($pos + 1));
-
- $filename =
PHPGW_ROOT.SEP.$appname.SEP.'class.'.$classname.'.php';
- if(file_exists($filename))
+ $args = new safe_args();
+ $args->set('function', REQUIRED);
+ $args->set('inputs',NOTSET);
+ $args->set('silent',false);
+ extract($args->get(func_get_args()));
+
+ if (!validate($function,'alphanumeric'))
{
- include_once($filename);
- if(!class_exists($class))
- {
- return createobject($class, $inputs, $silent);
- }
+ return;
}
- else
+
+ list($appname,$classname,$methodname) = explode('.', $function);
+ if (substr($methodname,0,2) == '__')
{
- return createobject($class, $inputs, $silent);
+ trigger_error('Attempted access for a private method: '
. $function,E_USER_ERROR);
+ return '##PRIVATE_METHOD##';
}
+ if(!validate($appname,'alphanumeric') &&
validate($classname,'alphanumeric') && validate($methodname,'alphanumeric'))
+ {
+ return;
+ }
-
if(isset($GLOBALS['phpgw_session']['serialized_classes'][$var_name]))
+ $filename = PHPGW_ROOT.SEP.$appname.SEP.'constructor.inc.php';
+ if(file_exists($filename))
{
- $obj =
unserialize($GLOBALS['phpgw_session']['serialized_classes'][$var_name]);
- if(is_object($obj))
- {
- if(method_exists($obj,'post_serialize'))
- {
- /* could recreate its db reference and
such */
- $obj->post_serialize();
- }
- return $obj;
- }
- else
+ include_once($filename);
+ }
+ $class = $appname.'_'.$classname;
+ $obj = createObject($class, NOTSET, $silent);
+ if (method_exists($obj,$methodname))
+ {
+ if($inputs == NOTSET)
{
- return createobject($class, $inputs, $silent);
+ return $obj->$methodname();
}
+ return $obj->$methodname($inputs);
}
- else
+
+ if(!$silent)
{
- return createobject($class, $inputs, $silent);
+ $msg = 'does not exist';
+ if(function_exists('lang'))
+ {
+ $msg = lang($msg, NOTSET, 'api');
+ }
+ trigger_error($appname . '.' . $classname . '.' .
$methodname . ' ' . $msg,E_USER_WARNING);
}
+ // If method didnt exist
+ return '##NOMETHOD##';
}
- function execmethod($function, $inputs='##NOTSET##', $silent = False)
+ /*!
+ @function fix_magic_quotes
+ @abstract cleans up magic_quotes
+ */
+ function fix_magic_quotes ($var = NULL, $sybase = NULL)
{
- if (sanitize($function,'alphanumeric'))
+ // if sybase style quoting isn't specified, use ini setting
+ if (!isset($sybase))
{
- list($appname,$classname,$methodname) = explode('.',
$function);
- if (substr($methodname,0,2) == '__')
- {
- $GLOBALS['msgbox']->add('Attempted access for a
private method: ' . $function,__LINE__,__FILE__, 'fatal');
- return '##PRIVATE_METHOD##';
- }
-
- if(sanitize($appname,'alphanumeric') &&
sanitize($classname,'alphanumeric') && sanitize($methodname,'alphanumeric'))
+ $sybase = ini_get('magic_quotes_sybase');
+ }
+
+ // if no var is specified, fix all affected superglobals
+ if (!isset($var))
+ {
+ // if magic quotes is enabled
+ if (get_magic_quotes_gpc())
{
- $filename =
PHPGW_ROOT.SEP.$appname.SEP.'constructor.inc.php';
- if(file_exists($filename))
- {
- include_once($filename);
- }
- $class = $appname.'_'.$classname;
- $obj = createobject($class, '##NOTSET##',
$silent);
- if (method_exists($obj,$methodname))
- {
- if($inputs == '##NOTSET##')
- {
- return $obj->$methodname();
- }
- else
- {
- return
$obj->$methodname($inputs);
- }
- }
- elseif(!$silent)
+ // workaround because magic_quotes does not
change $_SERVER['argv']
+ $argv = $_SERVER['argv'];
+
+ // fix all affected arrays
+ foreach
(array('_ENV','_REQUEST','_GET','_POST','_COOKIE','_SERVER') as $var)
{
- $msg = 'does not exist';
- if(function_exists('lang'))
- {
- $msg = lang($msg, '##NOTSET##',
'api');
- }
- $GLOBALS['msgbox']->add($appname . '.'
. $classname . '.' . $methodname . ' ' . $msg,__LINE__,__FILE__, 'warning');
+ $GLOBALS[$var] =
fix_magic_quotes($GLOBALS[$var],$sybase);
}
- /* If method didnt exist */
- return '##NOMETHOD##';
+
+ $_SERVER['argv'] = $argv;
+
+ // turn off magic quotes, this is so scripts
which
+ // are sensitive to the setting will work
correctly
+ ini_set('magic_quotes_gpc',0);
+ }
+
+ // disable magic_quotes_sybase
+ if ($sybase)
+ {
+ ini_set('magic_quotes_sybase',0);
}
+
+ // disable magic_quotes_runtime
+ set_magic_quotes_runtime(0);
+ return TRUE;
}
- }
-
- /*!
- @function filesystem_separator
- @abstract sets the file system seperator depending on OS
- @result file system separator
- */
- function filesystem_separator()
- {
- if (PHP_OS == 'Windows' || PHP_OS == 'OS/2')
+
+ // if var is an array, fix each element
+ if (is_array($var))
{
- return '\\';
+ foreach ($var as $key=>$val)
+ {
+ $var[$key] = fix_magic_quotes($val,$sybase);
+ }
+ return $var;
}
- else
+
+ // if var is a string, strip slashes
+ if (is_string($var))
{
- return '/';
+ return $sybase ? str_replace('\'\'','\'',$var) :
stripslashes($var);
}
+
+ // otherwise ignore
+ return $var;
}
- define('SEP',filesystem_separator());
-
-
/*!
@class safe_args
@abstract Allows for array and direct function params as well as
sanatization.
@author seek3r
@discussion This object is used to validate param data as well as
offer flexible function usage.
- @syntax safe_args($expected_args, $recieved_args,__LINE__,__FILE__);
+ @syntax safe_args($expected_args, $received_args);
@example
function somefunc()
{
@@ -348,9 +369,9 @@
$args->set('fname', 'joe', 'string');
$args->set('mname', 'hick', 'string');
$args->set('lname', 'bob', 'string');
- $args = $args->get(func_get_args(),__LINE__,__FILE__);
+ $args = $args->get(func_get_args());
- echo 'Full name: '.$args['fname'].' '.$args['fname'].'
'.$args['lname'].'<br>';
+ echo 'Full name: '.$args['fname'].' '.$args['mname'].'
'.$args['lname'].'<br>';
//default result would be:
// Full name: joe hick bob<br>
}
@@ -361,251 +382,312 @@
somefunc(array('jack','city','brown'));
or
somefunc(array('fname'=>'jack','mname'=>'city','lname'=>'brown'));
$args = new safe_args();
- $args->set('account_lid', '##REQUIRED##');
- $args->set('account_type', '##NOTSET##', 'any');
- $args->set('account_passwd', '##NOTSET##', 'any');
- $args->set('account_firstname', '##NOTSET##', 'any');
- $args->set('account_lastname', '##NOTSET##', 'any');
- $args->set('account_status', '##NOTSET##', 'any');
- $args->set('account_expires', '##NOTSET##', 'any'
$args = new safe_args();
- $args->set('prevop','##REQUIRED##','string');
- $args = $args->get(func_get_args(),__LINE__,__FILE__);
+ $args->set('account_lid', REQUIRED);
+ $args->set('account_type', NOTSET, 'any');
+ $args->set('account_passwd', NOTSET, 'any');
+ $args->set('account_firstname', NOTSET, 'any');
+ $args->set('account_lastname', NOTSET, 'any');
+ $args->set('account_status', NOTSET, 'any');
+ $args->set('account_expires', NOTSET, 'any'
$args = new safe_args();
+ $args->set('prevop',REQUIRED,'string');
+ $args = $args->get(func_get_args());
list($app,$class,$method) =
explode('.',$args['prevop']);
require_once(PHPGW_ROOT . SEP . $app . SEP . 'class . '
. $class . '.php');
if (! is_array($GLOBALS['functions'][$method]))
{
- $GLOBALS['msgbox']->add(lang('Could not store
form state due to missing definition array'),__LINE__,__FILE__, 'warning');
+ $GLOBALS['msgbox']->add(lang('Could not store
form state due to missing definition array'), 'warning');
});
- $args = $args->get(func_get_args(),__LINE__,__FILE__);
+ $args = $args->get(func_get_args());
or
somefunc(array('lname'=>'brown','fname'=>'jack','mname'=>'city'));
For the last one, when using named params in an array you dont
have to follow any order
All three would result in - Full name: jack city brown<br>
+
+ Another example of how to use this, but to have it still feel
more like a standard function you can use extract in this way
+ function somefunc()
+ {
+ $args = new safe_args();
+ $args->set('fname', 'joe', 'string');
+ $args->set('mname', 'hick', 'string');
+ $args->set('lname', 'bob', 'string');
+ extract($args->get(func_get_args()));
+
+ echo "Full name: $fname $mname $lname<br>";
+ //default result would be:
+ // Full name: joe hick bob<br>
+ }
When you use this method of handling params you can secure your
functions as well offer
flexibility needed for both normal use and web services use.
If you have params that are required just set the default as
##REQUIRED##
- Users of your functions can also use ##DEFAULT## to use your
default value for a param
+ Users of your functions can also use NULL to use your default
value for a param
when using the standard format like this:
- somefunc('jack','##DEFAULT##','brown');
+ somefunc('jack',NULL,'brown');
This would result in - Full name: jack hick brown<br>
Its using the default value for the second param.
Of course if you have the second param as a required field it
will fail to work.
*/
+ define('NOTSET', '##NOTSET##');
+ define('NOVAR', '##NOVAR##');
+ define('REQUIRED','##REQUIRED##');
+
class safe_args
{
- var $idx = 0;
var $ref = array();
var $defaults = array();
var $types = array();
- // Allows the rest of the class to know the current key its
sanitizing
- var $current_key = '';
- function set($name, $default='##NOTSET##', $type='any')
+ function set($name,$default=NOTSET,$type='any')
{
- //$this->expected[$this->idx] =
Array('name'=>$name,'default'=>$default, 'type'=>$type);
- //$this->ref[$name] = $this->idx;
-
- $this->ref[$this->idx] = $name;
+ $this->ref[] = $name;
$this->types[$name] = $type;
$this->defaults[$name] = $default;
- $this->idx++;
}
function idx2name($var)
{
- $num = count($var);
- for ($i = 0; $i < $num; $i++)
+ $newvar = array();
+ foreach ($this->ref as $idx=>$name)
{
- $newvar[$this->ref[$i]] = $var[$i];
+ if (isset($var[$idx]))
+ {
+ $newvar[$name] = $var[$idx];
+ }
}
return $newvar;
}
- function get($recieved,$line,$file)
+ function get($received=NULL)
{
- switch(count($recieved))
+ switch(count($received))
{
case 0:
- /* No params sent, so we need to
convert to array */
- $recieved[0] = array();
+ // No params sent, so we need to
convert to array
+ $received = array();
break;
case 1:
- /* If they sent an indexed array,
convert to normal function call. */
- if(is_array($recieved[0]) &&
array_key_exists(0,$recieved[0]))
+ // If they sent an indexed array,
convert to normal function call.
+ if(is_array($received[0]))
{
- $recieved = $recieved[0];
+ $received = $received[0];
+ // if they sent associative
array (most desired)
+ reset($received);
+ if (key($received) !== 0)
+ {
+ break;
+ }
}
- break;
- }
-
- if(!is_array($recieved[0]))
- {
- /* check to see if they used normal function
calls. */
- $recieved = $this->idx2name($recieved);
- }
- else
- {
- /* if they sent associative array (most
desired)*/
- $recieved = $recieved[0];
+ default:
+ // check to see if they used normal
function calls.
+ $received = $this->idx2name($received);
}
- /* Merge with the defaults */
- $args = array_merge($this->defaults, $recieved);
- foreach($args as $key=>$val)
- {
- if(isset($this->types[$key]))
+ $args = array();
+
+ foreach($this->ref as $key)
+ {
+ // enum type
+ if ($this->types[$key] == 'enum')
{
- $sval = (string)$val;
- switch($sval)
+ // Invalid specification of enum options
+ if (!is_array($this->defaults[$key]))
{
- case '##REQUIRED##':
- $msg = 'Missing
required paramater';
+ $msg = 'Invalid parameter for
enum type';
+ if (function_exists('lang'))
+ {
+ $msg =
lang($msg,NOTSET,'api');
+ }
+ $this->error($msg.'
"'.$key.'"',E_USER_ERROR);
+ continue;
+ }
+ // No val, use first option
+ if (!isset($received[$key]))
+ {
+ $args[$key] =
reset($this->defaults[$key]);
+ continue;
+ }
+ // Valid option
+ if
(in_array($received[$key],$this->defaults[$key]))
+ {
+ $args[$key] = $received[$key];
+ continue;
+ }
+ // Invalid option
+ $msg = 'Invalid parameter type for';
+ if (function_exists('lang'))
+ {
+ $msg = lang($msg,NOTSET,'api');
+ }
+ $this->error($msg.'
"'.$key.'"',E_USER_ERROR);
+ continue;
+ }
+ // not set
+ if (!isset($received[$key]))
+ {
+ switch(strval($this->defaults[$key]))
+ {
+ case REQUIRED:
+ $msg = 'Missing
required parameter';
if(function_exists('lang'))
{
- $msg =
lang($msg, '##NOTSET##', 'api');
+ $msg =
lang($msg,NOTSET,'api');
}
-
$GLOBALS['msgbox']->add($msg.' "'.$key.'"',$line,$file, 'fatal');
+ $this->error($msg.'
"'.$key.'"',E_USER_ERROR);
break;
- case '##DEFAULT##':
- $args[$key] =
$this->defaults[$key];
- break;
- case '##NOTSET##':
- unset($args[$key]);
+ case NOTSET:
break;
default:
- if ($this->types[$key]
== 'enum')
- {
- if (!
is_array($this->defaults[$key]))
- {
- $msg =
'Invalid paramater for enum type';
- if
(function_exists('lang'))
- {
-
$msg = lang($msg, '##NOTSET##', 'api');
- }
-
$GLOBALS['msgbox']->add($msg.' "'.$key.'"',$line,$file, 'fatal');
- }
- if ($val)
- {
- if (!
in_array($val,$this->defaults[$key]))
- {
-
$msg = 'Invalid paramater type for';
-
if (function_exists('lang'))
-
{
-
$msg = lang($msg, '##NOTSET##', 'api');
-
}
-
$GLOBALS['msgbox']->add($msg.' "'.$key.'"',$line,$file, 'fatal');
- }
- }
- else
- {
-
$args[$key] = current($this->defaults[$key]);
- }
- }
- else if (!
sanitize($val,$this->types[$key]))
- {
- $msg = 'Invalid
paramater type for';
- if
(function_exists('lang'))
- {
- $msg =
lang($msg, '##NOTSET##', 'api');
- }
-
$GLOBALS['msgbox']->add($msg.' "'.$key.'"',$line,$file, 'fatal');
- }
- }
- }
+ $args[$key] =
$this->defaults[$key];
+ }
+ continue;
+ }
+ // everything else
+ $val = $received[$key];
+ if (validate($val,$this->types[$key]))
+ {
+ $args[$key] = $val;
+ continue;
+ }
+ // try to fix if invalid
+ $val = sanitize($val,$this->types[$key]);
+ if (validate($val,$this->types[$key]))
+ {
+ $args[$key] = $val;
+ continue;
+ }
+ // Invalid & unfixable
+ $msg = 'Invalid parameter type for';
+ if (function_exists('lang'))
+ {
+ $msg = lang($msg,NOTSET,'api');
+ }
+ $this->error($msg.' "'.$key.'"',E_USER_ERROR);
}
return $args;
}
+
+ function error($msg,$type)
+ {
+ if (!function_exists('debug_backtrace') ||
!function_exists('phpgw_error_handler'))
+ {
+ trigger_error($msg,$type);
+ return;
+ }
+
+ $backtrace = debug_backtrace();
+ $classname = get_class($this);
+
+ foreach ($backtrace as $item)
+ {
+ if (!isset($item['class']) || $item['class'] !=
$classname)
+ {
+ break;
+ }
+ }
+
+ phpgw_error_handler($type,$item['function'].':
'.$msg,$item['file'],$item['line']);
+ }
+ }
+
+ function nice_addslashes($string)
+ {
+ if(ini_get('magic_quotes_gpc'))
+ {
+ return $string;
+ }
+ return addslashes($string);
}
/*!
- @function sanitize
+ @function validate
@abstract Validate data.
@author seek3r
@discussion This function is used to validate input data.
- @syntax sanitize('type', 'match string');
- @example sanitize('number',$somestring);
+ @syntax validate('type', 'match string');
+ @example validate('number',$somestring);
*/
/* Define your own types like this:
- $GLOBALS['phpgw_data']['server']['sanitize_types']['number'] =
'/^[0-9]+$/i';
+ $GLOBALS['phpgw_data']['server']['validate_types']['number'] =
'/^[0-9]+$/i';
*/
-
- function sanitize($input,$type)
+
+ function validate($input, $type, $min='', $max='')
{
- /* regexp doesnt like PHP boolean types, so I convert these to
integers */
- if($input === True || $input === False)
+ if($input === true || $input === false)
{
$input = (int)$input;
}
+
+ $minmaxas = 'text';
+
switch ($type)
{
+ case 'any': /* allows anything thru. VERY DANGEROUS */
+ return true;
+ break;
+ case 'paranoid': /* just letters and numbers */
+ $result = preg_match("/^[a-zA-Z0-9]+$/",
$input);
+ break;
+ case 'sqlsafe': /* standard sql safe string */
case 'string': /* standard sql safe string */
- return preg_match("/address@hidden&*()+=-]+$/",
$input);
+ $result =
preg_match("/address@hidden&*()+=-]+$/", $input);
break;
case 'bool': /* boolean value */
- return preg_match("/^(0|1|true|false)$/i",
$input);
+ $result = preg_match("/^(0|1|true|false)$/i",
$input);
break;
case 'alphaonly': /* letters ONLY */
- return preg_match("/^[[:alpha:]]+$/", $input);
+ $result = preg_match("/^[[:alpha:]]+$/",
$input);
+ break;
+ case 'alphanumeric': /* letters and numbers, along with
period, dash, underscore and spaces */
+ $result = preg_match("/^[\w\s.-]+$/", $input);
break;
case 'alpha': /* letters and spaces */
- return preg_match("/^[[:alpha:]\s]+$/", $input);
+ $result = preg_match("/^[[:alpha:]\s]+$/",
$input);
break;
case 'object':
- return is_object($input);
+ $result = is_object($input);
break;
case 'number': /* numbers only */
- case 'integer':
- case 'int': /* numbers only */
- return preg_match("/^\d+$/", $input);
- break;
- case 'alphanumeric': /* letters and numbers, along with
period, dash, underscore and spaces */
- return preg_match("/^[\w\s.-]+$/", $input);
+ case 'integer':
+ case 'int':
+ $result = preg_match("/^\d+$/", $input);
+ $minmaxas = 'int';
+ break;
+ case 'float':
+ $result = preg_match("/^\d+$/", $input);
+ $minmaxas = 'float';
break;
case 'isprint': /* html printable chars. excludes stuff
dangerous to sql */
- return (preg_match("/^[[:print:]]+$/", $input)
&& !preg_match("/['\"<>*#;]/$/", $input));
+ $result = (preg_match("/^[[:print:]]+$/",
$input) && !preg_match("/['\"<>*#;]/$/", $input));
+ break;
+ case 'systemsafe': /* safe as can be for using in an
exec */
+ $result = preg_match("/^\w+\.{1}[:alpha:]+$/",
$input);
+ break;
+ case 'email': /* email addres. Wouldnt allow
address@hidden because requires at least one period after the @ */
+ $result =
preg_match("/^[\w]+(\.[\w-]+)address@hidden(\.[\w-]+)+$/",$input);
break;
- /*
- case 'isxmlsafe':
- //return
(preg_match('/[\001-\031]|[\128-\255]+$/', $input));
- //return (preg_match('/[\128-\255]+$/',
$input));
- return (preg_match('/[\001-\177]+$/', $input));
+ case 'zip_us': /* US */
+ $result =
preg_match("/(^\d{5}$)|(^\d{5}-\d{4}$)/",$input);
break;
- */
- // FIXME: Add support for IPv6
case 'ip': /* IP4 address */
case 'ipv4': /* IP4 address */
- if
(preg_match("^([012]?\d{1,2}\.){3}[012]?\d{1,2}$",$input))
- {
- $octets = explode('.',$input);
- $n = count($octets);
- for($i=0;$i<$n;$i++)
- {
- if ($octets[$i] > 255)
- {
- return False;
- }
- }
- return True;
- }
- return False;
+ $result =
preg_match("{^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$}",$input);
break;
- case 'file': /* safe file path */
- return preg_match("/^\w+\.{1}[:alpha:]+$/",
$input);
+ case 'ipv6': /* IP6 address */
+ $result =
preg_match("/^([a-f0-9]+)((:[a-f0-9]+){7})$/i",$input);
break;
- case 'email': /* email addres. Wouldnt allow
address@hidden because requires at least one period after the @ */
- return
preg_match("/^[\w]+(\.[\w-]+)address@hidden(\.[\w-]+)+$/",$input);
- break;
- case 'us_zip': /* US */
- return
preg_match("/(^\d{5}$)|(^\d{5}-\d{4}$)/",$input);
+ case 'htmlsafe':
+ case 'ldap':
+ case 'utf8':
+ $result = true;
break;
case 'password': /* password with rules enforced */
+ $result = true;
if(@isset($GLOBALS['phpgw_data']['server']['pass_min_length']) &&
(int)$GLOBALS['phpgw_data']['server']['pass_min_length'] > 1)
{
$pass_length = strlen($input);
@@ -614,169 +696,319 @@
$msg = 'Password must be at
least';
if(function_exists('lang'))
{
- $msg = lang($msg,
'##NOTSET##', 'api');
+ $msg = lang($msg,
NOTSET, 'api');
}
$msg2 = 'characters';
if(function_exists('lang'))
{
- $msg2 = lang($msg2,
'##NOTSET##', 'api');
+ $msg2 = lang($msg2,
NOTSET, 'api');
}
- $GLOBALS['msgbox']->add($msg.'
'.$min_length.' '.$msg2,__LINE__,__FILE__, 'error');
- return False;
+ $GLOBALS['msgbox']->add($msg.'
'.$min_length.' '.$msg2, 'error');
+ $result = false;
}
}
-
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_non_alpha']) &&
$GLOBALS['phpgw_data']['server']['pass_require_non_alpha'] == True)
+
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_non_alpha']) &&
$GLOBALS['phpgw_data']['server']['pass_require_non_alpha'] == true)
{
if (!preg_match("[[:^alpha:]]", $input))
{
$msg = 'Password requires at
least one non-alpha character';
if(function_exists('lang'))
{
- $msg = lang($msg,
'##NOTSET##', 'api');
+ $msg = lang($msg,
NOTSET, 'api');
}
- $GLOBALS['msgbox']->add($msg
,__LINE__,__FILE__, 'error');
- return False;
+ $GLOBALS['msgbox']->add($msg ,
'error');
+ $result = false;
}
}
-
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_numbers']) &&
$GLOBALS['phpgw_data']['server']['pass_require_numbers'] == True)
+
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_numbers']) &&
$GLOBALS['phpgw_data']['server']['pass_require_numbers'] == true)
{
if (!preg_match("/^[0-9]+$/", $input))
{
$msg = 'Password requires at
least one numeric character';
if(function_exists('lang'))
{
- $msg = lang($msg,
'##NOTSET##', 'api');
+ $msg = lang($msg,
NOTSET, 'api');
}
- $GLOBALS['msgbox']->add($msg
,__LINE__,__FILE__, 'error');
- return False;
+ $GLOBALS['msgbox']->add($msg ,
'error');
+ $result = false;
}
}
-
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_special_char']) &&
$GLOBALS['phpgw_data']['server']['pass_require_special_char'] == True)
+
if(@isset($GLOBALS['phpgw_data']['server']['pass_require_special_char']) &&
$GLOBALS['phpgw_data']['server']['pass_require_special_char'] == true)
{
if (preg_match("[[:^alnum:]]", $input))
{
$msg = 'Password requires at
least one special character (non-letter and non-number)';
if(function_exists('lang'))
{
- $msg = lang($msg,
'##NOTSET##', 'api');
+ $msg = lang($msg,
NOTSET, 'api');
}
- $GLOBALS['msgbox']->add($msg
,__LINE__,__FILE__, 'error');
- return False;
+ $GLOBALS['msgbox']->add($msg ,
'error');
+ $result = false;
}
}
- return True;
break;
- case 'any': /* allows anything thru. VERY DANGEROUS */
- return True;
+ }
+
+ if($min != '' || $max != '')
+ {
+ switch($minmaxas)
+ {
+ case 'int':
+ $num = intval($input);
+ if((($min != '') && ($num < $min)) || (($max !=
'') && ($num > $max)))
+ {
+ $result = false;
+ }
+ break;
+ case 'float':
+ $num = floatval($input);
+ if((($min != '') && ($num < $min)) || (($max
!= '') && ($num > $max)))
+ {
+ $result = false;
+ }
+ break;
+ default: // for text
+ $len = strlen($input);
+ if((($min != '') && ($len < $min)) ||
(($max != '') && ($len > $max)))
+ {
+ $result = false;
+ }
+ }
+ }
+ return $result;
+ }
+
+ function sanitize($input, $type, $min='', $max='')
+ {
+ /* regexp doesnt like PHP boolean types, so I convert these to
integers */
+ if($input === true || $input === false)
+ {
+ $input = (int)$input;
+ }
+
+ $minmaxas = 'text';
+
+ switch ($type)
+ {
+ case 'paranoid': /* just letters and numbers */
+ $result = preg_replace("/[^a-zA-Z0-9]/", "",
$input);
break;
- default : /* allow developers to define their own types
*/
- if
(isset($GLOBALS['phpgw_data']['server']['sanitize_types'][$type]))
+ case 'number': /* numbers only */
+ case 'integer':
+ case 'int':
+ $result = intval($input);
+ $minmaxas = 'int';
+ break;
+ case 'float':
+ $result = floatval($input);
+ $minmaxas = 'float';
+ break;
+ case 'sqlsafe': /* standard sql safe string */
+ case 'string':
+ $input = nice_addslashes($input);
+ $result = preg_replace("/;/", "", $input);
+ break;
+ case 'bool': /* boolean value */
+ $test = preg_match("/^(0|1|true|false)$/i",
$input);
+ if(!$test)
+ {
+ $result = false;
+ }
+ else
{
- return
preg_match($GLOBALS['phpgw_data']['server']['sanitize_types'][$type], $input);
+ $result = $input;
}
- return False;
+ break;
+ case 'htmlsafe':
+ $pattern[0] = '/\&/';
+ $pattern[1] = '/</';
+ $pattern[2] = "/>/";
+ $pattern[3] = '/\n/';
+ $pattern[4] = '/"/';
+ $pattern[5] = "/'/";
+ $pattern[6] = "/%/";
+ $pattern[7] = '/\(/';
+ $pattern[8] = '/\)/';
+ $pattern[9] = '/\+/';
+ $pattern[10] = '/-/';
+ $replacement[0] = '&';
+ $replacement[1] = '<';
+ $replacement[2] = '>';
+ $replacement[3] = '<br>';
+ $replacement[4] = '"';
+ $replacement[5] = ''';
+ $replacement[6] = '%';
+ $replacement[7] = '(';
+ $replacement[8] = ')';
+ $replacement[9] = '+';
+ $replacement[10] = '-';
+ $result = preg_replace($pattern, $replacement,
$input);
+ break;
+ case 'ldap':
+ $result = preg_replace("/(\)|\(|\||&)/", "",
$input);
+ break;
+ case 'utf8':
+ $result = strtr($input,
"???????¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ",
"SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy");
+ break;
+ case 'systemsafe': /* safe as can be for using in an
exec */
+ $pattern =
'/(;|\||`|>|<|&|^|"|'."\n|\r|'".'|{|}|[|]|\)|\()/i';
+ /* no piping, passing possible environment
variables ($), seperate commands, nested execution, file redirection,
+ background processing, special commands
(backspace, etc.), quotes newlines, or some other special characters */
+ $input = preg_replace($pattern, '', $input);
+ $result = '"'.preg_replace('/\$/', '\\\$',
$input).'"'; //make sure this is only interpretted as ONE argument
+ break;
+ default:
+ $result = $input;
}
+
+ if($min != '' || $max != '')
+ {
+ switch($minmaxas)
+ {
+ case 'int':
+ $num = intval($result);
+ if(($min != '') && ($num < $min))
+ {
+ $result = $min;
+ }
+ if (($max != '') && ($num > $max))
+ {
+ $result = $max;
+ }
+ break;
+ case 'float':
+ $num = floatval($input);
+ if(($min != '') && ($num < $min))
+ {
+ $result = $min;
+ }
+ if (($max != '') && ($num > $max))
+ {
+ $result = $max;
+ }
+ break;
+ default: // for text
+ $len = strlen($input);
+ /*
+ if(($min != '') && ($len < $min))
+ {
+ // dont know what I should do
for this case
+ }
+ */
+ if(($max != '') && ($len > $max))
+ {
+ $result = substr($result, 0,
$max);
+ }
+ }
+ }
+ return $result;
}
-
- function reg_var_sub($type, $default, $value = '##NOTSET##')
+
+ function reg_var_sub($type, $default, $value = NULL)
{
- if (@!is_array($value))
- {
- if ($value == '##NOTSET##')
+ if (!isset($value))
+ {
+ if($default == NOTSET)
{
- if($default == '##NOTSET##')
- {
- return;
- }
- $value = $default;
+ return;
}
- if(sanitize($value,$type))
+ return $default;
+ }
+
+ if (!is_array($value))
+ {
+ if(validate($value,$type))
+ {
+ return $value;
+ }
+ $value = sanitize($value,$type);
+ if(validate($value,$type))
{
return $value;
}
return $default;
}
- else
+
+ foreach($value as $key=>$val)
{
- reset($value);
- foreach($value as $key=>$val)
+ if (@isset($type[$key]))
{
if (@isset($type[$key]))
{
- if (@isset($type[$key]))
- {
- $val_type = $type[$key];
- }
- else
- {
- $val_type = 'string';
- }
+ $val_type = $type[$key];
}
else
{
- $val_type = $type;
+ $val_type = 'string';
}
+ }
+ else
+ {
+ $val_type = $type;
+ }
+ if (@isset($default[$key]))
+ {
if (@isset($default[$key]))
{
- if (@isset($default[$key]))
- {
- $val_default = $default[$key];
- }
- else
- {
- $val_default = '##NOTSET##';
- }
+ $val_default = $default[$key];
}
else
{
- $val_default = $default;
+ $val_default = NOTSET;
}
-
- $result[$key] = reg_var_sub($val_type,
$val_default, $val);
}
- return $result;
- }
+ else
+ {
+ $val_default = $default;
+ }
+
+ $result[$key] = reg_var_sub($val_type, $val_default,
$val);
+ }
+ return $result;
}
/*
method choices are: any, post, get, cookie, session, server,
and global. Default will be used internally only.
*/
-
+
function reg_var()
{
$args = new safe_args();
- $args->set('varname', '##REQUIRED##', 'alphanumeric');
+ $args->set('varname', REQUIRED, 'alphanumeric');
$args->set('method', 'any', 'any');
$args->set('type', 'alphanumeric', 'alpha');
- $args->set('default', '##NOTSET##', 'any');
+ $args->set('default', NOTSET, 'any');
$args->set('appname', 'api', 'string');
- $args->set('register', True, 'bool');
- $args = $args->get(func_get_args(),__LINE__,__FILE__);
+ $args->set('register', true, 'bool');
+ $args = $args->get(func_get_args());
if($args['method'] == 'any')
{
$args['method'] =
Array('POST','GET','COOKIE','SESSION','SERVER');
}
+ elseif(is_string($args['method']))
+ {
+ $args['method'] = explode(',',$args['method']);
+ }
elseif(!is_array($args['method']))
{
$args['method'] = Array($args['method']);
}
-
- $cnt = count($args['method']);
- for($i=0;$i<$cnt;$i++)
+
+ foreach ($args['method'] as $method)
{
- $args['method'][$i] = strtoupper($args['method'][$i]);
- switch($args['method'][$i])
+ $method = strtoupper($method);
+ switch($method)
{
case 'GLOBAL':
if(@isset($GLOBALS[$args['varname']]))
{
$value =
$GLOBALS[$args['varname']];
- $i = $cnt+1;
+ break 2;
}
break;
case 'POST':
@@ -784,30 +1016,27 @@
case 'COOKIE':
case 'FILES':
case 'SERVER':
- $meth =
'HTTP_'.$args['method'][$i].'_VARS';
-
if(@isset($GLOBALS[$meth][$args['varname']]))
+
if(@isset($GLOBALS['_'.$method][$args['varname']]))
{
- $value =
$GLOBALS[$meth][$args['varname']];
- $i = $cnt+1;
+ $value =
$GLOBALS['_'.$method][$args['varname']];
+ break 2;
}
break;
case 'SESSION':
-
if(@isset($HTTP_SESSION_VARS['phpgw_session'][$args['varname']]))
+
if(@isset($_SESSION['phpgw_session'][$args['varname']]))
{
- $value =
$HTTP_SESSION_VARS['phpgw_session'][$args['varname']];
- $i = $cnt+1;
+ $value =
$_SESSION['phpgw_session'][$args['varname']];
+ break 2;
}
break;
default:
-
if(@isset($GLOBALS[$args['method'][$i]][$args['varname']]))
+
if(@isset($GLOBALS[$method][$args['varname']]))
{
- $value =
$GLOBALS[$args['method'][$i]][$args['varname']];
- $i = $cnt+1;
+ $value =
$GLOBALS[$method][$args['varname']];
+ break 2;
}
- break;
}
}
-
$result = reg_var_sub($args['type'], $args['default'], $value);
if(isset($result))
@@ -817,7 +1046,7 @@
$GLOBALS['phpgw_data'][$args['appname']][$args['varname']] = $result;
}
return $result;
- }
+ }
return;
}
@@ -835,13 +1064,13 @@
function get_var()
{
$args = new safe_args();
- $args->set('varname', '##REQUIRED##', 'alphanumeric');
+ $args->set('varname', REQUIRED, 'alphanumeric');
$args->set('method', 'any', 'any');
$args->set('type', 'alphanumeric', 'alpha');
- $args->set('default', '##NOTSET##', 'any');
- $args = $args->get(func_get_args(),__LINE__,__FILE__);
+ $args->set('default', NOTSET, 'any');
+ $args = $args->get(func_get_args());
- $args['register'] = False;
+ $args['register'] = false;
return reg_var($args);
}
@@ -901,7 +1130,7 @@
function html_print_r($var)
{
- echo '<pre>'; print_r($var); echo '</pre>';
+ echo "<table><tr><td align=\"left\">\n<pre>"; print_r($var);
echo '</pre></td</tr></table>';
}
/*
@@ -909,9 +1138,9 @@
@abstract phpgw version checking, is param 1 < param 2 in phpgw
versionspeak?
@param $a phpgw version number to check if less than $b
@param $b phpgw version number to check $a against
- #return True if $a < $b
+ #return true if $a < $b
*/
- function alessthanb($a,$b,$DEBUG=False)
+ function alessthanb($a,$b,$DEBUG=false)
{
$num = array('1st','2nd','3rd','4th');
@@ -920,8 +1149,8 @@
echo'<br>Input values: '
. 'A="'.$a.'", B="'.$b.'"';
}
- $newa = ereg_replace('pre','.',$a);
- $newb = ereg_replace('pre','.',$b);
+ $newa = str_replace('pre','.',$a);
+ $newb = str_replace('pre','.',$b);
$testa = explode('.',$newa);
if(@$testa[1] == '')
{
@@ -979,17 +1208,17 @@
if ($less>0)
{
if ($DEBUG) { echo '<br>A is less than B'; }
- return True;
+ return true;
}
elseif($less<0)
{
if ($DEBUG) { echo '<br>A is greater than B'; }
- return False;
+ return false;
}
else
{
if ($DEBUG) { echo '<br>A is equal to B'; }
- return False;
+ return false;
}
}
@@ -998,9 +1227,9 @@
@abstract phpgw version checking, is param 1 > param 2 in phpgw
versionspeak?
@param $a phpgw version number to check if more than $b
@param $b phpgw version number to check $a against
- #return True if $a < $b
+ #return true if $a < $b
*/
- function amorethanb($a,$b,$DEBUG=False)
+ function amorethanb($a,$b,$DEBUG=false)
{
$num = array('1st','2nd','3rd','4th');
@@ -1009,8 +1238,8 @@
echo'<br>Input values: '
. 'A="'.$a.'", B="'.$b.'"';
}
- $newa = ereg_replace('pre','.',$a);
- $newb = ereg_replace('pre','.',$b);
+ $newa = str_replace('pre','.',$a);
+ $newb = str_replace('pre','.',$b);
$testa = explode('.',$newa);
if($testa[3] == '')
{
@@ -1060,17 +1289,17 @@
if ($less>0)
{
if ($DEBUG) { echo '<br>A is greater than B'; }
- return True;
+ return true;
}
elseif($less<0)
{
if ($DEBUG) { echo '<br>A is less than B'; }
- return False;
+ return false;
}
else
{
if ($DEBUG) { echo '<br>A is equal to B'; }
- return False;
+ return false;
}
}
@@ -1079,3 +1308,48 @@
return ($_SERVER['HTTP_X_FORWARDED_FOR'] ?
$_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
}
+ function make2digit($num = '')
+ {
+ return sprintf('%02d',$num);
+ }
+
+ function gmtime()
+ {
+ return gmdate('U');
+ }
+
+ function phpgw_getdate($date = NOTSET)
+ {
+ if($date == NOTSET)
+ {
+ $result = getdate(gmtime());
+ }
+ else
+ {
+ $result = getdate($date);
+ }
+
+ $result['mon'] = make2digit($result['mon']);
+ $result['mday'] = make2digit($result['mday']);
+
+ $result['hours_ampm'] = $result['hours'];
+ if ($result['hours_ampm'] < 12)
+ {
+ $result['hours_ampm'] =
make2digit($result['hours_ampm']);
+ $result['ampm'] = ' AM';
+ }
+ elseif ($result['hours_ampm'] == 12)
+ {
+ $result['ampm'] = ' PM';
+ }
+ else
+ {
+ $result['hours_ampm'] = $result['hours_ampm'] - 12;
+ $result['ampm'] = ' PM';
+ }
+
+ $result['hours'] = make2digit($result['hours']);
+ $result['minutes'] = make2digit($result['minutes']);
+ $result['seconds'] = make2digit($result['seconds']);
+ return $result;
+ }
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [Phpgroupware-cvs] api/core_functions.inc.php, 1.1.1.1.2.21,
nomail <=