*/
function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
{
global $_DB_DATAOBJECT;
if ($obj === false) {
$this->_join = '';
return;
}
//echo ''; print_r(func_get_args());
$useWhereAsOn = false;
// support for 2nd argument as an array of options
if (is_array($joinType)) {
// new options can now go in here... (dont forget to document them)
$useWhereAsOn = !empty($joinType['useWhereAsOn']);
$joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
$joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
$joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
}
// support for array as first argument
// this assumes that you dont have a links.ini for the specified table.
// and it doesnt exist as am extended dataobject!! - experimental.
$ofield = false; // object field
$tfield = false; // this field
$toTable = false;
if (is_array($obj)) {
$tfield = $obj[0];
if (count($obj) == 3) {
$ofield = $obj[2];
$obj = $obj[1];
} else {
list($toTable,$ofield) = explode(':',$obj[1]);
$obj = is_string($toTable) ? DB_DataObject::factory($toTable) : $toTable;
if (!$obj || !is_object($obj) || is_a($obj,'PEAR_Error')) {
$obj = new DB_DataObject;
$obj->__table = $toTable;
}
$obj->_connect();
}
// set the table items to nothing.. - eg. do not try and match
// things in the child table...???
$items = array();
}
if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
}
/* make sure $this->_database is set. */
$this->_connect();
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
/// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
/* otherwise see if there are any links from this table to the obj. */
//print_r($this->links());
if (($ofield === false) && ($links = $this->links())) {
// this enables for support for arrays of links in ini file.
// link contains this_column[] = linked_table:linked_column
// or standard way.
// link contains this_column = linked_table:linked_column
foreach ($links as $k => $linkVar) {
if (!is_array($linkVar)) {
$linkVar = array($linkVar);
}
foreach($linkVar as $v) {
/* link contains {this column} = {linked table}:{linked column} */
$ar = explode(':', $v);
// Feature Request #4266 - Allow joins with multiple keys
if (strpos($k, ',') !== false) {
$k = explode(',', $k);
}
if (strpos($ar[1], ',') !== false) {
$ar[1] = explode(',', $ar[1]);
}
if ($ar[0] != $obj->tableName()) {
continue;
}
if ($joinCol !== false) {
if ($k == $joinCol) {
// got it!?
$tfield = $k;
$ofield = $ar[1];
break;
}
continue;
}
$tfield = $k;
$ofield = $ar[1];
break;
}
}
}
/* look up the links for obj table */
//print_r($obj->links());
if (!$ofield && ($olinks = $obj->links())) {
foreach ($olinks as $k => $linkVar) {
/* link contains {this column} = array ( {linked table}:{linked column} )*/
if (!is_array($linkVar)) {
$linkVar = array($linkVar);
}
foreach($linkVar as $v) {
/* link contains {this column} = {linked table}:{linked column} */
$ar = explode(':', $v);
// Feature Request #4266 - Allow joins with multiple keys
$links_key_array = strpos($k,',');
if ($links_key_array !== false) {
$k = explode(',', $k);
}
$ar_array = strpos($ar[1],',');
if ($ar_array !== false) {
$ar[1] = explode(',', $ar[1]);
}
if ($ar[0] != $this->tableName()) {
continue;
}
// you have explictly specified the column
// and the col is listed here..
// not sure if 1:1 table could cause probs here..
if ($joinCol !== false) {
$this->raiseError(
"joinAdd: You cannot target a join column in the " .
"'link from' table ({$obj->tableName()}). " .
"Either remove the fourth argument to joinAdd() ".
"({$joinCol}), or alter your links.ini file.",
DB_DATAOBJECT_ERROR_NODATA);
return false;
}
$ofield = $k;
$tfield = $ar[1];
break;
}
}
}
// finally if these two table have column names that match do a join by default on them
if (($ofield === false) && $joinCol) {
$ofield = $joinCol;
$tfield = $joinCol;
}
/* did I find a conneciton between them? */
if ($ofield === false) {
$this->raiseError(
"joinAdd: {$obj->tableName()} has no link with {$this->tableName()}",
DB_DATAOBJECT_ERROR_NODATA);
return false;
}
$joinType = strtoupper($joinType);
// we default to joining as the same name (this is remvoed later..)
if ($joinAs === false) {
$joinAs = $obj->tableName();
}
$quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
$options = $_DB_DATAOBJECT['CONFIG'];
// not sure how portable adding database prefixes is..
$objTable = $quoteIdentifiers ?
$DB->quoteIdentifier($obj->tableName()) :
$obj->tableName() ;
$dbPrefix = '';
if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
$dbPrefix = ($quoteIdentifiers
? $DB->quoteIdentifier($obj->_database)
: $obj->_database) . '.';
}
// if they are the same, then dont add a prefix...
if ($obj->_database == $this->_database) {
$dbPrefix = '';
}
// as far as we know only mysql supports database prefixes..
// prefixing the database name is now the default behaviour,
// as it enables joining mutiple columns from multiple databases...
// prefix database (quoted if neccessary..)
$objTable = $dbPrefix . $objTable;
$cond = '';
// if obj only a dataobject - eg. no extended class has been defined..
// it obvioulsy cant work out what child elements might exist...
// until we get on the fly querying of tables..
// note: we have already checked that it is_a(db_dataobject earlier)
if ( strtolower(get_class($obj)) != 'db_dataobject') {
// now add where conditions for anything that is set in the object
$items = $obj->table();
// will return an array if no items..
// only fail if we where expecting it to work (eg. not joined on a array)
if (!$items) {
$this->raiseError(
"joinAdd: No table definition for {$obj->tableName()}",
DB_DATAOBJECT_ERROR_INVALIDCONFIG);
return false;
}
$ignore_null = !isset($options['disable_null_strings'])
|| !is_string($options['disable_null_strings'])
|| strtolower($options['disable_null_strings']) !== 'full' ;
foreach($items as $k => $v) {
if (!isset($obj->$k) && $ignore_null) {
continue;
}
$kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
if (DB_DataObject::_is_null($obj,$k)) {
$obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
continue;
}
if ($v & DB_DATAOBJECT_STR) {
$obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
($v & DB_DATAOBJECT_BOOL) ?
// this is thanks to the braindead idea of postgres to
// use t/f for boolean.
(($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
$obj->$k
)));
continue;
}
if (is_numeric($obj->$k)) {
$obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
continue;
}
if (is_object($obj->$k) && is_a($obj->$k,'DB_DataObject_Cast')) {
$value = $obj->$k->toString($v,$DB);
if (PEAR::isError($value)) {
$this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
return false;
}
$obj->whereAdd("{$joinAs}.{$kSql} = $value");
continue;
}
/* this is probably an error condition! */
$obj->whereAdd("{$joinAs}.{$kSql} = 0");
}
if ($this->_query === false) {
$this->raiseError(
"joinAdd can not be run from a object that has had a query run on it,
clone the object or create a new one and use setFrom()",
DB_DATAOBJECT_ERROR_INVALIDARGS);
return false;
}
}
// and finally merge the whereAdd from the child..
if ($obj->_query['condition']) {
$cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
if (!$useWhereAsOn) {
$this->whereAdd($cond);
}
}
// nested (join of joined objects..)
$appendJoin = '';
if ($obj->_join) {
// postgres allows nested queries, with ()'s
// not sure what the results are with other databases..
// may be unpredictable..
if (in_array($DB->dsn["phptype"],array('pgsql'))) {
$objTable = "($objTable {$obj->_join})";
} else {
$appendJoin = $obj->_join;
}
}
// fix for #2216
// add the joinee object's conditions to the ON clause instead of the WHERE clause
if ($useWhereAsOn && strlen($cond)) {
$appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
}
$table = $this->tableName();
if ($quoteIdentifiers) {
$joinAs = $DB->quoteIdentifier($joinAs);
$table = $DB->quoteIdentifier($table);
$ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
$tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
}
// add database prefix if they are different databases
$fullJoinAs = '';
$addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->tableName()) : $obj->tableName()) != $joinAs;
if ($addJoinAs) {
// join table a AS b - is only supported by a few databases and is probably not needed
// , however since it makes the whole Statement alot clearer we are leaving it in
// for those databases.
$fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
} else {
// if
$joinAs = $dbPrefix . $joinAs;
}
switch ($joinType) {
case 'INNER':
case 'LEFT':
case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
// Feature Request #4266 - Allow joins with multiple keys
$jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
//$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
if (is_array($ofield)) {
$key_count = count($ofield);
for($i = 0; $i < $key_count; $i++) {
if ($i == 0) {
$jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
}
else {
$jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
}
}
$jadd .= ' ' . $appendJoin . ' ';
} else {
$jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
}
// jadd avaliable for debugging join build.
//echo $jadd ."\n";
$this->_join .= $jadd;
break;
case '': // this is just a standard multitable select..
$this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
$this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
}
return true;
}
/**
* autoJoin - using the links.ini file, it builds a query with all the joins
* usage:
* $x = DB_DataObject::factory('mytable');
* $x->autoJoin();
* $x->get(123);
* will result in all of the joined data being added to the fetched object..
*
* $x = DB_DataObject::factory('mytable');
* $x->autoJoin();
* $ar = $x->fetchAll();
* will result in an array containing all the data from the table, and any joined tables..
*
* $x = DB_DataObject::factory('mytable');
* $jdata = $x->autoJoin();
* $x->selectAdd(); //reset..
* foreach($_REQUEST['requested_cols'] as $c) {
* if (!isset($jdata[$c])) continue; // ignore columns not available..
* $x->selectAdd( $jdata[$c] . ' as ' . $c);
* }
* $ar = $x->fetchAll();
* will result in only the columns requested being fetched...
*
*
*
* @param array Configuration
* exclude Array of columns to exclude from results (eg. modified_by_id)
* links The equivilant links.ini data for this table eg.
* array( 'person_id' => 'person:id', .... )
* include Array of columns to include
* distinct Array of distinct columns.
*
* @return array info about joins
* cols => map of resulting {joined_tablename}.{joined_table_column_name}
* join_names => map of resulting {join_name_as}.{joined_table_column_name}
* count => the column to count on.
* @access public
*/
function autoJoin($cfg = array())
{
global $_DB_DATAOBJECT;
//var_Dump($cfg);exit;
$pre_links = $this->links();
if (!empty($cfg['links'])) {
$this->links(array_merge( $pre_links , $cfg['links']));
}
$map = $this->links( );
$this->databaseStructure();
$dbstructure = $_DB_DATAOBJECT['INI'][$this->_database];
//print_r($map);
$tabdef = $this->table();
// we need this as normally it's only cleared by an empty selectAs call.
$keys = array_keys($tabdef);
if (!empty($cfg['exclude'])) {
$keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
}
if (!empty($cfg['include'])) {
$keys = array_intersect($keys, $cfg['include']);
}
$selectAs = array();
if (!empty($keys)) {
$selectAs = array(array( $keys , '%s', false));
}
$ret = array(
'cols' => array(),
'join_names' => array(),
'count' => false,
);
$has_distinct = false;
if (!empty($cfg['distinct']) && $keys) {
// reset the columsn?
$cols = array();
//echo '' ;print_r($xx);exit;
foreach($keys as $c) {
//var_dump($c);
if ( $cfg['distinct'] == $c) {
$has_distinct = 'DISTINCT( ' . $this->tableName() .'.'. $c .') as ' . $c;
$ret['count'] = 'DISTINCT ' . $this->tableName() .'.'. $c .'';
continue;
}
// cols is in our filtered keys...
$cols = $c;
}
// apply our filtered version, which excludes the distinct column.
$selectAs = empty($cols) ? array() : array(array(array( $cols) , '%s', false)) ;
}
foreach($keys as $k) {
$ret['cols'][$k] = $this->tableName(). '.' . $k;
}
foreach($map as $ocl=>$info) {
list($tab,$col) = explode(':', $info);
// what about multiple joins on the same table!!!
// if links point to a table that does not exist - ignore.
if (!isset($dbstructure[$tab])) {
continue;
}
$xx = DB_DataObject::factory($tab);
if (!is_object($xx) || !is_a($xx, 'DB_DataObject')) {
continue;
}
// skip columns that are excluded.
// we ignore include here... - as
// this is borked ... for multiple jions..
$this->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
if (!empty($cfg['exclude']) && in_array($ocl, $cfg['exclude'])) {
continue;
}
$tabdef = $xx->table();
$table = $xx->tableName();
$keys = array_keys($tabdef);
if (!empty($cfg['exclude'])) {
$keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
foreach($keys as $k) {
if (in_array($ocl.'_'.$k, $cfg['exclude'])) {
$keys = array_diff($keys, $k); // removes the k..
}
}
}
if (!empty($cfg['include'])) {
// include will basically be BASECOLNAME_joinedcolname
$nkeys = array();
foreach($keys as $k) {
if (in_array( sprintf($ocl.'_%s', $k), $cfg['include'])) {
$nkeys[] = $k;
}
}
$keys = $nkeys;
}
if (empty($keys)) {
continue;
}
// got distinct, and not yet found it..
if (!$has_distinct && !empty($cfg['distinct'])) {
$cols = array();
foreach($keys as $c) {
$tn = sprintf($ocl.'_%s', $c);
if ( $tn == $cfg['distinct']) {
$has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$c .') as ' . $tn ;
$ret['count'] = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$c;
// var_dump($this->countWhat );
continue;
}
$cols[] = $c;
}
if (!empty($cols)) {
$selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
}
} else {
$selectAs[] = array($keys, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
}
foreach($keys as $k) {
$ret['cols'][sprintf('%s_%s', $ocl, $k)] = $tab.'.'.$k;
$ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s',$ocl, $col, $k);
}
}
// fill in the select details..
$this->selectAdd();
if ($has_distinct) {
$this->selectAdd($has_distinct);
}
foreach($selectAs as $ar) {
$this->selectAs($ar[0], $ar[1], $ar[2]);
}
// restore links..
$this->links( $pre_links );
return $ret;
}
/**
* Factory method for calling DB_DataObject_Cast
*
* if used with 1 argument DB_DataObject_Cast::sql($value) is called
*
* if used with 2 arguments DB_DataObject_Cast::$value($callvalue) is called
* valid first arguments are: blob, string, date, sql
*
* eg. $member->updated = $member->sqlValue('NOW()');
*
*
* might handle more arguments for escaping later...
*
*
* @param string $value (or type if used with 2 arguments)
* @param string $callvalue (optional) used with date/null etc..
*/
function sqlValue($value)
{
$method = 'sql';
if (func_num_args() == 2) {
$method = $value;
$value = func_get_arg(1);
}
require_once 'DB/DataObject/Cast.php';
return call_user_func(array('DB_DataObject_Cast', $method), $value);
}
/**
* Copies items that are in the table definitions from an
* array or object into the current object
* will not override key values.
*
*
* @param array | object $from
* @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
* @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
* @access public
* @return true on success or array of key=>setValue error message
*/
function setFrom($from, $format = '%s', $skipEmpty=false)
{
global $_DB_DATAOBJECT;
$keys = $this->keys();
$items = $this->table();
if (!$items) {
$this->raiseError(
"setFrom:Could not find table definition for {$this->tableName()}",
DB_DATAOBJECT_ERROR_INVALIDCONFIG);
return;
}
$overload_return = array();
foreach (array_keys($items) as $k) {
if (in_array($k,$keys)) {
continue; // dont overwrite keys
}
if (!$k) {
continue; // ignore empty keys!!! what
}
$chk = is_object($from) &&
(version_compare(phpversion(), "5.1.0" , ">=") ?
property_exists($from, sprintf($format,$k)) : // php5.1
array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
);
// if from has property ($format($k)
if ($chk) {
$kk = (strtolower($k) == 'from') ? '_from' : $k;
if (method_exists($this,'set'.$kk)) {
$ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
if (is_string($ret)) {
$overload_return[$k] = $ret;
}
continue;
}
$this->$k = $from->{sprintf($format,$k)};
continue;
}
if (is_object($from)) {
continue;
}
if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
continue;
}
if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
continue;
}
$kk = (strtolower($k) == 'from') ? '_from' : $k;
if (method_exists($this,'set'. $kk)) {
$ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
if (is_string($ret)) {
$overload_return[$k] = $ret;
}
continue;
}
$val = $from[sprintf($format,$k)];
if (is_a($val, 'DB_DataObject_Cast')) {
$this->$k = $val;
continue;
}
if (is_object($val) || is_array($val)) {
continue;
}
$ret = $this->fromValue($k,$val);
if ($ret !== true) {
$overload_return[$k] = 'Not A Valid Value';
}
//$this->$k = $from[sprintf($format,$k)];
}
if ($overload_return) {
return $overload_return;
}
return true;
}
/**
* Returns an associative array from the current data
* (kind of oblivates the idea behind DataObjects, but
* is usefull if you use it with things like QuickForms.
*
* you can use the format to return things like user[key]
* by sending it $object->toArray('user[%s]')
*
* will also return links converted to arrays.
*
* @param string sprintf format for array
* @param bool||number [true = elemnts that have a value set],
* [false = table + returned colums] ,
* [0 = returned columsn only]
*
* @access public
* @return array of key => value for row
*/
function toArray($format = '%s', $hideEmpty = false)
{
global $_DB_DATAOBJECT;
// we use false to ignore sprintf.. (speed up..)
$format = $format == '%s' ? false : $format;
$ret = array();
$rf = ($this->_resultFields !== false) ? $this->_resultFields :
(isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
$_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
$ar = ($rf !== false) ?
(($hideEmpty === 0) ? $rf : array_merge($rf, $this->table())) :
$this->table();
foreach($ar as $k=>$v) {
if (!isset($this->$k)) {
if (!$hideEmpty) {
$ret[$format === false ? $k : sprintf($format,$k)] = '';
}
continue;
}
// call the overloaded getXXXX() method. - except getLink and getLinks
if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
$ret[$format === false ? $k : sprintf($format,$k)] = $this->{'get'.$k}();
continue;
}
// should this call toValue() ???
$ret[$format === false ? $k : sprintf($format,$k)] = $this->$k;
}
if (!$this->_link_loaded) {
return $ret;
}
foreach($this->_link_loaded as $k) {
$ret[$format === false ? $k : sprintf($format,$k)] = $this->$k->toArray();
}
return $ret;
}
/**
* validate the values of the object (usually prior to inserting/updating..)
*
* Note: This was always intended as a simple validation routine.
* It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
*
* This should be moved to another class: DB_DataObject_Validate
* FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
*
* Usage:
* if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
*
* Logic:
* - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
* - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
* These methods should return
* true = everything ok
* false|object = something is wrong!
*
* - This method loads and uses the PEAR Validate Class.
*
*
* @access public
* @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
*/
function validate()
{
global $_DB_DATAOBJECT;
require_once 'Validate.php';
$table = $this->table();
$ret = array();
$seq = $this->sequenceKey();
$options = $_DB_DATAOBJECT['CONFIG'];
foreach($table as $key => $val) {
// call user defined validation always...
$method = "Validate" . ucfirst($key);
if (method_exists($this, $method)) {
$ret[$key] = $this->$method();
continue;
}
// if not null - and it's not set.......
if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
// dont check empty sequence key values..
if (($key == $seq[0]) && ($seq[1] == true)) {
continue;
}
$ret[$key] = false;
continue;
}
if (DB_DataObject::_is_null($this, $key)) {
if ($val & DB_DATAOBJECT_NOTNULL) {
$this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
$ret[$key] = false;
continue;
}
continue;
}
// ignore things that are not set. ?
if (!isset($this->$key)) {
continue;
}
// if the string is empty.. assume it is ok..
if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
continue;
}
// dont try and validate cast objects - assume they are problably ok..
if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
continue;
}
// at this point if you have set something to an object, and it's not expected
// the Validate will probably break!!... - rightly so! (your design is broken,
// so issuing a runtime error like PEAR_Error is probably not appropriate..
switch (true) {
// todo: date time.....
case ($val & DB_DATAOBJECT_STR):
$ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
continue;
case ($val & DB_DATAOBJECT_INT):
$ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
continue;
}
}
// if any of the results are false or an object (eg. PEAR_Error).. then return the array..
foreach ($ret as $key => $val) {
if ($val !== true) {
return $ret;
}
}
return true; // everything is OK.
}
/**
* Gets the DB object related to an object - so you can use funky peardb stuf with it :)
*
* @access public
* @return object The DB connection
*/
function getDatabaseConnection()
{
global $_DB_DATAOBJECT;
if (($e = $this->_connect()) !== true) {
return $e;
}
if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
$r = false;
return $r;
}
return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
}
/**
* Gets the DB result object related to the objects active query
* - so you can use funky pear stuff with it - like pager for example.. :)
*
* @access public
* @return object The DB result object
*/
function getDatabaseResult()
{
global $_DB_DATAOBJECT;
$this->_connect();
if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
$r = false;
return $r;
}
return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
}
/**
* Overload Extension support
* - enables setCOLNAME/getCOLNAME
* if you define a set/get method for the item it will be called.
* otherwise it will just return/set the value.
* NOTE this currently means that a few Names are NO-NO's
* eg. links,link,linksarray, from, Databaseconnection,databaseresult
*
* note
* - set is automatically called by setFrom.
* - get is automatically called by toArray()
*
* setters return true on success. = strings on failure
* getters return the value!
*
* this fires off trigger_error - if any problems.. pear_error,
* has problems with 4.3.2RC2 here
*
* @access public
* @return true?
* @see overload
*/
function _call($method,$params,&$return) {
//$this->debug("ATTEMPTING OVERLOAD? $method");
// ignore constructors : - mm
if (strtolower($method) == strtolower(get_class($this))) {
return true;
}
$type = strtolower(substr($method,0,3));
$class = get_class($this);
if (($type != 'set') && ($type != 'get')) {
return false;
}
// deal with naming conflick of setFrom = this is messy ATM!
if (strtolower($method) == 'set_from') {
$return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
return true;
}
$element = substr($method,3);
// dont you just love php's case insensitivity!!!!
$array = array_keys(get_class_vars($class));
/* php5 version which segfaults on 5.0.3 */
if (class_exists('ReflectionClass')) {
$reflection = new ReflectionClass($class);
$array = array_keys($reflection->getdefaultProperties());
}
if (!in_array($element,$array)) {
// munge case
foreach($array as $k) {
$case[strtolower($k)] = $k;
}
if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
$element = strtolower($element);
}
// does it really exist?
if (!isset($case[$element])) {
return false;
}
// use the mundged case
$element = $case[$element]; // real case !
}
if ($type == 'get') {
$return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
return true;
}
$return = $this->fromValue($element, $params[0]);
return true;
}
/**
* standard set* implementation.
*
* takes data and uses it to set dates/strings etc.
* normally called from __call..
*
* Current supports
* date = using (standard time format, or unixtimestamp).... so you could create a method :
* function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
*
* time = using strtotime
* datetime = using same as date - accepts iso standard or unixtimestamp.
* string = typecast only..
*
* TODO: add formater:: eg. d/m/Y for date! ???
*
* @param string column of database
* @param mixed value to assign
*
* @return true| false (False on error)
* @access public
* @see DB_DataObject::_call
*/
function fromValue($col,$value)
{
global $_DB_DATAOBJECT;
$options = $_DB_DATAOBJECT['CONFIG'];
$cols = $this->table();
// dont know anything about this col..
if (!isset($cols[$col]) || is_a($value, 'DB_DataObject_Cast')) {
$this->$col = $value;
return true;
}
//echo "FROM VALUE $col, {$cols[$col]}, $value\n";
switch (true) {
// set to null and column is can be null...
case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
$this->$col = $value;
return true;
// fail on setting null on a not null field..
case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
return false;
case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
// empty values get set to '' (which is inserted/updated as NULl
if (!$value) {
$this->$col = '';
}
if (is_numeric($value)) {
$this->$col = date('Y-m-d H:i:s', $value);
return true;
}
// eak... - no way to validate date time otherwise...
$this->$col = (string) $value;
return true;
case ($cols[$col] & DB_DATAOBJECT_DATE):
// empty values get set to '' (which is inserted/updated as NULl
if (!$value) {
$this->$col = '';
return true;
}
if (is_numeric($value)) {
$this->$col = date('Y-m-d',$value);
return true;
}
// try date!!!!
require_once 'Date.php';
$x = new Date($value);
$this->$col = $x->format("%Y-%m-%d");
return true;
case ($cols[$col] & DB_DATAOBJECT_TIME):
// empty values get set to '' (which is inserted/updated as NULl
if (!$value) {
$this->$col = '';
}
$guess = strtotime($value);
if ($guess != -1) {
$this->$col = date('H:i:s', $guess);
return $return = true;
}
// otherwise an error in type...
return false;
case ($cols[$col] & DB_DATAOBJECT_STR):
$this->$col = (string) $value;
return true;
// todo : floats numerics and ints...
default:
$this->$col = $value;
return true;
}
}
/**
* standard get* implementation.
*
* with formaters..
* supported formaters:
* date/time : %d/%m/%Y (eg. php strftime) or pear::Date
* numbers : %02d (eg. sprintf)
* NOTE you will get unexpected results with times like 0000-00-00 !!!
*
*
*
* @param string column of database
* @param format foramt
*
* @return true Description
* @access public
* @see DB_DataObject::_call(),strftime(),Date::format()
*/
function toValue($col,$format = null)
{
if (is_null($format)) {
return $this->$col;
}
$cols = $this->table();
switch (true) {
case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
if (!$this->$col) {
return '';
}
$guess = strtotime($this->$col);
if ($guess != -1) {
return strftime($format, $guess);
}
// eak... - no way to validate date time otherwise...
return $this->$col;
case ($cols[$col] & DB_DATAOBJECT_DATE):
if (!$this->$col) {
return '';
}
$guess = strtotime($this->$col);
if ($guess != -1) {
return strftime($format,$guess);
}
// try date!!!!
require_once 'Date.php';
$x = new Date($this->$col);
return $x->format($format);
case ($cols[$col] & DB_DATAOBJECT_TIME):
if (!$this->$col) {
return '';
}
$guess = strtotime($this->$col);
if ($guess > -1) {
return strftime($format, $guess);
}
// otherwise an error in type...
return $this->$col;
case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
if (!$this->$col) {
return '';
}
require_once 'Date.php';
$x = new Date($this->$col);
return $x->format($format);
case ($cols[$col] & DB_DATAOBJECT_BOOL):
if ($cols[$col] & DB_DATAOBJECT_STR) {
// it's a 't'/'f' !
return ($this->$col === 't');
}
return (bool) $this->$col;
default:
return sprintf($format,$this->col);
}
}
/* ----------------------- Debugger ------------------ */
/**
* Debugger. - use this in your extended classes to output debugging information.
*
* Uses DB_DataObject::DebugLevel(x) to turn it on
*
* @param string $message - message to output
* @param string $logtype - bold at start
* @param string $level - output level
* @access public
* @return none
*/
function debug($message, $logtype = 0, $level = 1)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
(is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
return;
}
// this is a bit flaky due to php's wonderfull class passing around crap..
// but it's about as good as it gets..
$class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
if (!is_string($message)) {
$message = print_r($message,true);
}
if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
}
if (!ini_get('html_errors')) {
echo "$class : $logtype : $message\n";
flush();
return;
}
if (!is_string($message)) {
$message = print_r($message,true);
}
$colorize = ($logtype == 'ERROR') ? '' : '';
echo "{$colorize}$class: $logtype: ". nl2br(htmlspecialchars($message)) . "
\n";
}
/**
* sets and returns debug level
* eg. DB_DataObject::debugLevel(4);
*
* @param int $v level
* @access public
* @return none
*/
static function debugLevel($v = null)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
if ($v !== null) {
$r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
$_DB_DATAOBJECT['CONFIG']['debug'] = $v;
return $r;
}
return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
}
/**
* Last Error that has occured
* - use $this->_lastError or
* $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
*
* @access public
* @var object PEAR_Error (or false)
*/
var $_lastError = false;
/**
* Default error handling is to create a pear error, but never return it.
* if you need to handle errors you should look at setting the PEAR_Error callback
* this is due to the fact it would wreck havoc on the internal methods!
*
* @param int $message message
* @param int $type type
* @param int $behaviour behaviour (die or continue!);
* @access public
* @return error object
*/
function raiseError($message, $type = null, $behaviour = null)
{
global $_DB_DATAOBJECT;
if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
$behaviour = null;
}
$error = &PEAR::getStaticProperty('DB_DataObject','lastError');
// no checks for production here?....... - we log errors before we throw them.
DB_DataObject::debug($message,'ERROR',1);
if (PEAR::isError($message)) {
$error = $message;
} else {
require_once 'DB/DataObject/Error.php';
$dor = new PEAR();
$error = $dor->raiseError($message, $type, $behaviour,
$opts=null, $userinfo=null, 'DB_DataObject_Error'
);
}
// this will never work totally with PHP's object model.
// as this is passed on static calls (like staticGet in our case)
$_DB_DATAOBJECT['LASTERROR'] = $error;
if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
$this->_lastError = $error;
}
return $error;
}
/**
* Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
*
* After Profiling DB_DataObject, I discoved that the debug calls where taking
* considerable time (well 0.1 ms), so this should stop those calls happening. as
* all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
* THIS STILL NEEDS FURTHER INVESTIGATION
*
* @access public
* @return object an error object
*/
function _loadConfig()
{
global $_DB_DATAOBJECT;
$_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
}
/**
* Free global arrays associated with this object.
*
*
* @access public
* @return none
*/
function free()
{
global $_DB_DATAOBJECT;
if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
}
if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
}
// clear the staticGet cache as well.
$this->_clear_cache();
// this is a huge bug in DB!
if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
}
if (is_array($this->_link_loaded)) {
foreach ($this->_link_loaded as $do) {
if (
!empty($this->{$do}) &&
is_object($this->{$do}) &&
method_exists($this->{$do}, 'free')
) {
$this->{$do}->free();
}
}
}
}
/**
* Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
* If the value is a string set to "null" and the "disable_null_strings" option is not set to
* true, then the value is considered to be null.
* If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
* the value "full", then it will also be considered null. - this can not differenticate between not set
*
*
* @param object|array $obj_or_ar
* @param string|false $prop prperty
* @access private
* @return bool object
*/
function _is_null($obj_or_ar , $prop)
{
global $_DB_DATAOBJECT;
$isset = $prop === false ? isset($obj_or_ar) :
(is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
$value = $isset ?
($prop === false ? $obj_or_ar :
(is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
: null;
$options = $_DB_DATAOBJECT['CONFIG'];
$null_strings = !isset($options['disable_null_strings'])
|| $options['disable_null_strings'] === false;
$crazy_null = isset($options['disable_null_strings'])
&& is_string($options['disable_null_strings'])
&& strtolower($options['disable_null_strings'] === 'full');
if ( $null_strings && $isset && is_string($value) && (strtolower($value) === 'null') ) {
return true;
}
if ( $crazy_null && !$isset ) {
return true;
}
return false;
}
/**
* (deprecated - use ::get / and your own caching method)
*/
static function staticGet($class, $k, $v = null)
{
$lclass = strtolower($class);
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
$key = "$k:$v";
if ($v === null) {
$key = $k;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
}
if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
}
$obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
if (PEAR::isError($obj)) {
$dor = new DB_DataObject();
$dor->raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
$r = false;
return $r;
}
if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
$_DB_DATAOBJECT['CACHE'][$lclass] = array();
}
if (!$obj->get($k,$v)) {
$dor = new DB_DataObject();
$dor->raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
$r = false;
return $r;
}
$_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
}
/**
* autoload Class relating to a table
* (deprecited - use ::factory)
*
* @param string $table table
* @access private
* @return string classname on Success
*/
function staticAutoloadTable($table)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
$p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
$_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
$class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
$ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
$class = $ce ? $class : DB_DataObject::_autoloadClass($class);
return $class;
}
/* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
function _get_table() { return $this->table(); }
function _get_keys() { return $this->keys(); }
}
// technially 4.3.2RC1 was broken!!
// looks like 4.3.3 may have problems too....
if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
if (version_compare( phpversion(), "5") < 0) {
overload('DB_DataObject');
}
$GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
}
}