Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Tue, May 20, 7:23 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: trunk/kernel/include/adodb/adodb.inc.php
===================================================================
--- trunk/kernel/include/adodb/adodb.inc.php (revision 3215)
+++ trunk/kernel/include/adodb/adodb.inc.php (revision 3216)
@@ -1,3395 +1,3396 @@
<?php
/*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* This is the main include file for ADOdb.
* Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
*
* The ADOdb files are formatted so that doxygen can be used to generate documentation.
* Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
*/
/**
\mainpage
@version V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim\@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
PHP's database access functions are not standardised. This creates a need for a database
class library to hide the differences between the different database API's (encapsulate
the differences) so we can easily switch databases.
We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere,
Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
ADO and ODBC. We have had successful reports of connecting to Progress and DB2 via ODBC.
We hope more people will contribute drivers to support other databases.
Latest Download at http://php.weblogs.com/adodb<br>
Manual is at http://php.weblogs.com/adodb_manual
*/
if (!defined('_ADODB_LAYER')) {
define('_ADODB_LAYER',1);
//==============================================================================================
// CONSTANT DEFINITIONS
//==============================================================================================
define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
define('ADODB_FETCH_DEFAULT',0);
define('ADODB_FETCH_NUM',1);
define('ADODB_FETCH_ASSOC',2);
define('ADODB_FETCH_BOTH',3);
/*
Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
This currently works only with mssql, odbc, oci8po and ibase derived drivers.
0 = assoc lowercase field names. $rs->fields['orderid']
1 = assoc uppercase field names. $rs->fields['ORDERID']
2 = use native-case field names. $rs->fields['OrderID']
*/
if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
// allow [ ] @ ` and . in table names
define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)');
if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
/**
* Set ADODB_DIR to the directory where this file resides...
* This constant was formerly called $ADODB_RootPath
*/
if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
//==============================================================================================
// GLOBAL VARIABLES
//==============================================================================================
GLOBAL
$ADODB_vers, // database version
$ADODB_Database, // last database driver used
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_EXTENSION, // ADODB extension installed
$ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
$ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
//==============================================================================================
// GLOBAL SETUP
//==============================================================================================
if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {
define('ADODB_PHPVER',0x4300);
} else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {
define('ADODB_PHPVER',0x4200);
} else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
define('ADODB_PHPVER',0x4050);
} else {
define('ADODB_PHPVER',0x4000);
}
$ADODB_EXTENSION = defined('ADODB_EXTENSION');
//if (extension_loaded('dbx')) define('ADODB_DBX',1);
/**
Accepts $src and $dest arrays, replacing string $data
*/
function ADODB_str_replace($src, $dest, $data)
{
if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
$s = reset($src);
$d = reset($dest);
while ($s !== false) {
$data = str_replace($s,$d,$data);
$s = next($src);
$d = next($dest);
}
return $data;
}
function ADODB_Setup()
{
GLOBAL
$ADODB_vers, // database version
$ADODB_Database, // last database driver used
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
if (!isset($ADODB_CACHE_DIR)) {
$ADODB_CACHE_DIR = '/tmp';
} else {
// do not accept url based paths, eg. http:/ or ftp:/
if (strpos($ADODB_CACHE_DIR,'://') !== false)
die("Illegal path http:// or ftp://");
}
// Initialize random number generator for randomizing cache flushes
srand(((double)microtime())*1000000);
/**
* Name of last database driver loaded into memory. Set by ADOLoadCode().
*/
$ADODB_Database = '';
/**
* ADODB version as a string.
*/
$ADODB_vers = 'V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved. Released BSD & LGPL.';
/**
* Determines whether recordset->RecordCount() is used.
* Set to false for highest performance -- RecordCount() will always return -1 then
* for databases that provide "virtual" recordcounts...
*/
$ADODB_COUNTRECS = true;
}
//==============================================================================================
// CHANGE NOTHING BELOW UNLESS YOU ARE CODING
//==============================================================================================
ADODB_Setup();
//==============================================================================================
// CLASS ADOFieldObject
//==============================================================================================
/**
* Helper class for FetchFields -- holds info on a column
*/
class ADOFieldObject {
var $name = '';
var $max_length=0;
var $type="";
// additional fields by dannym... (danny_milo@yahoo.com)
var $not_null = false;
// actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
// so we can as well make not_null standard (leaving it at "false" does not harm anyways)
var $has_default = false; // this one I have done only in mysql and postgres for now ...
// others to come (dannym)
var $default_value; // default, if any, and supported. Check has_default first.
}
function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
{
//print "Errorno ($fn errno=$errno m=$errmsg) ";
$thisConnection->_transOK = false;
if ($thisConnection->_oldRaiseFn) {
$fn = $thisConnection->_oldRaiseFn;
$fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
}
}
//==============================================================================================
// CLASS ADOConnection
//==============================================================================================
/**
* Connection object. For connecting to databases, and executing queries.
*/
class ADOConnection {
//
// PUBLIC VARS
//
var $dataProvider = 'native';
var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
var $database = ''; /// Name of database to be used.
var $host = ''; /// The hostname of the database server
var $user = ''; /// The username which is used to connect to the database server.
var $password = ''; /// Password for the username. For security, we no longer store it.
var $debug = false; /// if set to true will output sql statements
var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
var $true = '1'; /// string that represents TRUE for a database
var $false = '0'; /// string that represents FALSE for a database
var $replaceQuote = "\\'"; /// string to use to replace quotes
var $charSet=false; /// character set to use - only for interbase
var $metaDatabasesSQL = '';
var $metaTablesSQL = '';
var $uniqueOrderBy = false; /// All order by columns have to be unique
var $emptyDate = '&nbsp;';
//--
var $hasInsertID = false; /// supports autoincrement ID?
var $hasAffectedRows = false; /// supports affected rows for update/delete?
var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
var $readOnly = false; /// this is a readonly database - used by phpLens
var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
var $hasGenID = false; /// can generate sequences using GenID();
var $hasTransactions = true; /// has transactions
//--
var $genID = 0; /// sequence id used by GenID();
var $raiseErrorFn = false; /// error function to call
var $upperCase = false; /// uppercase function to call for searching/where
var $isoDates = false; /// accepts dates in ISO format
var $cacheSecs = 3600; /// cache for 1 hour
var $sysDate = false; /// name of function that returns the current date
var $sysTimeStamp = false; /// name of function that returns the current timestamp
var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
var $numCacheHits = 0;
var $numCacheMisses = 0;
var $pageExecuteCountRows = true;
var $uniqueSort = false; /// indicates that all fields in order by must be unique
var $leftOuter = false; /// operator to use for left outer join in WHERE clause
var $rightOuter = false; /// operator to use for right outer join in WHERE clause
var $ansiOuter = false; /// whether ansi outer join syntax supported
var $autoRollback = false; // autoRollback on PConnect().
var $poorAffectedRows = false; // affectedRows not working or unreliable
var $fnExecute = false;
var $fnCacheExecute = false;
var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
var $dbxDriver = false;
//
// PRIVATE VARS
//
var $_oldRaiseFn = false;
var $_transOK = null;
var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
var $_errorMsg = ''; /// A variable which was used to keep the returned last error message. The value will
/// then returned by the errorMsg() function
var $_queryID = false; /// This variable keeps the last created result link identifier
var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
var $autoCommit = true; /// do not modify this yourself - actually private
var $transOff = 0; /// temporarily disable transactions
var $transCnt = 0; /// count of nested transactions
var $fetchMode=false;
/**
* Constructor
*/
function ADOConnection()
{
die('Virtual Class -- cannot instantiate');
}
/**
Get server version info...
@returns An array with 2 elements: $arr['string'] is the description string,
and $arr[version] is the version (also a string).
*/
function ServerInfo()
{
return array('description' => '', 'version' => '');
}
function _findvers($str)
{
if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
else return '';
}
/**
* All error messages go through this bottleneck function.
* You can define your own handler by defining the function name in ADODB_OUTP.
*/
function outp($msg,$newline=true)
{
global $HTTP_SERVER_VARS;
if (defined('ADODB_OUTP')) {
$fn = ADODB_OUTP;
$fn($msg,$newline);
return;
}
if ($newline) $msg .= "<br>\n";
if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;
else echo strip_tags($msg);
flush();
}
/**
* Connect to database
*
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
* @param [forceNew] force new connection
*
* @return true or false
*/
function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
{
if ($argHostname != "") $this->host = $argHostname;
if ($argUsername != "") $this->user = $argUsername;
if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
if ($argDatabaseName != "") $this->database = $argDatabaseName;
$this->_isPersistentConnection = false;
if ($fn = $this->raiseErrorFn) {
if ($forceNew) {
if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
} else {
if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
}
$err = $this->ErrorMsg();
if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
$fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
} else {
if ($forceNew) {
if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
} else {
if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
}
}
if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
return false;
}
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
{
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
}
/**
* Always force a new connection to database - currently only works with oracle
*
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
*
* @return true or false
*/
function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
{
return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
}
/**
* Establish persistent connect to database
*
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
*
* @return return true or false
*/
function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
{
if (defined('ADODB_NEVER_PERSIST'))
return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
if ($argHostname != "") $this->host = $argHostname;
if ($argUsername != "") $this->user = $argUsername;
if ($argPassword != "") $this->password = $argPassword;
if ($argDatabaseName != "") $this->database = $argDatabaseName;
$this->_isPersistentConnection = true;
if ($fn = $this->raiseErrorFn) {
if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
$err = $this->ErrorMsg();
if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
$fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
} else
if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
return false;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysDate;
return $col; // child class implement
}
/**
* Should prepare the sql statement and return the stmt resource.
* For databases that do not support this, we return the $sql. To ensure
* compatibility with databases that do not support prepare:
*
* $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
* $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
* $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
*
* @param sql SQL to send to database
*
* @return return FALSE, or the prepared statement, or the original sql if
* if the database does not support prepare.
*
*/
function Prepare($sql)
{
return $sql;
}
/**
* Some databases, eg. mssql require a different function for preparing
* stored procedures. So we cannot use Prepare().
*
* Should prepare the stored procedure and return the stmt resource.
* For databases that do not support this, we return the $sql. To ensure
* compatibility with databases that do not support prepare:
*
* @param sql SQL to send to database
*
* @return return FALSE, or the prepared statement, or the original sql if
* if the database does not support prepare.
*
*/
function PrepareSP($sql)
{
return $this->Prepare($sql);
}
/**
* PEAR DB Compat
*/
function Quote($s)
{
return $this->qstr($s,false);
}
function q(&$s)
{
$s = $this->qstr($s,false);
}
/**
* PEAR DB Compat - do not use internally.
*/
function ErrorNative()
{
return $this->ErrorNo();
}
/**
* PEAR DB Compat - do not use internally.
*/
function nextId($seq_name)
{
return $this->GenID($seq_name);
}
/**
* Lock a row, will escalate and lock the table if row locking not supported
* will normally free the lock at the end of the transaction
*
* @param $table name of table to lock
* @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
*/
function RowLock($table,$where)
{
return false;
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
/**
* PEAR DB Compat - do not use internally.
*
* The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
* for easy porting :-)
*
* @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
* @returns The previous fetch mode
*/
function SetFetchMode($mode)
{
$old = $this->fetchMode;
$this->fetchMode = $mode;
if ($old === false) {
global $ADODB_FETCH_MODE;
return $ADODB_FETCH_MODE;
}
return $old;
}
/**
* PEAR DB Compat - do not use internally.
*/
function &Query($sql, $inputarr=false)
{
$rs = &$this->Execute($sql, $inputarr);
if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
return $rs;
}
/**
* PEAR DB Compat - do not use internally
*/
function &LimitQuery($sql, $offset, $count)
{
$rs = &$this->SelectLimit($sql, $count, $offset); // swap
if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
return $rs;
}
/**
* PEAR DB Compat - do not use internally
*/
function Disconnect()
{
return $this->Close();
}
/*
Usage in oracle
$stmt = $db->Prepare('select * from table where id =:myid and group=:group');
$db->Parameter($stmt,$id,'myid');
$db->Parameter($stmt,$group,'group',64);
$db->Execute();
@param $stmt Statement returned by Prepare() or PrepareSP().
@param $var PHP variable to bind to
@param $name Name of stored procedure variable name to bind to.
@param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
@param [$maxLen] Holds an maximum length of the variable.
@param [$type] The data type of $var. Legal values depend on driver.
*/
function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
{
return false;
}
/**
Improved method of initiating a transaction. Used together with CompleteTrans().
Advantages include:
a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
Only the outermost block is treated as a transaction.<br>
b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
are disabled, making it backward compatible.
*/
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->_oldRaiseFn = $this->raiseErrorFn;
$this->raiseErrorFn = $errfn;
$this->_transOK = true;
if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
/**
Used together with StartTrans() to end a transaction. Monitors connection
for sql errors, and will commit or rollback as appropriate.
@autoComplete if true, monitor sql errors and commit and rollback as appropriate,
and if set to false force rollback even if no SQL error detected.
@returns true on commit, false on rollback.
*/
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->raiseErrorFn = $this->_oldRaiseFn;
$this->transOff = 0;
if ($this->_transOK && $autoComplete) $this->CommitTrans();
else $this->RollbackTrans();
return $this->_transOK;
}
/*
At the end of a StartTrans/CompleteTrans block, perform a rollback.
*/
function FailTrans()
{
if ($this->debug && $this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
}
$this->_transOK = false;
}
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
/**
* Execute SQL
*
* @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
* @param [inputarr] holds the input data to bind to. Null elements will be set to null.
* @param [arg3] reserved for john lim for future use
* @return RecordSet or false
*/
function &Execute($sql,$inputarr=false,$arg3=false)
{
global $pathtoroot, $totalsql, $sqlcount;
if ($this->fnExecute) {
$fn = $this->fnExecute;
$fn($this,$sql,$inputarr);
}
if (!$this->_bindInputArray && $inputarr) {
$sqlarr = explode('?',$sql);
$sql = '';
$i = 0;
foreach($inputarr as $v) {
$sql .= $sqlarr[$i];
// from Ron Baldwin <ron.baldwin@sourceprose.com>
// Only quote string types
if (gettype($v) == 'string')
$sql .= $this->qstr($v);
else if ($v === null)
$sql .= 'NULL';
else
$sql .= $v;
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
$inputarr = false;
}
// debug version of query
- if ($this->debug) {
+ if ($this->debug && isset($GLOBALS['debugger']) )
+ {
global $HTTP_SERVER_VARS, $debugger;
$ss = '';
if ($inputarr) {
foreach ($inputarr as $kk => $vv) {
if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
$ss .= "($kk=>'$vv') ";
}
$ss = "[ $ss ]";
}
$sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
// check if running from browser or command-line
$inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
if ($inBrowser)
ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);
else
ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
flush();
$profileSQLs = dbg_ConstOn('DBG_SQL_PROFILE');
if($profileSQLs)
{
$isSkipTable = isSkipTable($sql);
$queryID = $debugger->generateID();
if(!$isSkipTable) $debugger->profileStart('sql_'.$queryID, $debugger->formatSQL($sql) );
//$debugger->appendTrace();
}
$this->_queryID = $this->_query($sql,$inputarr,$arg3);
if($profileSQLs && !$isSkipTable) $debugger->profileFinish('sql_'.$queryID);
/*
Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
because ErrorNo() calls Execute('SELECT @ERROR'), causing recure
*/
if ($this->databaseType == 'mssql') {
// ErrorNo is a slow function call in mssql, and not reliable
// in PHP 4.0.6
if($emsg = $this->ErrorMsg()) {
$err = $this->ErrorNo();
if ($err) {
ADOConnection::outp($err.': '.$emsg);
flush();
}
}
} else
if (!$this->_queryID) {
$e = $this->ErrorNo();
$m = $this->ErrorMsg();
$errorLevel = dbg_ConstOn('DBG_SQL_FAILURE') && !dbg_ConstOn('IS_INSTALL') ? E_USER_ERROR : E_USER_WARNING;
$debugger->dumpVars($_REQUEST);
$debugger->appendTrace();
$error_msg = '<span class="debug_error">'.$m.' ('.$e.')</span><br><a href="javascript:SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$debugger->formatSQL($sql);
$long_id=$debugger->mapLongError($error_msg);
trigger_error( substr($m.' ('.$e.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
ADOConnection::outp($e .': '. $m );
flush();
}
} else {
// non-debug version of query
$sqlcount++;
$sql_start = $this->getmicrotime();
$this->_queryID =@$this->_query($sql,$inputarr,$arg3);
$sql_end = $this->getmicrotime();
$elapsed = $sql_end - $sql_start;
$totalsql += $elapsed;
//$fp = @fopen ($pathtoroot."log.sql", "aw");
$starttime = 0; // by Alex (variable was not defined)
$d=time()-$starttime;
$t=date("Y-m-d\tH:i:s",$starttime);
$e = round($elapsed,5);
if(function_exists("LogEntry"))
@LogEntry("\t\t$sqlcount|$e:|$sql\n");
}
// error handling if query fails
if ($this->_queryID === false) {
$fn = $this->raiseErrorFn;
if ($fn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
}
return false;
} else if ($this->_queryID === true) {
// return simplified empty recordset for inserts/updates/deletes with lower overhead
$rs = new ADORecordSet_empty();
return $rs;
}
// return real recordset from select statement
$rsclass = "ADORecordSet_".$this->databaseType;
$rs = new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions
$rs->connection = &$this; // Pablo suggestion
$rs->Init();
if (is_array($sql)) $rs->sql = $sql[0];
else $rs->sql = $sql;
if ($rs->_numOfRows <= 0) {
global $ADODB_COUNTRECS;
if ($ADODB_COUNTRECS) {
if (!$rs->EOF){
$rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
$rs->_queryID = $this->_queryID;
} else
$rs->_numOfRows = 0;
}
}
return $rs;
}
function CreateSequence($seqname='adodbseq',$startID=1)
{
if (empty($this->_genSeqSQL)) return false;
return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
}
function DropSequence($seqname)
{
if (empty($this->_dropSeqSQL)) return false;
return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
function GenID($seqname='adodbseq',$startID=1)
{
if (!$this->hasGenID) {
return 0; // formerly returns false pre 1.60
}
$getnext = sprintf($this->_genIDSQL,$seqname);
$rs = @$this->Execute($getnext);
if (!$rs) {
$createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
$rs = $this->Execute($getnext);
}
if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
else $this->genID = 0; // false
if ($rs) $rs->Close();
return $this->genID;
}
/**
* @return the last inserted ID. Not all databases support this.
*/
function Insert_ID()
{
if ($this->hasInsertID) return $this->_insertid();
if ($this->debug) ADOConnection::outp( '<p>Insert_ID error</p>');
return false;
}
/**
* Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
*
* @return the last inserted ID. All databases support this. But aware possible
* problems in multiuser environments. Heavy test this before deploying.
*/
function PO_Insert_ID($table="", $id="")
{
if ($this->hasInsertID){
return $this->Insert_ID();
} else {
return $this->GetOne("SELECT MAX($id) FROM $table");
}
}
/**
* @return # rows affected by UPDATE/DELETE
*/
function Affected_Rows()
{
if ($this->hasAffectedRows) {
$val = $this->_affectedrows();
return ($val < 0) ? false : $val;
}
if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
return false;
}
/**
* @return the last error message
*/
function ErrorMsg()
{
return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
}
/**
* @return the last error number. Normally 0 means no error.
*/
function ErrorNo()
{
return ($this->_errorMsg) ? -1 : 0;
}
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false) $err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p)) return $p;
return false;
}
/**
* Choose a database to connect to. Many databases do not support this.
*
* @param dbName is the name of the database to select
* @return true or false
*/
function SelectDB($dbName)
{return false;}
/**
* Will select, getting rows from $offset (1-based), for $nrows.
* This simulates the MySQL "select * from table limit $offset,$nrows" , and
* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
* MySQL and PostgreSQL parameter ordering is the opposite of the other.
* eg.
* SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
* SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
*
* Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
* BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
*
* @param sql
* @param [offset] is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to get
* @param [inputarr] array of bind variables
* @param [arg3] is a private parameter only used by jlim
* @param [secs2cache] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
*/
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)
{
if ($this->hasTop && $nrows > 0) {
// suggested by Reinhard Balling. Access requires top after distinct
// Informix requires first before distinct - F Riosa
$ismssql = (strpos($this->databaseType,'mssql') !== false);
if ($ismssql) $isaccess = false;
else $isaccess = (strpos($this->databaseType,'access') !== false);
if ($offset <= 0) {
// access includes ties in result
if ($isaccess) {
$sql = preg_replace(
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
if ($secs2cache>0) return $this->CacheExecute($secs2cache, $sql,$inputarr,$arg3);
else return $this->Execute($sql,$inputarr,$arg3);
} else if ($ismssql){
$sql = preg_replace(
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
} else {
$sql = preg_replace(
'/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
}
} else {
$nn = $nrows + $offset;
if ($isaccess || $ismssql) {
$sql = preg_replace(
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
} else {
$sql = preg_replace(
'/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
}
}
}
// if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
// 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
global $ADODB_COUNTRECS;
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
if ($offset>0){
if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3);
else $rs = &$this->Execute($sql,$inputarr,$arg3);
} else {
if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3);
else $rs = &$this->Execute($sql,$inputarr,$arg3);
}
$ADODB_COUNTRECS = $savec;
if ($rs && !$rs->EOF) {
return $this->_rs2rs($rs,$nrows,$offset);
}
//print_r($rs);
return $rs;
}
/**
* Convert database recordset to an array recordset
* input recordset's cursor should be at beginning, and
* old $rs will be closed.
*
* @param rs the recordset to copy
* @param [nrows] number of rows to retrieve (optional)
* @param [offset] offset by number of rows (optional)
* @return the new recordset
*/
function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
{
if (! $rs) return false;
$dbtype = $rs->databaseType;
if (!$dbtype) {
$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
return $rs;
}
if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
$rs->MoveFirst();
$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
return $rs;
}
$flds = array();
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
$flds[] = $rs->FetchField($i);
}
$arr =& $rs->GetArrayLimit($nrows,$offset);
//print_r($arr);
if ($close) $rs->Close();
$arrayClass = $this->arrayClass;
$rs2 = new $arrayClass();
$rs2->connection = &$this;
$rs2->sql = $rs->sql;
$rs2->dataProvider = $this->dataProvider;
$rs2->InitArrayFields($arr,$flds);
return $rs2;
}
function &GetArray($sql, $inputarr=false)
{
return $this->GetAll($sql,$inputarr);
}
/**
* Return first element of first row of sql statement. Recordset is disposed
* for you.
*
* @param sql SQL statement
* @param [inputarr] input bind array
*/
function GetOne($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$ret = false;
$rs = &$this->Execute($sql,$inputarr);
if ($rs) {
if (!$rs->EOF) $ret = reset($rs->fields);
$rs->Close();
}
$ADODB_COUNTRECS = $crecs;
return $ret;
}
function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
{
$ret = false;
$rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
if ($rs) {
if (!$rs->EOF) $ret = reset($rs->fields);
$rs->Close();
}
return $ret;
}
function GetCol($sql, $inputarr = false, $trim = false)
{
$rv = false;
$rs = &$this->Execute($sql, $inputarr);
if ($rs) {
if ($trim) {
while (!$rs->EOF) {
$rv[] = trim(reset($rs->fields));
$rs->MoveNext();
}
} else {
while (!$rs->EOF) {
$rv[] = reset($rs->fields);
$rs->MoveNext();
}
}
$rs->Close();
}
return $rv;
}
function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
{
$rv = false;
$rs = &$this->CacheExecute($secs, $sql, $inputarr);
if ($rs) {
if ($trim) {
while (!$rs->EOF) {
$rv[] = trim(reset($rs->fields));
$rs->MoveNext();
}
} else {
while (!$rs->EOF) {
$rv[] = reset($rs->fields);
$rs->MoveNext();
}
}
$rs->Close();
}
return $rv;
}
/*
Calculate the offset of a date for a particular database and generate
appropriate SQL. Useful for calculating future/past dates and storing
in a database.
If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
*/
function OffsetDate($dayFraction,$date=false)
{
if (!$date) $date = $this->sysDate;
return '('.$date.'+'.$dayFraction.')';
}
/**
* Return all rows. Compat with PEAR DB
*
* @param sql SQL statement
* @param [inputarr] input bind array
*/
function &GetAll($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = $this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $savec;
if (!$rs)
if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
else return false;
$arr =& $rs->GetArray();
$rs->Close();
return $arr;
}
function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
{
global $ADODB_COUNTRECS;
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
$ADODB_COUNTRECS = $savec;
if (!$rs)
if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
else return false;
$arr =& $rs->GetArray();
$rs->Close();
return $arr;
}
/**
* Return one row of sql statement. Recordset is disposed for you.
*
* @param sql SQL statement
* @param [inputarr] input bind array
*/
function &GetRow($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = $this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $crecs;
if ($rs) {
$arr = array();
if (!$rs->EOF) $arr = $rs->fields;
$rs->Close();
return $arr;
}
return false;
}
function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
{
$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
if ($rs) {
$arr = false;
if (!$rs->EOF) $arr = $rs->fields;
$rs->Close();
return $arr;
}
return false;
}
/**
* Insert or replace a single record. Note: this is not the same as MySQL's replace.
* ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
* Also note that no table locking is done currently, so it is possible that the
* record be inserted twice by two programs...
*
* $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
*
* $table table name
* $fieldArray associative array of data (you must quote strings yourself).
* $keyCol the primary key field name or if compound key, array of field names
* autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
* but does not work with dates nor SQL functions.
* has_autoinc the primary key is an auto-inc field, so skip in insert.
*
* Currently blob replace not supported
*
* returns 0 = fail, 1 = update, 2 = insert
*/
function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
{
if (count($fieldArray) == 0) return 0;
$first = true;
$uSet = '';
if (!is_array($keyCol)) {
$keyCol = array($keyCol);
}
foreach($fieldArray as $k => $v) {
if ($autoQuote && !is_numeric($v) and substr($v,0,1) != "'" and strcasecmp($v,'null')!=0) {
$v = $this->qstr($v);
$fieldArray[$k] = $v;
}
if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
if ($first) {
$first = false;
$uSet = "$k=$v";
} else
$uSet .= ",$k=$v";
}
$first = true;
foreach ($keyCol as $v) {
if ($first) {
$first = false;
$where = "$v=$fieldArray[$v]";
} else {
$where .= " and $v=$fieldArray[$v]";
}
}
if ($uSet) {
$update = "UPDATE $table SET $uSet WHERE $where";
$rs = $this->Execute($update);
if ($rs) {
if ($this->poorAffectedRows) {
/*
The Select count(*) wipes out any errors that the update would have returned.
http://phplens.com/lens/lensforum/msgs.php?id=5696
*/
if ($this->ErrorNo()<>0) return 0;
# affected_rows == 0 if update field values identical to old values
# for mysql - which is silly.
$cnt = $this->GetOne("select count(*) from $table where $where");
if ($cnt > 0) return 1; // record already exists
} else
if (($this->Affected_Rows()>0)) return 1;
}
}
// print "<p>Error=".$this->ErrorNo().'<p>';
$first = true;
foreach($fieldArray as $k => $v) {
if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
if ($first) {
$first = false;
$iCols = "$k";
$iVals = "$v";
} else {
$iCols .= ",$k";
$iVals .= ",$v";
}
}
$insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
$rs = $this->Execute($insert);
return ($rs) ? 2 : 0;
}
/**
* Will select, getting rows from $offset (1-based), for $nrows.
* This simulates the MySQL "select * from table limit $offset,$nrows" , and
* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
* MySQL and PostgreSQL parameter ordering is the opposite of the other.
* eg.
* CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
* CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
*
* BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
*
* @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
* @param sql
* @param [offset] is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to get
* @param [inputarr] array of bind variables
* @param [arg3] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
*/
function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false)
{
if (!is_numeric($secs2cache)) {
if ($sql === false) $sql = -1;
if ($offset == -1) $offset = false;
// sql, nrows, offset,inputarr,arg3
return $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$inputarr,$this->cacheSecs);
} else {
if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
return $this->SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
}
}
/**
* Flush cached recordsets that match a particular $sql statement.
* If $sql == false, then we purge all files in the cache.
*/
function CacheFlush($sql=false,$inputarr=false)
{
global $ADODB_CACHE_DIR;
if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
if (strpos(strtoupper(PHP_OS),'WIN') !== false) {
$cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
} else {
$cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
// old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
}
if ($this->debug) {
ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
} else {
exec($cmd);
}
return;
}
$f = $this->_gencachename($sql.serialize($inputarr),false);
adodb_write_file($f,''); // is adodb_write_file needed?
@unlink($f);
}
/**
* Private function to generate filename for caching.
* Filename is generated based on:
*
* - sql statement
* - database type (oci8, ibase, ifx, etc)
* - database name
* - userid
*
* We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
* Assuming that we can have 50,000 files per directory with good performance,
* then we can scale to 12.8 million unique cached recordsets. Wow!
*/
function _gencachename($sql,$createdir)
{
global $ADODB_CACHE_DIR;
$m = md5($sql.$this->databaseType.$this->database.$this->user);
$dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
if ($createdir && !file_exists($dir)) {
$oldu = umask(0);
if (!mkdir($dir,0771))
if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
umask($oldu);
}
return $dir.'/adodb_'.$m.'.cache';
}
/**
* Execute SQL, caching recordsets.
*
* @param [secs2cache] seconds to cache data, set to 0 to force query.
* This is an optional parameter.
* @param sql SQL statement to execute
* @param [inputarr] holds the input data to bind to
* @param [arg3] reserved for john lim for future use
* @return RecordSet or false
*/
function &CacheExecute($secs2cache,$sql=false,$inputarr=false,$arg3=false)
{
if (!is_numeric($secs2cache)) {
$arg3 = $inputarr;
$inputarr = $sql;
$sql = $secs2cache;
$secs2cache = $this->cacheSecs;
}
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
$md5file = $this->_gencachename($sql.serialize($inputarr),true);
$err = '';
if ($secs2cache > 0){
$rs = &csv2rs($md5file,$err,$secs2cache);
$this->numCacheHits += 1;
} else {
$err='Timeout 1';
$rs = false;
$this->numCacheMisses += 1;
}
if (!$rs) {
// no cached rs found
if ($this->debug) {
if (get_magic_quotes_runtime()) {
ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
}
ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
}
$rs = &$this->Execute($sql,$inputarr,$arg3);
if ($rs) {
$eof = $rs->EOF;
$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
$txt = _rs2serialize($rs,false,$sql); // serialize
if (!adodb_write_file($md5file,$txt,$this->debug)) {
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
}
if ($this->debug) ADOConnection::outp( " Cache write error");
}
if ($rs->EOF && !$eof) {
$rs->MoveFirst();
//$rs = &csv2rs($md5file,$err);
$rs->connection = &$this; // Pablo suggestion
}
} else
@unlink($md5file);
} else {
if ($this->fnCacheExecute) {
$fn = $this->fnCacheExecute;
$fn($this, $secs2cache, $sql, $inputarr);
}
// ok, set cached object found
$rs->connection = &$this; // Pablo suggestion
if ($this->debug){
global $HTTP_SERVER_VARS;
$inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
$ttl = $rs->timeCreated + $secs2cache - time();
$s = is_array($sql) ? $sql[0] : $sql;
if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
}
}
return $rs;
}
/**
* Generates an Update Query based on an existing recordset.
* $arrFields is an associative array of fields with the value
* that should be assigned.
*
* Note: This function should only be used on a recordset
* that is run against a single table and sql should only
* be a simple select stmt with no groupby/orderby/limit
*
* "Jonathan Younger" <jyounger@unilab.com>
*/
function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
{
include_once(ADODB_DIR.'/adodb-lib.inc.php');
return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
}
/**
* Generates an Insert Query based on an existing recordset.
* $arrFields is an associative array of fields with the value
* that should be assigned.
*
* Note: This function should only be used on a recordset
* that is run against a single table.
*/
function GetInsertSQL(&$rs, $arrFields,$magicq=false)
{
include_once(ADODB_DIR.'/adodb-lib.inc.php');
return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
}
/**
* Update a blob column, given a where clause. There are more sophisticated
* blob handling functions that we could have implemented, but all require
* a very complex API. Instead we have chosen something that is extremely
* simple to understand and use.
*
* Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
*
* Usage to update a $blobvalue which has a primary key blob_id=1 into a
* field blobtable.blobcolumn:
*
* UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
*
* Insert example:
*
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
*/
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
{
return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
}
/**
* Usage:
* UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
*
* $blobtype supports 'BLOB' and 'CLOB'
*
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
*/
function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
{
$fd = fopen($path,'rb');
if ($fd === false) return false;
$val = fread($fd,filesize($path));
fclose($fd);
return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
}
function BlobDecode($blob)
{
return $blob;
}
function BlobEncode($blob)
{
return $blob;
}
/**
* Usage:
* UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
*
* $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
* $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
*/
function UpdateClob($table,$column,$val,$where)
{
return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
}
/**
* $meta contains the desired type, which could be...
* C for character. You will have to define the precision yourself.
* X for teXt. For unlimited character lengths.
* B for Binary
* F for floating point, with no need to define scale and precision
* N for decimal numbers, you will have to define the (scale, precision) yourself
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
* and if you want to use double-byte, add a 2 to the end, like C2 or X2.
*
*
* @return the actual type of the data or false if no such type available
*/
function ActualType($meta)
{
switch($meta) {
case 'C':
case 'X':
return 'VARCHAR';
case 'B':
case 'D':
case 'T':
case 'L':
case 'R':
case 'I':
case 'N':
return false;
}
}
/*
* Maximum size of C field
*/
function CharMax()
{
return 255; // make it conservative if not defined
}
/*
* Maximum size of X field
*/
function TextMax()
{
return 4000; // make it conservative if not defined
}
/**
* Close Connection
*/
function Close()
{
return $this->_close();
// "Simon Lee" <simon@mediaroad.com> reports that persistent connections need
// to be closed too!
//if ($this->_isPersistentConnection != true) return $this->_close();
//else return true;
}
/**
* Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
*
* @return true if succeeded or false if database does not support transactions
*/
function BeginTrans() {return false;}
/**
* If database does not support transactions, always return true as data always commited
*
* @param $ok set to false to rollback transaction, true to commit
*
* @return true/false.
*/
function CommitTrans($ok=true)
{ return true;}
/**
* If database does not support transactions, rollbacks always fail, so return false
*
* @return true/false.
*/
function RollbackTrans()
{ return false;}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function MetaDatabases()
{
global $ADODB_FETCH_MODE;
if ($this->metaDatabasesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$arr = $this->GetCol($this->metaDatabasesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $arr;
}
return false;
}
/**
* @return array of tables for current database.
*/
function &MetaTables()
{
global $ADODB_FETCH_MODE;
if ($this->metaTablesSQL) {
// complicated state saving by the need for backward compat
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
$arr =& $rs->GetArray();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
$arr2[] = $arr[$i][0];
}
$rs->Close();
return $arr2;
}
return false;
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param table table name to query
* @param upper uppercase table name (required by some databases)
*
* @return array of ADOFieldObjects for current table.
*/
function &MetaColumns($table,$upper=true)
{
global $ADODB_FETCH_MODE;
if (!empty($this->metaColumnsSQL)) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
if (isset($rs->fields[3]) && $rs->fields[3]) {
if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
$fld->scale = $rs->fields[4];
if ($fld->scale>0) $fld->max_length += 1;
} else
$fld->max_length = $rs->fields[2];
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) return false;
$arr = array();
foreach($objarr as $v) {
$arr[] = $v->name;
}
return $arr;
}
/**
* Different SQL databases used different methods to combine strings together.
* This function provides a wrapper.
*
* param s variable number of string parameters
*
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
return implode($this->concat_operator, $arr);
}
/**
* Converts a date "d" to a string that the database can understand.
*
* @param d a date in Unix date time format.
*
* @return date string in database date format
*/
function DBDate($d)
{
if (empty($d) && $d !== 0) return 'null';
if (is_string($d) && !is_numeric($d)) {
if ($d === 'null') return $d;
if ($this->isoDates) return "'$d'";
$d = ADOConnection::UnixDate($d);
}
return adodb_date($this->fmtDate,$d);
}
/**
* Converts a timestamp "ts" to a string that the database can understand.
*
* @param ts a timestamp in Unix date time format.
*
* @return timestamp string in database timestamp format
*/
function DBTimeStamp($ts)
{
if (empty($ts) && $ts !== 0) return 'null';
if (is_string($ts) && !is_numeric($ts)) {
if ($ts === 'null') return $ts;
if ($this->isoDates) return "'$ts'";
else $ts = ADOConnection::UnixTimeStamp($ts);
}
return adodb_date($this->fmtTimeStamp,$ts);
}
/**
* Also in ADORecordSet.
* @param $v is a date string in YYYY-MM-DD format
*
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
*/
function UnixDate($v)
{
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
($v), $rr)) return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
// h-m-s-MM-DD-YY
return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
}
/**
* Also in ADORecordSet.
* @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
*
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
*/
function UnixTimeStamp($v)
{
if (!preg_match(
"|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
($v), $rr)) return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
}
/**
* Also in ADORecordSet.
*
* Format database date based on user defined format.
*
* @param v is the character date in YYYY-MM-DD format, returned by database
* @param fmt is the format to apply to it, using date()
*
* @return a date formated as user desires
*/
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false) return $v;
else if ($tt == 0) return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
/**
* Correctly quotes a string so that all strings are escaped. We prefix and append
* to the string single-quotes.
* An example is $db->qstr("Don't bother",magic_quotes_runtime());
*
* @param s the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
* This undoes the stupidity of magic quotes for GPC.
*
* @return quoted string to be sent back to database
*/
function qstr($s,$magic_quotes=false)
{
if (!$magic_quotes) {
if ($this->replaceQuote[0] == '\\'){
// only since php 4.0.5
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
}
return "'".str_replace("'",$this->replaceQuote,$s)."'";
}
// undo magic quotes for "
$s = str_replace('\\"','"',$s);
if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
return "'$s'";
else {// change \' to '' for sybase/mssql
$s = str_replace('\\\\','\\',$s);
return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
}
}
/**
* Will select the supplied $page number from a recordset, given that it is paginated in pages of
* $nrows rows per page. It also saves two boolean values saying if the given page is the first
* and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
*
* See readme.htm#ex8 for an example of usage.
*
* @param sql
* @param nrows is the number of rows per page to get
* @param page is the page number to get (1-based)
* @param [inputarr] array of bind variables
* @param [arg3] is a private parameter only used by jlim
* @param [secs2cache] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
*
* NOTE: phpLens uses a different algorithm and does not use PageExecute().
*
*/
function &PageExecute($sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0)
{
include_once(ADODB_DIR.'/adodb-lib.inc.php');
if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache);
return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache);
}
/**
* Will select the supplied $page number from a recordset, given that it is paginated in pages of
* $nrows rows per page. It also saves two boolean values saying if the given page is the first
* and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
*
* @param secs2cache seconds to cache data, set to 0 to force query
* @param sql
* @param nrows is the number of rows per page to get
* @param page is the page number to get (1-based)
* @param [inputarr] array of bind variables
* @param [arg3] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
*/
function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false, $arg3=false)
{
/*switch($this->dataProvider) {
case 'postgres':
case 'mysql':
break;
default: $secs2cache = 0; break;
}*/
return $this->PageExecute($sql,$nrows,$page,$inputarr,$arg3,$secs2cache);
}
} // end class ADOConnection
//==============================================================================================
// CLASS ADOFetchObj
//==============================================================================================
/**
* Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
*/
class ADOFetchObj {
};
//==============================================================================================
// CLASS ADORecordSet_empty
//==============================================================================================
/**
* Lightweight recordset when there are no records to be returned
*/
class ADORecordSet_empty
{
var $dataProvider = 'empty';
var $databaseType = false;
var $EOF = true;
var $_numOfRows = 0;
var $fields = false;
var $connection = false;
function RowCount() {return 0;}
function RecordCount() {return 0;}
function PO_RecordCount(){return 0;}
function Close(){return true;}
function FetchRow() {return false;}
function FieldCount(){ return 0;}
}
//==============================================================================================
// DATE AND TIME FUNCTIONS
//==============================================================================================
include_once(ADODB_DIR.'/adodb-time.inc.php');
//==============================================================================================
// CLASS ADORecordSet
//==============================================================================================
/**
* RecordSet class that represents the dataset returned by the database.
* To keep memory overhead low, this class holds only the current row in memory.
* No prefetching of data is done, so the RecordCount() can return -1 ( which
* means recordcount not known).
*/
class ADORecordSet {
/*
* public variables
*/
var $dataProvider = "native";
var $fields = false; /// holds the current row data
var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
/// in other words, we use a text area for editting.
var $canSeek = false; /// indicates that seek is supported
var $sql; /// sql text
var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $debug = false;
var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
var $bind = false; /// used by Fields() to hold array - should be private?
var $fetchMode; /// default fetch mode
var $connection = false; /// the parent connection
/*
* private variables
*/
var $_numOfRows = -1; /** number of rows, or -1 */
var $_numOfFields = -1; /** number of fields in recordset */
var $_queryID = -1; /** This variable keeps the result link identifier. */
var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
var $_closed = false; /** has recordset been closed */
var $_inited = false; /** Init() should only be called once */
var $_obj; /** Used by FetchObj */
var $_names; /** Used by FetchObj */
var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */
var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
var $_lastPageNo = -1;
var $_maxRecordCount = 0;
var $dateHasTime = false;
/**
* Constructor
*
* @param queryID this is the queryID returned by ADOConnection->_query()
*
*/
function ADORecordSet($queryID)
{
$this->_queryID = $queryID;
}
function Init()
{
if ($this->_inited) return;
$this->_inited = true;
if ($this->_queryID) @$this->_initrs();
else {
$this->_numOfRows = 0;
$this->_numOfFields = 0;
}
if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
$this->_currentRow = 0;
if ($this->EOF = ($this->_fetch() === false)) {
$this->_numOfRows = 0; // _numOfRows could be -1
}
} else {
$this->EOF = true;
}
}
/**
* Generate a SELECT tag string from a recordset, and return the string.
* If the recordset has 2 cols, we treat the 1st col as the containing
* the text to display to the user, and 2nd col as the return value. Default
* strings are compared with the FIRST column.
*
* @param name name of SELECT tag
* @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
* @param [blank1stItem] true to leave the 1st item in list empty
* @param [multiple] true for listbox, false for popup
* @param [size] #rows to show for listbox. not used by popup
* @param [selectAttr] additional attributes to defined for SELECT tag.
* useful for holding javascript onChange='...' handlers.
& @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
* column 0 (1st col) if this is true. This is not documented.
*
* @return HTML
*
* changes by glen.davies@cce.ac.nz to support multiple hilited items
*/
function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
include_once(ADODB_DIR.'/adodb-lib.inc.php');
return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
$size, $selectAttr,$compareFields0);
}
/**
* Generate a SELECT tag string from a recordset, and return the string.
* If the recordset has 2 cols, we treat the 1st col as the containing
* the text to display to the user, and 2nd col as the return value. Default
* strings are compared with the SECOND column.
*
*/
function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
{
include_once(ADODB_DIR.'/adodb-lib.inc.php');
return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
$size, $selectAttr,false);
}
/**
* return recordset as a 2-dimensional array.
*
* @param [nRows] is the number of rows to return. -1 means every row.
*
* @return an array indexed by the rows (0-based) from the recordset
*/
function &GetArray($nRows = -1)
{
global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
/*
* Some databases allow multiple recordsets to be returned. This function
* will return true if there is a next recordset, or false if no more.
*/
function NextRecordSet()
{
return false;
}
/**
* return recordset as a 2-dimensional array.
* Helper function for ADOConnection->SelectLimit()
*
* @param offset is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to return
*
* @return an array indexed by the rows (0-based) from the recordset
*/
function &GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) {
return $this->GetArray($nrows);
}
$this->Move($offset);
$results = array();
$cnt = 0;
while (!$this->EOF && $nrows != $cnt) {
$results[$cnt++] = $this->fields;
$this->MoveNext();
}
return $results;
}
/**
* Synonym for GetArray() for compatibility with ADO.
*
* @param [nRows] is the number of rows to return. -1 means every row.
*
* @return an array indexed by the rows (0-based) from the recordset
*/
function &GetRows($nRows = -1)
{
return $this->GetArray($nRows);
}
/**
* return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
* The first column is treated as the key and is not included in the array.
* If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
* $force_array == true.
*
* @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
* array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
* read the source.
*
* @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
* instead of returning array[col0] => array(remaining cols), return array[col0] => col1
*
* @return an associative array indexed by the first column of the array,
* or false if the data has less than 2 cols.
*/
function &GetAssoc($force_array = false, $first2cols = false) {
$cols = $this->_numOfFields;
if ($cols < 2) {
return false;
}
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($cols > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
// return scalar values
if ($numIndex) {
while (!$this->EOF) {
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
return $results;
}
/**
*
* @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
* @param fmt is the format to apply to it, using date()
*
* @return a timestamp formated as user desires
*/
function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
{
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false) return $v;
if ($tt == 0) return $this->emptyTimeStamp;
return adodb_date($fmt,$tt);
}
/**
* @param v is the character date in YYYY-MM-DD format, returned by database
* @param fmt is the format to apply to it, using date()
*
* @return a date formated as user desires
*/
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false) return $v;
else if ($tt == 0) return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
/**
* @param $v is a date string in YYYY-MM-DD format
*
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
*/
function UnixDate($v)
{
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
($v), $rr)) return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
// h-m-s-MM-DD-YY
return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
}
/**
* @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
*
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
*/
function UnixTimeStamp($v)
{
if (!preg_match(
"|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
($v), $rr)) return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
}
/**
* PEAR DB Compat - do not use internally
*/
function Free()
{
return $this->Close();
}
/**
* PEAR DB compat, number of rows
*/
function NumRows()
{
return $this->_numOfRows;
}
/**
* PEAR DB compat, number of cols
*/
function NumCols()
{
return $this->_numOfFields;
}
/**
* Fetch a row, returning false if no more rows.
* This is PEAR DB compat mode.
*
* @return false or array containing the current record
*/
function FetchRow()
{
if ($this->EOF) return false;
$arr = $this->fields;
$this->_currentRow++;
if (!$this->_fetch()) $this->EOF = true;
return $arr;
}
/**
* Fetch a row, returning PEAR_Error if no more rows.
* This is PEAR DB compat mode.
*
* @return DB_OK or error object
*/
function FetchInto(&$arr)
{
if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
$arr = $this->fields;
$this->MoveNext();
return 1; // DB_OK
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Move to the last row in the recordset.
*
* @return true or false
*/
function MoveLast()
{
if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
if ($this->EOF) return false;
while (!$this->EOF) {
$f = $this->fields;
$this->MoveNext();
}
$this->fields = $f;
$this->EOF = false;
return true;
}
/**
* Move to next record in the recordset.
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if ($this->_fetch()) return true;
}
$this->EOF = true;
/* -- tested error handling when scrolling cursor -- seems useless.
$conn = $this->connection;
if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
$fn = $conn->raiseErrorFn;
$fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
}
*/
return false;
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
$this->EOF = false;
if ($rowNumber == $this->_currentRow) return true;
if ($rowNumber >= $this->_numOfRows)
if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
if ($this->canSeek) {
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
} else {
$this->EOF = true;
return false;
}
} else {
if ($rowNumber < $this->_currentRow) return false;
global $ADODB_EXTENSION;
if ($ADODB_EXTENSION) {
while (!$this->EOF && $this->_currentRow < $rowNumber) {
adodb_movenext($this);
}
} else {
while (! $this->EOF && $this->_currentRow < $rowNumber) {
$this->_currentRow++;
if (!$this->_fetch()) $this->EOF = true;
}
}
return !($this->EOF);
}
$this->fields = false;
$this->EOF = true;
return false;
}
/**
* Get the value of a field in the current row by column name.
* Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
*
* @param colname is the field to access
*
* @return the value of $colname column
*/
function Fields($colname)
{
return $this->fields[$colname];
}
function GetAssocKeys($upper=true)
{
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
if ($upper === 2) $this->bind[$o->name] = $i;
else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
}
}
/**
* Use associative array to get fields array for databases that do not support
* associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
*
* If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
* before you execute your SQL statement, and access $rs->fields['col'] directly.
*
* $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
*/
function GetRowAssoc($upper=1)
{
if (!$this->bind) {
$this->GetAssocKeys($upper);
}
$record = array();
foreach($this->bind as $k => $v) {
$record[$k] = $this->fields[$v];
}
return $record;
}
/**
* Clean up recordset
*
* @return true or false
*/
function Close()
{
// free connection object - this seems to globally free the object
// and not merely the reference, so don't do this...
// $this->connection = false;
if (!$this->_closed) {
$this->_closed = true;
return $this->_close();
} else
return true;
}
/**
* synonyms RecordCount and RowCount
*
* @return the number of rows or -1 if this is not supported
*/
function RecordCount() {return $this->_numOfRows;}
/*
* If we are using PageExecute(), this will return the maximum possible rows
* that can be returned when paging a recordset.
*/
function MaxRecordCount()
{
return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
}
/**
* synonyms RecordCount and RowCount
*
* @return the number of rows or -1 if this is not supported
*/
function RowCount() {return $this->_numOfRows;}
/**
* Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
*
* @return the number of records from a previous SELECT. All databases support this.
*
* But aware possible problems in multiuser environments. For better speed the table
* must be indexed by the condition. Heavy test this before deploying.
*/
function PO_RecordCount($table="", $condition="") {
$lnumrows = $this->_numOfRows;
// the database doesn't support native recordcount, so we do a workaround
if ($lnumrows == -1 && $this->connection) {
IF ($table) {
if ($condition) $condition = " WHERE " . $condition;
$resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows) $lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
/**
* @return the current row in the recordset. If at EOF, will return the last row. 0-based.
*/
function CurrentRow() {return $this->_currentRow;}
/**
* synonym for CurrentRow -- for ADO compat
*
* @return the current row in the recordset. If at EOF, will return the last row. 0-based.
*/
function AbsolutePosition() {return $this->_currentRow;}
/**
* @return the number of columns in the recordset. Some databases will set this to 0
* if no records are returned, others will return the number of columns in the query.
*/
function FieldCount() {return $this->_numOfFields;}
/**
* Get the ADOFieldObject of a specific column.
*
* @param fieldoffset is the column position to access(0-based).
*
* @return the ADOFieldObject for that column, or false.
*/
function &FetchField($fieldoffset)
{
// must be defined by child class
}
/**
* Get the ADOFieldObjects of all columns in an array.
*
*/
function FieldTypesArray()
{
$arr = array();
for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
$arr[] = $this->FetchField($i);
return $arr;
}
/**
* Return the fields array of the current row as an object for convenience.
* The default case is lowercase field names.
*
* @return the object with the properties set to the fields of the current row
*/
function &FetchObj()
{
return FetchObject(false);
}
/**
* Return the fields array of the current row as an object for convenience.
* The default case is uppercase.
*
* @param $isupper to set the object property names to uppercase
*
* @return the object with the properties set to the fields of the current row
*/
function &FetchObject($isupper=true)
{
if (empty($this->_obj)) {
$this->_obj = new ADOFetchObj();
$this->_names = array();
for ($i=0; $i <$this->_numOfFields; $i++) {
$f = $this->FetchField($i);
$this->_names[] = $f->name;
}
}
$i = 0;
$o = &$this->_obj;
for ($i=0; $i <$this->_numOfFields; $i++) {
$name = $this->_names[$i];
if ($isupper) $n = strtoupper($name);
else $n = $name;
$o->$n = $this->Fields($name);
}
return $o;
}
/**
* Return the fields array of the current row as an object for convenience.
* The default is lower-case field names.
*
* @return the object with the properties set to the fields of the current row,
* or false if EOF
*
* Fixed bug reported by tim@orotech.net
*/
function &FetchNextObj()
{
return $this->FetchNextObject(false);
}
/**
* Return the fields array of the current row as an object for convenience.
* The default is upper case field names.
*
* @param $isupper to set the object property names to uppercase
*
* @return the object with the properties set to the fields of the current row,
* or false if EOF
*
* Fixed bug reported by tim@orotech.net
*/
function &FetchNextObject($isupper=true)
{
$o = false;
if ($this->_numOfRows != 0 && !$this->EOF) {
$o = $this->FetchObject($isupper);
$this->_currentRow++;
if ($this->_fetch()) return $o;
}
$this->EOF = true;
return $o;
}
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 200 chars
* X for teXt (>= 200 chars)
* B for Binary
* N for numeric floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
// changed in 2.32 to hashing instead of switch stmt for speed...
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
##
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INTEGER' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X'
);
$tmap = false;
$t = strtoupper($t);
$tmap = @$typeMap[$t];
switch ($tmap) {
case 'C':
// is the char field is too long, return as text field...
if (!empty($this->blobSize)) {
if ($len > $this->blobSize) return 'X';
} else if ($len > 250) {
return 'X';
}
return 'C';
case 'I':
if (!empty($fieldobj->primary_key)) return 'R';
return 'I';
case false:
return 'N';
case 'B':
if (isset($fieldobj->binary))
return ($fieldobj->binary) ? 'B' : 'X';
return 'B';
case 'D':
if (!empty($this->dateHasTime)) return 'T';
return 'D';
default:
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
function _close() {}
/**
* set/returns the current recordset page when paginating
*/
function AbsolutePage($page=-1)
{
if ($page != -1) $this->_currentPage = $page;
return $this->_currentPage;
}
/**
* set/returns the status of the atFirstPage flag when paginating
*/
function AtFirstPage($status=false)
{
if ($status != false) $this->_atFirstPage = $status;
return $this->_atFirstPage;
}
function LastPageNo($page = false)
{
if ($page != false) $this->_lastPageNo = $page;
return $this->_lastPageNo;
}
/**
* set/returns the status of the atLastPage flag when paginating
*/
function AtLastPage($status=false)
{
if ($status != false) $this->_atLastPage = $status;
return $this->_atLastPage;
}
} // end class ADORecordSet
//==============================================================================================
// CLASS ADORecordSet_array
//==============================================================================================
/**
* This class encapsulates the concept of a recordset created in memory
* as an array. This is useful for the creation of cached recordsets.
*
* Note that the constructor is different from the standard ADORecordSet
*/
class ADORecordSet_array extends ADORecordSet
{
var $databaseType = 'array';
var $_array; // holds the 2-dimensional data array
var $_types; // the array of types of each column (C B I L M)
var $_colnames; // names of each column in array
var $_skiprow1; // skip 1st row because it holds column names
var $_fieldarr; // holds array of field objects
var $canSeek = true;
var $affectedrows = false;
var $insertid = false;
var $sql = '';
var $compat = false;
/**
* Constructor
*
*/
function ADORecordSet_array($fakeid=1)
{
global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
// fetch() on EOF does not delete $this->fields
$this->compat = !empty($ADODB_COMPAT_FETCH);
$this->ADORecordSet($fakeid); // fake queryID
$this->fetchMode = $ADODB_FETCH_MODE;
}
/**
* Setup the Array. Later we will have XML-Data and CSV handlers
*
* @param array is a 2-dimensional array holding the data.
* The first row should hold the column names
* unless paramter $colnames is used.
* @param typearr holds an array of types. These are the same types
* used in MetaTypes (C,B,L,I,N).
* @param [colnames] array of column names. If set, then the first row of
* $array should not hold the column names.
*/
function InitArray($array,$typearr,$colnames=false)
{
$this->_array = $array;
$this->_types = $typearr;
if ($colnames) {
$this->_skiprow1 = false;
$this->_colnames = $colnames;
} else $this->_colnames = $array[0];
$this->Init();
}
/**
* Setup the Array and datatype file objects
*
* @param array is a 2-dimensional array holding the data.
* The first row should hold the column names
* unless paramter $colnames is used.
* @param fieldarr holds an array of ADOFieldObject's.
*/
function InitArrayFields($array,$fieldarr)
{
$this->_array = $array;
$this->_skiprow1= false;
if ($fieldarr) {
$this->_fieldobjects = $fieldarr;
}
$this->Init();
}
function &GetArray($nRows=-1)
{
if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
return $this->_array;
} else {
return ADORecordSet::GetArray($nRows);
}
}
function _initrs()
{
$this->_numOfRows = sizeof($this->_array);
if ($this->_skiprow1) $this->_numOfRows -= 1;
$this->_numOfFields =(isset($this->_fieldobjects)) ?
sizeof($this->_fieldobjects):sizeof($this->_types);
}
/* Use associative array to get fields array */
function Fields($colname)
{
if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function &FetchField($fieldOffset = -1)
{
if (isset($this->_fieldobjects)) {
return $this->_fieldobjects[$fieldOffset];
}
$o = new ADOFieldObject();
$o->name = $this->_colnames[$fieldOffset];
$o->type = $this->_types[$fieldOffset];
$o->max_length = -1; // length not known
return $o;
}
function _seek($row)
{
if (sizeof($this->_array) && $row < $this->_numOfRows) {
$this->fields = $this->_array[$row];
return true;
}
return false;
}
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
$pos = $this->_currentRow;
if ($this->_skiprow1) $pos += 1;
if ($this->_numOfRows <= $pos) {
if (!$this->compat) $this->fields = false;
} else {
$this->fields = $this->_array[$pos];
return true;
}
$this->EOF = true;
}
return false;
}
function _fetch()
{
$pos = $this->_currentRow;
if ($this->_skiprow1) $pos += 1;
if ($this->_numOfRows <= $pos) {
if (!$this->compat) $this->fields = false;
return false;
}
$this->fields = $this->_array[$pos];
return true;
}
function _close()
{
return true;
}
} // ADORecordSet_array
//==============================================================================================
// HELPER FUNCTIONS
//==============================================================================================
/**
* Synonym for ADOLoadCode.
*
* @deprecated
*/
function ADOLoadDB($dbType)
{
return ADOLoadCode($dbType);
}
/**
* Load the code for a specific database driver
*/
function ADOLoadCode($dbType)
{
GLOBAL $ADODB_Database;
if (!$dbType) return false;
$ADODB_Database = strtolower($dbType);
switch ($ADODB_Database) {
case 'maxsql': $ADODB_Database = 'mysqlt'; break;
case 'postgres':
case 'pgsql': $ADODB_Database = 'postgres7'; break;
}
// Karsten Kraus <Karsten.Kraus@web.de>
return @include_once(ADODB_DIR."/drivers/adodb-".$ADODB_Database.".inc.php");
}
/**
* synonym for ADONewConnection for people like me who cannot remember the correct name
*/
function &NewADOConnection($db='')
{
return ADONewConnection($db);
}
/**
* Instantiate a new Connection class for a specific database driver.
*
* @param [db] is the database Connection object to create. If undefined,
* use the last database driver that was loaded by ADOLoadCode().
*
* @return the freshly created instance of the Connection class.
*/
function &ADONewConnection($db='')
{
global $ADODB_Database;
$rez = true;
if ($db) {
if ($ADODB_Database != $db) ADOLoadCode($db);
} else {
if (!empty($ADODB_Database)) {
ADOLoadCode($ADODB_Database);
} else {
$rez = false;
}
}
$errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
if (!$rez) {
if ($errorfn) {
// raise an error
$errorfn('ADONewConnection', 'ADONewConnection', -998,
"could not load the database driver for '$db",
$dbtype);
} else
ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
return false;
}
$cls = 'ADODB_'.$ADODB_Database;
$obj = new $cls();
if ($errorfn) $obj->raiseErrorFn = $errorfn;
return $obj;
}
function &NewDataDictionary(&$conn)
{
$provider = $conn->dataProvider;
$drivername = $conn->databaseType;
if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado')
$drivername = $conn->dataProvider;
else {
if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
else
switch($drivername) {
case 'oracle': $drivername = 'oci8';break;
case 'sybase': $drivername = 'mssql';break;
case 'access':
case 'db2':
break;
default:
$drivername = 'generic';
break;
}
}
include_once(ADODB_DIR.'/adodb-lib.inc.php');
include_once(ADODB_DIR.'/adodb-datadict.inc.php');
$path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
if (!file_exists($path)) {
ADOConnection::outp("Database driver '$path' not available");
return false;
}
include_once($path);
$class = "ADODB2_$drivername";
$dict =& new $class();
$dict->dataProvider = $conn->dataProvider;
$dict->connection = &$conn;
$dict->upperName = strtoupper($drivername);
if (is_resource($conn->_connectionID))
$dict->serverInfo = $conn->ServerInfo();
return $dict;
}
/**
* Save a file $filename and its $contents (normally for caching) with file locking
*/
function adodb_write_file($filename, $contents,$debug=false)
{
# http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
# So to simulate locking, we assume that rename is an atomic operation.
# First we delete $filename, then we create a $tempfile write to it and
# rename to the desired $filename. If the rename works, then we successfully
# modified the file exclusively.
# What a stupid need - having to simulate locking.
# Risks:
# 1. $tempfile name is not unique -- very very low
# 2. unlink($filename) fails -- ok, rename will fail
# 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
# 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
if (strpos(strtoupper(PHP_OS),'WIN') !== false) {
// skip the decimal place
$mtime = substr(str_replace(' ','_',microtime()),2);
// unlink will let some latencies develop, so uniqid() is more random
@unlink($filename);
// getmypid() actually returns 0 on Win98 - never mind!
$tmpname = $filename.uniqid($mtime).getmypid();
if (!($fd = fopen($tmpname,'a'))) return false;
$ok = ftruncate($fd,0);
if (!fwrite($fd,$contents)) $ok = false;
fclose($fd);
chmod($tmpname,0644);
if (!@rename($tmpname,$filename)) {
unlink($tmpname);
$ok = false;
}
if (!$ok) {
if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
}
return $ok;
}
if (!($fd = fopen($filename, 'a'))) return false;
if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
$ok = fwrite( $fd, $contents );
fclose($fd);
chmod($filename,0644);
}else {
fclose($fd);
if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
$ok = false;
}
return $ok;
}
function adodb_backtrace($print=true)
{
$s = '';
if (PHPVERSION() >= 4.3) {
$MAXSTRLEN = 64;
$s = '<pre align=left>';
$traceArr = debug_backtrace();
array_shift($traceArr);
$tabs = sizeof($traceArr)-1;
foreach ($traceArr as $arr) {
$args = array();
for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
$tabs -= 1;
$s .= '<font face="Courier New,Courier">';
if (isset($arr['class'])) $s .= $arr['class'].'.';
if (isset($arr['args']))
foreach($arr['args'] as $v) {
if (is_null($v)) $args[] = 'null';
else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
else if (is_object($v)) $args[] = 'Object:'.get_class($v);
else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
else {
$v = (string) @$v;
$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
if (strlen($v) > $MAXSTRLEN) $str .= '...';
$args[] = $str;
}
}
$s .= $arr['function'].'('.implode(', ',$args).')';
$s .= @sprintf("</font><font color=#808080 size=-1> # line %4d, file: <a href=\"file:/%s\">%s</a></font>",
$arr['line'],$arr['file'],$arr['file']);
$s .= "\n";
}
$s .= '</pre>';
if ($print) print $s;
}
return $s;
}
} // defined
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/adodb/adodb.inc.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.14
\ No newline at end of property
+1.15
\ No newline at end of property
Index: trunk/kernel/startup.php
===================================================================
--- trunk/kernel/startup.php (revision 3215)
+++ trunk/kernel/startup.php (revision 3216)
@@ -1,217 +1,217 @@
<?php
if( !defined('FULL_PATH') ) define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
require_once FULL_PATH.'/globals.php';
if( !isset($FrontEnd) ) $FrontEnd = 0;
# New path detection method: begin
// safeDefine('REL_PATH', '/admin');
$k4_path_detection = false;
if( defined('REL_PATH') )
{
$ps = preg_replace("/".preg_quote(rtrim(REL_PATH, '/'), '/')."$/", '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));
safeDefine('BASE_PATH', $ps); // in case in-portal has defined it before
# New path detection method: end
// KENEL4 INIT: BEGIN
if($FrontEnd != 1 && !defined('ADMIN') ) define('ADMIN', 1);
if( !defined('APPLICATION_CLASS') ) define('APPLICATION_CLASS', 'MyApplication');
include_once(FULL_PATH.'/kernel/kernel4/startup.php');
// just to make sure that this is correctly detected
- if( defined('DEBUG_MODE') && DEBUG_MODE ) $debugger->appendHTML('FULL_PATH: <b>'.FULL_PATH.'</b>');
+ if( IsDebugMode() ) $debugger->appendHTML('FULL_PATH: <b>'.FULL_PATH.'</b>');
$application =& kApplication::Instance();
$application->Init();
// compatibility constants
$g_TablePrefix = TABLE_PREFIX;
$pathtoroot = FULL_PATH.'/';
$admin = 'admin';
$rootURL = PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').BASE_PATH.'/';
$localURL = $rootURL.'kernel/';
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL.'/images';
$browseURL = $adminURL.'/browse';
$cssURL = $adminURL.'/include';
$pathchar = '/';
// KERNEL4 INIT: END
$k4_path_detection = true;
}
if(!get_magic_quotes_gpc())
{
function addSlashesA($a)
{
foreach($a as $k => $v)
{
$a[$k] = is_array($v) ? addSlashesA($v) : addslashes($v);
}
return $a;
}
foreach(Array(
'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS',
'_POST','_GET','_COOKIE','_SESSION','_SERVER','_REQUEST') as $_)
if(isset($GLOBALS[$_]))
$GLOBALS[$_]=addSlashesA($GLOBALS[$_]);
}
/*
startup.php: this is the primary startup sequence for in-portal services
*/
if( file_exists(FULL_PATH.'/debug.php') && !defined('DEBUG_MODE') ) include_once(FULL_PATH.'/debug.php');
if( !defined('DEBUG_MODE') ) error_reporting(0);
ini_set('memory_limit', '32M');
ini_set('include_path', '.');
$kernel_version = "1.0.0";
$FormError = array();
$FormValues = array();
/* include PHP version compatibility functions */
require_once(FULL_PATH.'/compat.php');
/* set global variables and module lists */
-include_once(FULL_PATH.'/kernel/include/'.( IsDebugMode() ? 'debugger.php' : 'debugger_dummy.php') );
+if( constOn('DEBUG_MODE') ) include_once(FULL_PATH.'/kernel/include/debugger.php');
// put all non-checked checkboxes in $_POST & $_REQUEST with 0 values
if( GetVar('form_fields') )
{
$form_fields = GetVar('form_fields');
foreach($form_fields as $checkbox_name)
{
if( GetVar($checkbox_name) === false ) SetVar($checkbox_name,0);
}
}
LogEntry("Initalizing System..\n");
/* for 64 bit timestamps */
require_once(FULL_PATH.'/kernel/include/adodb/adodb-time.inc.php');
require_once(FULL_PATH.'/kernel/include/dates.php');
/* create the global error object */
require_once(FULL_PATH.'/kernel/include/error.php');
$Errors = new clsErrorManager();
require_once(FULL_PATH.'/kernel/include/itemdb.php');
require_once(FULL_PATH.'/kernel/include/db.class.php'); // moved from kernel/include/config.php
require_once(FULL_PATH.'/kernel/include/adodb/adodb.inc.php'); // moved from kernel/include/config.php
require_once(FULL_PATH.'/kernel/include/config.php');
/* create the global configuration object */
LogEntry("Creating Config Object..\n");
$objConfig = new clsConfig();
$objConfig->Load(); /* Populate our configuration data */
LogEntry("Done Loading Configuration\n");
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
LogEntry("ADO Extension: ".ADODB_EXTENSION."\n");
require_once(FULL_PATH.'/kernel/include/parseditem.php');
require_once(FULL_PATH.'/kernel/include/itemreview.php'); // moved from kernel/include/item.php
require_once(FULL_PATH.'/kernel/include/itemrating.php'); // moved from kernel/include/item.php
require_once(FULL_PATH.'/kernel/include/item.php');
require_once(FULL_PATH.'/kernel/include/syscache.php');
require_once(FULL_PATH.'/kernel/include/modlist.php');
require_once(FULL_PATH.'/kernel/include/searchconfig.php');
require_once(FULL_PATH.'/kernel/include/banrules.php');
$objModules = new clsModList();
$objSystemCache = new clsSysCacheList();
$objSystemCache->PurgeExpired();
$objBanList = new clsBanRuleList();
require_once(FULL_PATH.'/kernel/include/image.php');
require_once(FULL_PATH.'/kernel/include/itemtypes.php');
$objItemTypes = new clsItemTypeList();
require_once(FULL_PATH.'/kernel/include/theme.php');
$objThemes = new clsThemeList();
require_once(FULL_PATH.'/kernel/include/language.php');
$objLanguages = new clsLanguageList();
$objImageList = new clsImageList();
/* Load session and user class definitions */
//require_once("include/customfield.php");
//require_once("include/custommetadata.php");
require_once(FULL_PATH.'/kernel/include/usersession.php');
require_once(FULL_PATH.'/kernel/include/favorites.php');
require_once(FULL_PATH.'/kernel/include/portaluser.php');
require_once(FULL_PATH.'/kernel/include/portalgroup.php');
/* create the user management class */
$objFavorites = new clsFavoriteList();
$objUsers = new clsUserManager();
$objGroups = new clsGroupList();
require_once(FULL_PATH.'/kernel/include/cachecount.php');
require_once(FULL_PATH.'/kernel/include/customfield.php');
require_once(FULL_PATH.'/kernel/include/custommetadata.php');
require_once(FULL_PATH.'/kernel/include/permissions.php');
require_once(FULL_PATH.'/kernel/include/relationship.php');
require_once(FULL_PATH.'/kernel/include/category.php');
require_once(FULL_PATH.'/kernel/include/statitem.php');
/* category base class, used by all the modules at some point */
$objPermissions = new clsPermList();
$objPermCache = new clsPermCacheList();
$objCatList = new clsCatList();
$objCustomFieldList = new clsCustomFieldList();
$objCustomDataList = new clsCustomDataList();
$objCountCache = new clsCacheCountList();
require_once(FULL_PATH.'/kernel/include/smtp.php');
require_once(FULL_PATH.'/kernel/include/emailmessage.php');
require_once(FULL_PATH.'/kernel/include/events.php');
LogEntry("Creating Mail Queue..\n");
$objMessageList = new clsEmailMessageList();
$objEmailQueue = new clsEmailQueue();
LogEntry("Done creating Mail Queue Objects\n");
require_once(FULL_PATH.'/kernel/include/searchitems.php');
require_once(FULL_PATH.'/kernel/include/advsearch.php');
require_once(FULL_PATH.'/kernel/include/parse.php');
require_once(FULL_PATH.'/kernel/include/socket.php');
/* responsible for including module code as required
This script also creates an instance of the user session onject and
handles all session management. The global session object is created
and populated, then the global user object is created and populated
each module's parser functions and action code is included here
*/
LogEntry("Startup complete\n");
include_once("include/modules.php");
-if( defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 && function_exists('DebugByFile') ) DebugByFile();
+if( IsDebugMode() && function_exists('DebugByFile') ) DebugByFile();
/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/
$objEmailQueue->SendMailQeue();
$ado=&GetADODBConnection();
$rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0");
$kernel_version = $rs->fields['Version'];
$adminDir = $objConfig->Get("AdminDirectory");
if ($adminDir == '') {
$adminDir = 'admin';
}
if (strstr(__FILE__, $adminDir) && !GetVar('logout') && !strstr(__FILE__, "install") && !strstr(__FILE__, "index")) {
//echo "testz [".admin_login()."]<br>";
require_login(null, 'expired='.(int)GetVar('expired') );
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.31
\ No newline at end of property
+1.32
\ No newline at end of property
Index: trunk/admin/index4.php
===================================================================
--- trunk/admin/index4.php (revision 3215)
+++ trunk/admin/index4.php (revision 3216)
@@ -1,55 +1,56 @@
<?php
$start = getmicrotime();
define('ADMIN', 1);
define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
define('APPLICATION_CLASS', 'MyApplication');
include_once(FULL_PATH.'/kernel/kernel4/startup.php');
/*
kApplication $application
*/
$application =& kApplication::Instance();
$application->Init();
$application->Run();
$application->Done();
$end = getmicrotime();
-if (defined('DEBUG_MODE')) {
+if ( constOn('DEBUG_MODE') )
+{
echo ' <br><br>
<style> .dbg_flat_table TD { font-family: arial,verdana; font-size: 9pt; } </style>
<table class="dbg_flat_table">
<tr>
<td>Memory used:</td>
<td>'.round(memory_get_usage()/1024/1024, 1).' MB ('.memory_get_usage().')</td>
</tr>
<tr>
<td>Time used:</td>
<td>'.round(($end - $start), 5).' sec</td>
</tr>
</table>';
}
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//update_memory_check_script();
function update_memory_check_script() {
$files = get_included_files();
$script = '$files = Array('."\n";
foreach ($files as $file_name) {
$script .= "\t\t'".str_replace(FULL_PATH, '', $file_name)."',\n";
}
$script .= ");\n";
echo "<pre>";
echo $script;
echo "</pre>";
}
?>
\ No newline at end of file
Property changes on: trunk/admin/index4.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/admin/install.php
===================================================================
--- trunk/admin/install.php (revision 3215)
+++ trunk/admin/install.php (revision 3216)
@@ -1,2033 +1,2033 @@
<?php
error_reporting(E_ALL);
ini_set('max_execution_time', 0);
define('BACKUP_NAME', 'dump(.*).txt'); // how backup dump files are named
$general_error = '';
$pathtoroot = "";
if( !(isset($pathtoroot) && $pathtoroot) )
{
$path=dirname(realpath(__FILE__));
//$path=dirname(realpath(__FILE__));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
if( !isset($pathtoroot) ) $pathtoroot = '';
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if( !(isset($pathtoroot) && $pathtoroot) )
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$path_char = GetPathChar();
//phpinfo(INFO_VARIABLES);
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
ini_set('include_path', '.');
-if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
+if( file_exists($pathtoroot.'debug.php') && !(defined('DEBUG_MODE') && DEBUG_MODE) ) include_once($pathtoroot.'debug.php');
if(!defined('IS_INSTALL'))define('IS_INSTALL',1);
$admin = substr($path,strlen($pathtoroot));
$state = isset($_GET["state"]) ? $_GET["state"] : '';
if(!strlen($state))
{
$state = isset($_POST['state']) ? $_POST['state'] : '';
}
if (!defined("GET_LICENSE_URL")) {
define("GET_LICENSE_URL", "http://www.intechnic.com/myaccount/license.php");
}
require_once $pathtoroot.$admin.'/install/install_lib.php';
$install_type = GetVar('install_type', true);
$force_finish = isset($_REQUEST['ff']) ? true : false;
$ini_file = $pathtoroot."config.php";
if(file_exists($ini_file))
{
$write_access = is_writable($ini_file);
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace('-', '', $key);
global $$key;
$$key = $value;
}
}
}
else
{
$state="";
$write_access = is_writable($pathtoroot);
if($write_access)
{
set_ini_value("Database", "DBType", "");
set_ini_value("Database", "DBHost", "");
set_ini_value("Database", "DBUser", "");
set_ini_value("Database", "DBUserPassword", "");
set_ini_value("Database", "DBName", "");
set_ini_value("Module Versions", "In-Portal", "");
save_values();
}
}
$titles[1] = "General Site Setup";
$configs[1] = "in-portal:configure_general";
$mods[1] = "In-Portal";
$titles[2] = "User Setup";
$configs[2] = "in-portal:configure_users";
$mods[2] = "In-Portal:Users";
$titles[3] = "Category Display Setup";
$configs[3] = "in-portal:configure_categories";
$mods[3] = "In-Portal";
// simulate rootURL variable: begin
$rootURL = 'http://'.dirname($_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
$tmp = explode('/', $rootURL);
if( $tmp[ count($tmp) - 1 ] == $admin) unset( $tmp[ count($tmp) - 1 ] );
$rootURL = implode('/', $tmp).'/';
unset($tmp);
//echo "RU: $rootURL<br>";
// simulate rootURL variable: end
$db_savings = Array('dbinfo', 'db_config_save', 'db_reconfig_save'); //, 'reinstall_process'
if( isset($g_DBType) && $g_DBType && strlen($state)>0 && !in_array($state, $db_savings) )
{
require_once($pathtoroot."kernel/startup.php");
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
//admin only util
$pathtolocal = $pathtoroot."kernel/";
require_once ($pathtoroot.$admin."/include/elements.php");
//require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once ($pathtolocal."admin/include/navmenu.php");
require_once($pathtoroot.$admin."/toolbar.php");
}
function GetPathChar($path = null)
{
if( !isset($path) ) $path = $GLOBALS['pathtoroot'];
$pos = strpos($path, ':');
return ($pos === false) ? "/" : "\\";
}
function SuperStrip($str, $inverse = false)
{
$str = $inverse ? str_replace("%5C","\\",$str) : str_replace("\\","%5C",$str);
return stripslashes($str);
}
$skip_step = false;
require_once($pathtoroot.$admin."/install/inst_ado.php");
$helpURL = $rootURL.$admin.'/help/install_help.php?destform=popup&help_usage=install';
?>
<html>
<head>
<title>In-Portal Installation</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<meta name="generator" content="Notepad">
<link rel="stylesheet" type="text/css" href="include/style.css">
<LINK REL="stylesheet" TYPE="text/css" href="install/2col.css">
<SCRIPT LANGUAGE="JavaScript1.2">
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function swap(imgid, src){
var ob = document.getElementById(imgid);
ob.src = 'images/' + src;
}
function Continue() {
document.iform1.submit();
}
function CreatePopup(window_name, url, width, height)
{
// creates a popup window & returns it
if(url == null && typeof(url) == 'undefined' ) url = '';
if(width == null && typeof(width) == 'undefined' ) width = 750;
if(height == null && typeof(height) == 'undefined' ) height = 400;
return window.open(url,window_name,'width='+width+',height='+height+',status=yes,resizable=yes,menubar=no,scrollbars=yes,toolbar=no');
}
function ShowHelp(section)
{
var frm = document.getElementById('help_form');
frm.section.value = section;
frm.method = 'POST';
CreatePopup('HelpPopup','<?php echo $rootURL.$admin; ?>/help/blank.html'); // , null, 600);
frm.target = 'HelpPopup';
frm.submit();
}
</SCRIPT>
</head>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" style="height: 100%">
<form name="help_form" id="help_form" action="<?php echo $helpURL; ?>" method="post"><input type="hidden" id="section" name="section" value=""></form>
<form enctype="multipart/form-data" name="iform1" id="iform1" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
<tr>
<td height="90">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="90">
<tr>
<td rowspan="3" valign="top"><a href="http://www.in-portal.net" target="_top"><img title="In-portal" src="images/globe.gif" width="84" height="91" border="0"></a></td>
<td rowspan="3" valign="top"><a href="http://www.in-portal.net" target="_top"><img title="In-portal" src="images/logo.gif" width="150" height="91" border="0"></a></td>
<td rowspan="3" width="100000" align="right">&nbsp;</td>
<td width="400"><img title="" src="images/blocks.gif" width="400" height="73"></td>
</tr>
<tr><td align="right" background="images/version_bg.gif" class="head_version" valign="top"><img title="" src="images/spacer.gif" width="1" height="14">In-Portal Version <?php echo GetMaxPortalVersion($pathtoroot.$admin)?>: English US</td></tr>
<tr><td><img title="" src="images/blocks2.gif" width="400" height="2"><br></td></tr>
<tr><td bgcolor="black" colspan="4"><img title="" src="images/spacer.gif" width="1" height="1"><br></td></tr>
</table>
</td>
</tr>
<?php
require_once($pathtoroot."kernel/include/adodb/adodb.inc.php");
if(!strlen($state))
$state = @$_POST["state"];
//echo $state;
if(strlen($state)==0)
{
$ado =& inst_GetADODBConnection();
$installed = $ado ? TableExists($ado,"ConfigurationAdmin,Category,Permissions") : false;
if(!minimum_php_version("4.1.2"))
{
$general_error = "You have version ".phpversion()." - please upgrade!";
//die();
}
if(!$write_access)
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "Install cannot write to config.php in the root directory of your in-portal installation ($pathtoroot).";
//die();
}
if(!is_writable($pathtoroot."themes/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Theme directory must be writable (".$pathtoroot."themes/).";
//die();
}
if(!is_writable($pathtoroot."kernel/images/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Image Upload directory must be writable (".$pathtoroot."kernel/images/).";
//die();
}
if(!is_writable($pathtoroot."kernel/images/pending"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Pending Image Upload directory must be writable (".$pathtoroot."kernel/images/pending).";
//die();
}
if(!is_writable($pathtoroot."admin/backupdata/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Backup directory must be writable (".$pathtoroot."admin/backupdata/).";
//die();
}
if(!is_writable($pathtoroot."admin/export/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Export directory must be writable (".$pathtoroot."admin/export/).";
//die();
}
if(!is_writable($pathtoroot."kernel/stylesheets/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's stylesheets directory must be writable (".$pathtoroot."kernel/stylesheets/).";
//die();
}
if(!is_writable($pathtoroot."kernel/user_files/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's CMS images directory must be writable (".$pathtoroot."kernel/user_files/).";
//die();
}
if(!is_writable($pathtoroot."kernel/cache/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's templates cache directory must be writable (".$pathtoroot."kernel/cache/).";
//die();
}
if($installed)
{
$state="reinstall";
}
else {
$state="dbinfo";
}
}
if($state=="reinstall_process")
{
$login_err_mesg = ''; // always init vars before use
if( !isset($g_License) ) $g_License = '';
$lic = base64_decode($g_License);
if(strlen($lic))
{
a83570933e44bc66b31dd7127cf3f23a($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
$LoggedIn = FALSE;
if($_POST["UserName"]=="root")
{
$ado =& inst_GetADODBConnection();
$sql = "SELECT * FROM ".$g_TablePrefix."ConfigurationValues WHERE VariableName='RootPass'";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
{
$RootPass = $rs->fields["VariableValue"];
if(strlen($RootPass)>0)
$LoggedIn = ($RootPass==md5($_POST["UserPass"]));
}
}
else
{
$act = '';
if (ConvertVersion($g_InPortal) >= ConvertVersion("1.0.5")) {
$act = 'check';
}
$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['UserName'])."&password=".md5($_POST['UserPass'])."&action=$act&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
$login_err_mesg = "Unable to connect to the Intechnic server!";
$LoggedIn = false;
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$login_err_mesg = substr($rcontents, 6);
$LoggedIn = false;
}
else {
$LoggedIn = true;
}
}
//$LoggedIn = ($i_User == $_POST["UserName"] && ($i_Pswd == $_POST["UserPass"]) && strlen($i_User)>0) || strlen($i_User)==0;
}
if($LoggedIn)
{
if (!(int)$_POST["inp_opt"]) {
$state="reinstall";
$inst_error = "Please select one of the options above!";
}
else {
switch((int)$_POST["inp_opt"])
{
case 0:
$inst_error = "Please select an option above";
break;
case 1:
/* clean out all tables */
$install_type = 4;
$ado =& inst_GetADODBConnection();
$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
RunSchemaFile($ado,$filename);
// removing other tables
$tables = $ado->MetaTables();
foreach($tables as $tab_name) {
if (stristr($tab_name, $g_TablePrefix."ses_")) {
$sql = "DROP TABLE IF EXISTS $tab_name";
$ado->Execute($sql);
}
}
/* run install again */
$state="license";
break;
case 2:
$install_type = 3;
$state="dbinfo";
break;
case 3:
$install_type = 5;
$state="license";
break;
case 4:
$install_type = 6;
/* clean out all tables */
$ado =& inst_GetADODBConnection();
//$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
//RunSchemaFile($ado,$filename);
/* run install again */
$state="restore_select";
break;
case 5:
$install_type = 7;
/* change DB config */
$state="db_reconfig";
break;
case 6:
$install_type = 8;
$state = "upgrade";
break;
case 7:
$install_type = 9;
$state = "fix_paths";
break;
}
}
}
else
{
$state="reinstall";
$login_error = $login_err_mesg;//"Invalid Username or Password - Try Again";
}
}
if ($state == "upgrade") {
$ado =& inst_GetADODBConnection();
$Modules = array();
$Texts = array();
if (ConvertVersion(GetMaxPortalVersion($pathtoroot.$admin)) >= ConvertVersion("1.0.5") && ($g_LicenseCode == '' && $g_License != '')) {
$state = 'reinstall';
$inst_error = "Your license must be updated before you can upgrade. Please don't use 'Existing License' option, instead either Download from Intechnic or Upload a new license file!";
}
else {
$sql = "SELECT Name, Version, Path FROM ".$g_TablePrefix."Modules ORDER BY LoadOrder asc";
$rs = $ado->Execute($sql);
$i = 0;
while ($rs && !$rs->EOF) {
$p = $rs->fields['Path'];
if ($rs->fields['Name'] == 'In-Portal') {
$p = '';
}
$dir_name = $pathtoroot.$p."admin";///install/upgrades/";
if($rs->fields['Version'] != $newver = GetMaxPortalVersion($dir_name))
{
////////////////////
$mod_path = $rs->fields['Path'];
$current_version = $rs->fields['Version'];
if ($rs->fields['Name'] == 'In-Portal') $mod_path = '';
$dir_name = $pathtoroot.$mod_path."/admin/install/upgrades/";
$dir = @dir($dir_name);
$upgrades_arr = Array();
$new_version = '';
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) {
if (strstr($file, 'inportal_check_v')) {
$upgrades_arr[] = $file;
}
}
}
usort($upgrades_arr, "VersionSort");
$result=0;
$failCheck=1;
$stopCheck=2;
$CheckErrors = Array();
foreach($upgrades_arr as $file)
{
$file_tmp = str_replace("inportal_check_v", "", $file);
$file_tmp = str_replace(".php", "", $file_tmp);
if (ConvertVersion($file_tmp) > ConvertVersion($current_version)) {
$filename = $pathtoroot.$mod_path."/admin/install/upgrades/$file";
if(file_exists($filename))
{
include($filename);
if($result&2)break;
}
}
}
////////////////////
$Modules[] = Array('module'=>$rs->fields['Name'],'curver'=>$rs->fields['Version'],'newver'=>$newver,'error'=>$result!='pass');
// $Texts[] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".GetMaxPortalVersion($dir_name).")";
}
/*$dir = @dir($dir_name);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
if (strstr($file, 'inportal_upgrade_v')) {
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
//$sql = "SELECT count(*) AS count FROM ".$g_TablePrefix."Modules WHERE Name = '".$rs->fields['Name']."' AND Version = '$file'";
//$rs1 = $ado->Execute($sql);
if ($rs1->fields['count'] == 0 && ConvertVersion($file) > ConvertVersion($rs->fields['Version'])) {
if ($Modules[$i-1] == $rs->fields['Name']) {
$Texts[$i-1] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
$i--;
}
else {
$Texts[$i] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
$Modules[$i] = $rs->fields['Name'];
}
$i++;
}
}
}
}*/
$rs->MoveNext();
}
$sql = 'DELETE FROM '.$g_TablePrefix.'Cache WHERE VarName = "config_files"';
$ado->Execute($sql);
$include_file = $pathtoroot.$admin."/install/upgrade.php";
}
}
if ($state == "upgrade_process") {
$ado =& inst_GetADODBConnection();
$mod_arr = $_POST['modules'];
$mod_str = '';
foreach ($mod_arr as $tmp_mod) {
$mod_str .= "'$tmp_mod',";
}
$mod_str = substr($mod_str, 0, strlen($mod_str) - 1);
$sql = "SELECT Name FROM ".$g_TablePrefix."Modules WHERE Name IN ($mod_str) ORDER BY LoadOrder";
$rs = $ado->Execute($sql);
$mod_arr = array();
while ($rs && !$rs->EOF) {
$mod_arr[] = $rs->fields['Name'];
$rs->MoveNext();
}
foreach($mod_arr as $p)
{
$mod_name = strtolower($p);
$sql = "SELECT Version, Path FROM ".$g_TablePrefix."Modules WHERE Name = '$p'";
$rs = $ado->Execute($sql);
$current_version = $rs->fields['Version'];
if ($mod_name == 'in-portal') {
$mod_path = '';
}
else {
$mod_path = $rs->fields['Path'];
}
$dir_name = $pathtoroot.$mod_path."/admin/install/upgrades/";
$dir = @dir($dir_name);
$upgrades_arr = Array();
$new_version = '';
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) {
if (strstr($file, 'inportal_upgrade_v')) {
$upgrades_arr[] = $file;
}
}
}
usort($upgrades_arr, "VersionSort");
foreach($upgrades_arr as $file)
{
preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $file, $rets);
$tmp_version = $rets[1];
$tmp_extension = $rets[2];
if (ConvertVersion($tmp_version) > ConvertVersion($current_version) )
{
$filename = $pathtoroot.$mod_path."/admin/install/upgrades/$file";
//echo "Running: $filename<br>";
if( file_exists($filename) )
{
if($tmp_extension == 'sql')
{
RunSQLFile($ado, $filename);
}
else
{
include_once $filename;
}
}
}
}
set_ini_value("Module Versions", $p, GetMaxPortalVersion($pathtoroot.$mod_path."/admin/"));
save_values();
}
// compile stylesheets: begin
define('FULL_PATH', realpath(dirname(__FILE__).'/..'));
define('APPLICATION_CLASS', 'MyApplication');
include_once(FULL_PATH.'/kernel/kernel4/startup.php');
$application =& kApplication::Instance();
$application->Init();
$css_hash = $application->DB->GetCol('SELECT LOWER(Name) AS Name, StylesheetId FROM '.TABLE_PREFIX.'Stylesheets', 'StylesheetId');
$application->setUnitOption('css', 'AutoLoad', false);
$css_table = $application->getUnitOption('css','TableName');
$css_idfield = $application->getUnitOption('css','IDField');
$theme_table = $application->getUnitOption('theme', 'TableName');
$theme_idfield = $application->getUnitOption('theme', 'IDField');
$theme_update_sql = 'UPDATE '.$theme_table.' SET '.$css_idfield.' = %s WHERE LOWER(Name) = %s';
foreach($css_hash as $stylesheet_id => $theme_name)
{
$css_item =& $application->recallObject('css');
$css_item->Load($stylesheet_id);
$css_item->Compile();
$application->DB->Query( sprintf($theme_update_sql, $stylesheet_id, $application->DB->qstr( getArrayValue($css_hash,$stylesheet_id) ) ) );
}
$application->Done();
// compile stylesheets: end
$state = 'languagepack_upgrade';
}
// upgrade language pack
if($state=='languagepack_upgrade')
{
$state = 'lang_install_init';
if( is_object($application) ) $application->SetVar('lang', Array('english.lang') );
$force_finish = true;
}
if ($state == 'fix_paths') {
$ado = inst_GetADODBConnection();
$sql = "SELECT * FROM ".$g_TablePrefix."ConfigurationValues WHERE VariableName = 'Site_Name' OR VariableName LIKE '%Path%'";
$path_rs = $ado->Execute($sql);
$include_file = $pathtoroot.$admin."/install/fix_paths.php";
}
if ($state == 'fix_paths_process') {
$ado = inst_GetADODBConnection();
//$state = 'fix_paths';
//$include_file = $pathtoroot.$admin."/install/fix_paths.php";
foreach($_POST["values"] as $key => $value) {
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '".$value."' WHERE VariableName = '".$key."'";
$ado->Execute($sql);
}
$state = "finish";
}
if($state=="db_reconfig_save")
{
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace("-", "", $key);
global $$key;
$$key = $value;
}
}
unset($ado);
$ado = VerifyDB('db_reconfig', 'finish', 'SaveDBConfig', true);
}
if($state=="db_reconfig")
{
$include_file = $pathtoroot.$admin."/install/db_reconfig.php";
}
if($state=="restore_file")
{
if($_POST["submit"]=="Update")
{
$filepath = $_POST["backupdir"];
$state="restore_select";
}
else
{
$filepath = stripslashes($_POST['backupdir']);
$backupfile = $filepath.$path_char.str_replace('(.*)', $_POST['backupdate'], BACKUP_NAME);
if(file_exists($backupfile) && is_readable($backupfile))
{
$ado =& inst_GetADODBConnection();
$show_warning = false;
if (!$_POST['warning_ok']) {
// Here we comapre versions between backup and config
$file_contents = file_get_contents($backupfile);
$file_tmp_cont = explode("#------------------------------------------", $file_contents);
$tmp_vers = $file_tmp_cont[0];
$vers_arr = explode(";", $tmp_vers);
$ini_values = inst_parse_portal_ini($ini_file);
foreach ($ini_values as $key => $value) {
foreach ($vers_arr as $k) {
if (strstr($k, $key)) {
if (!strstr($k, $value)) {
$show_warning = true;
}
}
}
}
//$show_warning = true;
}
if (!$show_warning) {
$filename = $pathtoroot.$admin.$path_char.'install'.$path_char.'inportal_remove.sql';
RunSchemaFile($ado,$filename);
$state="restore_run";
}
else {
$state = "warning";
$include_file = $pathtoroot.$admin."/install/warning.php";
}
}
else {
if ($_POST['backupdate'] != '') {
$include_file = $pathtoroot.$admin."/install/restore_select.php";
$restore_error = "$backupfile not found or could not be read";
}
else {
$include_file = $pathtoroot.$admin."/install/restore_select.php";
$restore_error = "No backup selected!!!";
}
}
}
//echo $restore_error;
}
if($state=="restore_select")
{
if( isset($_POST['backupdir']) ) $filepath = stripslashes($_POST['backupdir']);
$include_file = $pathtoroot.$admin."/install/restore_select.php";
}
if($state=="restore_run")
{
$ado =& inst_GetADODBConnection();
$FileOffset = (int)$_GET["Offset"];
if(!strlen($backupfile))
$backupfile = SuperStrip($_GET['File'], true);
$include_file = $pathtoroot.$admin."/install/restore_run.php";
}
if($state=="db_config_save")
{
set_ini_value("Database", "DBType",$_POST["ServerType"]);
set_ini_value("Database", "DBHost",$_POST["ServerHost"]);
set_ini_value("Database", "DBName",$_POST["ServerDB"]);
set_ini_value("Database", "DBUser",$_POST["ServerUser"]);
set_ini_value("Database", "DBUserPassword",$_POST["ServerPass"]);
set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);
save_values();
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace("-", "", $key);
global $$key;
$$key = $value;
}
}
unset($ado);
$ado = VerifyDB('dbinfo', 'license');
}
if($state=="dbinfo")
{
if ($install_type == '') {
$install_type = 1;
}
$include_file = $pathtoroot.$admin."/install/dbinfo.php";
}
if ($state == "download_license") {
$ValidLicense = FALSE;
$lic_login = isset($_POST['login']) ? $_POST['login'] : '';
$lic_password = isset($_POST['password']) ? $_POST['password'] : '';
if ($lic_login != '' && $lic_password != '') {
// Here we determine weather login is ok & check available licenses
$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['login'])."&password=".md5($_POST['password'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$get_license_error = substr($rcontents, 6);
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
if (substr($rcontents, 0, 3) == "SEL") {
$state = "download_license";
$license_select = substr($rcontents, 4);
$include_file = $pathtoroot.$admin."/install/download_license.php";
}
else {
// Here we get one license
$tmp_data = explode('Code==:', $rcontents);
$data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));
a83570933e44bc66b31dd7127cf3f23a($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
$got_license = 1;
}
else {
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
}
}
}
}
else if ($_POST['licenses'] == '') {
$state = "get_license";
$get_license_error = "Username and / or password not specified!!!";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
// Here we download license
$rfile = @fopen(GET_LICENSE_URL."?license_id=".md5($_POST['licenses'])."&dlog=".md5($_POST['dlog'])."&dpass=".md5($_POST['dpass'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_POST['domain']), "r");
if (!$rfile) {
$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$download_license_error = substr($rcontents, 6);
$state = "download_license";
$include_file = $pathtoroot.$admin."/install/download_license.php";
}
else {
$tmp_data = explode('Code==:', $rcontents);
$data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));
a83570933e44bc66b31dd7127cf3f23a($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
// old licensing script doen't return 2nd parameter (licanse code)
if( isset($tmp_data[1]) ) set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
}
else {
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
}
}
}
}
if($state=="license_process")
{
$ValidLicense = FALSE;
$tmp_lic_opt = GetVar('lic_opt', true);
switch($tmp_lic_opt)
{
case 1: /* download from intechnic */
$include_file = $pathtoroot.$admin."/install/get_license.php";
$state = "get_license";
//if(!$ValidLicense)
//{
// $state="license";
//}
break;
case 2: /* upload file */
$file = $_FILES["licfile"];
if(is_array($file))
{
move_uploaded_file($file["tmp_name"],$pathtoroot."themes/tmp.lic");
@chmod($pathtoroot."themes/tmp.lic", 0666);
$fp = @fopen($pathtoroot."themes/tmp.lic","rb");
if($fp)
{
$lic = fread($fp,filesize($pathtoroot."themes/tmp.lic"));
fclose($fp);
}
$tmp_data = ae666b1b8279502f4c4b570f133d513e(FALSE,$pathtoroot."themes/tmp.lic");
$data = $tmp_data[0];
@unlink($pathtoroot."themes/tmp.lic");
a83570933e44bc66b31dd7127cf3f23a($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
}
else
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
break;
case 3: /* existing */
if(strlen($g_License))
{
$lic = base64_decode($g_License);
a83570933e44bc66b31dd7127cf3f23a($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
$state="domain_select";
}
else
{
$state="license";
$license_error="Invalid or corrupt license detected";
}
}
else
{
$state="license";
$license_error="Missing License File";
}
if(!$ValidLicense)
{
$state="license";
}
break;
case 4:
//set_ini_value("Intechnic","License",base64_encode("local"));
//set_ini_value("Intechnic","LicenseCode",base64_encode("local"));
//save_values();
$state="domain_select";
break;
}
if($ValidLicense)
$state="domain_select";
}
if($state=="license")
{
$include_file = $pathtoroot.$admin."/install/sel_license.php";
}
if($state=="reinstall")
{
$ado =& inst_GetADODBConnection();
$show_upgrade = false;
$sql = "SELECT Name FROM ".$g_TablePrefix."Modules";
$rs = $ado->Execute($sql);
$modules = '';
while ($rs && !$rs->EOF) {
$modules .= strtolower($rs->fields['Name']).',';
$rs->MoveNext();
}
$mod_arr = explode(",", substr($modules, 0, strlen($modules) - 1));
foreach($mod_arr as $p)
{
if ($p == 'in-portal') {
$p = '';
}
$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
$dir = @dir($dir_name);
//echo "<pre>"; print_r($dir); echo "</pre>";
if ($dir === false) continue;
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
if( preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $file, $rets) )
{
if($p == '') $p = 'in-portal';
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
$rs = $ado->Execute($sql);
if( ConvertVersion($rs->fields['Version']) < ConvertVersion( $rets[1] ) )
{
$show_upgrade = true;
}
}
}
}
}
if ( !isset($install_type) || $install_type == '') {
$install_type = 2;
}
$include_file = $pathtoroot.$admin."/install/reinstall.php";
}
if($state=="login")
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
a83570933e44bc66b31dd7127cf3f23a($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
if(!$ValidLicense)
{
$state="license";
}
else
if($i_User == $_POST["UserName"] || $i_Pswd == $_POST["UserPass"])
{
$state = "domain_select";
}
else
{
$state="getuser";
$login_error = "Invalid User Name or Password. If you don't know your username or password, contact Intechnic Support";
}
//die();
}
if($state=="getuser")
{
$include_file = $pathtoroot.$admin."/install/login.php";
}
if($state=="set_domain")
{
if( !is_array($i_Keys) || !count($i_Keys) )
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
a83570933e44bc66b31dd7127cf3f23a($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
}
if($_POST["domain"]==1)
{
$domain = $_SERVER['HTTP_HOST'];
if (strstr($domain, $i_Keys[0]['domain']) || de3ec1b7a142cccd0d51f03d24280744($domain)) {
set_ini_value("Intechnic","Domain",$domain);
save_values();
$state="runsql";
}
else {
$DomainError = 'Domain name selected does not match domain name in the license!';
$state = "domain_select";
}
}
else
{
$domain = str_replace(" ", "", $_POST["other"]);
if ($domain != '') {
if (strstr($domain, $i_Keys[0]['domain']) || de3ec1b7a142cccd0d51f03d24280744($domain)) {
set_ini_value("Intechnic","Domain",$domain);
save_values();
$state="runsql";
}
else {
$DomainError = 'Domain name entered does not match domain name in the license!';
$state = "domain_select";
}
}
else {
$DomainError = 'Please enter valid domain!';
$state = "domain_select";
}
}
}
if($state=="domain_select")
{
if(!is_array($i_Keys))
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
a83570933e44bc66b31dd7127cf3f23a($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
}
$include_file = $pathtoroot.$admin."/install/domain.php";
}
if($state=="runsql")
{
$ado =& inst_GetADODBConnection();
$installed = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
if(!$installed)
{
// create tables
$filename = $pathtoroot.$admin."/install/inportal_schema.sql";
RunSchemaFile($ado,$filename);
// insert default info
$filename = $pathtoroot.$admin."/install/inportal_data.sql";
RunSQLFile($ado,$filename);
$sql = 'UPDATE '.$g_TablePrefix.'ConfigurationValues SET VariableValue = %s WHERE VariableName = %s';
$ado->Execute( sprintf($sql, $ado->qstr('portal@'.$ini_vars['Intechnic']['Domain']), $ado->qstr('Smtp_AdminMailFrom') ) );
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = 'In-Portal'";
$rs = $ado->Execute($sql);
set_ini_value("Module Versions", "In-Portal", $rs->fields['Version']);
save_values();
require_once $pathtoroot.'kernel/include/tag-class.php';
if( !is_object($objTagList) ) $objTagList = new clsTagList();
// install kernel specific tags
$objTagList->DeleteTags(); // delete all existing tags in db
// create 3 predifined tags (because there no functions with such names
$t = new clsTagFunction();
$t->Set("name","include");
$t->Set("description","insert template output into the current template");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert","",TRUE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
unset($t);
$t = new clsTagFunction();
$t->Set("name","perm_include");
$t->Set("description","insert template output into the current template if permissions are set");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert","",TRUE);
$t->AddAttribute("_noaccess","tpl","Template to insert if access is denied","",FALSE);
$t->AddAttribute("_permission","","Comma-separated list of permissions, any of which will grant access","",FALSE);
$t->AddAttribute("_module","","Used in place of the _permission attribute, this attribute verifies the module listed is enabled","",FALSE);
$t->AddAttribute("_system","bool","Must be set to true if any permissions in _permission list is a system permission","",FALSE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
unset($t);
$t = new clsTagFunction();
$t->Set("name","mod_include");
$t->Set("description","insert templates from all enabled modules. No error occurs if the template does not exist.");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert. This template path should be relative to the module template root directory","",TRUE);
$t->AddAttribute("_modules","","Comma-separated list of modules. Defaults to all enabled modules if not set","",FALSE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
$objTagList->ParseFile($pathtoroot.'kernel/parser.php'); // insert module tags
if( is_array($ItemTagFiles) )
foreach($ItemTagFiles as $file)
$objTagList->ParseItemFile($pathtoroot.$file);
$state="RootPass";
}
else {
$include_file = $pathtoroot.$admin."/install/install_finish.php";
$state="finish";
}
}
if ($state == "finish") {
$ado =& inst_GetADODBConnection();
$PhraseTable = $g_TablePrefix."ImportPhrases";
$EventTable = $g_TablePrefix."ImportEvents";
$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
$ado->Execute("DROP TABLE IF EXISTS $EventTable");
$include_file = $pathtoroot.$admin."/install/install_finish.php";
}
if($state=="RootSetPass")
{
$pass = $_POST["RootPass"];
if(strlen($pass)<4)
{
$PassError = "Root Password must be at least 4 characters";
$state = "RootPass";
}
else if ($pass != $_POST["RootPassConfirm"]) {
$PassError = "Passwords does not match";
$state = "RootPass";
}
else
{
$pass = md5($pass);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$pass' WHERE VariableName='RootPass' OR VariableName='RootPassVerify'";
$ado =& inst_GetADODBConnection();
$ado->Execute($sql);
$state="modselect";
}
}
if($state=="RootPass")
{
$include_file = $pathtoroot.$admin."/install/rootpass.php";
}
if($state=="lang_install_init")
{
$ado =& inst_GetADODBConnection();
if( TableExists($ado, 'Language,Phrase') )
{
// KERNEL 4 INIT: BEGIN
define('FULL_PATH', realpath(dirname(__FILE__).'/..'));
define('APPLICATION_CLASS', 'MyApplication');
include_once(FULL_PATH.'/kernel/kernel4/startup.php');
$application =& kApplication::Instance();
$application->Init();
// KERNEL 4 INIT: END
$lang_xml =& $application->recallObject('LangXML');
$lang_xml->renameTable('phrases', TABLE_PREFIX.'ImportPhrases');
$lang_xml->renameTable('emailmessages', TABLE_PREFIX.'ImportEvents');
$lang_xml->lang_object->TableName = $application->getUnitOption('lang','TableName');
$languages = $application->GetVar('lang');
if($languages)
{
$kernel_db =& $application->GetADODBConnection();
$modules_table = $application->getUnitOption('mod','TableName');
$modules = $kernel_db->GetCol('SELECT Path, Name FROM '.$modules_table, 'Name');
$modules['In-Portal'] = '';
foreach($languages as $lang_file)
{
foreach($modules as $module_name => $module_folder)
{
$lang_path = MODULES_PATH.'/'.$module_folder.ADMIN_DIR.'/install/langpacks';
$lang_xml->Parse($lang_path.'/'.$lang_file, '|0|1|2|', '');
if($force_finish) $lang_xml->lang_object->Update();
}
}
$state = 'lang_install';
}
else
{
$state = 'lang_select';
}
$application->Done();
}
else
{
$general_error = 'Database error! No language tables found!';
}
}
if($state=="lang_install")
{
/* do pack install */
$Offset = (int)$_GET["Offset"];
$Status = (int)$_GET["Status"];
$PhraseTable = $g_TablePrefix."ImportPhrases";
$EventTable = $g_TablePrefix."ImportEvents";
$Total = TableCount($Status == 0 ? $PhraseTable : $EventTable, '', 0);
if($Status == 0)
{
$Offset = $objLanguages->ReadImportTable($PhraseTable, 1,"0,1,2", $force_finish ? false : true, 200,$Offset);
if($Offset >= $Total)
{
$Offset=0;
$Status=1;
}
$next_step = GetVar('next_step', true);
if($force_finish == true) $next_step = 3;
$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&state=lang_install&next_step=$next_step&install_type=$install_type";
if($force_finish == true) $NextUrl .= '&ff=1';
$include_file = $pathtoroot.$admin."/install/lang_run.php";
}
else
{
if(!is_object($objMessageList))
$objMessageList = new clsEmailMessageList();
$Offset = $objMessageList->ReadImportTable($EventTable, $force_finish ? false : true,100,$Offset);
if($Offset > $Total)
{
$next_step = GetVar('next_step', true);
if($force_finish == true) $next_step = 3;
$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&State=lang_install&next_step=$next_step&install_type=$install_type";
if($force_finish == true) $NextUrl .= '&ff=1';
$include_file = $pathtoroot.$admin."/install/lang_run.php";
}
else
{
$db =& GetADODBConnection();
$prefix = $g_TablePrefix;
$db->Execute('DROP TABLE IF EXISTS '.$PhraseTable);
$db->Execute('DROP TABLE IF EXISTS '.$EventTable);
if(!$force_finish)
{
$state = 'lang_default';
}
else
{
$_POST['next_step'] = 4;
$state = 'finish';
$include_file = $pathtoroot.$admin."/install/install_finish.php";
}
}
}
}
if($state=="lang_default_set")
{
// phpinfo(INFO_VARIABLES);
/*$ado =& inst_GetADODBConnection();
$PhraseTable = GetTablePrefix()."ImportPhrases";
$EventTable = GetTablePrefix()."ImportEvents";
$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
$ado->Execute("DROP TABLE IF EXISTS $EventTable");*/
$Id = $_POST["lang"];
$objLanguages->SetPrimary($Id);
$state="postconfig_1";
}
if($state=="lang_default")
{
$Packs = Array();
$objLanguages->Clear();
$objLanguages->LoadAllLanguages();
foreach($objLanguages->Items as $l)
{
$Packs[$l->Get("LanguageId")] = $l->Get("PackName");
}
$include_file = $pathtoroot.$admin."/install/lang_default.php";
}
if($state=="modinstall")
{
$doms = $_POST["domain"];
if(is_array($doms))
{
$ado =& inst_GetADODBConnection();
require_once $pathtoroot.'kernel/include/tag-class.php';
if( !isset($objTagList) || !is_object($objTagList) ) $objTagList = new clsTagList();
foreach($doms as $p)
{
$filename = $pathtoroot.$p.'/admin/install.php';
if(file_exists($filename) )
{
include($filename);
}
}
}
/* $sql = "SELECT Name FROM ".GetTablePrefix()."Modules";
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$p = $rs->fields['Name'];
$mod_name = strtolower($p);
if ($mod_name == 'in-portal') {
$mod_name = '';
}
$dir_name = $pathtoroot.$mod_name."/admin/install/upgrades/";
$dir = @dir($dir_name);
$new_version = '';
$tmp1 = 0;
$tmp2 = 0;
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
if ($file != '' && !strstr($file, 'changelog') && !strstr($file, 'readme')) {
$tmp1 = str_replace(".", "", $file);
if ($tmp1 > $tmp2) {
$new_version = $file;
}
}
}
$tmp2 = $tmp1;
}
$version_nrs = explode(".", $new_version);
for ($i = 0; $i < $version_nrs[0] + 1; $i++) {
for ($j = 0; $j < $version_nrs[1] + 1; $j++) {
for ($k = 0; $k < $version_nrs[2] + 1; $k++) {
$try_version = "$i.$j.$k";
$filename = $pathtoroot.$mod_name."/admin/install/upgrades/inportal_upgrade_v$try_version.sql";
if(file_exists($filename))
{
RunSQLFile($ado, $filename);
set_ini_value("Module Versions", $p, $try_version);
save_values();
}
}
}
}
$rs->MoveNext();
}
*/
$state="lang_select";
}
if($state=="modselect")
{
/* /admin/install.php */
$UrlLen = (strlen($admin) + 12)*-1;
$pathguess =substr($_SERVER["SCRIPT_NAME"],0,$UrlLen);
$sitepath = $pathguess;
$esc_path = str_replace("\\","/",$pathtoroot);
$esc_path = str_replace("/","\\",$esc_path);
//set_ini_value("Site","DomainName",$_SERVER["HTTP_HOST"]);
//$g_DomainName= $_SERVER["HTTP_HOST"];
save_values();
$ado =& inst_GetADODBConnection();
if(substr($sitepath,0,1)!="/")
$sitepath="/".$sitepath;
if(substr($sitepath,-1)!="/")
$sitepath .= "/";
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$sitepath' WHERE VariableName='Site_Path'";
$ado->Execute($sql);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$g_Domain' WHERE VariableName='Server_Name'";
$ado->Execute($sql);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '".$_SERVER['DOCUMENT_ROOT'].$sitepath."admin/backupdata' WHERE VariableName='Backup_Path'";
$ado->Execute($sql);
$Modules = a48d819089308a9aeb447e7248b2587f();
if (count($Modules) > 0) {
$include_file = $pathtoroot.$admin."/install/modselect.php";
}
else {
$state = "lang_select";
$skip_step = true;
}
}
if($state=="lang_select")
{
$Packs = GetLanguageList();
$include_file = $pathtoroot.$admin."/install/lang_select.php";
}
if(substr($state,0,10)=="postconfig")
{
$p = explode("_",$state);
$step = $p[1];
if ($_POST['Site_Path'] != '') {
$sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules";
$rs = $ado->Execute($sql);
$modules_str = '';
while ($rs && !$rs->EOF) {
$modules_str .= $rs->fields['Name'].' ('.$rs->fields['Version'].'),';
$rs->MoveNext();
}
$modules_str = substr($modules_str, 0, strlen($modules_str) - 1);
$rfile = @fopen(GET_LICENSE_URL."?url=".base64_encode($_SERVER['HTTP_HOST'].$_POST['Site_Path'])."&modules=".base64_encode($modules_str)."&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".md5($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
//$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
//$state = "postconfig_1";
//$include_file = $pathtoroot.$admin."/install/postconfig.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
}
}
if(strlen($_POST["oldstate"])>0)
{
$s = explode("_",$_POST["oldstate"]);
$oldstep = $s[1];
if($oldstep<count($configs))
{
$section = $configs[$oldstep];
$module = $mods[$oldstep];
$title = $titles[$oldstep];
$objAdmin = new clsConfigAdmin($module,$section,TRUE);
$objAdmin->SaveItems($_POST,TRUE);
}
}
$section = $configs[$step];
$module = $mods[$step];
$title = $titles[$step];
$step++;
if($step <= count($configs)+1)
{
$include_file = $pathtoroot.$admin."/install/postconfig.php";
}
else
$state = "theme_sel";
}
if($state=="theme_sel")
{
$objThemes->CreateMissingThemes(true);
$include_file = $pathtoroot.$admin."/install/theme_select.php";
}
if($state=="theme_set")
{
## get & define Non-Blocking & Blocking versions ##
$blocking_sockets = minimum_php_version("4.3.0")? 0 : 1;
$ado =& inst_GetADODBConnection();
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$blocking_sockets' WHERE VariableName='SocketBlockingMode'";
$ado->Execute($sql);
## get & define Non-Blocking & Blocking versions ##
$theme_id = $_POST["theme"];
$pathchar="/";
//$objThemes->SetPrimaryTheme($theme_id);
$t = $objThemes->GetItem($theme_id);
$t->Set("Enabled",1);
$t->Set("PrimaryTheme",1);
$t->Update();
$t->VerifyTemplates();
$include_file = $pathtoroot.$admin."/install/install_finish.php";
$state="finish";
}
if ($state == "adm_login") {
echo "<script>window.location='index.php';</script>";
}
// init variables
$vars = Array('db_error','restore_error','PassError','DomainError','login_error','inst_error');
foreach($vars as $var_name) ReSetVar($var_name);
switch($state)
{
case "modselect":
$title = "Select Modules";
$help = "<p>Select the In-Portal modules you wish to install. The modules listed to the right ";
$help .="are all modules included in this installation that are licensed to run on this server. </p>";
break;
case "reinstall":
$title = "Installation Maintenance";
$help = "<p>A Configuration file has been detected on your system and it appears In-Portal is correctly installed. ";
$help .="In order to work with the maintenance functions provided to the left you must provide the Intechnic ";
$help .="Username and Password you used when obtaining the license file residing on the server, or your admin Root password. ";
$help .=" <i>(Use Username 'root' if using your root password)</i></p>";
$help .= "<p>To removing your existing database and start with a fresh installation, select the first option ";
$help .= "provided. Note that this operation cannot be undone and no backups are made! Use at your own risk.</p>";
$help .="<p>If you wish to scrap your current installation and install to a new location, choose the second option. ";
$help .="If this option is selected you will be prompted for new database configuration information.</p>";
$help .="<p>The <i>Update License Information</i> option is used to update your In-Portal license data. Select this option if you have ";
$help .="modified your licensing status with Intechnic, or you have received new license data via email</p>";
$help .="<p>The <i>Fix Paths</i> option should be used when the location of the In-portal files has changed. For example, if you moved them from one folder to another. It will update all settings and ensure the program is operational at the new location.</p>";
break;
case "fix_paths":
$title = "Fix Paths";
$help = "<p>The <i>Fix Paths</i> option should be used when the location of the In-portal files has changed. For example, if you moved them from one folder to another. It will update all settings and ensure the program is operational at the new location.<p>";
break;
case "RootPass":
$title = "Set Admin Root Password";
$help = "<p>The Root Password is initially required to access the admin sections of In-Portal. ";
$help .="The root user cannot be used to access the front-end of the system, so it is recommended that you ";
$help .="create additional users with admin privlidges.</p>";
break;
case "finish":
$title = "Thank You!";
$help ="<P>Thanks for using In-Portal! Be sure to visit <A TARGET=\"_new\" HREF=\"http://www.in-portal.net\">www.in-portal.net</A> ";
$help.=" for the latest news, module releases and support. </p>";
break;
case "license":
$title = "License Configuration";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN. ";
$help.="If Intechnic has provided you with a license file, upload it here. Otherwise select the first ";
$help.="option to allow Install to download your license for you.</p>";
$help.="<p>If a valid license has been detected on your server, you can choose the <i>Use Existing License</i> ";
$help.="and continue the installation process</p>";
break;
case "domain_select":
$title="Select Licensed Domain";
$help ="<p>Select the domain you wish to configure In-Portal for. The <i>Other</i> option ";
$help.=" can be used to configure In-Portal for use on a local domain.</p>";
$help.="<p>For local domains, enter the hostname or LAN IP Address of the machine running In-Portal.</p>";
break;
case "db_reconfig":
case "dbinfo":
$title="Database Configuration";
$help = "<p>In-Portal needs to connect to your Database Server. Please provide the database server type*, ";
$help .="host name (<i>normally \"localhost\"</i>), Database user name, and database Password. ";
$help .="These fields are required to connect to the database.</p><p>If you would like In-Portal ";
$help .="to use a table prefix, enter it in the field provided. This prefix can be any ";
$help .=" text which can be used in the names of tables on your system. The characters entered in this field ";
$help .=" are placed <i>before</i> the names of the tables used by In-Portal. For example, if you enter \"inp_\"";
$help .=" into the prefix field, the table named Category will be named inp_Category.</p>";
break;
case "lang_select":
$title="Language Pack Installation";
$help = "<p>Select the language packs you wish to install. Each language pack contains all the phrases ";
$help .="used by the In-Portal administration and the default template set. Note that at least one ";
$help .="pack <b>must</b> be installed.</p>";
break;
case "lang_default":
$title="Select Default Language";
$help = "<p>Select which language should be considered the \"default\" language. This is the language ";
$help .="used by In-Portal when a language has not been selected by the user. This selection is applicable ";
$help .="to both the administration and front-end.</p>";
break;
case "lang_install":
$title="Installing Language Packs";
$help = "<p>The language packs you have selected are being installed. You may install more languages at a ";
$help.="later time from the Regional admin section.</p>";
break;
case "postconfig_1":
$help = "<P>These options define the general operation of In-Portal. Items listed here are ";
$help .="required for In-Portal's operation.</p><p>When you have finished, click <i>save</i> to continue.</p>";
break;
case "postconfig_2":
$help = "<P>User Management configuration options determine how In-Portal manages your user base.</p>";
$help .="<p>The groups listed to the right are pre-defined by the installation process and may be changed ";
$help .="through the Groups section of admin.</p>";
break;
case "postconfig_3":
$help = "<P>The options listed here are used to control the category list display functions of In-Portal. </p>";
break;
case "theme_sel":
$title="Select Default Theme";
$help = "<P>This theme will be used whenever a front-end session is started. ";
$help .="If you intend to upload a new theme and use that as default, you can do so through the ";
$help .="admin at a later date. A default theme is required for session management.</p>";
break;
case "get_license":
$title="Download License from Intechnic";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN.</p>";
$help.="<p>Here as you have selected download license from Intechnic you have to input your username and ";
$help.="password of your In-Business account in order to download all your available licenses.</p>";
break;
case "download_license":
$title="Download License from Intechnic";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN.</p>";
$help.="<p>Please choose the license from the drop down for this site! </p> ";
break;
case "restore_select":
$title="Select Restore File";
$help = "<P>Select the restore file to use to reinstall In-Portal. If your backups are not performed ";
$help .= "in the default location, you can enter the location of the backup directory and click the ";
$help .="<i>Update</i> button.</p>";
case "restore_run":
$title= "Restore in Progress";
$help = "<P>Restoration of your system is in progress. When the restore has completed, the installation ";
$help .="will continue as normal. Hitting the <i>Cancel</i> button will restart the entire installation process. ";
break;
case "warning":
$title = "Restore in Progress";
$help = "<p>Please approve that you understand that you are restoring your In-Portal data base from other version of In-Portal.</p>";
break;
case "update":
$title = "Update In-Portal";
$help = "<p>Select modules from the list, you need to update to the last downloaded version of In-Portal</p>";
break;
}
$tmp_step = GetVar('next_step', true);
if (!$tmp_step) {
$tmp_step = 1;
}
if ( isset($got_license) && $got_license == 1) {
$tmp_step++;
}
$next_step = $tmp_step + 1;
if ($general_error != '') {
$state = '';
$title = '';
$help = '';
$general_error = $general_error.'<br /><br />Installation cannot continue!';
}
if ($include_file == '' && $general_error == '' && $state == '') {
$state = '';
$title = '';
$help = '';
$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
RunSQLFile($ado,$filename);
$general_error = 'Unexpected installation error! <br /><br />Installation has been stopped!';
}
if ($restore_error != '') {
$next_step = 3;
$tmp_step = 2;
}
if ($PassError != '') {
$tmp_step = 4;
$next_step = 5;
}
if ($DomainError != '') {
$tmp_step--;
$next_step = $tmp_step + 1;
}
if ($db_error != '') {
$tmp_step--;
$next_step = $tmp_step + 1;
}
if ($state == "warning") {
$tmp_step--;
$next_step = $tmp_step + 1;
}
if ($skip_step) {
$tmp_step++;
$next_step = $tmp_step + 1;
}
?>
<tr height="100%">
<td valign="top">
<table cellpadding=10 cellspacing=0 border=0 width="100%" height="100%">
<tr valign="top">
<td style="width: 200px; background: #009ff0 url(images/bg_install_menu.gif) no-repeat bottom right; border-right: 1px solid #000">
<img src="images/spacer.gif" width="180" height="1" border="0" title=""><br>
<span class="admintitle-white">Installation</span>
<!--<ol class="install">
<li class="current">Licence Verification
<li>Configuration
<li>File Permissions
<li>Security
<li>Integrity Check
</ol>
</td>-->
<?php
$lic_opt = isset($_POST['lic_opt']) ? $_POST['lic_opt'] : false;
if ($general_error == '') {
?>
<?php if ($install_type == 1) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1) { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 2 || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4 ) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 2) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<!--<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish-->
</ol>
<?php } else if ($install_type == 3) { ?>
<ol class="install">
<li>License Verification
<li <?php if ($tmp_step == 2) { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 3 || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 4 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 9) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 4) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 5) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 6) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_GET['show_prev'] == 1 || $_POST['backupdir']) { ?>class="current"<?php } ?>>Select Backup File
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1 && $_GET['show_prev'] != 1 && !$_POST['backupdir']) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 7) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 8) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Select Modules to Upgrade
<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Language Pack Upgrade
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 9) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Fix Paths
<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } ?>
<?php include($include_file); ?>
<?php } else { ?>
<?php include("install/general_error.php"); ?>
<?php } ?>
<td width="40%" style="border-left: 1px solid #000; background: #f0f0f0">
<table width="100%" border="0" cellspacing="0" cellpadding="4">
<tr>
<td class="subsectiontitle" style="border-bottom: 1px solid #000000; background-color:#999"><?php if( isset($title) ) echo $title;?></td>
</tr>
<tr>
<td class="text"><?php if( isset($help) ) echo $help;?></td>
</tr>
</table>
</td>
</tr>
</table>
<br>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td id="footer">
Powered by In-portal &copy; 1997-2005, Intechnic Corporation. All rights reserved.
<br><img src="images/spacer.gif" width="1" height="10" title="">
</td>
</tr>
</table>
</form>
</body>
</html>
\ No newline at end of file
Property changes on: trunk/admin/install.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.94
\ No newline at end of property
+1.95
\ No newline at end of property
Index: trunk/admin/listview/listview.php
===================================================================
--- trunk/admin/listview/listview.php (revision 3215)
+++ trunk/admin/listview/listview.php (revision 3216)
@@ -1,472 +1,472 @@
<?php
require($pathtoroot.$admin."/listview/columnheader.php");
require($pathtoroot.$admin."/listview/viewmenu.php");
class clsListView
{
var $Formatters = Array(); // formatters to apply while printing list
var $ColumnHeaders;
var $ToolBar;
var $ListItems;
var $PageLinkTemplate;
var $PerPageVar;
var $CurrentPageVar;
var $CurrentPage;
var $TotalItemCount;
var $SortField;
var $SortOrder;
var $IdField;
var $PrintToolBar=TRUE;
var $ShowColumnHeaders=TRUE;
var $checkboxes=TRUE;
var $SelectorType;
var $CheckboxName;
var $CheckArray;
var $RowIcons;
var $SearchBar=FALSE;
var $SearchKeywords;
var $SearchAction;
var $SearchDropdownId="";
var $PageLinks;
var $extra_env;
var $PriorityField;
var $PageURL;
var $ViewMenu;
var $JSCheckboxName;
function clsListView($ToolBar=NULL,$ListItems=NULL)
{
$this->SetToolBar($ToolBar);
$this->SetListItems($ListItems);
$this->ColumnHeaders = new clsColumnHeaderList();
$this->CurrentPage=1;
$this->CheckboxName = "itemlist[]";
$this->SelectorType="checkbox";
$this->RowIcons = array();
$this->PageLinks = "";
$this->SearchAction = "";
$this->extra_env="";
$this->PriorityField="Priority";
$this->TotalItemCount = 0;
if (!is_null($ToolBar))
$this->JSCheckboxName = $ToolBar->Get("CheckClass");
$this->SetFormatters(); // for setting custom formatters
}
function SetToolbar($ToolBar)
{
$this->ToolBar=$ToolBar;
if(is_object($this->ToolBar))
$this->CheckArray=$this->ToolBar->Get("CheckClass");
}
function GetPage()
{
// get current page
$this->RefreshPageVar();
return $this->CurrentPage;
}
function GetLimitSQL()
{
return GetLimitSQL($this->GetPage(), $this->GetPerPage() );
}
function SetListItems(&$ListItems)
{
$this->ListItems =& $ListItems;
}
function SetIDfield($field)
{
$this->IdField = $field;
}
function SetSort($SortField,$SortOrderVariable)
{
$this->ColumnHeaders->SetSort($SortField,$SortOrder);
}
function SetRowIcon($index,$url)
{
$this->RowIcons[$index] = $url;
}
function ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSort,$FilterVar,$FilterValue,$FilterMax)
{
global $objConfig;
//$FilterVal = $this->CurrentFilter;
//$fMax = $this->Filtermax;
//$sOrder = $this->CurrentSortOrder;
//$sOrderVar = $this->OrderVar;
//$sField = $this->CurrentSortField;
//$sDefault = $this->DefaultSortField;
$this->ViewMenu = new clsViewMenu();
$this->ViewMenu->PerPageVar = $this->PerPageVar;
$this->ViewMenu->PerPageValue = (int)$objConfig->Get($this->PerPageVar);
if($this->ViewMenu->PerPageValue==0)
$this->ViewMenu->PerPageValue = 20;
$this->ViewMenu->CurrentSortField = $objConfig->Get($SortFieldVar);
$this->ViewMenu->CurrentSortOrder = $objConfig->get($SortOrderVar);
$this->ViewMenu->SortVar = $SortFieldVar;
$this->ViewMenu->OrderVar = $SortOrderVar;
$this->ViewMenu->CurrentFilter= $FilterValue;
$this->ViewMenu->FilterVar = $FilterVar;
$this->ViewMenu->FilterMax = $FilterMax;
foreach($this->ColumnHeaders->Columns as $col)
{
$this->ViewMenu->AddSortField($col->field,$col->label,$DefaultSort==$col->field);
}
}
function AddViewMenuFilter($Label,$Bit)
{
if(is_object($this->ViewMenu))
$this->ViewMenu->AddFilterField($Label,$Bit);
}
function GetViewMenu($imagesURL)
{
if(is_object($this->ViewMenu))
{
$this->ViewMenu->CheckboxName = $this->JSCheckboxName;
return $this->ViewMenu->GetViewMenuJS($imagesURL);
}
else
return "";
}
function SetFormatters()
{
// for setting custom formatters
// abstract
}
function SetFormatter($field, $type, $params)
{
// by Alex
// all params after 2nd are formmater type specific
$this->Formatters[$field]['type'] = $type;
switch($type)
{
case FT_OPTION:
$this->Formatters[$field]['options'] = $params;
break;
}
}
function PrintItem($index)
{
if( !isset($this->ListItems->Items[$index]) ) return '';
$li = $this->ListItems->Items[$index];
$o = "";
$first=1;
if(is_object($li))
{
// ==== new by Alex: begin ====
$li->Formatters =& $this->Formatters;
// ==== new by Alex: end ====
$id_field = $this->IdField;
$row_id = $li->Get($id_field);
if(is_numeric($li->Get($this->PriorityField)))
{
$Priority = (int)$li->Get($this->PriorityField);
}
else
$Priority=0;
$o = "<TR ".int_table_color_ret()." ID=\"$row_id\">\n";
foreach($this->ColumnHeaders->Columns as $col)
{
$width="";
$ColId = $row_id."_col_".$col->field;
if($first==1)
{
if(strlen($col->width))
{
$width = $col->width;
}
$o .= "<TD $width valign=\"top\" class=\"text\">";
if($this->checkboxes)
{
$onclick = "onclick=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\"";
$onclicksrc = "onclicksrc=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\"";
$o .= "<input rowId='".$row_id."' checkArrayName='".$this->CheckArray."' isSelector=\"true\" type=\"".$this->SelectorType."\" name=\"".$this->CheckboxName."\" value=\"$row_id\" $onclick $onclicksrc>";
}
if(isset($this->RowIcons[$index]))
{
$url = $this->RowIcons[$index];
if(strlen($url))
$o .= "<img src=\"".$url."\"> ";
}
$first=0;
}
else
{
if(strlen($col->width))
{
$o .= "<TD ".$col->width.">";
}
else
$o .= "<TD>";
}
if($Priority!=0)
{
$o .= "<span class=\"priority\"><sup>$Priority</sup></span>";
$Priority=0;
}
$o .= "<SPAN ID=\"$ColId\">".($li->GetFormatted($col->field))."</SPAN></TD>\n";
}
$o .= "</TR>\n";
}
return $o;
}
function PrintItems()
{
$o = '';
$numitems = $this->ListItems->NumItems();
for($index=0;$index<=$numitems;$index++)
{
$o .= $this->PrintItem($index);
}
return $o;
}
function TotalPageNumbers()
{
if($this->PerPage>0)
{
$ret = $this->ListItems->NumItems() / $this->PerPage;
$ret = (int)$ret;
}
else
$ret = 1;
return $ret;
}
function GetPerPage()
{
global $objConfig;
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage < 1)
{
- if( defined('DEBUG_MODE') ) echo 'PerPage Variable [<b>'.$this->PerPageVar.'</b>] not defined in Config<br>';
+ if( IsDebugMode() ) echo 'PerPage Variable [<b>'.$this->PerPageVar.'</b>] not defined in Config<br>';
$PerPage = 20;
//$objConfig->Set($this->PerPageVar,20);
//$objConfig->Save();
}
return $PerPage;
}
function GetAdminPageLinkList($url)
{
global $objConfig;
$PerPage = $this->GetPerPage();
if($this->TotalItemCount>0)
{
$NumPages = ceil($this->TotalItemCount / $PerPage);
}
else
$NumPages = ceil($this->ListItems->NumItems() / $PerPage);
if($NumPages<1)
$NumPages =1;
//echo $this->CurrentPage." of ".$NumPages." Pages";
$o = "";
if($this->CurrentPage>$NumPages)
$this->CurrentPage=$NumPages;
$StartPage = $this->CurrentPage - 5;
if($StartPage<1)
$StartPage=1;
$EndPage = $StartPage+9;
if($EndPage>$NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage-10;
if($StartPage<1)
$StartPage=1;
}
$o .= "<b class=\"text\">".admin_language("la_Page")."</b> ";
if($StartPage>1)
{
$target = $this->CurrentPage-10;
$prev_url = str_replace("{TargetPage}",$target,$url);
$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->CurrentPage)
{
$href = str_replace("{TargetPage}",$p,$url);
$o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
}
else
{
$o .= " <SPAN class=\"CURRENT_PAGE\">$p</SPAN> ";
}
}
if($EndPage<$NumPages-1)
{
$target = $this->CurrentPage+10;
$next_url = str_replace("{TargetPage}",$target,$url);
$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\"> &gt;&gt;</A>";
}
return $o;
}
function SliceItems()
{
global $objConfig;
$PerPage = (int)$objConfig->Get($this->PerPageVar);
if($PerPage<1)
$PerPage=20;
$NumPages = ceil($this->ListItems->NumItems() / $PerPage);
if($NumPages>1)
{
$Start = ($this->CurrentPage-1)*$PerPage;
$this->ListItems->Items = array_slice($this->ListItems->Items,$Start,$PerPage);
}
}
function RefreshPageVar()
{
global $objSession;
if( (int)GetVar('lpn') > 0)
{
$this->CurrentPage = $_GET["lpn"];
$objSession->SetVariable($this->CurrentPageVar,$this->CurrentPage);
}
else
$this->CurrentPage = $objSession->GetVariable($this->CurrentPageVar);
$this->ListItems->Page = $this->CurrentPage;
}
function PrintPageLinks($add_search = '')
{
global $imagesURL, $objSession, $lvErrorString;
if(strlen($this->PageLinks)>0)
{
return $this->PageLinks;
}
$this->RefreshPageVar();
if($this->CurrentPage<1)
$this->CurrentPage = 1;
if(!strlen($this->PageURL))
{
$this->PageURL = $_SERVER["PHP_SELF"]."?env=".BuildEnv();
if(strlen($this->extra_env))
$this->PageURL .= "&".$this->extra_env;
$this->PageURL .= "&lpn={TargetPage}";
}
$cols = $this->ColumnHeaders->Count();
$o = "<TABLE cellSpacing=0 cellPadding=2 width=\"100%\" class=\"pagenav\"><tbody><TR >\n";
if(strlen($lvErrorString))
{
$o .= "<TD STYLE=\"border-bottom: 1px solid #000000;\" colspan=2><span class=\"validation_error\">$lvErrorString</SPAN></TD></TR><TR>";
}
if($this->SearchBar==FALSE)
{
$o .= '<TD colspan="2">';
$o .= $this->GetAdminPageLinkList($this->PageURL);
$o .= "</TD>\n";
}
else
{
$val = inp_htmlize(str_replace(","," ", $this->SearchKeywords),1);
$o .= "<TD>";
$o .= $this->GetAdminPageLinkList($this->PageURL)."</TD>";
$o .= "<TD align=\"right\" valign=\"top\">$add_search".admin_language("la_prompt_Search");
$o .= " <INPUT TYPE=\"TEXT\" ID=\"ListSearchWord\" NAME=\"ListSearchWord\" VALUE=\"$val\">";
$o .= " <IMG align=\"middle\" height=24 width=24 name=\"imgSearch\" ID=\"imgSearch\" src=\"$imagesURL/itemicons/icon16_search.gif\" ";
$o .= " onMouseOut=\"swap('imgSearch', '$imagesURL/itemicons/icon16_search.gif');\" ";
$o .= " onMouseOver=\"swap('imgSearch','$imagesURL/itemicons/icon16_search_f2.gif');\" ";
$o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."');\">";
$o .= " <IMG align=\"middle\" height=24 width=24 name=\"imgResetSearch\" ID=\"imgResetSearch\" src=\"$imagesURL/itemicons/icon16_search_reset.gif\" ";
$o .= " onMouseOut=\"swap('imgResetSearch', '$imagesURL/itemicons/icon16_search_reset.gif');\" ";
$o .= " onMouseOver=\"swap('imgResetSearch','$imagesURL/itemicons/icon16_search_reset_f2.gif');\" ";
$o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."_reset');\">";
if(strlen($this->SearchDropdownId)>0)
{
$o .= " <IMG height=16 width=16 name=\"imgSearchDropDown\" src=\"$imagesURL/itemicons/icon16_search_dropdown.gif\" ";
$o .= " onMouseOut=\"swap('imgResetDropDown', '$imagesURL/itemicons/icon16_search_dropdown.gif');\" ";
$o .= " onMouseOver=\"swap('imgResetDropDown','$imagesURL/itemicons/icon16_search_dropdown.gif');\" ";
$o .= " onClick=\"ListSearch_PopUp('".$this->SearchDropdownId."');\">";
}
$o .= "</TD>";
}
$o .= "</TR></TABLE>";
return $o;
}
function PrintJavaScriptInit()
{
$o = '';
if($this->checkboxes)
{
$o = "<script language=\"javascript\">\n";
$o .="<!--\n";
foreach($this->ListItems->Items as $li)
{
$o .= $this->CheckArray.".CheckList[".$this->CheckArray.".CheckList.length] = '".$li->Get($this->IdField)."';\n";
}
$o .= $this->CheckArray.".setImages();\n";
$o .="//-->\n";
$o .="</script>";
}
return $o;
}
function PrintList($footer = '',$add_search = '')
{
global $objSession;
if((int)$this->CurrentPage<1)
$this->CurrentPage=1;
$o = "\n";
if(is_object($this->ToolBar))
{
if($this->PrintToolBar)
$o .= $this->ToolBar->Build();
}
$o .= $this->PrintPageLinks($add_search);
$o .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">\n";
if($this->ShowColumnHeaders)
{
$o .= $this->ColumnHeaders->PrintColumns();
}
if($this->ListItems->NumItems()>0)
{
$o .= $this->PrintItems();
}
$o .= "$footer</TABLE>";
if($this->ListItems->NumItems()>0)
$o .= $this->PrintJavaScriptInit();
return $o;
}
}
Property changes on: trunk/admin/listview/listview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/core/kernel/utility/unit_config_reader.php
===================================================================
--- trunk/core/kernel/utility/unit_config_reader.php (revision 3215)
+++ trunk/core/kernel/utility/unit_config_reader.php (revision 3216)
@@ -1,469 +1,470 @@
<?php
class kUnitConfigReader extends kBase {
/**
* Configs readed
*
* @var Array
* @access private
*/
var $configData=Array();
var $configFiles=Array();
var $CacheExpired = false;
/**
* Module names found during
* config reading
*
* @var Array
*/
var $modules_installed = Array();
/**
* Scan kernel and user classes
* for available configs
*
* @access protected
*/
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$db =& $this->Application->GetADODBConnection();
$this->modules_installed = $db->GetCol('SELECT CONCAT(\'/\',Path) AS Path, Name FROM '.TABLE_PREFIX.'Modules WHERE Loaded = 1','Name');
$this->scanModules(MODULES_PATH);
}
/**
* Checks if config file is allowed for includion (if module of config is installed)
*
* @param string $config_path relative path from in-portal directory
*/
function configAllowed($config_path)
{
$module_found = false;
foreach($this->modules_installed as $module_path)
{
if( substr($config_path, 0, strlen($module_path)) == $module_path )
{
$module_found = true;
break;
}
}
return $module_found;
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
return isset($this->configData[$prefix]) ? true : false;
}
/**
* Read configs from all directories
* on path specified
*
* @param string $folderPath
* @access public
*/
function processFolder($folderPath, $cached)
{
$fh=opendir($folderPath);
while(($sub_folder=readdir($fh)))
{
$full_path=$folderPath.'/'.$sub_folder;
if( $this->isDir($full_path) && file_exists($this->getConfigName($full_path)) )
{
if (filemtime($full_path) > $cached) {
$this->CacheExpired = true;
$file = $this->getConfigName($full_path);
- if ( defined('DEBUG_MODE') && dbg_ConstOn('DBG_PROFILE_INCLUDES')) {
+ if ( $this->Application->isDebugMode() && constOn('DBG_PROFILE_INCLUDES') )
+ {
if ( in_array($file, get_required_files()) ) return;
global $debugger;
$debugger->IncludeLevel++;
$before_time = getmicrotime();
$before_mem = memory_get_usage();
include_once(FULL_PATH.$file);
$used_time = getmicrotime() - $before_time;
$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $file);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = -1;
}
else {
include_once($file);
}
if ( !isset($config) || !$config ) continue;
$prefix = $config['Prefix'];
$config['BasePath'] = $full_path;
$this->configData[$prefix] = $config;
}
}
}
}
function ParseConfigClones($prefix)
{
$config = $this->configData[$prefix];
if(!getArrayValue($config, 'Clones'))
{
return;
}
unset($this->configData[$prefix]['Clones']);
foreach($config['Clones'] as $clone_prefix => $clone_config)
{
$clone_config['Prefix'] = $clone_prefix;
$this->configData[$clone_prefix] = array_merge_recursive2($this->configData[$prefix], $clone_config);
foreach($clone_config as $cloned_property => $cloned_value)
{
if(!$cloned_value) unset($this->configData[$clone_prefix][$cloned_property]);
}
$this->ParseConfigClones($clone_prefix);
}
}
function ParseConfigs()
{
foreach ($this->configData as $prefix => $config)
{
$this->parseConfig($prefix);
}
}
function findConfigFiles($folderPath)
{
$folderPath = str_replace(FULL_PATH, '', $folderPath); // this make sense, since $folderPath may NOT contain FULL_PATH
$fh=opendir(FULL_PATH.$folderPath);
while(($sub_folder=readdir($fh)))
{
$full_path=FULL_PATH.$folderPath.'/'.$sub_folder;
if( $this->isDir($full_path))
{
if ( file_exists(FULL_PATH.$this->getConfigName($folderPath.'/'.$sub_folder)) ) {
$this->configFiles[] = $this->getConfigName($folderPath.'/'.$sub_folder);
}
$this->findConfigFiles($full_path);
// if (filemtime($full_path) > $cached) { }
}
}
}
function includeConfigFiles()
{
$db =& $this->Application->GetADODBConnection();
foreach ($this->configFiles as $filename)
{
$config_found = file_exists(FULL_PATH.$filename) && $this->configAllowed($filename);
- if( defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_INCLUDES'))
+ if( $this->Application->isDebugMode() && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($filename, get_required_files()) ) return;
global $debugger;
$debugger->IncludeLevel++;
$before_time = getmicrotime();
$before_mem = memory_get_usage();
if($config_found) include_once(FULL_PATH.$filename);
$used_time = getmicrotime() - $before_time;
$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $filename);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = -1;
}
else
{
if($config_found) include_once(FULL_PATH.$filename);
}
if($config_found && isset($config) && $config)
{
$prefix = $config['Prefix'];
preg_match('/\/(.*)\//U', $filename, $rets);
$config['ModuleFolder'] = $rets[1];
$config['BasePath'] = dirname(FULL_PATH.$filename);
$this->configData[$prefix] = $config;
$this->ParseConfigClones($prefix);
}
}
}
function scanModules($folderPath)
{
global $debugger;
if (defined('CACHE_CONFIGS_FILES')) {
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "config_files"');
if ($data && $data['Cached'] > (time() - 3600) ) {
$this->configFiles = unserialize($data['Data']);
$files_cached = $data['Cached'];
}
else {
$files_cached = 0;
}
}
else {
$files_cached = 0;
}
if (defined('CACHE_CONFIGS_DATA') && CACHE_CONFIGS_DATA) {
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "config_data"');
if ($data && $data['Cached'] > (time() - 3600) ) {
$this->configData = unserialize($data['Data']);
$data_cached = $data['Cached'];
}
else {
$data_cached = 0;
}
}
else {
$data_cached = 0;
}
if ( !defined('CACHE_CONFIGS_FILES') || $files_cached == 0 ) {
$this->findConfigFiles($folderPath);
}
if ( !defined('CACHE_CONFIGS_DATA') || $data_cached == 0) {
$this->includeConfigFiles();
}
/*// && (time() - $cached) > 600) - to skip checking files modified dates
if ( !defined('CACHE_CONFIGS') ) {
$fh=opendir($folderPath);
while(($sub_folder=readdir($fh)))
{
$full_path=$folderPath.'/'.$sub_folder.'/units';
if( $this->isDir($full_path) )
{
$this->processFolder($full_path, $cached);
}
}
}*/
if (defined('CACHE_CONFIGS_DATA') && $data_cached == 0) {
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("config_data", '.$conn->qstr(serialize($this->configData)).', '.time().')');
}
$this->ParseConfigs();
if (defined('CACHE_CONFIGS_FILES') && $files_cached == 0) {
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("config_files", '.$conn->qstr(serialize($this->configFiles)).', '.time().')');
}
unset($this->configFiles);
// unset($this->configData);
}
/**
* Register nessasary classes
*
* @param string $prefix
* @access private
*/
function parseConfig($prefix)
{
$config =& $this->configData[$prefix];
$event_manager =& $this->Application->recallObject('EventManager');
$class_params=Array('ItemClass','ListClass','EventHandlerClass','TagProcessorClass');
foreach($class_params as $param_name)
{
if ( !(isset($config[$param_name]) ) ) continue;
$class_info =& $config[$param_name];
$pseudo_class = $this->getPrefixByParamName($param_name,$prefix);
$this->Application->registerClass( $class_info['class'],
$config['BasePath'].'/'.$class_info['file'],
$pseudo_class);
$event_manager->registerBuildEvent($pseudo_class,$class_info['build_event']);
// register classes on which current class depends
$require_classes = getArrayValue($class_info, 'require_classes');
if($require_classes)
{
foreach($require_classes as $require_class)
{
$this->Application->Factory->registerDependency($class_info['class'], $require_class);
}
}
}
$register_classes = getArrayValue($config,'RegisterClasses');
if($register_classes)
{
foreach($register_classes as $class_info)
{
$this->Application->registerClass( $class_info['class'],
$config['BasePath'].'/'.$class_info['file'],
$class_info['pseudo']);
}
}
$regular_events = getArrayValue($config, 'RegularEvents');
if($regular_events)
{
foreach($regular_events as $short_name => $regular_event_info)
{
$event_manager->registerRegularEvent( $short_name, $config['Prefix'].':'.$regular_event_info['EventName'], $regular_event_info['RunInterval'], $regular_event_info['Type'] );
}
}
if ( is_array(getArrayValue($config, 'Hooks')) ) {
foreach ($config['Hooks'] as $hook) {
$do_prefix = $hook['DoPrefix'] == '' ? $config['Prefix'] : $hook['DoPrefix'];
if ( !is_array($hook['HookToEvent']) ) {
$hook_events = Array( $hook['HookToEvent'] );
}
else {
$hook_events = $hook['HookToEvent'];
}
foreach ($hook_events as $hook_event) {
$this->Application->registerHook($hook['HookToPrefix'], $hook['HookToSpecial'], $hook_event, $hook['Mode'], $do_prefix, $hook['DoSpecial'], $hook['DoEvent'], $hook['Conditional']);
}
}
}
if ( is_array(getArrayValue($config, 'AggregateTags')) ) {
foreach ($config['AggregateTags'] as $aggregate_tag) {
$aggregate_tag['LocalPrefix'] = $config['Prefix'];
$this->Application->registerAggregateTag($aggregate_tag);
}
}
if ( $this->Application->isDebugMode() && dbg_ConstOn('DBG_VALIDATE_CONFIGS') && isset($config['TableName']) )
{
global $debugger;
$tablename = $config['TableName'];
$conn =& $this->Application->GetADODBConnection();
$res = $conn->Query("DESCRIBE $tablename");
foreach ($res as $field) {
$f_name = $field['Field'];
if (getArrayValue($config, 'Fields')) {
if ( !array_key_exists ($f_name, $config['Fields']) ) {
$debugger->appendHTML("<b class='debug_error'>Config Warning: </b>Field $f_name exists in the database, but is not defined in config file for prefix <b>".$config['Prefix']."</b>!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
else {
$options = $config['Fields'][$f_name];
if ($field['Null'] == '') {
if ( $f_name != $config['IDField'] && !isset($options['not_null']) && !isset($options['required']) ) {
$debugger->appendHTML("<b class='debug_error'>Config Error: </b>Field $f_name in config for prefix <b>".$config['Prefix']."</b> is NOT NULL in the database, but is not configured as not_null or required!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
if ( isset($options['not_null']) && !isset($options['default']) ) {
$debugger->appendHTML("<b class='debug_error'>Config Error: </b>Field $f_name in config for prefix <b>".$config['Prefix']."</b> is described as NOT NULL, but does not have DEFAULT value!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
}
}
}
}
}
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @return string
* @access public
*/
function getUnitOption($prefix,$name)
{
return isset($this->configData[$prefix][$name]) ? $this->configData[$prefix][$name] : false;
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
*/
function getUnitOptions($prefix)
{
return $this->prefixRegistred($prefix) ? $this->configData[$prefix] : false;
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @access public
*/
function setUnitOption($prefix,$name,$value)
{
$this->configData[$prefix][$name] = $value;
}
function getPrefixByParamName($paramName,$prefix)
{
$pseudo_class_map=Array(
'ItemClass'=>'%s',
'ListClass'=>'%s_List',
'EventHandlerClass'=>'%s_EventHandler',
'TagProcessorClass'=>'%s_TagProcessor'
);
return sprintf($pseudo_class_map[$paramName],$prefix);
}
/**
* Get's config file name based
* on folder name supplied
*
* @param string $folderPath
* @return string
* @access private
*/
function getConfigName($folderPath)
{
return $folderPath.'/'.basename($folderPath).'_config.php';
}
/**
* is_dir ajustment to work with
* directory listings too
*
* @param string $folderPath
* @return bool
* @access private
*/
function isDir($folderPath)
{
$base_name=basename($folderPath);
$ret=!($base_name=='.'||$base_name=='..');
return $ret&&is_dir($folderPath);
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/unit_config_reader.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19
\ No newline at end of property
+1.20
\ No newline at end of property
Index: trunk/core/kernel/utility/email.php
===================================================================
--- trunk/core/kernel/utility/email.php (revision 3215)
+++ trunk/core/kernel/utility/email.php (revision 3216)
@@ -1,433 +1,433 @@
<?php
class kEmailMessage extends kBase {
var $Compiled;
var $Headers;
var $HeadersArray;
var $BodyText;
var $BodyHtml;
var $Body;
var $Subject;
// var $From;
// var $To;
// var $ReplyTo;
// var $CC;
// var $BCC;
var $Charset;
var $LineFeed;
var $TransferEncoding;
var $From;
var $To;
var $IsMultipart;
var $Parts;
var $Files;
var $TextBoundary;
var $EmailBoundary;
function kEmailMessage(){
//$this->TextBoundary = uniqid(time());
$this->EmailBoundary = uniqid(time());
$this->LineFeed = "\n";
$this->Charset='ISO-8859-1';
$this->TransferEncoding='8bit';
$this->Body = '';
$this->setHeader('Subject', 'Automatically generated message');
$this->HeadersArray=array();
$this->setHeader('Mime-Version', '1.0');
}
function setHeader($header, $value){
$this->HeadersArray[$header] = $value;
$this->Compiled = false;
}
function setHeaders($headers){
$headers=str_replace("\r", "", $headers);
$headers_lines = explode("\n", $headers);
foreach ($headers_lines as $line_num => $line){
list($header_field, $header_value) = explode(':', $line, 2);
$header_value = trim($header_value);
$this->setHeader($header_field, $header_value);
if ($header_field == 'Subject') $this->Subject = $header_value;
}
}
function appendHeader($header, $value){
$this->HeadersArray[$header][] = $value;
$this->Compiled = false;
}
function setFrom($from, $name=''){
$this->From = $from;
if ($name!=''){
$from = trim($name).' <'.$from.'>';
}
$this->setHeader('From', trim($from));
}
function setTo($to, $name=''){
$this->To = $to;
if ($name!=''){
$to = trim($name).' <'.$to.'>';
}
$this->setHeader('To', trim($to));
}
function setSubject($subj){
$this->setHeader('Subject', $subj);
}
function SetCC($to_cc){
$this->appendHeader('CC', $to_cc);
}
function SetBCC($to_bcc){
$this->appendHeader('BCC', $to_bcc);
}
function setReplyTo($reply_to){
$this->setHeader('Reply-to', $reply_to);
}
function Clear()
{
$this->Compiled = false;
$this->Body = '';
$this->BodyHtml = '';
$this->BodyText = '';
$this->Headers = '';
$this->Files = '';
$this->From = '';
$this->To = '';
}
function setTextBody($body_text){
$this->BodyText = $body_text;
$this->Compiled = false;
}
function setHTMLBody($body_html){
$this->BodyHtml = $body_html;
$this->IsMultipart = true;
$this->Compiled = false;
}
function compileBody(){
$search = array (
"'(<\/td>.*)[\r\n]+(.*<td)'i",//formating text in tables
"'(<br[ ]?[\/]?>)|(<\/p>)|(<\/div>)|(<\/tr>)'i",
"'<head>(.*?)</head>'si",
"'<style(.*?)</style>'si",
"'<title>(.*?)</title>'si",
"'<script(.*?)</script>'si",
// "'^[\s\n\r\t]+'", //strip all spacers & newlines in the begin of document
// "'[\s\n\r\t]+$'", //strip all spacers & newlines in the end of document
"'&(quot|#34);'i",
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'&#(\d+);'e"
);
$replace = array (
"\\1\t\\2",
"\n",
"",
"",
"",
"",
// "",
// "",
"\"",
"&",
"<",
">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\\1)"
);
if($this->BodyHtml){
$not_html = preg_replace ($search, $replace, $this->BodyHtml);
$not_html = strip_tags($not_html);
// $not_html = $this->removeBlankLines($not_html);
// Fixing problem with add exclamation characters "!" into the body of the email.
$not_html = wordwrap($not_html, 72);
$this->BodyHtml = wordwrap($this->BodyHtml, 72);
$this->Body = '';
//$this->Body .= 'Content-Type: multipart/alternative;'.$this->LF()." ".'boundary="----='.$this->TextBoundary.'"'.$this->LF();
//$this->Body .= $this->LF();
$this->Body .= '------='.$this->EmailBoundary.$this->LF();
$this->Body .= 'Content-Type: text/plain;'.$this->LF()." ".'charset="'.$this->Charset.'"'.$this->LF();
$this->Body .= $this->LF();
$this->Body .= $not_html.$this->LF().$this->LF();
$this->Body .= '------='.$this->EmailBoundary.$this->LF();
$this->Body .= 'Content-Type: text/html;'.$this->LF()." ".'charset="'.$this->Charset.'"'.$this->LF();
$this->Body .= 'Content-Transfer-Encoding: '.$this->TransferEncoding.$this->LF();
$this->Body .= 'Content-Description: HTML part'.$this->LF();
$this->Body .= 'Content-Disposition: inline'.$this->LF();
$this->Body .= $this->LF();
$this->BodyHtml = str_replace("\r", "", $this->BodyHtml);
$this->BodyHtml = str_replace("\n", $this->LF(), $this->BodyHtml);
$this->Body .= $this->BodyHtml;
$this->Body .= $this->LF().$this->LF();
$this->IsMultipart = true;
}else{
$not_html = preg_replace ($search, $replace, $this->BodyText);
$not_html = strip_tags($not_html);
// $not_html = $this->removeBlankLines($not_html);
// Fixing problem with add exclamation characters "!" into the body of the email.
$not_html = wordwrap($not_html, 72);
if ($this->IsMultipart){
$this->Body .= '------='.$this->EmailBoundary.$this->LF();
$this->Body .= 'Content-Type: text/plain;'.$this->LF()." ".'charset="'.$this->Charset.'"'.$this->LF();
$this->Body .= 'Content-Disposition: inline'.$this->LF();
$this->Body .= $this->LF();
$this->Body .= $not_html.$this->LF().$this->LF();
}else{
//$this->BodyText = str_replace("\r", "", $this->BodyText);
//$this->BodyText = str_replace("\n", $this->LF(), $this->BodyText);
$this->Body = $not_html;
}
}
}
function setCharset($charset){
$this->Charset = $charset;
$this->Compiled = false;
}
function setLineFeed($linefeed){
$this->LineFeed=$linefeed;
}
function attachFile($filepath, $mime="application/octet-stream"){
if(is_file($filepath)){
$file_info = array('path'=>$filepath, 'mime'=>$mime);
$this->Files[] = $file_info;
}else{
die('File "'.$filepath.'" not exist...'."\n");
}
$this->IsMultipart = true;
$this->Compiled = false;
}
function LF($str=''){
$str = str_replace("\n", "", $str);
$str = str_replace("\r", "", $str);
return $str.$this->LineFeed;
}
function getContentType(){
$content_type="";
if ($this->IsMultipart){
$content_type .= $this->LF('multipart/alternative;');
$content_type .= $this->LF(" ".'boundary="----='.$this->EmailBoundary.'"');
}else{
$content_type .= $this->LF('text/plain;');
$content_type .= $this->LF(" ".'charset='.$this->Charset);
}
return $content_type;
}
// ========================================
function compileHeaders(){
$this->Headers="";
// $this->Headers .= "From: ".$this->LF($this->From);
//if ($this->ReplyTo){
// $this->Headers .= "Reply-To: ".$this->ReplyTo.$this->LF();
//}
//$this->Headers .= "To: ".$this->LF($this->To);
//$this->Headers .= "Subject: ".$this->LF($this->Subject);
/*
if (sizeof($this->CC)){
$this->Headers .= "Cc: ";
foreach ($this->Cc as $key => $addr){
$this->Headers.=$this->LF($addr.',');
}
}
if (sizeof($this->BCC)){
$this->Headers .= "Bcc: ";
foreach ($this->BCC as $key => $addr){
$this->Headers.=$this->LF($addr.',');
}
}
*/
foreach ($this->HeadersArray as $key => $val){
if ($key=="To" || $key=="") continue; // avoid duplicate "To" field in headers
if (is_array($val)){
$val = chunk_split(implode(', ', $val),72, $this->LF().' ');
$this->Headers .= $key.": ".$val.$this->LF();
}else{
$this->Headers .= $key.": ".$val.$this->LF();
}
}
$this->Headers .= "Content-Type: ".$this->getContentType();
//$this->Headers .= "Content-Transfer-Encoding: ".$this->TransferEncoding.$this->LF();
}
function compileFiles(){
if ($this->Files){
foreach($this->Files as $key => $file_info)
{
$filepath = $file_info['path'];
$mime = $file_info['mime'];
$attachment_header = $this->LF('------='.$this->EmailBoundary);
$attachment_header .= $this->LF('Content-Type: '.$mime.'; name="'.basename($filepath).'"');
$attachment_header .= $this->LF('Content-Transfer-Encoding: base64');
$attachment_header .= $this->LF('Content-Description: '.basename($filepath));
$attachment_header .= $this->LF('Content-Disposition: attachment; filename="'.basename($filepath).'"');
$attachment_header .= $this->LF('');
$attachment_data = fread(fopen($filepath,"rb"),filesize($filepath));
$attachment_data = base64_encode($attachment_data);
$attachment_data = chunk_split($attachment_data,72);
$this->Body .= $attachment_header.$attachment_data.$this->LF('');
$this->IsMultipart = true;
}
}
}
function compile(){
if ($this->Compiled) return;
$this->compileBody();
$this->compileFiles();
$this->compileHeaders();
// Compile
if ($this->IsMultipart){
$this->Body .= '------='.$this->EmailBoundary.'--'.$this->LF();
}
$this->Compiled = true;
}
// ========================================
function getHeaders(){
$this->Compile();
return $this->Headers;
}
function getBody(){
$this->Compile();
return $this->Body;
}
function send(){
return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody());
//return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody(), '-f'.$this->From);
}
function sendSMTP(&$smtp_object, $smtp_host, $user, $pass, $auth_used = 0){
$params['host'] = $smtp_host; // The smtp server host/ip
$params['port'] = 25; // The smtp server port
$params['helo'] = $_SERVER['HTTP_HOST']; // What to use when sending the helo command. Typically, your domain/hostname
$params['auth'] = TRUE; // Whether to use basic authentication or not
$params['user'] = $user; // Username for authentication
$params['pass'] = $pass; // Password for authentication
$params['debug'] = 1;
if ($auth_used == 0){
$params['authmethod'] = 'NOAUTH'; // forse disabling auth
}
$send_params['recipients'] = array($this->To); // The recipients (can be multiple)
$send_params['headers'] = array(
'From: '.$this->HeadersArray['From'], // Headers
'To: '.$this->HeadersArray['To'],
'Subject: '.$this->HeadersArray['Subject'],
'Content-type: '.$this->getContentType(),
$this->getBody(),
);
$send_params['from'] = $this->From; // This is used as in the MAIL FROM: cmd
// It should end up as the Return-Path: header
$send_params['body']="\n";
if($smtp_object->connect($params) && $smtp_object->send($send_params)){
return true;
}else {
- if (defined('DEBUG_MODE')){
- global $debugger;
- $debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
+ if ( $this->Application->isDebugMode() )
+ {
+ $this->Application->Debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
//define('DBG_REDIRECT', 1);
}
return false;
}
}
}
?>
Property changes on: trunk/core/kernel/utility/email.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/core/kernel/globals.php
===================================================================
--- trunk/core/kernel/globals.php (revision 3215)
+++ trunk/core/kernel/globals.php (revision 3216)
@@ -1,382 +1,385 @@
<?php
if( !function_exists('array_merge_recursive2') )
{
/**
* array_merge_recursive2()
*
* Similar to array_merge_recursive but keyed-valued are always overwritten.
* Priority goes to the 2nd array.
*
* @static yes
* @param $paArray1 array
* @param $paArray2 array
* @return array
* @access public
*/
function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
foreach ($paArray2 AS $sKey2 => $sValue2)
{
$paArray1[$sKey2] = array_merge_recursive2( getArrayValue($paArray1,$sKey2), $sValue2);
}
return $paArray1;
}
}
/**
* @return int
* @param $array array
* @param $value mixed
* @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
*/
function array_unshift_ref(&$array, &$value)
{
$return = array_unshift($array,'');
$array[0] =& $value;
return $return;
}
if (!function_exists('print_pre')) {
/**
* Same as print_r, budet designed for viewing in web page
*
* @param Array $data
* @param string $label
*/
function print_pre($data, $label='')
{
- if( defined('DEBUG_MODE') && DEBUG_MODE )
+ if( constOn('DEBUG_MODE') )
{
global $debugger;
if($label) $debugger->appendHTML('<b>'.$label.'</b>');
$debugger->dumpVars($data);
}
else
{
if($label) echo '<b>',$label,'</b><br>';
echo '<pre>',print_r($data,true),'</pre>';
}
}
}
if (!function_exists('getArrayValue')) {
/**
* Returns array value if key exists
*
* @param Array $array searchable array
* @param int $key array key
* @return string
* @access public
*/
//
function getArrayValue(&$array,$key)
{
$ret = isset($array[$key]) ? $array[$key] : false;
if ($ret && func_num_args() > 2) {
for ($i = 2; $i < func_num_args(); $i++) {
$cur_key = func_get_arg($i);
$ret = getArrayValue( $ret, $cur_key );
if ($ret === false) break;
}
}
return $ret;
}
}
/**
* Rename key in associative array, maintaining keys order
*
* @param Array $array Associative Array
* @param mixed $old Old key name
* @param mixed $new New key name
* @access public
*/
function array_rename_key(&$array, $old, $new)
{
foreach ($array as $key => $val)
{
$new_array[ $key == $old ? $new : $key] = $val;
}
$array = $new_array;
}
if( !function_exists('safeDefine') )
{
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
function safeDefine($const_name, $const_value)
{
if(!defined($const_name)) define($const_name,$const_value);
}
}
if( !function_exists('parse_portal_ini') )
{
function parse_portal_ini($file, $parse_section = false)
{
if (!file_exists($file)) return false;
if( file_exists($file) && !is_readable($file) ) die('Could Not Open Ini File');
$contents = file($file);
$retval = Array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if($resave)
{
$fp = fopen($file, 'w');
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
}
if( !function_exists('getmicrotime') )
{
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
if( !function_exists('k4_include_once') )
{
function k4_include_once($file)
{
- if ( defined('DEBUG_MODE') && DEBUG_MODE && defined('DBG_PROFILE_INCLUDES') && DBG_PROFILE_INCLUDES )
+ if ( constOn('DEBUG_MODE') && isset($debugger) && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($file, get_required_files()) ) return;
global $debugger;
$debugger->IncludeLevel++;
$before_time = getmicrotime();
$before_mem = memory_get_usage();
include_once($file);
$used_time = getmicrotime() - $before_time;
$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $file);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = $debugger->IncludeLevel;
}
else
{
include_once($file);
}
}
}
/**
* Checks if string passed is serialized array
*
* @param string $string
* @return bool
*/
function IsSerialized($string)
{
if( is_array($string) ) return false;
return preg_match('/a:([\d]+):{/', $string);
}
if (!function_exists('makepassword4')){
function makepassword4($length=10)
{
$pass_length=$length;
$p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2=array('a','e','i','o','u');
$p3=array('1','2','3','4','5','6','7','8','9');
$p4=array('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1=21;// this is the count of $p1
$s2=5; // this is the count of $p2
$s3=9; // this is the count of $p3
$s4=5; // this is the count of $p4
// possible readable combinations
$c1='121'; // will be like 'bab'
$c2='212'; // will be like 'aba'
$c3='12'; // will be like 'ab'
$c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3
// $c5='4'; // uncomment to active the strong stuff
$comb='4'; // the amount of combinations you made above (and did not comment out)
for ($p=0;$p<$pass_length;)
{
mt_srand((double)microtime()*1000000);
$strpart=mt_rand(1,$comb);
// checking if the stringpart is not the same as the previous one
if($strpart<>$previous)
{
$pass_structure.=${'c'.$strpart};
// shortcutting the loop a bit
$p=$p+strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g=0;$g<strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
$sel=substr($pass_structure,$g,1);
$pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
}
return $pass;
}
}
if( !function_exists('unhtmlentities') )
{
function unhtmlentities($string)
{
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip ($trans_tbl);
return strtr($string, $trans_tbl);
}
}
if( !function_exists('curl_post') )
{
/**
* submits $url with $post as POST
*
* @param string $url
* @param unknown_type $post
* @return unknown
*/
function curl_post($url, $post)
{
if( is_array($post) )
{
$params_str = '';
foreach($post as $key => $value) $params_str .= $key.'='.urlencode($value).'&';
$post = $params_str;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_REFERER, PROTOCOL.SERVER_NAME);
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 0);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
}
if( !function_exists('memory_get_usage') )
{
function memory_get_usage(){ return -1; }
}
function &ref_call_user_func_array($callable, $args)
{
if( is_scalar($callable) )
{
// $callable is the name of a function
$call = $callable;
}
else
{
if( is_object($callable[0]) )
{
// $callable is an object and a method name
$call = "\$callable[0]->{$callable[1]}";
}
else
{
// $callable is a class name and a static method
$call = "{$callable[0]}::{$callable[1]}";
}
}
// Note because the keys in $args might be strings
// we do this in a slightly round about way.
$argumentString = Array();
$argumentKeys = array_keys($args);
foreach($argumentKeys as $argK)
{
$argumentString[] = "\$args[$argumentKeys[$argK]]";
}
$argumentString = implode($argumentString, ', ');
// Note also that eval doesn't return references, so we
// work around it in this way...
eval("\$result =& {$call}({$argumentString});");
return $result;
}
- /**
- * Checks if constant is defined and has positive value
- *
- * @param string $const_name
- * @return bool
- */
- function constOn($const_name)
+ if( !function_exists('constOn') )
{
- return defined($const_name) && constant($const_name);
+ /**
+ * Checks if constant is defined and has positive value
+ *
+ * @param string $const_name
+ * @return bool
+ */
+ function constOn($const_name)
+ {
+ return defined($const_name) && constant($const_name);
+ }
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.15
\ No newline at end of property
+1.16
\ No newline at end of property
Index: trunk/index.php
===================================================================
--- trunk/index.php (revision 3215)
+++ trunk/index.php (revision 3216)
@@ -1,28 +1,29 @@
<?php
$start = getmicrotime();
define('FULL_PATH', realpath(dirname(__FILE__)));
define('APPLICATION_CLASS', 'MyApplication');
include_once(FULL_PATH.'/kernel/kernel4/startup.php');
$application =& kApplication::Instance();
$application->Init();
$application->Run();
$application->Done();
$end = getmicrotime();
-if (defined('DEBUG_MODE')&&DEBUG_MODE) {
+if ( $application->isDebugMode() )
+{
echo '<br><br><div style="font-family: arial,verdana; font-size: 8pt;">Memory used: '.round(memory_get_usage()/1024/1024, 1).' Mb <br>';
echo 'Time used: '.round(($end - $start), 5).' Sec <br></div>';
}
//print_pre(get_included_files());
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
\ No newline at end of file
Property changes on: trunk/index.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.15
\ No newline at end of property
+1.16
\ No newline at end of property
Index: trunk/tools/debug_sample.php
===================================================================
--- trunk/tools/debug_sample.php (revision 3215)
+++ trunk/tools/debug_sample.php (revision 3216)
@@ -1,39 +1,39 @@
<?php
define('DEBUG_MODE',1);
- if( defined('DEBUG_MODE')&&DEBUG_MODE ) InitDebugger();
+ if( defined('DEBUG_MODE') && DEBUG_MODE ) InitDebugger();
function InitDebugger()
{
define('WINDOWS_ROOT', 'w:');
//define('DBG_RAISE_ON_WARNINGS',1);
define('DBG_SQL_PROFILE',1); // profile SQL queries
define('DBG_SQL_FAILURE',1); // assume sql errors as php fatal errors, warning otherwise
// for ADODB
define('ADODB_OUTP', 'dbg_SQLLog');
function dbg_SQLLog($msg,$new_line=false)
{
}
function isSkipTable($sql)
{
static $skipTables = Array( 'Modules','Language','PermissionConfig','PermCache',
'SessionData','ConfigurationValues','Events','Phrase',
'PersistantSessionData','EmailQueue','UserSession',
'Permissions','ThemeFiles');
foreach($skipTables as $table) if( tableMatch($table,$sql) ) return true;
return false;
}
function tableMatch($table_name,$sql)
{
static $prefix = '';
$prefix = defined('TABLE_PREFIX')?TABLE_PREFIX:GetTablePrefix();
return strpos($sql,$prefix.$table_name)!==false;
}
}
?>
\ No newline at end of file
Property changes on: trunk/tools/debug_sample.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/globals.php
===================================================================
--- trunk/globals.php (revision 3215)
+++ trunk/globals.php (revision 3216)
@@ -1,2036 +1,2052 @@
<?php
if (!function_exists('parse_portal_ini')) {
function parse_portal_ini($file, $parse_section = false) {
if (!file_exists($file)) return;
if(file_exists($file) && !is_readable($file))
die('Could Not Open Ini File');
$contents = file($file);
$retval = array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if ($resave) {
$fp = fopen($file, "w");
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
}
$vars = parse_portal_ini(FULL_PATH.'/config.php');
while($key = key($vars))
{
$key = "g_".$key;
global $$key;
$$key = current($vars); //variable variables
next($vars);
}
/*list the tables which contain item data */
$ItemTables = array();
$KeywordIgnore = array();
global $debuglevel;
$debuglevel = 0;
//$GLOBALS['debuglevel'] = 0;
/*New, Hot, Pop field values */
define('NEVER', 0);
define('ALWAYS', 1);
define('AUTO', 2);
/*Status Values */
if( !defined('STATUS_DISABLED') ) define('STATUS_DISABLED', 0);
if( !defined('STATUS_ACTIVE') ) define('STATUS_ACTIVE', 1);
if( !defined('STATUS_PENDING') ) define('STATUS_PENDING', 2);
$LogLevel = 0;
$LogFile = NULL;
/**
* @return object
* @desc Returns reference to database connection
*/
function &GetADODBConnection()
{
static $DB = null;
global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;
if( !isset($DB) && strlen($g_DBType) > 0 )
{
$DB = ADONewConnection($g_DBType);
$connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
if(!$connected) die("Error connecting to database $g_DBHost <br>\n");
$ADODB_CACHE_DIR = $pathtoroot."cache";
$ADODB_FETCH_MODE = 2;
$ADODB_COUNTRECS = false;
$DB->debug = defined('ADODB_OUTP') ? 1 : 0;
$DB->cacheSecs = 3600;
$DB->Execute('SET SQL_BIG_SELECTS = 1');
}
elseif( !strlen($g_DBType) )
{
global $rootURL;
echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
echo 'Please use the installation script to fix the problem.<br><br>';
if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/';
echo '<a href="'.$rootURL.$ins.'install.php">Go to installation script</a><br><br>';
flush();
exit;
}
return $DB;
}
function GetNextResourceId($Increment=1)
{
global $objModules, $pathtoroot;
$table_name = GetTablePrefix().'IdGenerator';
$db = &GetADODBConnection();
// dummy protection: get maximal resource id used actually and fix last_id used
$max_resourceid = 0;
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot. $value."admin/include/parser.php";
if(file_exists($path))
{
include_once($path);
}
}
$table_info = $objModules->ExecuteFunction('GetModuleInfo', 'dupe_resourceids');
$sql_template = 'SELECT MAX(ResourceId) FROM '.GetTablePrefix().'%s';
foreach($table_info as $module_name => $module_info)
{
foreach($module_info as $module_sub_info)
{
$sql = sprintf($sql_template,$module_sub_info['Table']);
$tmp_resourceid = $db->GetOne($sql);
if($tmp_resourceid > $max_resourceid) $max_resourceid = $tmp_resourceid;
}
}
// update lastid to be next resourceid available
$db->Execute('LOCK TABLES '.$table_name.' WRITE');
$last_id = $db->GetOne('SELECT lastid FROM '.$table_name);
if ($last_id - 1 > $max_resourceid) $max_resourceid = $last_id - 1;
$id_diff = $db->GetOne('SELECT '.$max_resourceid.' + 1 - lastid FROM '.$table_name);
if($id_diff) $Increment += $id_diff;
$sql = 'UPDATE '.$table_name.' SET lastid = lastid + '.$Increment; // set new id in db
$db->Execute($sql);
$val = $db->GetOne('SELECT lastid FROM '.$table_name);
if($val === false)
{
$db->Execute('INSERT INTO '.$table_name.' (lastid) VALUES ('.$Increment.')');
$val = $Increment;
}
$db->Execute('UNLOCK TABLES');
return $val - $Increment + $id_diff; // return previous free id (-1) ?
}
function AddSlash($s)
{
if(substr($s,-1) != "/")
{
return $s."/";
}
else
return $s;
}
function StripNewline($s)
{
$bfound = false;
while (strlen($s)>0 && !$bfound)
{
if(ord(substr($s,-1))<32)
{
$s = substr($s,0,-1);
}
else
$bfound = true;
}
return $s;
}
function DeleteElement($array, $indice)
{
for($i=$indice;$i<count($array)-1;$i++)
$array[$i] = $array[$i+1];
unset($array[count($array)-1]);
return $array;
}
function DeleteElementValue($needle, &$haystack)
{
while(($gotcha = array_search($needle,$haystack)) > -1)
unset($haystack[$gotcha]);
}
function TableCount($TableName, $where="",$JoinCats=1)
{
$db = &GetADODBConnection();
if(!$JoinCats)
{
$sql = "SELECT count(*) as TableCount FROM $TableName";
}
else
$sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
if(strlen($where)>0)
$sql .= " WHERE ".$where;
$rs = $db->Execute($sql);
// echo "SQL TABLE COUNT: ".$sql."<br>\n";
$res = $rs->fields["TableCount"];
return $res;
}
Function QueryCount($sql)
{
$sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql);
$sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql);
$sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql);
//echo $sql;
$db =& GetADODBConnection();
return $db->GetOne($sql);
}
function GetPageCount($ItemsPerPage,$NumItems)
{
if($ItemsPerPage==0 || $NumItems==0)
{
return 1;
}
$value = $NumItems/$ItemsPerPage;
return ceil($value);
}
/**
* @return string
* @desc Returns database table prefix entered while installation
*/
function GetTablePrefix()
{
global $g_TablePrefix;
return $g_TablePrefix;
}
function TableHasPrefix($t)
{
$pre = GetTablePrefix();
if(strlen($pre)>0)
{
if(substr($t,0,strlen($pre))==$pre)
{
return TRUE;
}
else
return FALSE;
}
else
return TRUE;
}
function AddTablePrefix($t)
{
if(!TableHasPrefix($t))
$t = GetTablePrefix().$t;
return $t;
}
function ThisDomain()
{
global $objConfig, $g_Domain;
if($objConfig->Get("DomainDetect"))
{
$d = $_SERVER['HTTP_HOST'];
}
else
$d = $g_Domain;
return $d;
}
function GetIndexUrl($secure=0)
{
global $indexURL, $rootURL, $secureURL;
if ( class_exists('kApplication') )
{
$application =& kApplication::Instance();
return $application->BaseURL().'index.php';
}
switch($secure)
{
case 0:
$ret = $indexURL;
break;
case 1:
$ret = $secureURL."index.php";
break;
case 2:
$ret = $rootURL."index.php";
break;
default:
$ret = $i;
break;
}
return $ret;
}
function GetLimitSQL($Page,$PerPage)
{
if($Page<1)
$Page=1;
if(is_numeric($PerPage))
{
if($PerPage==0)
$PerPage = 20;
$Start = ($Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function filelist ($currentdir, $startdir=NULL,$ext=NULL)
{
global $pathchar;
//chdir ($currentdir);
// remember where we started from
if (!$startdir)
{
$startdir = $currentdir;
}
$d = @opendir($currentdir);
$files = array();
if(!$d)
return $files;
//list the files in the dir
while (false !== ($file = readdir($d)))
{
if ($file != ".." && $file != ".")
{
if (is_dir($currentdir."/".$file))
{
// If $file is a directory take a look inside
$a = filelist ($currentdir."/".$file, $startdir,$ext);
if(is_array($a))
$files = array_merge($files,$a);
}
else
{
if($ext!=NULL)
{
$extstr = stristr($file,".".$ext);
if(strlen($extstr))
$files[] = $currentdir."/".$file;
}
else
$files[] = $currentdir.'/'.$file;
}
}
}
closedir ($d);
return $files;
}
function DecimalToBin($dec,$WordLength=8)
{
$bits = array();
$str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
for($i=$WordLength;$i>0;$i--)
{
$bits[$i-1] = (int)substr($str,$i-1,1);
}
return $bits;
}
/*
function inp_escape($in, $html_enable=0)
{
$out = stripslashes($in);
$out = str_replace("\n", "\n^br^", $out);
if($html_enable==0)
{
$out=ereg_replace("<","&lt;",$out);
$out=ereg_replace(">","&gt;",$out);
$out=ereg_replace("\"","&quot;",$out);
$out = str_replace("\n^br^", "\n<br />", $out);
}
else
$out = str_replace("\n^br^", "\n", $out);
$out=addslashes($out);
return $out;
}
*/
function inp_escape($var,$html=0)
{
if($html)return $var;
if(is_array($var))
foreach($var as $k=>$v)
$var[$k]=inp_escape($v);
else
// $var=htmlspecialchars($var,ENT_NOQUOTES);
$var=strtr($var,Array('<'=>'&lt;','>'=>'&gt;',));
return $var;
}
function inp_striptags($var,$html=0)
{
if($html)return $var;
if(is_array($var))
foreach($var as $k=>$v)
$var[$k]=inp_striptags($v);
else
$var=strip_tags($var);
return $var;
}
function inp_unescape($in)
{
// if (get_magic_quotes_gpc())
return $in;
$out=stripslashes($in);
return $out;
}
function inp_textarea_unescape($in)
{
// if (get_magic_quotes_gpc())
return $in;
$out=stripslashes($in);
$out = str_replace("\n<br />", "\n", $out);
return $out;
}
function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($Keywords as $k) {
for ($i = 0; $i < count($r); $i++) {
if ($r[$i] == "<") {
$i++; continue;
}
$r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
}
}
return join("", $r);
}
/*
function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$ret = strip_tags($html);
foreach ($Keywords as $k)
{
if(strlen($k))
{
//$html = str_replace("<$k>", ":#:", $html);
//$html = str_replace("</$k>", ":##:", $html);
//$html = strip_tags($html);
if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
//if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
$ret = $html;
//$ret = str_replace(":#:", "<$k>", $ret);
//$ret = str_replace(":##:", "</$k>", $ret);
}
}
return $ret;
}
*/
function ExtractDatePart($part,$datestamp)
{
switch($part)
{
case "month":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("m",$datestamp);
break;
case "day":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("d", $datestamp);
break;
case "year":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("Y", $datestamp);
break;
case "time_24hr":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("H:i", $datestamp);
break;
case "time_12hr":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("g:i a",$datestamp);
break;
default:
$ret = adodb_date($part, $datestamp);
break;
}
return $ret;
}
function GetLocalTime($TimeStamp,$TargetZone=NULL)
{
if($TargetZone==NULL)
$TargetZone = $objConfig->Get("Config_Site_Time");
$server = $objConfig->Get("Config_Server_Time");
if($TargetZone!=$server)
{
$offset = ($server - $TargetZone) * -1;
$TimeStamp = $TimeStamp + (3600 * $offset);
}
return $TimeStamp;
}
function _unhtmlentities ($string)
{
$trans_tbl = get_html_translation_table (HTML_ENTITIES);
$trans_tbl = array_flip ($trans_tbl);
return strtr ($string, $trans_tbl);
}
function getLastStr($hay, $need){
$getLastStr = 0;
$pos = strpos($hay, $need);
if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
while($pos) {
$getLastStr = $getLastStr + $pos + strlen($need);
$hay = substr ($hay , $pos + strlen($need));
$pos = strpos($hay, $need);
}
return $getLastStr - strlen($need);
} else {
return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
}
}
// --- bbcode processing function: begin ----
function PreformatBBCodes($text)
{
// convert phpbb url bbcode to valid in-bulletin's format
// 1. urls
$text = preg_replace('/\[url=(.*)\](.*)\[\/url\]/Ui','[url href="$1"]$2[/url]',$text);
$text = preg_replace('/\[url\](.*)\[\/url\]/Ui','[url href="$1"]$1[/url]',$text);
// 2. images
$text = preg_replace('/\[img\](.*)\[\/img\]/Ui','[img src="$1" border="0"][/img]',$text);
// 3. color
$text = preg_replace('/\[color=(.*)\](.*)\[\/color\]/Ui','[font color="$1"]$2[/font]',$text);
// 4. size
$text = preg_replace('/\[size=(.*)\](.*)\[\/size\]/Ui','[font size="$1"]$2[/font]',$text);
// 5. lists
$text = preg_replace('/\[list(.*)\](.*)\[\/list\]/Uis','[ul]$2[/ul]',$text);
// 6. email to link
$text = preg_replace('/\[email\](.*)\[\/email\]/Ui','[url href="mailto:$1"]$1[/url]',$text);
//7. b tag
$text = preg_replace('/\[(b|i|u):(.*)\](.*)\[\/(b|i|u):(.*)\]/Ui','[$1]$3[/$4]',$text);
//8. code tag
$text = preg_replace('/\[code:(.*)\](.*)\[\/code:(.*)\]/Uis','[code]$2[/code]',$text);
return $text;
}
/**
* @return string
* @param string $BBCode
* @param string $TagParams
* @param string $TextInside
* @param string $ParamsAllowed
* @desc Removes not allowed params from tag and returns result
*/
function CheckBBCodeAttribs($BBCode, $TagParams, $TextInside, $ParamsAllowed)
{
// $BBCode - bbcode to check, $TagParams - params string entered by user
// $TextInside - text between opening and closing bbcode tag
// $ParamsAllowed - list of allowed parameter names ("|" separated)
$TagParams=str_replace('\"','"',$TagParams);
$TextInside=str_replace('\"','"',$TextInside);
if( $ParamsAllowed && preg_match_all('/ +([^=]*)=["\']?([^ "\']*)["\']?/is',$TagParams,$params,PREG_SET_ORDER) )
{
$ret = Array();
foreach($params as $param)
{
// remove spaces in both parameter name & value & lowercase parameter name
$param[1] = strtolower(trim($param[1])); // name lowercased
if(($BBCode=='url')&&($param[1]=='href'))
if(false!==strpos(strtolower($param[2]),'script:'))
return $TextInside;
// $param[2]='about:blank';
if( isset($ParamsAllowed[ $param[1] ]) )
$ret[] = $param[1].'="'.$param[2].'"';
}
$ret = count($ret) ? ' '.implode(' ',$ret) : '';
return '<'.$BBCode.$ret.'>'.$TextInside.'</'.$BBCode.'>';
}
else
return '<'.$BBCode.'>'.$TextInside.'</'.$BBCode.'>';
return false;
}
function ReplaceBBCode($text)
{
global $objConfig;
// convert phpbb bbcodes to in-bulletin bbcodes
$text = PreformatBBCodes($text);
// $tag_defs = 'b:;i:;u:;ul:type|align;font:color|face|size;url:href;img:src|border';
$tags_defs = $objConfig->Get('BBTags');
foreach(explode(';',$tags_defs) as $tag)
{
$tag = explode(':',$tag);
$tag_name = $tag[0];
$tag_params = $tag[1]?array_flip(explode('|',$tag[1])):0;
$text = preg_replace('/\['.$tag_name.'(.*)\](.*)\[\/'.$tag_name.' *\]/Uise','CheckBBCodeAttribs("'.$tag_name.'",\'$1\',\'$2\',$tag_params);', $text);
}
// additional processing for [url], [*], [img] bbcode
$text = preg_replace('/<url>(.*)<\/url>/Usi','<url href="$1">$1</url>',$text);
$text = preg_replace('/<font>(.*)<\/font>/Usi','$1',$text); // skip empty fonts
$text = str_replace( Array('<url','</url>','[*]'),
Array('<a target="_blank"','</a>','<li>'),
$text);
// bbcode [code]xxx[/code] processing
$text = preg_replace('/\[code\](.*)\[\/code\]/Uise', "ReplaceCodeBBCode('$1')", $text);
return $text;
}
function leadSpace2nbsp($x)
{
return "\n".str_repeat('&nbsp;',strlen($x));
}
function ReplaceCodeBBCode($input_string)
{
$input_string=str_replace('\"','"',$input_string);
$input_string=$GLOBALS['objSmileys']->UndoSmileys(_unhtmlentities($input_string));
$input_string=trim($input_string);
$input_string=inp_htmlize($input_string);
$input_string=str_replace("\r",'',$input_string);
$input_string = str_replace("\t", " ", $input_string);
$input_string = preg_replace('/\n( +)/se',"leadSpace2nbsp('$1')",$input_string);
$input_string='<div style="border:1px solid #888888;width:100%;background-color:#eeeeee;margin-top:6px;margin-bottom:6px"><div style="padding:10px;"><code>'.$input_string.'</code></div></div>';
// $input_string='<textarea wrap="off" style="border:1px solid #888888;width:100%;height:200px;background-color:#eeeeee;">'.inp_htmlize($input_string).'</textarea>';
return $input_string;
if(false!==strpos($input_string,'<'.'?'))
{
$input_string=str_replace('<'.'?','<'.'?php',$input_string);
$input_string=str_replace('<'.'?phpphp','<'.'?php',$input_string);
$input_string=@highlight_string($input_string,1);
}
else
{
$input_string = @highlight_string('<'.'?php'.$input_string.'?'.'>',1);
$input_string = str_replace('&lt;?php', '', str_replace('?&gt;', '', $input_string));
}
return str_replace('<br />','',$input_string);
}
// --- bbcode processing function: end ----
function GetMinValue($Table,$Field, $Where=NULL)
{
$ret = 0;
$sql = "SELECT min($Field) as val FROM $Table ";
if(strlen($where))
$sql .= "WHERE $Where";
$ado = &GetADODBConnection();
$rs = $ado->execute($sql);
if($rs)
$ret = (int)$rs->fields["val"];
return $ret;
}
if (!function_exists( 'getmicrotime' ) ) {
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
function SetMissingDataErrors($f)
{
global $FormError;
$count = 0;
if(is_array($_POST))
{
if(is_array($_POST["required"]))
{
foreach($_POST["required"] as $r)
{
$found = FALSE;
if(is_array($_FILES))
{
if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
}
if(!strlen(trim($_POST[$r])) && !$found)
{
$count++;
if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
$r = "dob";
$tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
if(!strlen($tag))
$tag = "lu_ferror_".$f."_".$r;
$FormError[$f][$r] = language($tag);
}
}
}
}
return $count;
}
function makepassword($length=10)
{
$pass_length=$length;
$p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2=array('a','e','i','o','u');
$p3=array('1','2','3','4','5','6','7','8','9');
$p4=array('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1=21;// this is the count of $p1
$s2=5; // this is the count of $p2
$s3=9; // this is the count of $p3
$s4=5; // this is the count of $p4
// possible readable combinations
$c1='121'; // will be like 'bab'
$c2='212'; // will be like 'aba'
$c3='12'; // will be like 'ab'
$c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3
// $c5='4'; // uncomment to active the strong stuff
$comb='4'; // the amount of combinations you made above (and did not comment out)
for ($p=0;$p<$pass_length;)
{
mt_srand((double)microtime()*1000000);
$strpart=mt_rand(1,$comb);
// checking if the stringpart is not the same as the previous one
if($strpart<>$previous)
{
$pass_structure.=${'c'.$strpart};
// shortcutting the loop a bit
$p=$p+strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g=0;$g<strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
$sel=substr($pass_structure,$g,1);
$pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
}
return $pass;
}
function LogEntry($text,$writefile=FALSE)
{
global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
static $last;
if(strlen($g_LogFile))
{
$el = str_pad(getmicrotime()- $timestart,10," ");
if($last>0)
$elapsed = getmicrotime() - $last;
if(strlen($el)>10)
$el = substr($el,0,10);
$indent = str_repeat(" ",$LogLevel);
$text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
$LogData .= "$el:". round($elapsed,6).":$indent $text";
$last = getmicrotime();
if($writefile==TRUE && is_writable($g_LogFile))
{
if(!$LogFile)
{
if(file_exists($g_LogFile))
unlink($g_LogFile);
$LogFile=@fopen($g_LogFile,"w");
}
if($LogFile)
{
fputs($LogFile,$LogData);
}
}
}
}
function ValidEmail($email)
{
if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
{
return TRUE;
}
else
{
return FALSE;
}
}
function language($phrase,$LangId=0)
{
global $objSession, $objLanguageCache, $objLanguages;
if($LangId==0)
$LangId = $objSession->Get("Language");
if($LangId==0)
$LangId = $objLanguages->GetPrimary();
$translation = $objLanguageCache->GetTranslation($phrase,$LangId);
return $translation;
}
function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
{
global $objSession, $objLanguageCache, $objLanguages;
//echo "Language passed: $lang<br>";
if($lang==0)
$lang = $objSession->Get("Language");
//echo "Language from session: $lang<br>";
if($lang==0)
$lang = $objLanguages->GetPrimary();
//echo "Language after primary: $lang<br>";
//echo "Phrase: $phrase<br>";
$translation = $objLanguageCache->GetTranslation($phrase,$lang);
if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
{
$res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
return $res;
}
else
return $translation;
}
function prompt_language($phrase,$lang=0)
{
return admin_language($phrase,$lang,TRUE);
}
function GetPrimaryTranslation($Phrase)
{
global $objLanguages;
$l = $objLanguages->GetPrimary();
return language($Phrase,$l);
}
function CategoryNameCount($ParentId,$Name)
{
$cat_table = GetTablePrefix()."Category";
$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
$ado = &GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["Name"];
$rs->MoveNext();
}
return $ret;
}
function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
{
$Name=addslashes($Name);
$cat_table = GetTablePrefix()."CategoryItems";
$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
//echo $sql."<br>\n ";
$ado = &GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields[$Field];
$rs->MoveNext();
}
return $ret;
}
function &GetItemCollection($ItemName)
{
global $objItemTypes;
if(is_numeric($ItemName))
{
$item = $objItemTypes->GetItem($ItemName);
}
else
$item = $objItemTypes->GetTypeByName($ItemName);
if(is_object($item))
{
$module = $item->Get("Module");
$prefix = ModuleTagPrefix($module);
$func = $prefix."_ItemCollection";
if(function_exists($func))
{
$var =& $func();
}
}
return $var;
}
function UpdateCategoryCount($item_type,$CategoriesIds,$ListType='')
{
global $objCountCache, $objItemTypes;
$db=&GetADODBConnection();
if( !is_numeric($item_type) )
{
$sql = 'SELECT ItemType FROM '.$objItemTypes->SourceTable.' WHERE ItemName=\''.$item_type.'\'';
$item_type=$db->GetOne($sql);
}
$objCountCache->EraseGlobalTypeCache($item_type);
if($item_type)
{
if(is_array($CategoriesIds))
{
$CategoriesIds=implode(',',$CategoriesIds);
}
if (!$CategoriesIds)
{
}
if(!is_array($ListType)) $ListType=Array($ListType=>'opa');
$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId IN ('.$CategoriesIds.')';
$rs = $db->Execute($sql);
$parents = Array();
while (!$rs->EOF)
{
$tmp=$rs->fields['ParentPath'];
$tmp=substr($tmp,1,strlen($tmp)-2);
$tmp=explode('|',$tmp);
foreach ($tmp as $tmp_cat_id) {
$parents[$tmp_cat_id]=1;
}
$rs->MoveNext();
}
$parents=array_keys($parents);
$list_types=array_keys($ListType);
foreach($parents as $ParentCategoryId)
{
foreach ($list_types as $list_type) {
$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 0); // total count
$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 1); // total count today
}
}
}
else
{
die('wrong item type passed to "UpdateCategoryCount"');
}
/* if(is_object($item))
{
$ItemType = $item->Get("ItemType");
$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
$objCountCache->adodbConnection->Execute($sql);
} */
}
function ResetCache($CategoryId)
{
global $objCountCache;
$db =& GetADODBConnection();
$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
$parents = $db->GetOne($sql);
$parents = substr($parents,1,strlen($parents)-2);
$parents = explode('|',$parents);
foreach($parents as $ParentCategoryId)
{
$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 0); // total topic count
$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 1); // total
}
}
function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
{
}
function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
{
}
function GetTagCache($module,$tag,$attribs,$env)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache") && !$objSession->Get('PortalUserId'))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $n => $val)
{
$name .= "-".$val;
}
}
$CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
}
else
$CachedValue="";
return $CachedValue;
}
function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $a => $val)
{
$name .= "-".$val;
}
}
$objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
}
}
function DeleteTagCache($name,$extraparams, $env="")
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = "Name LIKE '$name%".$extraparams."'";
if(strlen($env))
$where .= " AND Context LIKE $env";
$objSystemCache->DeleteCachedItem($where);
}
}
/**
* Deletes whole tag cache for
* selected module
*
* @param string $module
* @param string $name
* @access public
*/
function DeleteModuleTagCache($module, $tagname='')
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = 'Module LIKE \''.$module.'\'';
if(strlen($tagname))
{
$where .= ' AND Name LIKE \''.$tagname.'\'';
}
$objSystemCache->DeleteCachedItem($where);
}
}
/*function ClearTagCache()
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = '';
$objSystemCache->DeleteCachedItem($where);
}
}*/
/*function EraseCountCache()
{
// global $objSystemCache, $objConfig;
$db =& GetADODBConnection();
$sql = 'DELETE * FROM '.GetTablePrefix().'CountCache';
return $db->Execute($sql) ? true : false;
}*/
function ParseTagLibrary()
{
$objTagList = new clsTagList();
$objTagList->ParseInportalTags();
unset($objTagList);
}
function GetDateFormat($LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$fmt = $l->Get("DateFormat");
}
else
$fmt = "m-d-Y";
if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd'])
return $fmt;
return preg_replace('/y+/i','Y',$fmt);
}
function GetTimeFormat($LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$fmt = $l->Get("TimeFormat");
}
else
$fmt = "H:i:s";
return $fmt;
}
/**
* Gets one of currently selected language options
*
* @param string $optionName
* @param int $LangId
* @return string
* @access public
*/
function GetRegionalOption($optionName,$LangId=0)
{
global $objLanguages, $objSession;
if(!$LangId) $LangId=$objSession->Get('Language');
if(!$LangId) $LangId=$objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
return is_object($l)?$l->Get($optionName):false;
}
function LangDate($TimeStamp=NULL,$LangId=0)
{
$fmt = GetDateFormat($LangId);
$ret = adodb_date($fmt,$TimeStamp);
return $ret;
}
function LangTime($TimeStamp=NULL,$LangId=0)
{
$fmt = GetTimeFormat($LangId);
$ret = adodb_date($fmt,$TimeStamp);
return $ret;
}
function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
}
else
$ret = $num;
return $ret;
}
function replacePngTags($x, $spacer="images/spacer.gif")
{
global $rootURL,$pathtoroot;
// make sure that we are only replacing for the Windows versions of Internet
// Explorer 5+, and not Opera identified as MSIE
$msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
$opera='/opera\s+[0-9]+/i';
if(!isset($_SERVER['HTTP_USER_AGENT']) ||
!preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
return $x;
// find all the png images in backgrounds
preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
for($i=0;$i<count($background[0]);$i++){
// simply replace:
// "background-image: url('image.png');"
// with:
// "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
// enabled=true, sizingMethod=scale src='image.png');"
// haven't tested to see if background-repeat styles work...
$x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
' src=\''.$background[1][$i].'\');',$x);
}
// OK, time to find all the IMG tags with ".png" in them
preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
while(list($imgnum,$v)=@each($images[0])){
$original=$v;
$atts=''; $width=0; $height=0;
// If the size is defined by styles, find
preg_match_all('/style=".*(width: ([0-9]+))px.*'.
'(height: ([0-9]+))px.*"/Ui',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
// size was defined by styles, get values
$width=$arr2[2][0];
$height=$arr2[4][0];
}
// size was not defined by styles, get values
preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$width=$arr2[1][0];
}
preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$height=$arr2[1][0];
}
preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
if(isset($arr2[1][0]) && !empty($arr2[1][0]))
$image=$arr2[1][0];
else
$image=NULL;
// We do this so that we can put our spacer.gif image in the same
// directory as the image
$tmp=split('[\\/]',$image);
array_pop($tmp);
$image_path=join('/',$tmp);
if(substr($image,0,strlen($rootURL))==$rootURL)
{
$path = str_replace($rootURL,$pathtoroot,$image);
}
else
{
$path = $pathtoroot."themes/telestial/$image";
}
// echo "Sizing $path.. <br>\n";
// echo "Full Tag: ".htmlentities($image)."<br>\n";
//if(!$height || !$width)
//{
$g = imagecreatefrompng($path);
if($g)
{
$height = imagesy($g);
$width = imagesx($g);
}
//}
if(strlen($image_path)) $image_path.='/';
// end quote is already supplied by originial src attribute
$replace_src_with=$spacer.'" style="width: '.$width.
'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
'\'scale\')';
// now create the new tag from the old
$new_tag=str_replace($image,$replace_src_with,$original);
// now place the new tag into the content
$x=str_replace($original,$new_tag,$x);
}
return $x;
}
if (!function_exists('print_pre')) {
function print_pre($str)
{
// no comments here :)
echo '<pre>'.print_r($str, true).'</pre>';
}
}
function GetOptions($field) // by Alex
{
// get dropdown values from custom field
$tmp =& new clsCustomField();
$tmp->LoadFromDatabase($field, 'FieldName');
$tmp_values = $tmp->Get('ValueList');
unset($tmp);
$tmp_values = explode(',', $tmp_values);
foreach($tmp_values as $mixed)
{
$elem = explode('=', trim($mixed));
$ret[ $elem[0] ] = $elem[1];
}
return $ret;
}
function ResetPage($module_prefix, $page_variable = 'p')
{
// resets page in specific module when category is changed
global $objSession;
if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
{
global $var_list, $SessionQueryString, $FrontEnd;
$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
}
$last_cat = $objSession->GetVariable('last_category');
$prev_cat = $objSession->GetVariable('prev_category');
//echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
}
if( !function_exists('GetVar') )
{
/**
* @return string
* @param string $name
* @param bool $post_priority
* @desc Get's variable from http query
*/
function GetVar($name, $post_priority = false)
{
if(!$post_priority) // follow gpc_order in php.ini
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
else // get variable from post 1stly if not found then from get
return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
}
}
function SetVar($VarName, $VarValue)
{
$_REQUEST[$VarName] = $VarValue;
$_POST[$VarName] = $VarValue;
$_GET[$VarName] = $VarValue;
}
function PassVar(&$source)
{
// source array + any count of key names in passed array
$params = func_get_args();
array_shift($params);
if( count($params) )
{
$ret = Array();
foreach($params as $var_name)
if( isset($source[$var_name]) )
$ret[] = $var_name.'='.$source[$var_name];
$ret = '&'.implode('&', $ret);
}
return $ret;
}
function GetSubmitVariable(&$array, $postfix)
{
// gets edit status of module
// used in case if some modules share
// common action parsed by kernel parser,
// but each module uses own EditStatus variable
$modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic', 'In-Portal'=>'Review');
foreach($modules as $module => $prefix)
if( isset($array[$prefix.$postfix]) )
return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
return false;
}
function GetModuleByAction()
{
$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
$action = GetVar('Action');
if($action)
{
$module_prefix = explode('_', $action);
return $prefix2module[ $module_prefix[0] ];
}
else
return false;
}
function dir_size($dir) {
// calculates folder size based on filesizes inside it (recursively)
$totalsize=0;
if ($dirstream = @opendir($dir)) {
while (false !== ($filename = readdir($dirstream))) {
if ($filename!="." && $filename!="..")
{
if (is_file($dir."/".$filename))
$totalsize+=filesize($dir."/".$filename);
if (is_dir($dir."/".$filename))
$totalsize+=dir_size($dir."/".$filename);
}
}
}
closedir($dirstream);
return $totalsize;
}
function size($bytes) {
// shows formatted file/directory size
$types = Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
$current = 0;
while ($bytes > 1024) {
$current++;
$bytes /= 1024;
}
return round($bytes,2)." ".language($types[$current]);
}
function echod($str)
{
// echo debug output
echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';
}
function PrepareParams($source, $to_lower, $mapping)
{
// prepare array with form values to use with item
$result = Array();
foreach($to_lower as $field)
$result[ $field ] = $source[ strtolower($field) ];
if( is_array($mapping) )
{
foreach($mapping as $field_from => $field_to)
$result[$field_to] = $source[$field_from];
}
return $result;
}
function GetELT($field, $phrases = Array())
{
// returns FieldOptions equivalent in In-Portal
$ret = Array();
foreach($phrases as $phrase)
$ret[] = admin_language($phrase);
$ret = "'".implode("','", $ret)."'";
return 'ELT('.$field.','.$ret.')';
}
function GetModuleImgPath($module)
{
global $rootURL, $admin;
return $rootURL.$module.'/'.$admin.'/images';
}
function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
{
// each action postprocessing stuff from admin
if( !isset($_REQUEST[$StatusField]) ) return false;
$list =& $GLOBALS[$ListObjectName];
if( !is_object($list) ) $list = new $ListClass();
$SFValue = $_REQUEST[$StatusField]; // status field value
switch($SFValue)
{
case 1: // User hit "Save" button
$list->CopyFromEditTable($IDField);
break;
case 2: // User hit "Cancel" button
$list->PurgeEditTable($IDField);
break;
}
if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
if($SFValue == 1 || $SFValue == 2) $list->Clear();
}
if( !function_exists('getArrayValue') )
{
/**
* Returns array value if key exists
*
* @param Array $aArray
* @param int $aIndex
* @return string
*/
function getArrayValue(&$aArray, $aIndex)
{
return isset($aArray[$aIndex]) ? $aArray[$aIndex] : false;
}
}
function MakeHTMLTag($element, $attrib_prefix)
{
$result = Array();
$ap_length = strlen($attrib_prefix);
foreach($element->attributes as $attib_name => $attr_value)
if( substr($attib_name, $ap_length) == $ap_length )
$result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
return count($result) ? implode(' ', $result) : false;
}
function GetImportScripts()
{
// return currently installed import scripts
static $import_scripts = Array();
if( count($import_scripts) == 0 )
{
$sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id';
$db =&GetADODBConnection();
$rs = $db->Execute($sql);
if( $rs && $rs->RecordCount() > 0 )
{
while(!$rs->EOF)
{
$rec =& $rs->fields;
$import_scripts[] = Array( 'label' => $rec['is_label'], 'url' => $rec['is_script'],
'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
'module' => strtolower($rec['is_Module']) );
$rs->MoveNext();
}
}
else
{
$import_scripts = Array();
}
}
return $import_scripts;
}
function GetImportScript($id)
{
$scripts = GetImportScripts();
return isset($scripts[$id]) ? $scripts[$id] : false;
}
function GetNextTemplate($current_template)
{
// used on front, returns next template to make
// redirect to
$dest = GetVar('dest', true);
if(!$dest) $dest = GetVar('DestTemplate', true);
return $dest ? $dest : $current_template;
}
// functions for dealign with enviroment variable construction
function GenerateModuleEnv($prefix, $var_list)
{
// globalize module varible arrays
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
// if update var count is zero, then do nothing
if( !is_array($update) || count($update) == 0 ) return '';
// ensure that we have no empty values in enviroment variable
foreach($update as $vl_key => $vl_value) {
if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
}
foreach($main as $vl_key => $vl_value) {
if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
}
$ret = Array();
foreach($var_list as $var_name) {
$value = GetEnvVar($prefix, $var_name);
if(!$value && $var_name == 'id') $value = '0';
$ret[] = $value;
}
// Removing all var_list_udpate
$keys = array_keys($update);
foreach ($keys as $key) {
unset($update[$key]);
}
return ':'.$prefix.implode('-',$ret);
}
// functions for dealign with enviroment variable construction
function GenerateModuleEnv_NEW($prefix, $var_list)
{
// globalize module varible arrays
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
if ( isset($update) && $update )
{
// ensure that we have no empty values in enviroment variable
foreach($update as $vl_key => $vl_value) {
if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
}
$app =& kApplication::Instance();
$passed = $app->GetVar('prefixes_passed');
$passed[] = $prefix;
$app->SetVar('prefixes_passed', $passed);
}
else
{
return Array();
}
foreach($main as $vl_key => $vl_value) {
if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
}
$ret = Array();
foreach($var_list as $src_name => $dst_name) {
$ret[$dst_name] = GetEnvVar($prefix, $src_name);
}
// Removing all var_list_udpate
if ( isset($update) && $update )
{
$keys = array_keys($update);
foreach ($keys as $key) unset($update[$key]);
}
return $ret;
}
function GetEnvVar($prefix, $name)
{
// get variable from template variable's list
// (used in module parsers to build env string)
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
}
/**
* Checks if debug mode is active
*
* @return bool
*/
-function IsDebugMode()
+function IsDebugMode($check_debugger = true)
{
- return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0;
+ $debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
+ if($check_debugger) $debug_mode = $debug_mode && isset($GLOBALS['debugger']);
+ return $debug_mode;
}
/**
* Checks if we are in admin
*
* @return bool
*/
function IsAdmin()
{
return defined('ADMIN') && constant('ADMIN') == 1 ? 1 : 0;
}
/**
* Two strings in-case-sensitive compare.
* Returns >0, when string1 > string2,
* <0, when string1 > string2,
* 0, when string1 = string2
*
* @param string $string1
* @param string $string2
* @return int
*/
function stricmp ($string1, $string2) {
return strcmp(strtolower($string1), strtolower($string2));
}
/**
* Generates unique code
*
* @return string
*/
function GenerateCode()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function bracket_comp($elem1, $elem2)
{
if( ($elem1['End']>$elem2['End'] || $elem1['End'] == -1) && $elem2['End'] != -1 )
{
return 1;
}
elseif ( ($elem1['End']<$elem2['End'] || $elem2['End'] == -1) && $elem1['End'] != -1 )
{
return -1;
}
else
{
return 0;
}
}
function bracket_id_sort($first_id, $second_id)
{
$first_abs = abs($first_id);
$second_abs = abs($second_id);
$first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
$second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
if($first_sign != $second_sign)
{
if($first_id > $second_id) {
$bigger =& $first_abs;
$smaller =& $second_abs;
}
else {
$bigger =& $second_abs;
$smaller =& $first_abs;
}
$smaller = $bigger + $smaller;
}
if($first_abs > $second_abs) {
return 1;
}
elseif ($first_abs < $second_abs)
{
return -1;
}
else
{
return 0;
}
}
function pr_bracket_comp($elem1, $elem2)
{
if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']!="" && $elem2['MaxQty']!="") return 1;
if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']=="" && $elem2['MaxQty']=="") return -1;
if ($elem1['MaxQty']=="" && $elem2['MaxQty']!="") return 1;
if ($elem1['MaxQty']!="" && $elem2['MaxQty']=="") return -1;
if( ($elem1['MaxQty']>$elem2['MaxQty'] && $elem2['MaxQty']!=-1) || ($elem1['MaxQty'] == -1 && $elem2['MaxQty'] != -1 ))
{
return 1;
}
elseif ( ($elem1['MaxQty']<$elem2['MaxQty']) || ($elem2['MaxQty'] == -1 && $elem1['MaxQty'] != -1 ))
{
return -1;
}
else
{
return 0;
}
}
function ap_bracket_comp($elem1, $elem2)
{
if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']!="" && $elem2['ToAmount']!="") return 1;
if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']=="" && $elem2['ToAmount']=="") return -1;
if ($elem1['ToAmount']=="" && $elem2['ToAmount']!="") return 1;
if ($elem1['ToAmount']!="" && $elem2['ToAmount']=="") return -1;
if( ($elem1['ToAmount']>$elem2['ToAmount'] && $elem2['ToAmount']!=-1) || ($elem1['ToAmount'] == -1 && $elem2['ToAmount'] != -1 ))
{
return 1;
}
elseif ( ($elem1['ToAmount']<$elem2['ToAmount']) || ($elem2['ToAmount'] == -1 && $elem1['ToAmount'] != -1 ))
{
return -1;
}
else
{
return 0;
}
}
function pr_bracket_id_sort($first_id, $second_id)
{
$first_abs = abs($first_id);
$second_abs = abs($second_id);
$first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
$second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
if($first_sign != $second_sign)
{
if($first_id > $second_id) {
$bigger =& $first_abs;
$smaller =& $second_abs;
}
else {
$bigger =& $second_abs;
$smaller =& $first_abs;
}
$smaller = $bigger + $smaller;
}
if($first_abs > $second_abs) {
return 1;
}
elseif ($first_abs < $second_abs)
{
return -1;
}
else
{
return 0;
}
}
function inp_htmlize($var, $strip = 0)
{
if( is_array($var) )
{
foreach($var as $k => $v) $var[$k] = inp_htmlize($v, $strip);
}
else
{
$var = htmlspecialchars($strip ? stripslashes($var) : $var);
}
return $var;
}
/**
* Sets in-portal cookies, that will not harm K4 to breath free :)
*
* @param string $name
* @param mixed $value
* @param int $expire
* @author Alex
*/
function set_cookie($name, $value, $expire = 0)
{
$cookie_path = IsAdmin() ? rtrim(BASE_PATH, '/').'/admin' : BASE_PATH;
setcookie($name, $value, $expire, $cookie_path, $_SERVER['HTTP_HOST']);
}
/**
* If we are on login required template, but we are not logged in, then logout user
*
* @return bool
*/
function require_login($condition = null, $redirect_params = 'logout=1', $pass_env = false)
{
if( !isset($condition) ) $condition = !admin_login();
if(!$condition) return false;
global $objSession, $adminURL;
if( !headers_sent() ) set_cookie(SESSION_COOKIE_NAME, ' ', time() - 3600);
$objSession->Logout();
if($pass_env) $redirect_params = 'env='.BuildEnv().'&'.$redirect_params;
header('Location: '.$adminURL.'/index.php?'.$redirect_params);
exit;
}
if( !function_exists('safeDefine') )
{
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
function safeDefine($const_name, $const_value)
{
if(!defined($const_name)) define($const_name,$const_value);
}
}
/**
* Builds up K4 url from data supplied by in-portal
*
* @param string $t template
* @param Array $params
* @param string $index_file
* @return string
*/
function HREF_Wrapper($t = '', $params = null, $index_file = null)
{
$url_params = BuildEnv_NEW();
if( isset($params) ) $url_params = array_merge_recursive2($url_params, $params);
if(!$t)
{
$t = $url_params['t'];
unset($url_params['t']);
}
$app =& kApplication::Instance();
return $app->HREF($t, '', $url_params, $index_file);
}
/**
* Set url params based on tag params & mapping hash passed
*
* @param Array $url_params - url params before change
* @param Array $tag_attribs - tag attributes
* @param Array $params_map key - tag_param, value - url_param
*/
function MapTagParams(&$url_params, $tag_attribs, $params_map)
{
foreach ($params_map as $tag_param => $url_param)
{
if( getArrayValue($tag_attribs, $tag_param) ) $url_params[$url_param] = $tag_attribs[$tag_param];
}
}
function ExtractParams($params_str, $separator = '&')
{
if(!$params_str) return Array();
$ret = Array();
$parts = explode($separator, trim($params_str, $separator) );
foreach ($parts as $part)
{
list($var_name, $var_value) = explode('=', $part);
$ret[$var_name] = $var_value;
}
return $ret;
}
+
+ if( !function_exists('constOn') )
+ {
+ /**
+ * Checks if constant is defined and has positive value
+ *
+ * @param string $const_name
+ * @return bool
+ */
+ function constOn($const_name)
+ {
+ return defined($const_name) && constant($const_name);
+ }
+ }
?>
Property changes on: trunk/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.86
\ No newline at end of property
+1.87
\ No newline at end of property

Event Timeline