1
0
mirror of https://github.com/e107inc/e107.git synced 2025-01-18 05:09:05 +01:00
php-e107/e107_handlers/mysql_class.php

2923 lines
72 KiB
PHP
Raw Normal View History

<?php
2006-12-02 04:36:16 +00:00
/*
2008-12-10 16:59:19 +00:00
* e107 website system
*
2013-04-15 12:44:56 +02:00
* Copyright (C) 2008-2013 e107 Inc (e107.org)
2008-12-10 16:59:19 +00:00
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
2013-04-15 12:44:56 +02:00
* MySQL Handler
2008-12-10 16:59:19 +00:00
*
2006-12-02 04:36:16 +00:00
*/
/**
* MySQL Abstraction class
*
* @package e107
* @subpackage e107_handlers
* @todo separate cache for db type tables
*
* WARNING!!! System config should be DIRECTLY called inside db handler like this:
2011-05-01 16:35:57 +00:00
* e107::getConfig('core', false);
* FALSE (don't load) is critical important - if missed, expect dead loop (preference handler is calling db handler as well
* when data is initally loaded)
* Always use $this->getConfig() method to avoid issues pointed above
*/
/*
Parameters related to auto-generation of field definitions on db_Insert() and db_Update()
*/
define('ALLOW_AUTO_FIELD_DEFS', TRUE); // Temporary so new functionality can be disabled if it causes problems
// Uses it's own cache directory now - see e_CACHE_DB
//define('e_DB_CACHE', e_CACHE);
if(defined('MYSQL_LIGHT'))
{
define('E107_DEBUG_LEVEL', 0);
define('e_QUERY', '');
$path = (MYSQL_LIGHT !== true ? MYSQL_LIGHT : '');
require_once($path.'e107_config.php');
define('MPREFIX', $mySQLprefix);
$sql = new db;
$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);
}
2009-12-02 16:51:04 +00:00
elseif(defined('E107_INSTALL'))
{
define('E107_DEBUG_LEVEL', 0);
2009-12-02 16:51:04 +00:00
require('e107_config.php');
$sql_info = compact('mySQLserver', 'mySQLuser', 'mySQLpassword', 'mySQLdefaultdb', 'mySQLprefix');
e107::getInstance()->initInstallSql($sql_info);
$sql = new db;
$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);
}
else
{
if (!defined('e107_INIT')) { exit; }
}
2006-12-02 04:36:16 +00:00
$db_time = 0.0; // Global total time spent in all db object queries
$db_mySQLQueryCount = 0; // Global total number of db object queries (all db's)
$db_ConnectionID = NULL; // Stores ID for the first DB connection used - which should be the main E107 DB - then used as default
2006-12-02 04:36:16 +00:00
2016-02-14 12:15:55 -08:00
2010-02-19 09:27:43 +00:00
class e_db_mysql
{
// TODO switch to protected vars where needed
2016-02-12 19:28:35 -08:00
public $mySQLserver;
public $mySQLuser;
2016-02-12 19:28:35 -08:00
protected $mySQLpassword;
protected $mySQLdefaultdb;
protected $mySQLport = 3306;
2016-02-12 19:28:35 -08:00
public $mySQLPrefix;
protected $mySQLaccess;
public $mySQLresult;
public $mySQLrows;
public $mySQLerror = ''; // Error reporting mode - TRUE shows messages
protected $mySQLlastErrNum = 0; // Number of last error - now protected, use getLastErrorNumber()
protected $mySQLlastErrText = ''; // Text of last error - now protected, use getLastErrorText()
protected $mySQLlastQuery = '';
public $mySQLcurTable;
public $mySQLlanguage;
2016-02-12 19:28:35 -08:00
public $mySQLinfo;
public $tabset;
public $mySQLtableList = array(); // list of all Db tables.
public $mySQLtableListLanguage = array(); // Db table list for the currently selected language
public $mySQLtablelist = array();
protected $dbFieldDefs = array(); // Local cache - Field type definitions for _FIELD_DEFS and _NOTNULL arrays
2016-02-12 19:28:35 -08:00
public $mySQLcharset;
public $mySqlServerInfo = '?'; // Server info - needed for various things
2016-02-12 19:28:35 -08:00
public $total_results = false; // Total number of results
2016-02-12 19:28:35 -08:00
private $pdo = false; // using PDO or not.
private $pdoBind= false;
2006-12-02 04:36:16 +00:00
2006-12-02 04:36:16 +00:00
/**
* Constructor - gets language options from the cookie or session
2006-12-02 04:36:16 +00:00
* @access public
*/
public function __construct()
{
2009-12-02 16:51:04 +00:00
global $pref, $db_defaultPrefix;
2016-02-14 12:15:55 -08:00
if((PHP_MAJOR_VERSION > 6) || (defined('e_PDO') && e_PDO === true))
{
$this->pdo = true;
}
2009-12-02 16:51:04 +00:00
e107::getSingleton('e107_traffic')->BumpWho('Create db object', 1);
$this->mySQLPrefix = MPREFIX; // Set the default prefix - may be overridden
2009-12-02 16:51:04 +00:00
if($port = e107::getMySQLConfig('port'))
{
$this->mySQLport = intval($port);
}
2011-05-01 16:35:57 +00:00
/*$langid = (isset($pref['cookie_name'])) ? 'e107language_'.$pref['cookie_name'] : 'e107language_temp';
2009-09-17 00:13:40 +00:00
if (isset($pref['user_tracking']) && ($pref['user_tracking'] == 'session'))
{
if (!isset($_SESSION[$langid])) { return; }
$this->mySQLlanguage = $_SESSION[$langid];
}
else
{
if (!isset($_COOKIE[$langid])) { return; }
$this->mySQLlanguage = $_COOKIE[$langid];
2011-05-01 16:35:57 +00:00
}*/
// Detect is already done in language handler, use it if not too early
if(defined('e_LANGUAGE')) $this->mySQLlanguage = e107::getLanguage()->e_language;
2006-12-02 04:36:16 +00:00
}
function getPDO()
{
return $this->pdo;
}
2015-02-15 16:07:27 -08:00
function getMode()
{
$this->gen('SELECT @@sql_mode');
$row = $this->fetch();
return $row['@@sql_mode'];
}
2006-12-02 04:36:16 +00:00
/**
* Connects to mySQL server and selects database - generally not required if your table is in the main DB.<br />
* <br />
* Example using e107 database with variables defined in e107_config.php:<br />
* <code>$sql = new db;
* $sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);</code>
* <br />
* OR to connect an other database:<br />
* <code>$sql = new db;
* $sql->db_Connect('url_server_database', 'user_database', 'password_database', 'name_of_database');</code>
*
* @param string $mySQLserver IP Or hostname of the MySQL server
* @param string $mySQLuser MySQL username
* @param string $mySQLpassword MySQL Password
* @param string $mySQLdefaultdb The database schema to connect to
* @param string $newLink force a new link connection if TRUE. Default FALSE
* @param string $mySQLPrefix Tables prefix. Default to $mySQLPrefix from e107_config.php
* @return null|string error code
*/
public function db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb, $newLink = FALSE, $mySQLPrefix = MPREFIX)
{
global $db_ConnectionID, $db_defaultPrefix;
e107::getSingleton('e107_traffic')->BumpWho('db Connect', 1);
$this->mySQLserver = $mySQLserver;
$this->mySQLuser = $mySQLuser;
$this->mySQLpassword = $mySQLpassword;
$this->mySQLdefaultdb = $mySQLdefaultdb;
$this->mySQLPrefix = $mySQLPrefix;
$this->mySQLerror = false;
if($this->pdo)
{
if(strpos($mySQLserver,':')!==false)
{
list($this->mySQLserver,$this->mySQLport) = explode(':',$mySQLserver,2);
}
if($this->mySQLserver === 'localhost')
{
$this->mySQLserver = '127.0.0.1'; // faster by almost 1 second
}
try
{
$this->mySQLaccess = new PDO("mysql:host=".$this->mySQLserver."; port=".$this->mySQLport, $this->mySQLuser, $this->mySQLpassword, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $ex)
{
$this->mySQLlastErrText = $ex->getMessage();
$this->mySQLlastErrNum = $ex->getCode();
return 'e1';
}
}
elseif(defined("USE_PERSISTANT_DB") && USE_PERSISTANT_DB == TRUE)
{
// No persistent link parameter permitted
if ( ! $this->mySQLaccess = @mysql_pconnect($this->mySQLserver, $this->mySQLuser, $this->mySQLpassword))
{
$this->mySQLlastErrText = mysql_error();
return 'e1';
}
}
else
{
if ( ! $this->mySQLaccess = @mysql_connect($this->mySQLserver, $this->mySQLuser, $this->mySQLpassword, $newLink))
{
$this->mySQLlastErrText = mysql_error();
return 'e1';
}
}
2006-12-02 04:36:16 +00:00
$this->mySqlServerInfo = ($this->pdo) ? $this->mySQLaccess->query('select version()')->fetchColumn() : mysql_get_server_info(); // We always need this for db_Set_Charset() - so make generally available
2010-01-07 21:05:24 +00:00
// Set utf8 connection?
//@TODO: simplify when yet undiscovered side-effects will be fixed
$this->db_Set_Charset();
$this->setSQLMode();
// if ($this->pdo!== true && !@mysql_select_db($this->mySQLdefaultdb, $this->mySQLaccess))
if (!$this->database($this->mySQLdefaultdb))
{
return 'e2';
}
2006-12-02 04:36:16 +00:00
if($this->pdo == true)
{
// $this->mySQLaccess->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
2016-03-22 06:10:56 -07:00
// $this->mySQLaccess->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
}
$this->dbError('dbConnect/SelectDB');
// Save the connection resource
if ($db_ConnectionID == null)
{
$db_ConnectionID = $this->mySQLaccess;
}
return true;
2006-12-02 04:36:16 +00:00
}
/**
* Connect ONLY - used in v2.x
* @param string $mySQLserver IP Or hostname of the MySQL server
* @param string $mySQLuser MySQL username
* @param string $mySQLpassword MySQL Password
* @param string $mySQLdefaultdb The database schema to connect to
* @param string $newLink force a new link connection if TRUE. Default FALSE
* @param string $mySQLPrefix Tables prefix. Default to $mySQLPrefix from e107_config.php
* @return boolean true on success, false on error.
*/
public function connect($mySQLserver, $mySQLuser, $mySQLpassword, $newLink = false)
{
global $db_ConnectionID, $db_defaultPrefix;
e107::getSingleton('e107_traffic')->BumpWho('db Connect', 1);
$this->mySQLserver = $mySQLserver;
$this->mySQLuser = $mySQLuser;
$this->mySQLpassword = $mySQLpassword;
$this->mySQLerror = false;
if(strpos($mySQLserver,':')!==false)
{
list($this->mySQLserver,$this->mySQLport) = explode(':',$mySQLserver,2);
}
if($this->mySQLserver === 'localhost')
{
$this->mySQLserver = '127.0.0.1'; // faster by almost 1 second.
}
if($this->pdo) // PDO
{
try
{
$this->mySQLaccess = new PDO("mysql:host=".$this->mySQLserver."; port=".$this->mySQLport, $this->mySQLuser, $this->mySQLpassword, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $ex)
{
$this->mySQLlastErrText = $ex->getMessage();
$this->mySQLLastErrNum = $ex->getCode();
e107::getDebug()->log($ex); // Useful for Debug.
return false;
}
// $this->mySqlServerInfo = $this->mySQLaccess->getAttribute(PDO::ATTR_SERVER_INFO);
$this->mySqlServerInfo = $this->mySQLaccess->query('select version()')->fetchColumn();
}
else // Legacy.
{
if (!$this->mySQLaccess = @mysql_connect($this->mySQLserver, $this->mySQLuser, $this->mySQLpassword, $newLink))
{
$this->mySQLlastErrText = mysql_error();
return false;
}
$this->mySqlServerInfo = mysql_get_server_info();
}
$this->db_Set_Charset();
$this->setSQLMode();
if ($db_ConnectionID == NULL){ $db_ConnectionID = $this->mySQLaccess; }
return true;
}
/**
* Get Server Info
* @return mixed
*/
public function getServerInfo()
{
return $this->mySqlServerInfo;
}
/**
* Select the database to use.
* @param string database name
* @param string table prefix . eg. e107_
* @return boolean true when database selection was successful otherwise false.
*/
public function database($database, $prefix = MPREFIX)
{
$this->mySQLdefaultdb = $database;
$this->mySQLPrefix = $prefix;
if($this->pdo)
{
try
{
$this->mySQLaccess->query("use ".$database);
// $this->mySQLaccess->select_db($database); $dbh->query("use newdatabase");
}
catch (PDOException $e)
{
$this->mySQLlastErrText = $e->getMessage();
$this->mySQLlastErrNum = $e->getCode();
return false;
}
return true;
}
if (!@mysql_select_db($database, $this->mySQLaccess))
{
return false;
}
return true;
}
/**
* Get system config
* @return e_core_pref
*/
public function getConfig()
{
return e107::getConfig('core', false);
}
2006-12-02 04:36:16 +00:00
/**
* @return void
2016-05-01 09:30:33 -07:00
* @param string $sMarker
2006-12-02 04:36:16 +00:00
* @desc Enter description here...
* @access private
*/
function db_Mark_Time($sMarker)
{
if (E107_DEBUG_LEVEL > 0)
{
global $db_debug;
$db_debug->Mark_Time($sMarker);
}
2006-12-02 04:36:16 +00:00
}
2006-12-02 04:36:16 +00:00
/**
* @deprecated
2006-12-02 04:36:16 +00:00
* @return void
* @desc Enter description here...
* @access private
*/
2009-12-02 16:51:04 +00:00
function db_Show_Performance()
{
// e107::getDebug()-Show_P
// return $db_debug->Show_Performance();
2006-12-02 04:36:16 +00:00
}
2006-12-02 04:36:16 +00:00
/**
* @return void
* @desc add query to dblog table
* @access private
*/
2009-12-02 16:51:04 +00:00
function db_Write_log($log_type = '', $log_remark = '', $log_query = '')
{
2006-12-02 04:36:16 +00:00
global $tp, $e107;
list($time_usec, $time_sec) = explode(" ", microtime());
2006-12-02 04:36:16 +00:00
$uid = (USER) ? USERID : '0';
$userstring = ( USER === true ? USERNAME : "LAN_ANONYMOUS");
$ip = e107::getIPHandler()->getIP(FALSE);
2006-12-02 04:36:16 +00:00
$qry = $tp->toDB($log_query);
$this->insert('dblog', "0, {$time_sec}, {$time_usec}, '{$log_type}', 'DBDEBUG', {$uid}, '{$userstring}', '{$ip}', '', '{$log_remark}', '{$qry}'");
2006-12-02 04:36:16 +00:00
}
2006-12-02 04:36:16 +00:00
/**
* This is the 'core' routine which handles much of the interface between other functions and the DB
2009-12-02 16:51:04 +00:00
*
* If a SELECT query includes SQL_CALC_FOUND_ROWS, the value of FOUND_ROWS() is retrieved and stored in $this->total_results
2016-03-20 18:31:11 -07:00
* @param string|array $query
* @param string $query['PREPARE'] PDO Format query.
*@param array $query['BIND'] eg. array['my_field'] = array('value'=>'whatever', 'type'=>'str');
* @param unknown $rli
* @return boolean | resource - as mysql_query() function.
* FALSE indicates an error
* For SELECT, SHOW, DESCRIBE, EXPLAIN and others returning a result set, returns a resource
* TRUE indicates success in other cases
2006-12-02 04:36:16 +00:00
*/
2009-12-02 16:51:04 +00:00
public function db_Query($query, $rli = NULL, $qry_from = '', $debug = FALSE, $log_type = '', $log_remark = '')
{
global $db_time,$db_mySQLQueryCount,$queryinfo;
2006-12-02 04:36:16 +00:00
$db_mySQLQueryCount++;
2010-02-19 09:27:43 +00:00
$this->mySQLlastQuery = $query;
2006-12-02 04:36:16 +00:00
2009-12-02 16:51:04 +00:00
if ($debug == 'now')
{
2013-10-16 18:13:21 +03:00
echo "<pre>** $query</pre><br />\n";
2006-12-02 04:36:16 +00:00
}
2011-11-25 17:36:40 +00:00
if ($debug !== FALSE || strstr($_SERVER['QUERY_STRING'], 'showsql'))
2006-12-02 04:36:16 +00:00
{
$queryinfo[] = "<b>{$qry_from}</b>: $query";
}
2009-12-02 16:51:04 +00:00
if ($log_type != '')
{
2006-12-02 04:36:16 +00:00
$this->db_Write_log($log_type, $log_remark, $query);
}
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
2006-12-02 04:36:16 +00:00
$b = microtime();
if($this->pdo)
{
2016-02-12 19:28:35 -08:00
2016-03-20 18:31:11 -07:00
if(is_array($query) && !empty($query['PREPARE']) && !empty($query['BIND']))
{
2016-03-20 18:31:11 -07:00
$prep = $this->mySQLaccess->prepare($query['PREPARE']);
foreach($query['BIND'] as $k=>$v)
{
$prep->bindValue(':'.$k, $v['value'],$v['type']);
}
try
{
$prep->execute();
$sQryRes = $prep->rowCount();
}
catch(PDOException $ex)
{
$sQryRes = false;
$this->mySQLlastErrText = $ex->getMessage();
$this->mySQLlastErrNum = $ex->getCode();
2016-03-20 18:31:11 -07:00
}
}
2016-03-20 18:31:11 -07:00
else
{
2016-03-20 18:31:11 -07:00
try
{
if(preg_match('#^(CREATE TABLE|DROP TABLE|ALTER TABLE|RENAME TABLE|CREATE DATABASE|CREATE INDEX)#',$query, $matches))
{
$sQryRes = is_null($rli) ? $this->mySQLaccess->exec($query) : $rli->exec($query);
if($sQryRes !==false)
{
$sQryRes = true; // match with non-PDO results.
}
}
else
{
$sQryRes = is_null($rli) ? $this->mySQLaccess->query($query) : $rli->query($query);
}
2016-03-22 06:10:56 -07:00
2016-03-20 18:31:11 -07:00
}
catch(PDOException $ex)
{
$sQryRes = false;
$this->mySQLlastErrText = $ex->getMessage();
$this->mySQLlastErrNum = $ex->getCode();
2016-03-20 18:31:11 -07:00
}
}
}
else
{
2016-08-01 12:50:48 -07:00
$sQryRes = is_null($rli) ? @mysql_query($query,$this->mySQLaccess) : @mysql_query($query, $rli);
$this->mySQLlastErrNum = mysql_errno();
$this->mySQLlastErrText = mysql_error();
}
2006-12-02 04:36:16 +00:00
$e = microtime();
e107::getSingleton('e107_traffic')->Bump('db_Query', $b, $e);
$mytime = e107::getSingleton('e107_traffic')->TimeDelta($b,$e);
2006-12-02 04:36:16 +00:00
$db_time += $mytime;
$this->mySQLresult = $sQryRes;
2016-03-29 14:55:38 -07:00
if (!E107_DEBUG_LEVEL)
{
$this->total_results = false;
}
// Need to get the total record count as well. Return code is a resource identifier
// Have to do this before any debug action, otherwise this bit gets messed up
2016-03-29 14:55:38 -07:00
if (!is_array($query) && (strpos($query,'EXPLAIN') !==0) && (strpos($query,'SQL_CALC_FOUND_ROWS') !== false) && (strpos($query,'SELECT') !== false))
{
2016-03-29 14:55:38 -07:00
if($this->pdo)
{
2016-03-29 14:55:38 -07:00
$rc = $this->mySQLaccess->query('SELECT FOUND_ROWS();')->fetch(PDO::FETCH_COLUMN);
$this->total_results = intval($rc);
}
else /* @XXX Subject of Removal. */
{
$fr = mysql_query('SELECT FOUND_ROWS()', $this->mySQLaccess);
$rc = mysql_fetch_array($fr);
$this->total_results = (int) $rc['FOUND_ROWS()'];
}
}
2009-12-02 16:51:04 +00:00
if (E107_DEBUG_LEVEL)
{
2006-12-02 04:36:16 +00:00
global $db_debug;
$aTrace = debug_backtrace();
$pTable = $this->mySQLcurTable;
if (!strlen($pTable)) {
$pTable = '(complex query)';
} else {
$this->mySQLcurTable = ''; // clear before next query
}
2009-12-02 16:51:04 +00:00
if(is_object($db_debug))
{
$buglink = is_null($rli) ? $this->mySQLaccess : $rli;
2016-03-20 18:31:11 -07:00
if($this->pdo == true)
2016-03-20 18:31:11 -07:00
{
if(is_array($query))
{
$query = "PREPARE: ".$query['PREPARE']."<br />BIND:".print_a($query['BIND'],true); // ,true);
}
if(isset($ex) && is_object($ex))
{
$query = $ex->getMessage();
$query .= print_a($ex->getTrace(),true);
}
2016-03-20 18:31:11 -07:00
}
// $query = var_export($query,true);
2016-02-12 19:28:35 -08:00
$db_debug->Mark_Query($query, $buglink, $sQryRes, $aTrace, $mytime, $pTable);
2009-12-02 16:51:04 +00:00
}
else
{
// echo "what happened to db_debug??!!<br />";
2006-12-02 04:36:16 +00:00
}
}
2016-03-20 18:31:11 -07:00
2006-12-02 04:36:16 +00:00
return $sQryRes;
}
/**
* Query and fetch at once
2015-02-15 02:37:36 -08:00
*
* Examples:
* <code>
* <?php
2015-02-15 02:37:36 -08:00
*
* // Get single value, $multi and indexField are ignored
* $string = e107::getDb()->retrieve('user', 'user_email', 'user_id=1');
2015-02-15 02:37:36 -08:00
*
* // Get single row set, $multi and indexField are ignored
* $array = e107::getDb()->retrieve('user', 'user_email, user_name', 'user_id=1');
2015-02-15 02:37:36 -08:00
*
* // Fetch all, don't append WHERE to the query, index by user_id, noWhere auto detected (string starts with upper case ORDER)
* $array = e107::getDb()->retrieve('user', 'user_id, user_email, user_name', 'ORDER BY user_email LIMIT 0,20', true, 'user_id');
2015-02-15 02:37:36 -08:00
*
* // Same as above but retrieve() is only used to fetch, not useable for single return value
* if(e107::getDb()->select('user', 'user_id, user_email, user_name', 'ORDER BY user_email LIMIT 0,20', true))
* {
2015-02-15 02:37:36 -08:00
* $array = e107::getDb()->retrieve(null, null, null, true, 'user_id');
* }
2015-02-15 02:37:36 -08:00
*
* // Using whole query example, in this case default mode is 'single'
* $array = e107::getDb()->retrieve('SELECT
* p.*, u.user_email, u.user_name FROM `#user` AS u
* LEFT JOIN `#myplug_table` AS p ON p.myplug_table=u.user_id
* ORDER BY u.user_email LIMIT 0,20'
* );
2015-02-15 02:37:36 -08:00
*
* // Using whole query example, multi mode - $fields argument mapped to $multi
* $array = e107::getDb()->retrieve('SELECT u.user_email, u.user_name FROM `#user` AS U ORDER BY user_email LIMIT 0,20', true);
2015-02-15 02:37:36 -08:00
*
* // Using whole query example, multi mode with index field
* $array = e107::getDb()->retrieve('SELECT u.user_email, u.user_name FROM `#user` AS U ORDER BY user_email LIMIT 0,20', null, null, true, 'user_id');
* </code>
2015-02-15 02:37:36 -08:00
*
* @param string $table if empty, enter fetch only mode
* @param string $fields comma separated list of fields or * or single field name (get one); if $fields is of type boolean and $where is not found, $fields overrides $multi
* @param string $where WHERE/ORDER/LIMIT etc clause, empty to disable
* @param boolean $multi if true, fetch all (multi mode)
* @param string $indexField field name to be used for indexing when in multi mode
* @param boolean $debug
2015-02-15 02:37:36 -08:00
* @return array
*/
public function retrieve($table, $fields = null, $where=null, $multi = false, $indexField = null, $debug = false)
{
// fetch mode
if(empty($table))
{
$ret = array();
if(!$multi) return $this->fetch();
while($row = $this->fetch())
{
if(null !== $indexField) $ret[$row[$indexField]] = $row;
else $ret[] = $row;
}
return $ret;
}
// detect mode
$mode = 'one';
if($table && !$where && is_bool($fields))
{
// table is the query, fields used for multi
if($fields) $mode = 'multi';
else $mode = 'single';
$fields = null;
}
elseif($fields && '*' !== $fields && strpos($fields, ',') === false && $where)
{
$mode = 'single';
}
if($multi)
{
$mode = 'multi';
}
// detect query type
$select = true;
$noWhere = false;
if(!$fields && !$where)
{
// gen()
$select = false;
if($mode == 'one') $mode = 'single';
}
// auto detect noWhere - if where string starts with upper case LATIN word
elseif(!$where || preg_match('/^[A-Z]+\S.*$/', trim($where)))
{
// FIXME - move auto detect to select()?
$noWhere = true;
}
// execute & fetch
switch ($mode)
{
case 'single':
if($select && !$this->select($table, $fields, $where, $noWhere, $debug))
{
return null;
}
elseif(!$select && !$this->gen($table, $debug))
{
return null;
}
2016-02-16 11:10:30 -08:00
$rows = $this->fetch();
return array_shift($rows);
break;
case 'one':
if($select && !$this->select($table, $fields, $where, $noWhere, $debug))
{
return array();
}
elseif(!$select && !$this->gen($table, $debug))
{
return array();
}
return $this->fetch();
break;
case 'multi':
if($select && !$this->select($table, $fields, $where, $noWhere, $debug))
{
return array();
}
elseif(!$select && !$this->gen($table, $debug))
{
return array();
}
$ret = array();
while($row = $this->fetch())
{
if(null !== $indexField) $ret[$row[$indexField]] = $row;
else $ret[] = $row;
}
return $ret;
break;
}
}
2006-12-02 04:36:16 +00:00
/**
* Perform a mysql_query() using the arguments suplied by calling db::db_Query()<br />
2006-12-02 04:36:16 +00:00
* <br />
* If you need more requests think to call the class.<br />
* <br />
* Example using a unique connection to database:<br />
* <code>e107::getDb()->select("comments", "*", "comment_item_id = '$id' AND comment_type = '1' ORDER BY comment_datestamp");</code><br />
2006-12-02 04:36:16 +00:00
* <br />
* OR as second connection:<br />
* <code>
* e107::getDb('sql2')->select("chatbox", "*", "ORDER BY cb_datestamp DESC LIMIT $from, ".$view, true);</code>
2006-12-02 04:36:16 +00:00
*
* @return integer Number of rows or false on error
2006-12-02 04:36:16 +00:00
*/
public function select($table, $fields = '*', $arg = '', $noWhere = false, $debug = FALSE, $log_type = '', $log_remark = '')
{
global $db_mySQLQueryCount;
2006-12-02 04:36:16 +00:00
$table = $this->db_IsLang($table);
2006-12-02 04:36:16 +00:00
$this->mySQLcurTable = $table;
2013-03-28 00:42:02 -07:00
if ($arg != '' && ($noWhere === false || $noWhere === 'default')) // 'default' for BC.
2006-12-02 04:36:16 +00:00
{
2009-12-02 16:51:04 +00:00
if ($this->mySQLresult = $this->db_Query('SELECT '.$fields.' FROM '.$this->mySQLPrefix.$table.' WHERE '.$arg, NULL, 'db_Select', $debug, $log_type, $log_remark))
{
2006-12-02 04:36:16 +00:00
$this->dbError('dbQuery');
return $this->rowCount();
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Select (SELECT $fields FROM ".$this->mySQLPrefix."{$table} WHERE {$arg})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
2009-12-02 16:51:04 +00:00
}
2013-03-28 00:42:02 -07:00
elseif ($arg != '' && ($noWhere !== false) && ($noWhere !== 'default')) // 'default' for BC.
{
2009-12-02 16:51:04 +00:00
if ($this->mySQLresult = $this->db_Query('SELECT '.$fields.' FROM '.$this->mySQLPrefix.$table.' '.$arg, NULL, 'db_Select', $debug, $log_type, $log_remark))
{
2006-12-02 04:36:16 +00:00
$this->dbError('dbQuery');
return $this->rowCount();
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Select (SELECT {$fields} FROM ".$this->mySQLPrefix."{$table} {$arg})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
2009-12-02 16:51:04 +00:00
}
else
{
2009-12-02 16:51:04 +00:00
if ($this->mySQLresult = $this->db_Query('SELECT '.$fields.' FROM '.$this->mySQLPrefix.$table, NULL, 'db_Select', $debug, $log_type, $log_remark))
{
2006-12-02 04:36:16 +00:00
$this->dbError('dbQuery');
return $this->rowCount();
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Select (SELECT {$fields} FROM ".$this->mySQLPrefix."{$table})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
}
}
/**
* select() alias
*
* @deprecated
*/
public function db_Select($table, $fields = '*', $arg = '', $mode = 'default', $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->select($table, $fields, $arg, $mode !== 'default', $debug, $log_type, $log_remark);
}
2006-12-02 04:36:16 +00:00
/**
* @return int Last insert ID or false on error. When using '_DUPLICATE_KEY_UPDATE' return ID, true on update, 0 on no change and false on error.
* @param string $tableName - Name of table to access, without any language or general DB prefix
* @param string/array $arg
2006-12-02 04:36:16 +00:00
* @param string $debug
* @desc Insert a row into the table<br />
* <br />
* Example:<br />
* <code>e107::getDb()->insert("links", "0, 'News', 'news.php', '', '', 1, 0, 0, 0");</code>
2006-12-02 04:36:16 +00:00
*
* @access public
*/
function insert($tableName, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
$table = $this->db_IsLang($tableName);
2006-12-02 04:36:16 +00:00
$this->mySQLcurTable = $table;
2010-02-19 09:27:43 +00:00
$REPLACE = false; // kill any PHP notices
$DUPEKEY_UPDATE = false;
2006-12-02 04:36:16 +00:00
if(is_array($arg))
{
2009-12-02 16:51:04 +00:00
if(isset($arg['WHERE'])) // use same array for update and insert.
{
unset($arg['WHERE']);
}
if(isset($arg['_REPLACE']))
{
$REPLACE = TRUE;
2009-12-02 16:51:04 +00:00
unset($arg['_REPLACE']);
}
2009-12-02 16:51:04 +00:00
if(isset($arg['_DUPLICATE_KEY_UPDATE']))
{
$DUPEKEY_UPDATE = true;
unset($arg['_DUPLICATE_KEY_UPDATE']);
}
if(!isset($arg['_FIELD_TYPES']) && !isset($arg['data']))
{
//Convert data if not using 'new' format
$_tmp = array();
$_tmp['data'] = $arg;
$arg = $_tmp;
unset($_tmp);
}
if(!isset($arg['data'])) { return false; }
// See if we need to auto-add field types array
if(!isset($arg['_FIELD_TYPES']) && ALLOW_AUTO_FIELD_DEFS)
{
$arg = array_merge($arg, $this->getFieldDefs($tableName));
}
$argUpdate = $arg; // used when DUPLICATE_KEY_UPDATE is active;
2016-03-20 18:31:11 -07:00
// Handle 'NOT NULL' fields without a default value
if (isset($arg['_NOTNULL']))
{
foreach ($arg['_NOTNULL'] as $f => $v)
{
if (!isset($arg['data'][$f]))
{
$arg['data'][$f] = $v;
}
}
}
2016-03-20 18:31:11 -07:00
$fieldTypes = $this->_getTypes($arg);
$keyList= '`'.implode('`,`', array_keys($arg['data'])).'`';
$tmp = array();
2016-03-20 18:31:11 -07:00
$bind = array();
foreach($arg['data'] as $fk => $fv)
{
2016-03-20 18:31:11 -07:00
$tmp[] = ($this->pdo == true) ? ':'.$fk : $this->_getFieldValue($fk, $fv, $fieldTypes);
$bind[$fk] = array('value'=>$this->_getPDOValue($fieldTypes[$fk],$fv), 'type'=> $this->_getPDOType($fieldTypes[$fk]));
}
2016-03-20 18:31:11 -07:00
$valList= implode(', ', $tmp);
2016-03-20 18:31:11 -07:00
unset($tmp);
2009-12-02 16:51:04 +00:00
2016-03-20 18:31:11 -07:00
if($REPLACE === false)
{
2009-12-02 16:51:04 +00:00
$query = "INSERT INTO `".$this->mySQLPrefix."{$table}` ({$keyList}) VALUES ({$valList})";
if($DUPEKEY_UPDATE === true)
{
$query .= " ON DUPLICATE KEY UPDATE ";
$query .= $this->_prepareUpdateArg($tableName, $argUpdate);
}
}
else
{
2009-12-02 16:51:04 +00:00
$query = "REPLACE INTO `".$this->mySQLPrefix."{$table}` ({$keyList}) VALUES ({$valList})";
}
2009-12-02 16:51:04 +00:00
2016-03-20 18:31:11 -07:00
if($this->pdo == true)
{
$query = array(
'PREPARE' => $query,
'BIND' => $bind,
);
}
2006-12-02 04:36:16 +00:00
}
else
{
$query = 'INSERT INTO '.$this->mySQLPrefix."{$table} VALUES ({$arg})";
2006-12-02 04:36:16 +00:00
}
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
2010-02-19 09:27:43 +00:00
2010-02-08 09:12:07 +00:00
$this->mySQLresult = $this->db_Query($query, NULL, 'db_Insert', $debug, $log_type, $log_remark);
2016-03-20 18:31:11 -07:00
if($DUPEKEY_UPDATE === true)
{
$result = false; // ie. there was an error.
if($this->pdo !== true)
{
$this->mySQLresult = mysql_affected_rows($this->mySQLaccess);
}
if($this->mySQLresult === 1 ) // insert.
{
$result = $this->lastInsertId();
}
elseif($this->mySQLresult === 2 || $this->mySQLresult === true) // updated
{
$result = true;
}
elseif($this->mySQLresult === 0) // updated (no change)
{
$result = 0;
}
$this->dbError('db_Insert');
return $result;
}
2010-02-08 09:12:07 +00:00
if ($this->mySQLresult)
{
2010-02-08 09:12:07 +00:00
if(true === $REPLACE)
{
2016-03-20 18:31:11 -07:00
$tmp = ($this->pdo) ? $this->mySQLresult : mysql_affected_rows($this->mySQLaccess);
2010-02-08 09:12:07 +00:00
$this->dbError('db_Replace');
// $tmp == -1 (error), $tmp == 0 (not modified), $tmp == 1 (added), greater (replaced)
if ($tmp == -1) { return false; } // mysql_affected_rows error
return $tmp;
}
2016-03-20 18:31:11 -07:00
// $tmp = ($this->pdo) ? $this->mySQLaccess->lastInsertId() : mysql_insert_id($this->mySQLaccess);
$tmp = $this->lastInsertId();
$this->dbError('db_Insert');
return ($tmp) ? $tmp : TRUE; // return true even if table doesn't have auto-increment.
}
else
{
// $this->dbError("db_Insert ({$query})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
}
public function lastInsertId()
{
$tmp = ($this->pdo) ? (int) $this->mySQLaccess->lastInsertId() : mysql_insert_id($this->mySQLaccess);
return ($tmp) ? $tmp : true; // return true even if table doesn't have auto-increment.
}
/**
2016-03-29 14:55:38 -07:00
* Return the total number of results on the last query regardless of the LIMIT value when SELECT SQL_CALC_FOUND_ROWS is used.
* @return bool
*/
2016-03-29 14:55:38 -07:00
public function foundRows()
{
return $this->total_results;
}
public function rowCount($result=null)
{
2016-02-12 19:28:35 -08:00
if($this->pdo)
{
if(!$this->mySQLresult)
{
return -1;
}
}
$rows = $this->mySQLrows = ($this->pdo) ? $this->mySQLresult->rowCount() : mysql_num_rows($this->mySQLresult);
$this->dbError('db_Rows');
return $rows;
}
/**
* insert() alias
* @deprecated
*/
function db_Insert($tableName, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->insert($tableName, $arg, $debug, $log_type, $log_remark);
}
2006-12-02 04:36:16 +00:00
/**
* @return int Last insert ID or false on error
* @param string $table
* @param array $arg
* @param string $debug
* @desc Insert/REplace a row into the table<br />
* <br />
* Example:<br />
* <code>e107::getDb()->replace("links", $array);</code>
*
* @access public
*/
function replace($table, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
$arg['_REPLACE'] = TRUE;
return $this->insert($table, $arg, $debug, $log_type, $log_remark);
}
/**
* replace() alias
* @deprecated
*/
function db_Replace($table, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->replace($table, $arg, $debug, $log_type, $log_remark);
}
private function _prepareUpdateArg($tableName, $arg)
{
if (is_array($arg)) // Remove the need for a separate db_UpdateArray() function.
{
if(!isset($arg['_FIELD_TYPES']) && !isset($arg['data']))
{
//Convert data if not using 'new' format
$_tmp = array();
if(isset($arg['WHERE']))
{
$_tmp['WHERE'] = $arg['WHERE'];
unset($arg['WHERE']);
}
$_tmp['data'] = $arg;
$arg = $_tmp;
unset($_tmp);
}
if(!isset($arg['data'])) { return false; }
// See if we need to auto-add field types array
if(!isset($arg['_FIELD_TYPES']) && ALLOW_AUTO_FIELD_DEFS)
{
$arg = array_merge($arg, $this->getFieldDefs($tableName));
}
$fieldTypes = $this->_getTypes($arg);
$new_data = '';
$this->pdoBind = array();
foreach ($arg['data'] as $fn => $fv)
{
$new_data .= ($new_data ? ', ' : '');
$ftype = isset($fieldTypes[$fn]) ? $fieldTypes[$fn] : 'str';
$new_data .= ($this->pdo == true && $ftype !='cmd') ? "`{$fn}`= :". $fn : "`{$fn}`=".$this->_getFieldValue($fn, $fv, $fieldTypes);
2016-08-06 11:22:16 -07:00
if($fv === '_NULL_')
{
$ftype = 'null';
}
2016-03-20 18:31:11 -07:00
if($ftype != 'cmd')
{
$this->pdoBind[$fn] = array('value'=>$this->_getPDOValue($ftype,$fv), 'type'=> $this->_getPDOType($ftype));
}
}
2016-03-20 18:31:11 -07:00
$arg = $new_data .(isset($arg['WHERE']) ? ' WHERE '. $arg['WHERE'] : '');
2016-03-20 18:31:11 -07:00
}
return $arg;
}
/**
* @return int number of affected rows, or false on error
* @param string $tableName - Name of table to access, without any language or general DB prefix
* @param array|string $arg (array preferred)
* @param bool $debug
* @desc Update fields in ONE table of the database corresponding to your $arg variable<br />
* <br />
* Think to call it if you need to do an update while retrieving data.<br />
* <br />
* Example using a unique connection to database:<br />
* <code>e107::getDb()->update("user", "user_viewed='$u_new' WHERE user_id='".USERID."' ");</code>
* <br />
* OR as second connection<br />
* <code>
* e107::getDb('sql2')->update("user", "user_viewed = '$u_new' WHERE user_id = '".USERID."' ");</code><br />
*
* @access public
*/
function update($tableName, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
$table = $this->db_IsLang($tableName);
$this->mySQLcurTable = $table;
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
$arg = $this->_prepareUpdateArg($tableName, $arg);
2009-09-06 20:04:04 +00:00
$query = 'UPDATE '.$this->mySQLPrefix.$table.' SET '.$arg;
2016-03-20 18:31:11 -07:00
if($this->pdo == true && !empty($this->pdoBind))
2016-03-20 18:31:11 -07:00
{
$query = array(
'PREPARE' => $query,
'BIND' => $this->pdoBind,
2016-03-20 18:31:11 -07:00
);
}
$result = $this->mySQLresult = $this->db_Query($query, NULL, 'db_Update', $debug, $log_type, $log_remark);
2016-03-20 18:31:11 -07:00
if ($result !==false)
{
2016-03-22 06:10:56 -07:00
if($this->pdo == true)
{
if(is_object($result))
{
// $result = $this->rowCount();
2016-03-22 06:10:56 -07:00
}
}
else
{
$result = mysql_affected_rows($this->mySQLaccess);
}
// $result = ($this->pdo) ? $result : mysql_affected_rows($this->mySQLaccess);
$this->dbError('db_Update');
2016-09-17 11:10:25 -07:00
if ($result === -1) { return false; } // Error return from mysql_affected_rows
2006-12-02 04:36:16 +00:00
return $result;
}
else
{
$this->dbError("db_Update ({$query})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
}
/**
* update() alias
* @deprecated
*/
function db_Update($tableName, $arg, $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->update($tableName, $arg, $debug, $log_type, $log_remark);
}
function _getTypes(&$arg)
{
if(isset($arg['_FIELD_TYPES']))
{
if(!isset($arg['_FIELD_TYPES']['_DEFAULT']))
{
$arg['_FIELD_TYPES']['_DEFAULT'] = 'string';
}
$fieldTypes = $arg['_FIELD_TYPES'];
unset($arg['_FIELD_TYPES']);
}
else
{
$fieldTypes = array();
$fieldTypes['_DEFAULT'] = 'string';
}
return $fieldTypes;
}
/**
* @return mixed
* @param string|array $fieldValue
* @desc Return new field value in proper format<br />
*
* @access private
*/
function _getFieldValue($fieldKey, $fieldValue, &$fieldTypes)
{
2008-11-29 18:22:46 +00:00
if($fieldValue === '_NULL_') { return 'NULL';}
$type = (isset($fieldTypes[$fieldKey]) ? $fieldTypes[$fieldKey] : $fieldTypes['_DEFAULT']);
switch ($type)
{
case 'int':
case 'integer':
2009-10-21 09:12:12 +00:00
return (int) $fieldValue;
2012-12-13 16:13:41 +02:00
break;
case 'cmd':
return $fieldValue;
2012-12-13 16:13:41 +02:00
break;
case 'safestr':
return "'{$fieldValue}'";
break;
case 'str':
case 'string':
2012-12-13 15:47:48 +02:00
//return "'{$fieldValue}'";
return "'".$this->escape($fieldValue, false)."'";
2012-12-13 16:13:41 +02:00
break;
2009-12-02 16:51:04 +00:00
case 'float':
// fix - convert localized float numbers
$larr = localeconv();
$search = array($larr['decimal_point'], $larr['mon_decimal_point'], $larr['thousands_sep'], $larr['mon_thousands_sep'], $larr['currency_symbol'], $larr['int_curr_symbol']);
$replace = array('.', '.', '', '', '', '');
return str_replace($search, $replace, floatval($fieldValue));
2009-10-21 09:12:12 +00:00
break;
2009-12-02 16:51:04 +00:00
case 'null':
2012-12-13 15:47:48 +02:00
//return ($fieldValue && $fieldValue !== 'NULL' ? "'{$fieldValue}'" : 'NULL');
return ($fieldValue && $fieldValue !== 'NULL' ? "'".$this->escape($fieldValue, false)."'" : 'NULL');
break;
case 'array':
if(is_array($fieldValue))
{
return "'".e107::getArrayStorage()->writeArray($fieldValue, true)."'";
}
return "'". (string) $fieldValue."'";
break;
2008-12-07 00:21:21 +00:00
case 'todb': // using as default causes serious BC issues.
if($fieldValue == '') { return "''"; }
2011-06-22 09:01:02 +00:00
return "'".e107::getParser()->toDB($fieldValue)."'";
2012-12-13 16:13:41 +02:00
break;
case 'escape':
default:
return "'".$this->escape($fieldValue, false)."'";
break;
}
}
2016-03-20 18:31:11 -07:00
/**
* Return a value for use in PDO bindValue() - based on field-type.
* @param $type
* @param $fieldValue
* @return int|string
*/
private function _getPDOValue($type, $fieldValue)
{
2016-08-06 11:22:16 -07:00
if(is_string($fieldValue) && ($fieldValue === '_NULL_'))
{
$type = 'null';
}
2016-03-20 18:31:11 -07:00
switch($type)
{
case "int":
case "integer":
return (int) $fieldValue;
break;
2016-03-20 18:31:11 -07:00
case 'float':
// fix - convert localized float numbers
$larr = localeconv();
$search = array($larr['decimal_point'], $larr['mon_decimal_point'], $larr['thousands_sep'], $larr['mon_thousands_sep'], $larr['currency_symbol'], $larr['int_curr_symbol']);
$replace = array('.', '.', '', '', '', '');
return str_replace($search, $replace, floatval($fieldValue));
break;
case 'null':
return null;
2016-03-20 18:31:11 -07:00
break;
case 'array':
if(is_array($fieldValue))
{
return e107::serialize($fieldValue);
2016-03-20 18:31:11 -07:00
}
return $fieldValue;
break;
case 'todb': // using as default causes serious BC issues.
if($fieldValue == '') { return ''; }
return e107::getParser()->toDB($fieldValue);
break;
case 'cmd':
case 'safestr':
case 'str':
case 'string':
case 'escape':
default:
return $fieldValue;
break;
2016-03-20 18:31:11 -07:00
}
}
/**
* Convert FIELD_TYPE to PDO compatible Field-Type
* @param $type
* @return int
*/
private function _getPDOType($type)
{
switch($type)
{
case "int":
case "integer":
return PDO::PARAM_INT;
break;
case 'null':
return PDO::PARAM_NULL;
break;
2016-03-20 18:31:11 -07:00
case 'cmd':
case 'safestr':
case 'str':
case 'string':
case 'escape':
case 'array':
case 'todb':
case 'float':
return PDO::PARAM_STR;
break;
}
// e107::getMessage()->addDebug("MySQL Missing Field-Type: ".$type);
return PDO::PARAM_STR;
2016-03-20 18:31:11 -07:00
}
/**
* @DEPRECATED
Similar to db_Update(), but splits the variables and the 'WHERE' clause.
2007-12-26 13:21:34 +00:00
$vars may be an array (fieldname=>newvalue) of fields to be updated, or a simple list.
$arg is usually a 'WHERE' clause
The way the code is written at the moment, a call to db_Update() with just the first two parameters specified can be
2007-12-30 11:03:57 +00:00
converted simply by changing the function name - it will still work.
Deprecated routine - use db_Update() with array parameters
2007-12-26 13:21:34 +00:00
*/
function db_UpdateArray($table, $vars, $arg='', $debug = FALSE, $log_type = '', $log_remark = '')
2007-12-26 13:21:34 +00:00
{
$table = $this->db_IsLang($table);
$this->mySQLcurTable = $table;
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
$new_data = '';
if (is_array($vars))
{
$spacer = '';
foreach ($vars as $fn => $fv)
{
$new_data .= $spacer."`{$fn}`='{$fv}'";
$spacer = ', ';
}
$vars = '';
}
if ($result = $this->mySQLresult = $this->db_Query('UPDATE '.$this->mySQLPrefix.$table.' SET '.$new_data.$vars.' '.$arg, NULL, 'db_UpdateArray', $debug, $log_type, $log_remark))
2007-12-26 13:21:34 +00:00
{
$result = ($this->pdo) ? $this->mySQLresult->rowCount() : mysql_affected_rows($this->mySQLaccess);
2007-12-26 13:21:34 +00:00
if ($result == -1) return FALSE; // Error return from mysql_affected_rows
return $result;
}
else
2007-12-26 13:21:34 +00:00
{
$this->dbError("db_Update ($query)");
return FALSE;
}
}
/**
* Truncate a table
* @param string $table - table name without e107 prefix
*/
function truncate($table=null)
{
if($table == null){ return; }
return $this->gen("TRUNCATE TABLE `#".$table."` ");
}
2006-12-02 04:36:16 +00:00
/**
2016-02-14 12:15:55 -08:00
* @param string $type assoc|num|both
2006-12-02 04:36:16 +00:00
* @return array MySQL row
* @desc Fetch an array containing row data (see PHP's mysql_fetch_array() docs)<br />
* @example
2006-12-02 04:36:16 +00:00
* Example :<br />
* <code>while($row = $sql->fetch()){
2006-12-02 04:36:16 +00:00
* $text .= $row['username'];
* }</code>
*
* @access public
*/
2017-01-06 19:30:34 -08:00
function fetch($type = null)
{
2017-01-06 19:30:34 -08:00
if(defined('e_LEGACY_MODE') && !is_int($type))
{
2017-01-06 19:30:34 -08:00
$type='both';
}
2016-02-14 12:15:55 -08:00
if(defined('MYSQL_ASSOC'))
{
2016-02-14 12:15:55 -08:00
switch ($type)
{
2016-02-14 12:15:55 -08:00
case 'both':
case 3: // MYSQL_BOTH:
2016-02-14 12:33:35 -08:00
$type = ($this->pdo) ? PDO::FETCH_BOTH: MYSQL_BOTH; // 3
2016-02-14 12:15:55 -08:00
break;
case 'num':
case 2; // MYSQL_NUM: // 2
2016-02-14 12:33:35 -08:00
$type = ($this->pdo) ? PDO::FETCH_NUM : MYSQL_NUM;
2016-02-14 12:15:55 -08:00
break;
2017-01-06 19:30:34 -08:00
default:
2016-02-14 12:15:55 -08:00
case 'assoc':
case 1; //: // 1
2017-01-06 19:30:34 -08:00
2016-02-14 12:33:35 -08:00
$type = ($this->pdo) ? PDO::FETCH_ASSOC : MYSQL_ASSOC;
2016-02-14 12:15:55 -08:00
break;
}
}
else
2016-02-14 12:15:55 -08:00
{
if($this->pdo) // convert type to PDO.
2016-02-14 12:15:55 -08:00
{
switch ($type)
{
case 'both': // 3
$type = PDO::FETCH_BOTH;
break;
case 'num': // 2
$type = PDO::FETCH_NUM;
break;
2016-02-14 12:15:55 -08:00
case 'assoc': // 1
default:
$type = PDO::FETCH_ASSOC;
break;
}
}
}
2016-02-14 12:15:55 -08:00
2016-02-14 12:33:35 -08:00
2006-12-02 04:36:16 +00:00
$b = microtime();
if($this->mySQLresult)
{
$row = ($this->pdo) ? $this->mySQLresult->fetch($type) : @mysql_fetch_array($this->mySQLresult,$type);
e107::getSingleton('e107_traffic')->Bump('db_Fetch', $b);
2009-12-02 16:51:04 +00:00
if ($row)
2009-10-03 14:54:46 +00:00
{
$this->dbError('db_Fetch');
return $row; // Success - return data
2009-12-02 16:51:04 +00:00
}
}
2009-10-03 14:54:46 +00:00
$this->dbError('db_Fetch');
return FALSE; // Failure
2006-12-02 04:36:16 +00:00
}
/**
* fetch() alias
* @deprecated
*/
2016-02-14 12:15:55 -08:00
function db_Fetch($type = null)
{
return $this->fetch($type);
}
2006-12-02 04:36:16 +00:00
/**
* @return int number of affected rows or false on error
* @param string $table
* @param string $fields
* @param string $arg
* @desc Count the number of rows in a select<br />
* <br />
* Example:<br />
2013-04-15 12:44:56 +02:00
* <code>$topics = e107::getDb()->count("forum_thread", "(*)", "thread_forum_id='".$forum_id."' AND thread_parent='0'");</code>
2006-12-02 04:36:16 +00:00
*
* @access public
*/
function count($table, $fields = '(*)', $arg = '', $debug = FALSE, $log_type = '', $log_remark = '')
{
2006-12-02 04:36:16 +00:00
$table = $this->db_IsLang($table);
2009-12-02 16:51:04 +00:00
if ($fields == 'generic')
{
2006-12-02 04:36:16 +00:00
$query=$table;
2009-12-02 16:51:04 +00:00
if ($this->mySQLresult = $this->db_Query($query, NULL, 'db_Count', $debug, $log_type, $log_remark))
{
$rows = $this->mySQLrows = ($this->pdo) ? $this->mySQLresult->fetch(PDO::FETCH_ASSOC) : @mysql_fetch_array($this->mySQLresult);
$this->dbError('db_Count');
2006-12-02 04:36:16 +00:00
return $rows['COUNT(*)'];
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Count ({$query})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
}
$this->mySQLcurTable = $table;
2009-12-02 16:51:04 +00:00
// normalize query arguments - only COUNT expected 'WHERE', not anymore
2009-11-26 17:14:07 +00:00
if($arg && stripos(trim($arg), 'WHERE') !== 0)
{
$arg = 'WHERE '.$arg;
}
$query='SELECT COUNT'.$fields.' FROM '.$this->mySQLPrefix.$table.' '.$arg;
2009-12-02 16:51:04 +00:00
if ($this->mySQLresult = $this->db_Query($query, NULL, 'db_Count', $debug, $log_type, $log_remark))
{
$rows = $this->mySQLrows = ($this->pdo) ? $this->mySQLresult->fetch(PDO::FETCH_NUM) : @mysql_fetch_array($this->mySQLresult);
$this->dbError('db_Count');
2006-12-02 04:36:16 +00:00
return $rows[0];
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Count({$query})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
}
/**
* @deprecated use count()
*/
function db_Count($table, $fields = '(*)', $arg = '', $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->count($table, $fields, $arg, $debug, $log_type, $log_remark);
}
2006-12-02 04:36:16 +00:00
2006-12-02 04:36:16 +00:00
/**
* @desc Closes the mySQL server connection.<br />
* <br />
* Only required if you open a second connection.<br />
* Native e107 connection is closed in the footer.php file<br />
* <br />
* Example :<br />
* <code>$sql->db_Close();</code>
*
* @access public
* @return void
*/
function close()
{
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
e107::getSingleton('e107_traffic')->BumpWho('db Close', 1);
$this->mySQLaccess = NULL; // correct way to do it when using shared links.
2006-12-02 04:36:16 +00:00
$this->dbError('dbClose');
}
/**
* BC Alias of close()
*/
function db_Close()
{
$this->close();
}
2006-12-02 04:36:16 +00:00
/**
* @return int number of affected rows, or false on error
* @param string $table
* @param string $arg
* @desc Delete rows from a table<br />
* <br />
* Example:
* <code>$sql->delete("tmp", "tmp_ip='$ip'");</code><br />
2006-12-02 04:36:16 +00:00
* <br />
* @access public
*/
function delete($table, $arg = '', $debug = FALSE, $log_type = '', $log_remark = '')
{
2006-12-02 04:36:16 +00:00
$table = $this->db_IsLang($table);
$this->mySQLcurTable = $table;
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
2009-12-02 16:51:04 +00:00
if (!$arg)
{
2009-12-02 16:51:04 +00:00
if ($result = $this->mySQLresult = $this->db_Query('DELETE FROM '.$this->mySQLPrefix.$table, NULL, 'db_Delete', $debug, $log_type, $log_remark))
{
$this->dbError('db_Delete');
2006-12-02 04:36:16 +00:00
return $result;
2009-12-02 16:51:04 +00:00
}
else
{
$this->dbError("db_Delete({$arg})");
2006-12-02 04:36:16 +00:00
return FALSE;
}
2009-12-02 16:51:04 +00:00
}
else
{
2009-12-02 16:51:04 +00:00
if ($result = $this->mySQLresult = $this->db_Query('DELETE FROM '.$this->mySQLPrefix.$table.' WHERE '.$arg, NULL, 'db_Delete', $debug, $log_type, $log_remark))
{
$tmp = ($this->pdo) ? $this->mySQLresult->rowCount() : mysql_affected_rows($this->mySQLaccess);
$this->dbError('db_Delete');
2006-12-02 04:36:16 +00:00
return $tmp;
2009-12-02 16:51:04 +00:00
}
else
{
2006-12-02 04:36:16 +00:00
$this->dbError('db_Delete ('.$arg.')');
return FALSE;
}
}
}
/**
* @deprecated use $sql->delete();
*/
function db_Delete($table, $arg = '', $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->delete($table, $arg, $debug, $log_type, $log_remark);
}
2006-12-02 04:36:16 +00:00
2006-12-02 04:36:16 +00:00
/**
* @deprecated
2006-12-02 04:36:16 +00:00
* @desc Enter description here...
* @access private
*/
2009-12-02 16:51:04 +00:00
function db_Rows()
{
return $this->rowCount();
2006-12-02 04:36:16 +00:00
}
/**
* @return void
* @param bool $mode
2006-12-02 04:36:16 +00:00
* @desc Enter description here...
* @access private
*/
2009-12-02 16:51:04 +00:00
function db_SetErrorReporting($mode)
{
2006-12-02 04:36:16 +00:00
$this->mySQLerror = $mode;
}
/**
* Function to handle any MySQL query
* @param string $query - the MySQL query string, where '#' represents the database prefix in front of table names.
* Strongly recommended to enclose all table names in backticks, to minimise the possibility of erroneous substitutions - its
* likely that this will become mandatory at some point
* @return boolean | integer
* Returns FALSE if there is an error in the query
* Returns TRUE if the query is successful, and it does not return a row count
* Returns the number of rows added/updated/deleted for DELETE, INSERT, REPLACE, or UPDATE
2006-12-02 04:36:16 +00:00
*/
public function gen($query, $debug = FALSE, $log_type = '', $log_remark = '')
{
global $db_mySQLQueryCount;
2010-02-19 09:27:43 +00:00
2006-12-02 04:36:16 +00:00
$this->tabset = FALSE;
2010-02-19 09:27:43 +00:00
2009-09-05 23:02:23 +00:00
$query .= " "; // temp fix for failing regex below, when there is no space after the table name;
2009-12-02 16:51:04 +00:00
if(strpos($query,'`#') !== FALSE)
2009-12-02 16:51:04 +00:00
{
2011-05-01 16:35:57 +00:00
//$query = str_replace('`#','`'.$this->mySQLPrefix,$query); // This simple substitution should be OK when backticks used
// SecretR - reverted back - breaks multi-language
$query = preg_replace_callback("/\s`#([\w]*?)`\W/", array($this, 'ml_check'), $query);
}
elseif(strpos($query,'#') !== FALSE)
{ // Deprecated scenario - caused problems when '#' appeared in data - hence use of backticks
2006-12-02 04:36:16 +00:00
$query = preg_replace_callback("/\s#([\w]*?)\W/", array($this, 'ml_check'), $query);
}
2009-12-02 16:51:04 +00:00
2010-02-19 09:27:43 +00:00
//$query = str_replace("#",$this->mySQLPrefix,$query); //FIXME - quick fix for those that slip-thru - but destroys
// the point of requiring backticks round table names - wrecks &#039;, for example
if (($this->mySQLresult = $this->db_Query($query, NULL, 'db_Select_gen', $debug, $log_type, $log_remark)) === FALSE)
{ // Failed query
$this->dbError('db_Select_gen('.$query.')');
return FALSE;
}
elseif ($this->mySQLresult === TRUE)
{ // Successful query which may return a row count (because it operated on a number of rows without returning a result set)
if(preg_match('#^(DELETE|INSERT|REPLACE|UPDATE)#',$query, $matches))
{ // Need to check mysql_affected_rows() - to return number of rows actually updated
$tmp = ($this->pdo) ? $this->mySQLresult->rowCount() : mysql_affected_rows($this->mySQLaccess);
$this->dbError('db_Select_gen');
return $tmp;
}
$this->dbError('db_Select_gen'); // No row count here
return TRUE;
}
else
{ // Successful query which does return a row count - get the count and return it
$this->dbError('db_Select_gen');
return $this->rowCount();
2006-12-02 04:36:16 +00:00
}
}
/**
* gen() alias
* @deprecated
*/
public function db_Select_gen($query, $debug = FALSE, $log_type = '', $log_remark = '')
{
return $this->gen($query, $debug, $log_type, $log_remark);
}
function ml_check($matches)
2009-12-02 16:51:04 +00:00
{
2006-12-02 04:36:16 +00:00
$table = $this->db_IsLang($matches[1]);
if($this->tabset == false)
{
2006-12-02 04:36:16 +00:00
$this->mySQLcurTable = $table;
$this->tabset = true;
}
return ' `'.$this->mySQLPrefix.$table.'`'.substr($matches[0],-1);
2006-12-02 04:36:16 +00:00
}
2006-12-02 04:36:16 +00:00
/**
* @return unknown
* @param unknown $offset
* @desc Enter description here...
* @access private
*/
/* Function not used
2009-12-02 16:51:04 +00:00
function db_Fieldname($offset)
{
2006-12-02 04:36:16 +00:00
$result = @mysql_field_name($this->mySQLresult, $offset);
return $result;
}
*/
2006-12-02 04:36:16 +00:00
2006-12-02 04:36:16 +00:00
/**
* @return unknown
* @desc Enter description here...
* @access private
*/
/*
2009-12-02 16:51:04 +00:00
function db_Field_info()
{
2006-12-02 04:36:16 +00:00
$result = @mysql_fetch_field($this->mySQLresult);
return $result;
}
*/
2006-12-02 04:36:16 +00:00
2006-12-02 04:36:16 +00:00
/**
* @return unknown
* @desc Enter description here...
* @access private
*/
/* Function not used
2009-12-02 16:51:04 +00:00
function db_Num_fields()
{
2006-12-02 04:36:16 +00:00
$result = @mysql_num_fields($this->mySQLresult);
return $result;
}
*/
2006-12-02 04:36:16 +00:00
/**
2009-12-02 16:51:04 +00:00
* Check for the existence of a matching language table when multi-language tables are active.
* @param string $table Name of table, without the prefix. or an array of table names.
2006-12-02 04:36:16 +00:00
* @access private
* @return mixed the name of the language table (eg. lan_french_news) or an array of all matching language tables. (with mprefix)
2006-12-02 04:36:16 +00:00
*/
function db_IsLang($table, $multiple=false)
{
2009-12-02 16:51:04 +00:00
//When running a multi-language site with english included. English must be the main site language.
// WARNING!!! FALSE is critical important - if missed, expect dead loop (prefs are calling db handler as well when loading)
// Temporary solution, better one is needed
2011-05-01 16:35:57 +00:00
$core_pref = $this->getConfig();
//if ((!$this->mySQLlanguage || !$pref['multilanguage'] || $this->mySQLlanguage=='English') && $multiple==FALSE)
if ((!$this->mySQLlanguage || !$core_pref->get('multilanguage') || !$core_pref->get('sitelanguage') /*|| $this->mySQLlanguage==$core_pref->get('sitelanguage')*/) && $multiple==FALSE)
{
2006-12-02 04:36:16 +00:00
return $table;
}
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
2009-12-02 16:51:04 +00:00
if($multiple == FALSE)
2009-12-02 16:51:04 +00:00
{
$mltable = "lan_".strtolower($this->mySQLlanguage.'_'.$table);
return ($this->isTable($table,$this->mySQLlanguage) ? $mltable : $table);
2006-12-02 04:36:16 +00:00
}
else // return an array of all matching language tables. eg [french]->e107_lan_news
2009-12-02 16:51:04 +00:00
{
if(!is_array($table))
{
2006-12-02 04:36:16 +00:00
$table = array($table);
}
if(!$this->mySQLtableList)
{
$this->mySQLtableList = $this->db_mySQLtableList();
}
$lanlist = array();
foreach($this->mySQLtableList as $tab)
{
if(substr($tab,0,4) == "lan_")
{
list($tmp,$lng,$tableName) = explode("_",$tab,3);
foreach($table as $t)
{
if($tableName == $t)
{
$lanlist[$lng][$this->mySQLPrefix.$t] = $this->mySQLPrefix.$tab; // prefix needed.
2006-12-02 04:36:16 +00:00
}
2006-12-02 04:36:16 +00:00
}
}
}
2009-12-02 16:51:04 +00:00
if(empty($lanlist))
{
return false;
}
else
{
return $lanlist;
}
2006-12-02 04:36:16 +00:00
}
// -------------------------
2006-12-02 04:36:16 +00:00
}
2013-03-16 03:57:28 -07:00
/**
* Deprecated alias of the rows() function below.
*/
function db_getList($fields = 'ALL', $amount = FALSE, $maximum = FALSE, $ordermode=FALSE)
{
return $this->rows($fields, $amount, $maximum, $ordermode);
}
2006-12-02 04:36:16 +00:00
/**
* @return array
* @param string fields to retrieve
* @desc returns fields as structured array
* @access public
2013-03-16 03:57:28 -07:00
* @return rows of the database as an array.
2006-12-02 04:36:16 +00:00
*/
2013-03-16 03:57:28 -07:00
function rows($fields = 'ALL', $amount = FALSE, $maximum = FALSE, $ordermode=FALSE)
{
2006-12-02 04:36:16 +00:00
$list = array();
$counter = 1;
2013-03-16 03:57:28 -07:00
while ($row = $this->fetch())
{
2009-12-02 16:51:04 +00:00
foreach($row as $key => $value)
{
2009-12-02 16:51:04 +00:00
if (is_string($key))
{
2009-12-02 16:51:04 +00:00
if (strtoupper($fields) == 'ALL' || in_array ($key, $fields))
{
2006-12-02 04:36:16 +00:00
if(!$ordermode)
{
$list[$counter][$key] = $value;
}
else
{
$list[$row[$ordermode]][$key] = $value;
}
}
}
}
2009-12-02 16:51:04 +00:00
if ($amount && $amount == $counter || ($maximum && $counter > $maximum))
{
2006-12-02 04:36:16 +00:00
break;
}
$counter++;
}
return $list;
}
/**
* Return the maximum value for a given table/field
* @param $table (without the prefix)
* @param $field
* @param string $where (optional)
* @return bool|resource
*/
public function max($table, $field, $where='')
{
$qry = "SELECT MAX(".$field.") FROM `".$this->mySQLPrefix.$table."` ";
if(!empty($where))
{
$qry .= "WHERE ".$where;
}
return $this->retrieve($qry);
}
2006-12-02 04:36:16 +00:00
/**
* @return integer
* @desc returns total number of queries made so far
* @access public
*/
2009-12-02 16:51:04 +00:00
function db_QueryCount()
{
2006-12-02 04:36:16 +00:00
global $db_mySQLQueryCount;
return $db_mySQLQueryCount;
}
/**
* Multi-language Query Function. Run a query on the same table across all languages.
* @param $query
* @param bool $debug
* @return bool
*/
function db_Query_all($query, $debug=false)
{
2006-12-02 04:36:16 +00:00
$error = "";
$query = str_replace("#", $this->mySQLPrefix, $query);
2006-12-02 04:36:16 +00:00
if(!$this->db_Query($query))
{ // run query on the default language first.
2006-12-02 04:36:16 +00:00
$error .= $query. " failed";
}
$table = array();
$search = array();
$tmp = explode(" ",$query); // split the query
foreach($tmp as $val)
{
if(strpos($val,$this->mySQLPrefix) !== false) // search for table names references using the mprefix
{
$table[] = str_replace(array($this->mySQLPrefix,"`"),"", $val);
$search[] = str_replace("`","",$val);
2006-12-02 04:36:16 +00:00
}
}
if(empty($table) || empty($search))
{
return false;
}
2006-12-02 04:36:16 +00:00
// Loop thru relevant language tables and replace each tablename within the query.
if($tablist = $this->db_IsLang($table, true))
{
foreach($tablist as $key=>$tab)
{
2006-12-02 04:36:16 +00:00
$querylan = $query;
foreach($search as $find)
{
2006-12-02 04:36:16 +00:00
$replace = ($tab[$find] !="") ? $tab[$find] : $find;
$querylan = str_replace($find,$replace,$querylan);
}
if(!$this->db_Query($querylan)) // run query on other language tables.
{
2006-12-02 04:36:16 +00:00
$error .= $querylan." failed for language";
}
2006-12-02 04:36:16 +00:00
if($debug){ echo "<br />** lang= ".$querylan; }
}
}
return ($error) ? false : true;
2006-12-02 04:36:16 +00:00
}
/**
* Return a list of the field names in a table.
*
* @param string $table - table name (no prefix)
* @param string $prefix - table prefix to apply. If empty, MPREFIX is used.
* @param boolean $retinfo = FALSE - just returns array of field names. TRUE - returns all field info
* @return array|boolean - FALSE on error, field list array on success
*/
function db_FieldList($table, $prefix = '', $retinfo = FALSE)
{
if(!$this->mySQLdefaultdb)
{
global $mySQLdefaultdb;
$this->mySQLdefaultdb = $mySQLdefaultdb;
}
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
if ($prefix == '') $prefix = $this->mySQLPrefix;
if (FALSE === ($result = $this->gen('SHOW COLUMNS FROM '.$prefix.$table)))
{
return FALSE; // Error return
}
$ret = array();
if ($this->rowCount() > 0)
{
while ($row = $this->fetch($result))
{
2010-02-19 09:27:43 +00:00
if ($retinfo)
{
$ret[$row['Field']] = $row['Field'];
}
else
{
2010-02-19 09:27:43 +00:00
$ret[] = $row['Field'];
}
}
}
return $ret;
}
2013-03-09 14:53:01 -08:00
function db_Field($table,$fieldid="",$key="", $retinfo = FALSE)
{
return $this->field($table,$fieldid,$key, $retinfo);
}
function columnCount()
{
if($this->pdo)
{
return $this->mySQLresult->columnCount();
}
else
{
return mysql_num_fields($this->mySQLresult);
}
}
/**
* Determines if a plugin field (and key) exist. OR if fieldid is numeric - return the field name in that position.
*
* @param string $table - table name (no prefix)
* @param string $fieldid - Numeric offset or field/key name
* @param string $key - PRIMARY|INDEX|UNIQUE - type of key when searching for key name
* @param boolean $retinfo = FALSE - just returns true|false. TRUE - returns all field info
* @return array|boolean - FALSE on error, field information on success
*/
2013-03-09 14:53:01 -08:00
function field($table,$fieldid="",$key="", $retinfo = FALSE)
{
if(!$this->mySQLdefaultdb)
{
global $mySQLdefaultdb;
$this->mySQLdefaultdb = $mySQLdefaultdb;
}
$convert = array("PRIMARY"=>"PRI","INDEX"=>"MUL","UNIQUE"=>"UNI");
2009-09-03 23:39:32 +00:00
$key = (isset($convert[$key])) ? $convert[$key] : "OFF";
2006-12-02 04:36:16 +00:00
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
$result = $this->gen("SHOW COLUMNS FROM ".$this->mySQLPrefix.$table);
if ($result && ($this->rowCount() > 0))
{
$c=0;
while ($row = $this->fetch())
{
if(is_numeric($fieldid))
{
if($c == $fieldid)
{
if ($retinfo) return $row;
return $row['Field']; // field number matches.
}
}
else
{ // Check for match of key name - and allow that key might not be used
if(($fieldid == $row['Field']) && (($key == "OFF") || ($key == $row['Key'])))
{
if ($retinfo) return $row;
return true;
}
}
$c++;
}
2006-12-02 04:36:16 +00:00
}
return FALSE;
}
2006-12-02 04:36:16 +00:00
/**
* A pointer to mysql_real_escape_string() - see http://www.php.net/mysql_real_escape_string
*
* @param string $data
* @return string
*/
function escape($data, $strip = true)
{
2016-02-14 12:15:55 -08:00
if ($strip)
{
2006-12-02 04:36:16 +00:00
$data = strip_if_magic($data);
}
if(!$this->mySQLaccess)
{
global $db_ConnectionID;
$this->mySQLaccess = $db_ConnectionID;
}
2016-02-14 12:15:55 -08:00
if($this->pdo)
{
return $data;
// return $this->mySQLaccess->quote($data);
}
return mysql_real_escape_string($data,$this->mySQLaccess);
2006-12-02 04:36:16 +00:00
}
2007-03-04 15:00:19 +00:00
/**
* Legacy Alias of isTable();
* @deprecated
* @param $table
* @param string $language
* @return bool
*/
public function db_Table_exists($table,$language='')
{
return $this->isTable($table, $language);
}
/**
2007-03-04 15:00:19 +00:00
* Verify whether a table exists, without causing an error
*
* @param string $table Table name without the prefix
* @param string $language (optional) leave blank to search for a regular table, or language-name to search for a language table.
* @example $sql->isTable('news','Spanish');
* @return boolean TRUE if exists
2007-03-04 15:00:19 +00:00
*
2009-12-02 16:51:04 +00:00
* NOTES: Slower (28ms) than "SELECT 1 FROM" (4-5ms), but doesn't produce MySQL errors.
* Multiple checks on a single page will only use 1 query. ie. faster on multiple calls.
2007-03-04 15:00:19 +00:00
*/
public function isTable($table, $language='')
{
// global $pref;
$table = strtolower($table); // precaution for multilanguage
if(!empty($language)) //ie. is it a language table?
{
$sitelanguage = $this->getConfig()->get('sitelanguage');
if($language == $sitelanguage)
{
return false;
}
if(!isset($this->mySQLtableListLanguage[$language]))
{
$this->mySQLtableListLanguage = $this->db_mySQLtableList($language);
2009-12-02 16:51:04 +00:00
}
2009-12-02 16:51:04 +00:00
return in_array('lan_'.strtolower($language)."_".$table,$this->mySQLtableListLanguage[$language]);
}
else // regular search
{
if(!$this->mySQLtableList)
{
2009-12-02 16:51:04 +00:00
$this->mySQLtableList = $this->db_mySQLtableList();
}
return in_array($table,$this->mySQLtableList);
}
2009-12-02 16:51:04 +00:00
}
/**
* Check if a database table is empty or not.
* @param $table
* @return bool
*/
function isEmpty($table)
{
if(empty($table))
{
return false;
}
$result = $this->gen("SELECT NULL FROM `#".$table."` LIMIT 1");
if($result === 0)
{
return true;
}
return false;
}
/**
2011-05-01 16:35:57 +00:00
* Populate mySQLtableList and mySQLtableListLanguage
* TODO - better runtime cache - use e107::getRegistry() && e107::setRegistry()
* @return array
*/
private function db_mySQLtableList($language='')
{
if($language)
{
if(!isset($this->mySQLtableListLanguage[$language]))
{
$table = array();
if($res = $this->db_Query("SHOW TABLES LIKE '".$this->mySQLPrefix."lan_".strtolower($language)."%' "))
2009-12-02 16:51:04 +00:00
{
2016-02-14 12:15:55 -08:00
while($rows = $this->fetch('num'))
{
2009-12-02 16:51:04 +00:00
$table[] = str_replace($this->mySQLPrefix,"",$rows[0]);
}
}
$ret = array($language=>$table);
2009-12-02 16:51:04 +00:00
return $ret;
}
else
{
2009-12-02 16:51:04 +00:00
return $this->mySQLtableListLanguage[$language];
}
}
if(!$this->mySQLtableList)
{
$table = array();
if($res = $this->db_Query("SHOW TABLES LIKE '".$this->mySQLPrefix."%' "))
2009-12-02 16:51:04 +00:00
{
$length = strlen($this->mySQLPrefix);
2016-02-14 12:15:55 -08:00
while($rows = $this->fetch('num'))
{
$table[] = substr($rows[0],$length);
}
}
2009-12-02 16:51:04 +00:00
return $table;
}
else
{
return $this->mySQLtableList;
}
}
2009-12-02 16:51:04 +00:00
public function db_ResetTableList()
{
$this->mySQLtableList = array();
$this->mySQLtableListLanguage = array();
}
/**
* Legacy Alias of tables
* @deprecated
* @param string $mode
2009-12-02 16:51:04 +00:00
* @return array
*/
public function db_TableList($mode='all')
{
return $this->tables($mode);
}
/**
* Return a filtered list of DB tables.
* @param object $mode [optional] all|lan|nolan|nologs
* @return array
*/
public function tables($mode='all')
{
2009-12-02 16:51:04 +00:00
if(!$this->mySQLtableList)
{
$this->mySQLtableList = $this->db_mySQLtableList();
}
if($mode == 'nologs')
{
$ret = array();
foreach($this->mySQLtableList as $table)
{
if(substr($table,-4) != '_log' && $table != 'download_requests')
{
$ret[] = $table;
}
}
return $ret;
}
2009-12-02 16:51:04 +00:00
if($mode == 'all')
{
return $this->mySQLtableList;
}
2009-12-02 16:51:04 +00:00
if($mode == 'lan' || $mode=='nolan')
{
$nolan = array();
$lan = array();
2009-12-02 16:51:04 +00:00
foreach($this->mySQLtableList as $tab)
{
if(substr($tab,0,4)!='lan_')
{
$nolan[] = $tab;
}
else
{
2009-12-02 16:51:04 +00:00
$lan[] = $tab;
}
}
2009-12-02 16:51:04 +00:00
return ($mode == 'lan') ? $lan : $nolan;
}
}
/**
* Duplicate a Table Row in a table.
*/
function db_CopyRow($table,$fields = '*', $args='')
{
if(!$table || !$args )
{
return false;
}
if($fields == '*')
{
$fields = $this->db_FieldList($table);
unset($fields[0]); // Remove primary_id.
$fieldList = implode(",",$fields);
}
else
{
$fieldList = $fields;
}
$id = $this->gen("INSERT INTO #".$table."(".$fieldList.") SELECT ".$fieldList." FROM #".$table." WHERE ".$args);
$lastInsertId = $this->lastInsertId();
return ($id && $lastInsertId) ? $lastInsertId : false;
}
2009-12-02 16:51:04 +00:00
function db_CopyTable($oldtable, $newtable, $drop = FALSE, $data = FALSE)
{
$old = $this->mySQLPrefix.strtolower($oldtable);
$new = $this->mySQLPrefix.strtolower($newtable);
2009-12-02 16:51:04 +00:00
if ($drop)
{
$this->gen("DROP TABLE IF EXISTS {$new}");
}
2009-12-02 16:51:04 +00:00
//Get $old table structure
$this->gen('SET SQL_QUOTE_SHOW_CREATE = 1');
2009-12-02 16:51:04 +00:00
$qry = "SHOW CREATE TABLE {$old}";
if ($this->gen($qry))
{
2016-02-14 12:15:55 -08:00
$row = $this->fetch('num');
$qry = $row[1];
// $qry = str_replace($old, $new, $qry);
$qry = preg_replace("#CREATE\sTABLE\s`{0,1}".$old."`{0,1}\s#", "CREATE TABLE `{$new}` ", $qry, 1); // More selective search
}
else
{
2009-12-02 16:51:04 +00:00
return FALSE;
}
2009-12-02 16:51:04 +00:00
if(!$this->isTable($newtable))
{
$result = $this->db_Query($qry);
}
2009-12-02 16:51:04 +00:00
if ($data) //We need to copy the data too
{
$qry = "INSERT INTO {$new} SELECT * FROM {$old}";
$result = $this->gen($qry);
}
return $result;
2007-03-04 15:00:19 +00:00
}
2013-03-04 14:17:07 -08:00
/**
* Dump MySQL Table(s) to a file in the Backup folder.
* @param $table string - name without the prefix or '*' for all
* @param $file string - optional file name. or leave blank to generate.
* @param $options - additional preferences.
* @return backup file path.
2013-03-04 14:17:07 -08:00
*/
function backup($table='*', $file='', $options=null)
{
$dbtable = $this->mySQLdefaultdb;
$fileName = ($table =='*') ? str_replace(" ","_",SITENAME) : $table;
2013-03-04 14:17:07 -08:00
$fileName = preg_replace('/[^\w]/i',"",$fileName);
2014-09-14 17:40:02 -07:00
$backupFile = ($file) ? e_BACKUP.$file : e_BACKUP.strtolower($fileName)."_".$this->mySQLPrefix.date("Y-m-d-H-i-s").".sql";
if($table=='*')
{
2014-09-14 17:40:02 -07:00
$nolog = vartrue($options['nologs']) ? 'nologs' : 'all';
$tableList = $this->tables($nolog);
}
else
{
$tableList = explode(",",$table);
}
2014-09-14 17:40:02 -07:00
$header = "-- e107 Database Backup File \n";
$header .= "-- Host: ".$_SERVER['SERVER_NAME']."\n";
$header .= "-- Generation Time: ".date('r')."\n";
$header .= "-- Encoding: ANSI\n\n\n";
file_put_contents($backupFile,$header, FILE_APPEND);
2013-03-04 14:17:07 -08:00
foreach ($tableList as $table)
{
unset($text);
$text = "";
$text .= vartrue($options['droptable']) ? "DROP TABLE IF EXISTS `".$this->mySQLPrefix.$table."`;\n" : "";
2013-03-04 14:17:07 -08:00
$this->gen("SHOW CREATE TABLE `".$this->mySQLPrefix.$table."`");
$row2 = $this->fetch();
$text .= $row2['Create Table'];
$text .= ";\n\n";
file_put_contents($backupFile,$text,FILE_APPEND);
// echo $text;
// ob_end_clean(); // prevents memory exhaustian on large databases but breaks layout. .
$count = $this->gen("SELECT * FROM `#".$table."`");
$data_array = "";
//TODO After so many rows (50,000?), make a new files to avoid overly large inserts.
while($row = $this->fetch())
{
$fields = array_keys($row);
$text = "\nINSERT INTO `".$this->mySQLPrefix.$table."` (`".implode("` ,`",$fields)."`) VALUES \n";
file_put_contents($backupFile,$text,FILE_APPEND);
$d = array();
foreach($fields as $val)
{
$d[] = is_numeric($row[$val]) ? $row[$val] : "'".mysql_real_escape_string($row[$val])."'";
}
$data_array = "(".implode(", ",$d).");\n";
file_put_contents($backupFile, $data_array, FILE_APPEND); // Do this here to save memory.
}
$text = "\n\n\n";
file_put_contents($backupFile, $text, FILE_APPEND);
unset($fields);
}
return $backupFile;
2013-03-04 14:17:07 -08:00
// file_put_contents('memory.log', 'memory used in line ' . __LINE__ . ' is: ' . memory_get_usage() . PHP_EOL, FILE_APPEND);
}
/**
* @return text string relating to error (empty string if no error)
2016-03-20 18:31:11 -07:00
* @param string $from
* @desc Calling method from within this class
* @access private
*/
2009-12-02 16:51:04 +00:00
function dbError($from)
{
// $this->mySQLaccess->getMessage();
if($this->pdo)
{
$this->mySQLerror = true;
if($this->mySQLlastErrNum == 0)
{
return null;
}
return $this->mySQLlastErrText;
}
$this->mySQLlastErrNum = mysql_errno();
$this->mySQLlastErrText = '';
if ($this->mySQLlastErrNum == 0)
{
return '';
}
$this->mySQLlastErrText = mysql_error(); // Get the error text.
2009-12-02 16:51:04 +00:00
if ($this->mySQLerror == TRUE)
{
message_handler('ADMIN_MESSAGE', '<b>mySQL Error!</b> Function: '.$from.'. ['.$this->mySQLlastErrNum.' - '.$this->mySQLlastErrText.']', __LINE__, __FILE__);
}
return $this->mySQLlastErrText;
}
// Return error number for last operation
function getLastErrorNumber()
{
return $this->mySQLlastErrNum; // Number of last error
}
// Return error text for last operation
function getLastErrorText()
{
return $this->mySQLlastErrText; // Text of last error (empty string if no error)
}
2011-05-01 16:35:57 +00:00
function resetLastError()
{
$this->mySQLlastErrNum = 0;
$this->mySQLlastErrText = '';
}
2010-02-19 09:27:43 +00:00
function getLastQuery()
{
return $this->mySQLlastQuery;
}
private function setSQLMode()
{
$this->db_Query("SET SESSION sql_mode='NO_ENGINE_SUBSTITUTION';");
}
/**
* Check if MySQL version is utf8 compatible and may be used as it accordingly to the user choice
*
* @TODO Simplify when the conversion script will be available
* @access public
* @param string MySQL charset may be forced in special circumstances
* UTF-8 encoding and decoding is left to the progammer
* @param bool TRUE enter debug mode. default FALSE
* @return string hardcoded error message
*/
function db_Set_Charset($charset = '', $debug = FALSE)
{
// Get the default user choice
global $mySQLcharset;
if (isset($mySQLcharset) && $mySQLcharset != 'utf8')
{
// Only utf8 is accepted
$mySQLcharset = '';
}
$charset = ($charset ? $charset : $mySQLcharset);
$message = (( ! $charset && $debug) ? 'Empty charset!' : '');
if($charset)
{
if ( ! $debug)
{
($this->pdo) ? $this->db_Query("SET NAMES `$charset`") : @mysql_query("SET NAMES `$charset`");
}
else
{
// Check if MySQL version is utf8 compatible
2010-01-07 21:05:24 +00:00
preg_match('/^(.*?)($|-)/', $this->mySqlServerInfo, $mysql_version);
if (version_compare($mysql_version[1], '4.1.2', '<'))
{
// reset utf8
//@TODO reset globally? $mySQLcharset = '';
$charset = '';
$message = 'MySQL version is not utf8 compatible!';
}
else
{
// Use db_Query() debug handler
$this->db_Query("SET NAMES `$charset`", NULL, '', $debug);
}
}
}
// Save mySQLcharset for further uses within this connection
$this->mySQLcharset = $charset;
return $message;
}
/**
* Get the _FIELD_DEFS and _NOTNULL definitions for a table
*<code>
* The information is sought in a specific order:
* a) In our internal cache
* b) in the directory e_CACHE_DBDIR - file name $tableName.php
* c) An override file for a core or plugin-related table. If found, the information is copied to the cache directory
* For core overrides, e_ADMIN.'core_sql/db_field_defs.php' is searched
* For plugins, $pref['e_sql_list'] is used as a search list - any file 'db_field_defs.php' in the plugin directory is earched
* d) The table structure is read from the DB, and a definition created:
* AUTOINCREMENT fields - ignored (or integer)
* integer type fields - 'int' processing
* character/string type fields - todb processing
* fields which are 'NOT NULL' but have no default are added to the '_NOTNULL' list
*</code>
* @param string $tableName - table name, without any prefixes (language or general)
* @return boolean|array - FALSE if not found/not to be used. Array of field names and processing types and null overrides if found
*/
public function getFieldDefs($tableName)
{
if (!isset($this->dbFieldDefs[$tableName]))
{
if (is_readable(e_CACHE_DB.$tableName.'.php'))
{
$temp = file_get_contents(e_CACHE_DB.$tableName.'.php', FILE_TEXT);
if ($temp !== FALSE)
{
$typeDefs = e107::unserialize($temp);
unset($temp);
$this->dbFieldDefs[$tableName] = $typeDefs;
}
}
else
{ // Need to try and find a table definition
$searchArray = array(e_CORE.'sql/db_field_defs.php');
// e107::getPref() shouldn't be used inside db handler! See db_IsLang() comments
$sqlFiles = (array) $this->getConfig()->get('e_sql_list', array()); // kill any PHP notices
foreach ($sqlFiles as $p => $f)
{
$searchArray[] = e_PLUGIN.$p.'/db_field_defs.php';
}
unset($sqlFiles);
$found = FALSE;
foreach ($searchArray as $defFile)
{
//echo "Check: {$defFile}, {$tableName}<br />";
if ($this->loadTableDef($defFile, $tableName))
{
$found = TRUE;
break;
}
}
if (!$found)
{ // Need to read table structure from DB and create the file
$this->makeTableDef($tableName);
}
}
}
return $this->dbFieldDefs[$tableName];
}
2010-02-19 09:27:43 +00:00
/**
* Search the specified file for a field type definition of the specified table.
* If found, generate and save a cache file in the e_CACHE_DB directory,
* Always also update $this->dbFieldDefs[$tableName] - FALSE if not found, data if found
* @param string $defFile - file name, including path
* @param string $tableName - name of table sought
* @return boolean TRUE on success, FALSE on not found (some errors intentionally ignored)
*/
protected function loadTableDef($defFile, $tableName)
{
$result = FALSE;
2011-12-27 12:00:55 +00:00
if (is_readable($defFile))
{
// Read the file using the array handler routines
// File structure is a nested array - first level is table name, second level is either FALSE (for do nothing) or array(_FIELD_DEFS => array(), _NOTNULL => array())
$temp = file_get_contents($defFile);
// Strip any comments (only /*...*/ supported)
$temp = preg_replace("#\/\*.*?\*\/#mis", '', $temp);
//echo "Check: {$defFile}, {$tableName}<br />";
if ($temp !== FALSE)
{
2011-12-27 12:00:55 +00:00
$array = e107::getArrayStorage();
$typeDefs = $array->ReadArray($temp);
unset($temp);
if (isset($typeDefs[$tableName]))
{
$this->dbFieldDefs[$tableName] = $typeDefs[$tableName];
$fileData = $array->WriteArray($typeDefs[$tableName], FALSE);
if (FALSE === file_put_contents(e_CACHE_DB.$tableName.'.php', $fileData))
{ // Could do something with error - but mustn't return FALSE - would trigger auto-generated structure
}
$result = TRUE;
}
}
}
2010-02-19 09:27:43 +00:00
if (!$result)
{
$this->dbFieldDefs[$tableName] = FALSE;
}
return $result;
}
/**
* Creates a field type definition from the structure of the table in the DB
* Generate and save a cache file in the e_CACHE_DB directory,
* Also update $this->dbFieldDefs[$tableName] - FALSE if error, data if found
* @param string $tableName - name of table sought
* @return boolean TRUE on success, FALSE on not found (some errors intentionally ignored)
*/
protected function makeTableDef($tableName)
{
require_once(e_HANDLER.'db_table_admin_class.php');
$dbAdm = new db_table_admin();
$baseStruct = $dbAdm->get_current_table($tableName);
$fieldDefs = $dbAdm->parse_field_defs($baseStruct[0][2]); // Required definitions
$outDefs = array();
foreach ($fieldDefs as $k => $v)
{
switch ($v['type'])
{
case 'field' :
if (vartrue($v['autoinc']))
{
//break; Probably include autoinc fields in array
}
$baseType = preg_replace('#\(\d+?\)#', '', $v['fieldtype']); // Should strip any length
switch ($baseType)
{
case 'int' :
case 'shortint' :
case 'tinyint' :
$outDefs['_FIELD_TYPES'][$v['name']] = 'int';
break;
case 'char' :
case 'text' :
case 'varchar' :
$outDefs['_FIELD_TYPES'][$v['name']] = 'escape'; //XXX toDB() causes serious BC issues.
break;
}
// if($v['name'])
if (isset($v['nulltype']) && !isset($v['default']))
{
$outDefs['_NOTNULL'][$v['name']] = '';
}
break;
case 'pkey' :
case 'ukey' :
case 'key' :
case 'ftkey' :
break; // Do nothing with keys for now
default :
echo "Unexpected field type: {$k} => {$v['type']}<br />";
}
}
$array = e107::getArrayStorage();
$this->dbFieldDefs[$tableName] = $outDefs;
$toSave = $array->WriteArray($outDefs, FALSE); // 2nd parameter to TRUE if needs to be written to DB
if (FALSE === file_put_contents(e_CACHE_DB.$tableName.'.php', $toSave))
{ // Could do something with error - but mustn't return FALSE - would trigger auto-generated structure
$mes = e107::getMessage();
$mes->addDebug("Error writing file: ".e_CACHE_DB.$tableName.'.php'); //Fix for during v1.x -> 2.x upgrade.
// echo "Error writing file: ".e_CACHE_DB.$tableName.'.php'.'<br />';
}
}
2006-12-02 04:36:16 +00:00
}
/**
* BC
*/
class db extends e_db_mysql
{
2009-12-02 16:51:04 +00:00
}