+
+
+
+
\ No newline at end of file
Index: trunk/kernel/include/adodb/adodb.inc.php
===================================================================
diff -u -r228 -r642
--- trunk/kernel/include/adodb/adodb.inc.php (.../adodb.inc.php) (revision 228)
+++ trunk/kernel/include/adodb/adodb.inc.php (.../adodb.inc.php) (revision 642)
@@ -1,3379 +1,3389 @@
-
- Manual is at http://php.weblogs.com/adodb_manual
-
- */
-
- if (!defined('_ADODB_LAYER')) {
- define('_ADODB_LAYER',1);
-
- //==============================================================================================
- // CONSTANT DEFINITIONS
- //==============================================================================================
-
- define('ADODB_BAD_RS','
Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;
');
-
- 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 = ' ';
- //--
- 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 .= " \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.
- b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
- 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
- // 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) {
- global $HTTP_SERVER_VARS;
-
- $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( "\n($this->databaseType): ".htmlspecialchars($sqlTxt)." $ss\n\n",false);
- else
- ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
- flush();
-
- $this->_queryID = $this->_query($sql,$inputarr,$arg3);
-
- /*
- 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();
- 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( '
Insert_ID error
');
- return false;
- }
-
-
- /**
- * Portable Insert ID. Pablo Roca
- *
- * @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( '
Affected_Rows error
',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 "
Error=".$this->ErrorNo().'
';
- $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
\n", system($cmd),"
");
- } 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 = ''.htmlspecialchars($s).'';
-
- 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"
- */
- 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" 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 = ' '; /// what to display when $time==0
- var $emptyDate = ' '; /// 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
- *
- * @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
- 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( "
ADONewConnection: Unable to load database driver '$db'
",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 \n");
- $ok = false;
- }
-
- return $ok;
- }
-
-
- function adodb_backtrace($print=true)
- {
- $s = '';
- if (PHPVERSION() >= 4.3) {
-
- $MAXSTRLEN = 64;
-
- $s = '
';
- if ($print) print $s;
- }
- return $s;
- }
-
-} // defined
+
+ Manual is at http://php.weblogs.com/adodb_manual
+
+ */
+
+ if (!defined('_ADODB_LAYER')) {
+ define('_ADODB_LAYER',1);
+
+ //==============================================================================================
+ // CONSTANT DEFINITIONS
+ //==============================================================================================
+
+ define('ADODB_BAD_RS','
Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;
');
+
+ 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 = ' ';
+ //--
+ 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 .= " \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.
+ b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
+ 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
+ // 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) {
+ global $HTTP_SERVER_VARS;
+
+ $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( "\n($this->databaseType): ".htmlspecialchars($sqlTxt)." $ss\n\n",false);
+ else
+ ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
+ flush();
+
+ $this->_queryID = $this->_query($sql,$inputarr,$arg3);
+
+ /*
+ 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();
+
+if(defined('SQL_ERROR_DIE')&&SQL_ERROR_DIE)
+{
+ echo '
';
+ exit;
+}
+ 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( '
Insert_ID error
');
+ return false;
+ }
+
+
+ /**
+ * Portable Insert ID. Pablo Roca
+ *
+ * @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( '
Affected_Rows error
',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 "
Error=".$this->ErrorNo().'
';
+ $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
\n", system($cmd),"
");
+ } 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 = ''.htmlspecialchars($s).'';
+
+ 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"
+ */
+ 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" 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 = ' '; /// what to display when $time==0
+ var $emptyDate = ' '; /// 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
+ *
+ * @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
+ 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( "
ADONewConnection: Unable to load database driver '$db'
",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 \n");
+ $ok = false;
+ }
+
+ return $ok;
+ }
+
+
+ function adodb_backtrace($print=true)
+ {
+ $s = '';
+ if (PHPVERSION() >= 4.3) {
+
+ $MAXSTRLEN = 64;
+
+ $s = '
",$innerText);
+ }
+ $tagText = substr($tagText,1,($endopen - $pos)-1);
+ //echo "Matched $tagText \n";
+ $tagText = "<".$tagText.">";
+ $replace_text = $tagText.$innerText."".$tag.">";
+ $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
+ return $text;
+ }
+ else
+ return $text;
+ }
+ else
+ return $text;
+}
+
+function ReplaceTag($tag,$text)
+{
+ $new_text = ReplaceSingleTag($tag,$text);
+
+ while($new_text != $text)
+ {
+ $text = $new_text;
+ $new_text = ReplaceSingleTag($tag,$text);
+ }
+ return $new_text;
+}
+
+function ReplaceURL($text)
+{
+
+ // process url bbtags without href parameter
+ $text = preg_replace('/\[url\]([^\]]*)\[\/url\]/U', '[url href="$1"]$1[/url]', $text);
+
+ // change bbcode to href's
+ while( stristr($text,'[url') )
+ {
+ $urlpos = strpos( strtolower($text), '[url');
+ $endopen = strpos($text,']',$urlpos);
+ if($endopen)
+ {
+ $url = '',''),$text);
+ return $text;
+}
+
+
+function ReplaceBBCode($text)
+{
+ global $objConfig;
+
+ // BBCode: [b], [i], [u], [ul], [font]
+ $tags = explode(",",$objConfig->Get("BBTags"));
+ for($i = 0; $i < count($tags); $i++)
+ {
+ $text = ReplaceTag(strtoupper($tags[$i]),$text);
+ }
+
+ // BBCode: [url href="xxx"]xxx[/url]
+ $text = ReplaceURL($text);
+
+ // BBCode: [code]xxx[/code]
+ $text = preg_replace('/\[code[^\]]*\](.*)\[\/code[^\]]*\]/Ues', 'highlight_string( _unhtmlentities(\'$1\') , true);', $text);
+
+ return $text;
+}
+
+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;
+}
+
+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;$g0)
+ $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 ";
+
+ if($lang==0)
+ $lang = $objSession->Get("Language");
+
+ //echo "Language from session: $lang ";
+
+ if($lang==0)
+ $lang = $objLanguages->GetPrimary();
+
+ //echo "Language after primary: $lang ";
+ //echo "Phrase: $phrase ";
+ $translation = $objLanguageCache->GetTranslation($phrase,$lang);
+ if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
+ {
+ $res = "$translation";
+ 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)
+{
+ $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." \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($ItemTypeName=0,$ListType=NULL)
+{
+ global $objCountCache, $objItemTypes;
+
+ if(is_numeric($ItemTypeName))
+ $item = $objItemTypes->GetItem($ItemTypeName);
+ else
+ $item = $objItemTypes->GetTypeByName($ItemTypeName);
+
+ 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 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"))
+ {
+ $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);
+ }
+}
+
+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;
+}
+
+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|)/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.. \n";
+// echo "Full Tag: ".htmlentities($image)." \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;
+}
+
+function print_pre($str)
+{
+ // no comments here :)
+ echo '
'.print_r($str, true).'
';
+}
+
+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;
+ //if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
+ $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
+ }
+ //echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].') ';
+ $last_cat = $objSession->GetVariable('last_category');
+ $prev_cat = $objSession->GetVariable('prev_category');
+ //echo "Resetting Page [$prev_cat] -> [$last_cat] ";
+
+ 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;
+}
+
+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');
+ 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('[', ']'), $str).' ';
+}
+
+
+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();
+}
+
+function GetElem(&$array, $index)
+{
+ // returns array element by index if
+ // such index exists
+ return isset($array[$index]) ? $array[$index] : 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] ";
+
+ // 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]);
+
+ // if update var count is zero, then do nothing
+ if(count($update) == 0) return '';
+
+ 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)
+ $ret[] = GetEnvVar($prefix, $var_name);
+
+ return ':'.$prefix.implode('-',$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] : '');
+}
+
+/**
+ * @return int
+ * @desc Checks for debug mode
+*/
+function IsDebugMode()
+{
+ return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0;
+}
+
+
+?>
Index: trunk/kernel/parser.php
===================================================================
diff -u -r640 -r642
--- trunk/kernel/parser.php (.../parser.php) (revision 640)
+++ trunk/kernel/parser.php (.../parser.php) (revision 642)
@@ -1,3416 +1,3416 @@
-";print_r($pieces);echo "";
- $m_var_list["cat"] = $pieces[0];
- $m_var_list["p"] = $pieces[1];
- $objCatList->Page = $m_var_list["p"];
-
- $m_var_list["lang"] = $pieces[2];
- $m_var_list["theme"] = $pieces[3];
- }
- else
- {
- $m_var_list["cat"]=0;
- $m_var_list["p"] = 1;
- $m_var_list["lang"] = $objLanguages->GetPrimary();
- $m_var_list["theme"]= $objThemes->GetPrimaryTheme();
- }
-}
-
-function m_BuildEnv()
-{
- global $m_var_list, $m_var_list_update;
- $module_vars = Array('cat','p','lang','theme');
- $ret = GenerateModuleEnv('m', $module_vars);
- if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']);
- return $ret;
-}
-
-function m_GetVar($name)
-{
- // get variable from template variable's list
- global $m_var_list, $m_var_list_update;
- return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name];
-}
-
-function &LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId)
-{
- global $objItemTypes;
-
- if(!is_object($Relations))
- {
- $Relations = new clsRelationshipList();
- }
- //$Relations->debuglevel = 2;
- if ($ResourceId != '') {
- $sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority,
- IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId,
- IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId,
- IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType,
- IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType
- FROM %%s", $ResourceId);
-
- $where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1";
- $Relations->LoadRelated($where,"",$sql);
- $ids = array();
- if($Relations->NumItems()>0)
- {
- foreach($Relations->Items as $r)
- {
- if($r->Get("SourceId")==$ResourceId)
- {
- $ids[$r->Get("TargetType")][] = $r->Get("TargetId");
- }
- if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1)
- {
- $ids[$r->Get("SourceType")][] = $ResourceId;
- }
- }
- foreach($ids as $ItemType=>$idlist)
- {
- $Item =& $objItemTypes->GetItem($ItemType);
- $table = GetTablePrefix().$Item->Get("SourceTable");
- if($ItemType!=1)
- {
- $cattable = GetTablePrefix()."CategoryItems";
- $sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON ";
- $sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 ";
- $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
- }
- else
- {
- $sql = "SELECT *,CategoryId FROM $table ";
- $sql .="WHERE $table.Status=1 ";
- $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
- }
- // echo $sql." \n";
- $RelatedItems->Query_Item($sql,-1,-1,$ItemType);
- }
- }
- }
-}
-
-
-/*
- @description: Inserts the html from a remote source
- @attrib: _url:: Remote URL to include
- @attrib: _StartPos:: Numeric start point of text to include, or string match
- @attrib: _EndPos:: Numeric end point of text to include, or string match
- @example:
-*/
-function m_insert_url($attribs=array())
-{
- global $pathtoroot;
-
- $url = $attribs["_url"];
- $StartPos = $attribs["_startpos"];
- $EndPos = $attribs["_endpos"];
-
- $socket = new Socket($url,0,NULL);
- $txt = $socket->socket_read_all();
- $lines = explode("\n",$txt);
- $txt = substr($txt,strpos($txt,"<"));
- $tmp = strtolower($txt);
- $bodypos = strpos($tmp,"0)
- {
- $head = substr($txt,0,$bodypos-1);
- $body = substr($txt,$bodypos);
- if(substr($tmp,-7)=="")
- $body = substr($body,0,-7);
- }
- else
- $body = $txt;
- if(strlen($body))
- {
- if(strlen($StartPos))
- {
- if(!is_numeric($StartPos))
- {
- $start = strpos($body,$StartPos);
- }
- else
- $start = (int)$StartPos;
- }
- else
- $start = 0;
- if(strlen($EndPos))
- {
- if(!is_numeric($EndPos))
- {
- $end = strpos($body,$EndPos,$start) + strlen($EndPos);
- }
- else
- $end = (int)$EndPos;
- }
- else
- $end = NULL;
- $o = substr($body,$start,$end-$start);
- }
- return $o;
-}
-
-/*
- @description: Displays a template depending on the login status of the user
- @attrib: _logintemplate:tpl: template to display when the user is NOT logged in
- @attrib: _LoggedinTemplate:tpl: template to display when the user is logged in
- @example:
-*/
-function m_loginbox($attribs = array())
-{
- global $var_list, $objSession, $objUsers, $objTemplate;
-
- $userid = $objSession->Get("PortalUserId");
- $groupid = $objSession->Get("GroupId");
- if ($userid == 0)
- {
- if (strlen($attribs["_logintemplate"]))
- $t = $objTemplate->ParseTemplate($attribs["_logintemplate"]);
- return $t;
- }
- else
- {
- $user =& $objUsers->GetItem($userid);
- if (strlen($attribs["_loggedintemplate"]))
- $t = $user->ParseTemplate($attribs["_loggedintemplate"]);
- return $t;
- }
-}
-/*
- @description: result of suggest site action
-*/
-function m_suggest_result()
-{
- global $suggest_result;
-
- return $suggest_result;
-}
-
-/*
- @description: result of subscribe to mailing list action
-*/
-function m_subscribe_result()
-{
- global $SubscribeResult;
-
- if(strlen($SubscribeResult))
- return language($SubscribeResult);
- return "";
-}
-
-/*
- @description: email address of user subscribing to mailing list
-*/
-function m_subscribe_address()
-{
- global $SubscribeAddress;
-
- if(strlen($SubscribeAddress))
- return $SubscribeAddress;
- return "";
-}
-
-/*
- @description: Error message of subscribe to mailing list action
-*/
-function m_subscribe_error()
-{
- global $SubscribeError;
-
- if(strlen($SubscribeError))
- return language($SubscribeError);
- return "";
-}
-
-
-/*
- @description: Displays a prompt for a form field
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _LangText:lang: Language var to use for field label
- @attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set)
- @attrib: _Template:tpl: template used to display the field label (if not set "" is used
- @attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set
-*/
-function m_form_prompt($attribs = array())
-{
- global $FormError, $objTemplate, $objConfig;
-
- $form = strtolower($attribs["_form"]);
- $field = strtolower($attribs["_field"]);
-
- if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
- {
- $o = "";
- }
- else
- {
- $t = $attribs["_template"];
- if(!strlen($t))
- {
- $templateText = "";
- }
- $e = $attribs["_errortemplate"];
- if(!strlen($e))
- $e = $t;
- if(strlen($attribs["_langtext"]))
- {
- $txt = language($attribs["_langtext"]);
- }
- else
- $txt = $attribs["_plaintext"];
-
- if (strtolower($field) == "dob")
- {
- if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")]))
- $rawtext = $objTemplate->GetTemplate($e, true);
- }
-
- if(isset($FormError[strtolower($form)][strtolower($field)]))
- {
- $rawtext = $objTemplate->GetTemplate($e);
- }
- elseif (strlen($t))
- $rawtext = $objTemplate->GetTemplate($t);
-
- if(is_object($rawtext))
- {
- $src = $rawtext->source;
- $o = str_replace("",$txt, $src);
- }
- else
- $o = str_replace("", $txt, $templateText);
-
- }
- return $o;
-}
-
-/*
- @description: Returns text if system is configured to use auto-generated passwords
- @attrib:_LangText:lang:Language tag to return
- @attrib:_PlainText::Plain text to return (_LangText takes precedece)
- @attrib:_Value:bool:Auto Password setting value to match
-*/
-function m_autopassword($attribs = array())
-{
- global $objConfig;
- if($attribs["_value"]=="true" || $attribs["_value"]==1)
- {
- $IsAuto = $objConfig->Get("User_Password_Auto");
- }
- else
- {
- $IsAuto = !$objConfig->Get("User_Password_Auto");
- }
-
- if($IsAuto)
- {
- if(strlen($attribs["_langtext"]))
- {
- $ret = language($attribs["_langtext"]);
- }
- else
- $ret = $attribs["_plaintext"];
- if(!$ret)
- return "true";
- }
- return $ret;
-}
-
-/*
- @description: checks if field specified is equals to value specified
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Value:: Field value to compare to
- @example: true
-*/
-function m_field_equals($attribs = array())
-{
- global $FormValues;
- //print_pre($attribs);
- $form = $attribs["_form"];
- $field = $attribs["_field"];
- if(isset($_POST[$field]))
- {
- $value = $_POST[$field];
- }
- else
- $value = $FormValues[$form][$field];
- //echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."] ";
- return $value == $attribs['_value'] ? 1 : '';
-}
-
-/*
- @description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _ForgetValue:bool: if true, forget value
- @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
- @example:
-*/
-function m_form_input($attribs = array())
-{
- global $FormValues, $objConfig;
-
- $html_attribs = ExtraAttributes($attribs);
- $form = $attribs["_form"];
- $field = strtolower($attribs["_field"]);
- if(isset($_POST[$field]) && $attribs['_forgetvalue'] != 1)
- {
- $value = $_POST[$field];
- }
- else {
- if ($attribs['_forgetvalue'] != 1) {
- $value = $FormValues[$form][$field];
- }
- }
- //echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']." \n";
- if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
- {
- $ret = "";
- }
- else
- {
- $ret = "";
- if($attribs["_required"])
- $ret .= "";
- if($attribs["_custom"])
- $ret .= "";
- }
- return $ret;
-}
-
-/*
- @description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Value:bool: If true, the radio button is CHECKED
- @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
- @attrib: _Custom:bool: If set, handled as a custom field
- @example:
-*/
-function m_form_checkbox($attribs = array())
-{
- global $FormValues, $objConfig;
-
- $html_attribs = ExtraAttributes($attribs);
- $form = $attribs["_form"];
- $field = strtolower($attribs["_field"]);
- if(isset($_POST[$field]))
- {
- $value = (int)$_POST[$field];
- if($value==1)
- $checked = " CHECKED";
- }
- else
- {
- $value = (int)$FormValues[$form][$field];
- if($value==1)
- $checked=" CHECKED";
- }
- //echo $form.".".$field."=".$value." \n";
- $ret = "";
- if($attribs["_required"])
- $ret .= "";
- if($attribs["_custom"])
- $ret .= "";
-
- return $ret;
-}
-
-/*
- @description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED
- @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
- @attrib: _Custom:bool: If set, handled as a custom field
- @example:
-*/
-function m_form_radio($attribs = array())
-{
- global $FormValues, $objConfig;
-
- $html_attribs = ExtraAttributes($attribs);
- $form = $attribs["_form"];
- $field = strtolower($attribs["_field"]);
- $val = $attribs["_value"];
- if(isset($_POST[$field]))
- {
- $value = (int)$_POST[$field];
- if($value==1)
- $checked = " CHECKED";
- }
- else
- {
- $value = (int)$FormValues[$form][$field];
- if($value==$val)
- $checked=" CHECKED";
- }
- //echo $form.".".$field."=".$value." \n";
- $ret = "";
- if($attribs["_required"])
- $ret .= "";
- if($attribs["_custom"])
- $ret .= "";
-
- return $ret;
-}
-/*
- @description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition)
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @example:
-*/
-function m_form_value($attribs = array())
-{
- global $FormValues;
-
- $form = $attribs["_form"];
- $field = strtolower($attribs["_field"]);
-
- if(isset($_POST[$field]))
- {
- $value = stripslashes($_POST[$field]);
- }
- else
- $value = stripslashes($FormValues[$form][$field]);
- //echo "
"; print_r($FormValues); echo "
";
- return $value;
-}
-
-/*
- @description: creates an form OPTION tag for a form SELECT tag.
- All extra attributes are passed to the OPTION tag.
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select
- field is the same as this attribute, then this option will be set SELECTED.
- @attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown
- @attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext)
- @example: $txt";
-
- return $o;
-}
-
-/*
- @description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
- @attrib: _Custom:bool: If set, handled as a custom field
- @example:
-*/
-function m_form_textarea($attribs = array())
-{
- global $FormValues;
- $html_attribs = ExtraAttributes($attribs);
- $field = $attribs["_field"];
- $form = $attribs["_form"];
- if(isset($_POST[$field]))
- {
- $value = stripslashes($_POST[$field]);
- }
- else
- $value = stripslashes($FormValues[$attribs["_form"]][$field]);
- $ret = "";
- if($attribs["_required"])
- $ret .= "";
- if($attribs["_custom"])
- $ret .= "";
- return $ret;
-}
-
-/*
- @description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
- @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
- @attrib: _ImageTypes:: Comma-separated list of file extensions allowed
- @attrib: _Thumbnail:bool: If true, image is treated as a thumbnail
- @attrib: _ImageName:: System name of image being uploaded
- @attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all
-*/
-function m_form_imageupload($attribs = array())
-{
- $html_attribs = ExtraAttributes($attribs);
- $field = $attribs["_field"];
- $form = $attribs["_form"];
- $TypesAllowed = $attribs["_imagetypes"];
- $isthumb = (int)$attribs["_thumbnail"];
- $imgname = $attribs["_imagename"];
- $maxsize = $attribs["_maxsize"];
-
- $ret = "";
- $ret .= "";
- $ret .= "";
- $ret .= "";
- $ret .= "";
- if($attribs["_required"])
- $ret .= "";
- return $ret;
-}
-
-/*
- @description: Returns the error text for a form field, or nothing if no error exists for the field
- @attrib: _Form:: Form name for the field
- @attrib: _Field:: Field Name
-*/
-function m_form_error($attribs = array())
-{
- global $FormError;
-
- $form = $attribs["_form"];
- $field = $attribs["_field"];
-
- return $FormError[$form][$field];
-}
-
-/**
- @description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable.
- @attrib: _Form:: Form name for the field
-*/
-function m_form_has_errors($attribs = array())
-{
- // shows specified template once if form has error(-s)
- global $FormError;
- $f = $attribs["_form"];
-
- $ret = is_array($FormError[$f]);
- if(!$ret) return '';
- return isset($attribs["_asif"]) ? true : language('lu_errors_on_form');
-}
-
-/**
- @description: Lists form errors for all fields in a form
- @attrib: _Form:: Form name for the field
- @attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "" is used)
-*/
-function m_list_form_errors($attribs = array())
-{
- global $FormError, $content_set, $objTemplate;
-
- $t = $attribs["_itemtemplate"];
- if(!strlen($t))
- $templateText = "";
- $f = $attribs["_form"];
- $o = "";
- if (strlen($t))
- {
- $rawtext = $objTemplate->GetTemplate($t, true);
- $src = $rawtext->source;
- }
- else
- $src = $templateText;
-
- //echo $f." ";
- //echo $t." ";
-// echo "
"; print_r($FormError); echo "
";
- if(is_array($FormError[$f]))
- {
- foreach($FormError[$f] as $e)
- {
- $o .= str_replace("",$e, $src);
- }
- }
- if(!strlen($o))
- $content_set = 0;
- return $o;
-}
-
-function m_form_load_values($FormName,$IdValue)
-{
- global $FormValues, $objUsers, $objSession, $objConfig;
-
- switch($FormName)
- {
- case "m_acctinfo":
- $u =& $objUsers->GetItem($IdValue);
- $FormValues[$FormName]["username"] = $u->Get("Login");
- //$FormValues[$FormName]["password"] = $u->Get("Password");
- //$FormValues[$FormName]["passwordverify"] = $u->Get("Password");
-
- $FormValues[$FormName]["password"] = "";
- $FormValues[$FormName]["passwordverify"] = "";
-
- $FormValues[$FormName]["firstname"] = $u->Get("FirstName");
- $FormValues[$FormName]["lastname"] = $u->Get("LastName");
- $FormValues[$FormName]["email"] = $u->Get("Email");
- $FormValues[$FormName]["phone"] = $u->Get("Phone");
- $FormValues[$FormName]["street"] = $u->Get("Street");
- $FormValues[$FormName]["city"] = $u->Get("City");
- $FormValues[$FormName]["state"] = $u->Get("State");
- $FormValues[$FormName]["zip"] = $u->Get("Zip");
- $FormValues[$FormName]["country"] = $u->Get("Country");
-
-// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob"));
- $FormValues[$FormName]["dob_day"] = date("d", $u->Get("dob"));
- $FormValues[$FormName]["dob_year"] = date("Y", $u->Get("dob"));
- $FormValues[$FormName]["dob_month"] = date("m", $u->Get("dob"));
-
- $u->LoadCustomFields();
- if(is_array($u->CustomFields->Items))
- {
- foreach($u->CustomFields->Items as $f)
- {
- $FormValues[$FormName][$f->Get("FieldName")] = $f->Get("Value");
- }
- }
- break;
- case "m_profile":
- $u =& $objUsers->GetItem($IdValue);
- if(is_object($u))
- {
- $FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname");
- $FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname");
- $FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob");
- $FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email");
- $FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone");
- $FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street");
- $FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city");
- $FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state");
- $FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip");
- $FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country");
- }
- break;
- case "m_simplesearch":
- $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
- break;
- case "m_simple_subsearch":
- $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
- break;
-
- }
-}
-
-/*
- @description: Generates the ACTTION property for a FORM tag used by In-Portal
- @attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template)
- @attrib: _Form:: The form name Possible Values:
-
-
login: user login
-
logout: user logout
-
forgotpw: Form to prompt the user for forgotten password information
-
forgotpw_confirm: confirmation form for forgotpw
-
suggest: form to suggest the site to a friend
-
suggest_confirm: form to confirm suggestion of the site to a friend
-
m_subscribe: form to subscribe to the mailing list
-
subscribe_confirm: form to confirm subscription to the mailing list
-
m_unsubscribe: form to unsubscribe from the mailing list
-
unsubscribe_confirm: form to confirm un-subscription from the mailing list
-
m_acctinfo: user account information
-
m_profile: system-level profile information
-
m_register: New User registration form
-
m_addcat: Suggest Category form
-
m_addcat_confirm: Confirmation for add category
-
m_simplesearch: Perform a simple search
-
m_simple_subsearch: Search within results
-
m_adv_searchtype: Form to select type of advanced search
-
m_adv_subsearch: Advanced Search
-
error_access: form displayed on the access denied template
-
error_template: Form displayed on the template error page
-
m_set_theme: Form displayed for theme selection
-
- @attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed.
- @attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed.
- @attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed.
- @attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed.
- @attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error.
- @attrib: _Referer:bool: The destination template will be taken from referer page we can from.
-
- @example: ">
-*/
-function m_form_action($attribs = array())
-{
- global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList;
-
- $target_template = $attribs["_template"];
- if(strlen($target_template))
- {
- $var_list_update["t"] = $target_template;
- }
- else
- $var_list_update["t"] = $var_list["t"];
-
- $ret = "";
- $form = strtolower($attribs["_form"]);
- switch($form)
- {
- case "login":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_login";
- if($attribs["_successtemplate"])
- {
- $ret .= "&dest=".$attribs["_successtemplate"];
- }
- else
- if(strlen($var_list["dest"]))
- $ret .= "&dest=".$var_list["dest"];
- }
- break;
- case "logout":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_logout";
- break;
- case "forgotpw":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- if(strlen($attribs["_errortemplate"]))
- {
- $err = $attribs["_errortemplate"];
- }
- else
- $err = $var_list["t"];
- $ret = GetIndexURL(2)."?env=".BuildEnv()."&Action=m_forgotpw&error=$err";
- }
- break;
- case "forgotpw_confirm":
- $ret = GetIndexURL(2)."?env=".BuildEnv();
- break;
- case "suggest":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_suggest_email";
- if(strlen($attribs["_confirmtemplate"])>0)
- {
- $ret .= "&Confirm=".$attribs["_confirmtemplate"];
- }
- if(strlen($Dest))
- {
- $ret .= "&DestTemplate=$Dest";
- }
- else
- {
- if(strlen($attribs["_confirmtemplate"])>0)
- $ret .="&DestTemplate=".$var_list["t"];
- }
-
- if(strlen($attribs["_errortemplate"])>0)
- {
- $ret .= "&Error=".$attribs["_errortemplate"];
- }
- }
- break;
- case "suggest_confirm":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- if(strlen($_GET["DestTemplate"]))
- {
- $var_list_update["t"] = $_GET["DestTemplate"];
- }
- else
- $var_list_update["t"] = "index";
-
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- break;
- case "m_subscribe":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe_confirm";
- if(strlen($attribs["_subscribetemplate"]))
- {
- $ret .="&Subscribe=".$attribs["_subscribetemplate"];
- }
-
- if(strlen($attribs["_unsubscribetemplate"])>0)
- {
- $ret .= "&Unsubscribe=".$attribs["_unsubscribetemplate"];
- }
- if(strlen($attribs["_errortemplate"])>0)
- {
- $ret .= "&Error=".$attribs["_errortemplate"];
- }
- }
- break;
-
- case "subscribe_confirm":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe";
- if($attribs["_subscribetemplate"])
- $ret .= "&Subscribe=".$attribs["_subscribetemplate"];
- break;
- case "unsubscribe_confirm":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe";
- if($attribs["_subscribetemplate"])
- $ret .= "&Subscribe=".$attribs["_subscribetemplate"];
- break;
- case "m_unsubscribe":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe";
- if(strlen($attribs["_confirmtemplate"])>0)
- {
- $ret .= "&Confirm=".$attribs["_confirmtemplate"];
- }
- if(strlen($Dest))
- {
- $ret .= "&DestTemplate=$Dest";
- }
- else
- {
- if(strlen($attribs["_confirmtemplate"])>0)
- $ret .="&DestTemplate=".$var_list["t"];
- }
- }
-
- if(strlen($attribs["_confirmtemplate"])>0)
- {
- $ret .="&ErrorTemplate=".$attribs["_confirmtemplate"];
- }
-
-
- break;
- case "m_unsubscribe_confirm":
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- break;
- case "m_acctinfo":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_acctinfo&UserId=".$objSession->Get("PortalUserId");
- m_form_load_values($form, $objSession->Get("PortalUserId"));
- break;
- case "m_profile":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_profile&UserId=".$objSession->Get("PortalUserId");
- m_form_load_values($form,$objSession->Get("PortalUserId"));
- break;
-
- case "m_set_theme":
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_set_theme";
- break;
-
- case "m_register":
-
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_register";
-
- switch ($objConfig->Get("User_Allow_New"))
- {
- case "1":
- if(strlen($attribs["_confirmtemplate"]) && $objConfig->Get("User_Password_Auto"))
- $_dest = "&dest=".$attribs["_confirmtemplate"];
- else
- $_dest = "&dest=".$attribs["_logintemplate"];
- break;
-
- case "2":
- if(strlen($attribs["_notallowedtemplate"]))
- $_dest = "&dest=".$attribs["_notallowedtemplate"];
- break;
-
- case "3":
- if(strlen($attribs["_pendingtemplate"]))
- $_dest = "&dest=".$attribs["_pendingtemplate"];
- break;
- }
-
- if (strlen($_dest))
- $ret .= $_dest;
- }
- break;
-
- case "register_confirm":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- break;
- case "m_addcat":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $action = "m_add_cat";
- if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING"))
- {
- if(strlen($attribs["_confirmpending"]))
- {
- $ConfirmTemplate = $attribs["_confirmpending"];
- }
- else
- $ConfirmTemplate = $attribs["_confirm"];
- $action="m_add_cat_confirm";
- }
-
- if ($objSession->HasCatPermission("CATEGORY.ADD"))
- {
- $ConfirmTemplate = $attribs["_confirm"];
- $action="m_add_cat_confirm";
- }
-
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=$action";
- if(strlen($ConfirmTemplate))
- $ret .= "&Confirm=$ConfirmTemplate";
-
- if (strlen($attribs["_mod_finishtemplate"])) {
-
- $CurrentCat = $objCatList->CurrentCategoryID();
- if((int)$CurrentCat>0)
- {
- $c = $objCatList->GetCategory($CurrentCat);
-
- //will prefix the template with module template root path depending on category
- $ids = $c->GetParentIds();
- $tpath = GetModuleArray("template");
- $roots = GetModuleArray("rootcat");
-
- // get template path of module, by searching for moudle name
- // in this categories first parent category
- // and then using found moudle name as a key for module template paths array
- $path = $tpath[array_search ($ids[0], $roots)];
- $t = $path . $attribs["_mod_finishtemplate"];
- }
- else {
- $t = $attribs["_mod_finishtemplate"]; //Just in case
- }
- }
- else {
- $t = $attribs["_finishtemplate"];
- }
-
- $ret .="&DestTemplate=".$t;
- }
- break;
- case "m_addcat_confirm":
- $target_template = $_GET["DestTemplate"];
- if(strlen($target_template))
- {
- $var_list_update["t"] = $target_template;
- }
- else
- $var_list_update["t"] = $var_list["t"];
- $ret = GetIndexURL(2)."?env=".BuildEnv();
- break;
- case "m_simplesearch":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_search";
-
- if(strlen($attribs["_errortemplate"]))
- $ret.= "&Error=".$attribs["_errortemplate"];
-
- m_form_load_values($form, 0);
- }
- break;
- case "m_simple_subsearch":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_subsearch";
- m_form_load_values($form,0);
- }
- break;
- case "m_adv_search_type":
- if(!$objSession->SessionEnabled())
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_advsearch_type";
- m_form_load_values($form,0);
- }
- break;
- case "m_adv_search":
- $SearchType = $_GET["type"];
- if(!is_numeric($SearchType))
- $SearchType = $_POST["itemtype"];
- if(!$objSession->SessionEnabled() && !strlen($SearchType))
- {
- $var_list_update["t"] = "error_session";
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- }
- else
- {
- $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_adv_search&type=$SearchType";
- m_form_load_values($form,0);
- }
- break;
-
- case "error_access":
- $target_template = $_GET["DestTemplate"];
- if(!strlen($target_template))
- $target_template="login";
- $var_list_update["t"] = $target_template;
-
- $ret = GetIndexURL(2)."?env=" . BuildEnv();
- break;
-
- case "error_template":
-
- $target_template = $_GET["DestTemplate"];
-
- if($attribs["_referer"] == 1)
- {
- $target_template = "_referer_";
- }
- elseif (!strlen($target_template))
- {
- $target_template = "index";
- }
-
- $var_list_update["t"] = $target_template;
-
-// $m_var_list_update["cat"]=0;
-
- $ret = GetIndexURL(2)."?env=".BuildEnv();
-
- break;
-
- }
- return $ret;
-}
-
-/*
- @description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link
-
-*/
-function m_logout_link($attribs)
-{
- $ret = m_template_link($attribs)."&Action=m_logout";
- return $ret;
-}
-
-/*
- @description: returns a URL to the current theme
- @attrib: _page:: Additional address to be added to the end of the theme URL
-*/
-function m_theme_url($attribs=array())
-{
- global $objConfig,$objSession, $objThemes, $CurrentTheme;
-
- if(!is_object($CurrentTheme))
- $CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
-
- $theme_url = "http://". ThisDomain().$objConfig->Get("Site_Path")."themes/".$CurrentTheme->Get("Name")."/";
- if($attribs["_page"])
- {
- if ($attribs["_page"] != 'current')
- {
- $theme_url .= $attribs["_page"];
- }
- else
- {
- $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
- }
- }
- return $theme_url;
-}
-
-/*
- @description: returns a URL to the current theme
-*/
-function m_current_page_url($attribs=array())
-{
- global $objConfig,$objSession;
-
- $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
-
- return $theme_url;
-}
-
-/*
- @description: returns a URL to the current theme
- @attrib: _fullpath:bool: Append the title with the full path of the current category
- @attrib: _currentcategory:bool: Append the title with the current category
- @attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name
-*/
-function m_page_title($attribs = array())
-{
- global $objConfig, $objCatList;
-
- $ret = $objConfig->Get("Site_Name");
- if($attribs["_fullpath"] || $attribs["_currentcategory"])
- {
- $CurrentCat = $objCatList->CurrentCategoryID();
- if((int)$CurrentCat>0)
- {
- $c = $objCatList->GetCategory($CurrentCat);
- if($attribs["_fullpath"])
- {
- $path = $c->Get("CachedNavbar");
-
- if(strlen($path))
- $ret .= " - ".$path;
- }
- else
- {
- if($attribs["_currentcategory"])
- {
- $f = $attribs["_catfield"];
- if(!strlen($f))
- $f = "Name";
- $ret .= " - ".$c->Get($f);
- }
- }
- }
- }
- $ret = stripslashes($ret);
- return $ret;
-}
-
-/*
- @description: list all active themes
- @attrib: _ItemTemplate:tpl: Template to display each theme in the list
-*/
-function m_list_themes($attribs=array())
-{
- global $objThemes;
-
- $t = $attribs["_itemtemplate"];
- if(strlen($t))
- {
- $objThemes->Clear();
- $objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC");
-
- foreach($objThemes->Items as $theme)
- {
- $o .= $theme->ParseTemplate($t);
- }
- }
- return $o;
-}
-
-/*
- @description: display text based on the user's language
- @attrib: _Phrase:lang: label to replace with language-specific text
- @example:
-*/
-function m_language($attribs)
-{
- global $objSession, $objLanguages, $ForceLanguage;
-
- $phrase = $attribs["_phrase"];
- $LangId = (int)$ForceLanguage;
- if(strlen($phrase))
- {
- $lang = $attribs["_language"];
- if(strlen($lang))
- {
- $l = $objLanguages->GetItemByField("PackName",$lang);
- if(is_object($l))
- {
- $LangId = $l->Get("LanguageId");
- }
- }
- return language($phrase,$LangId);
- }
- else
- return "";
-}
-
-/*
- @description: Creates a URL used to set the current language for a user
- @attrib: _language:: Language to set (this value should be the language Pack Name)
-*/
-function m_setlang_link($attribs)
-{
- global $m_var_list_update, $objSession,$objLanguages;
-
- $lang = $attribs["_language"];
- if(strlen($lang))
- {
- $l = $objLanguages->GetItemByField("PackName",$lang);
- if(is_object($l))
- $LangId = $l->Get("LanguageId");
- }
- else
- $LangId=$objSession->Get("Language");
- if($LangId)
- {
- $m_var_list_update["lang"] = $LangId;
- $ret = GetIndexURL()."?env=".BuildEnv();
- unset($m_var_list_update["lang"]);
- }
- else
- $ret = "";
- return $ret;
-}
-
-/*
- @description: list all active languages
- @attrib: _ItemTemplate:tpl: Template to display each language in the list
-*/
-function m_list_languages($attribs)
-{
- global $objLanguages, $content_set;
-
- $sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1";
- $objLanguages->Clear();
- $objLanguages->Query_Item($sql);
-
- if($objLanguages->NumItems()>0)
- {
- foreach($objLanguages->Items as $l)
- $o .= $l->ParseTemplate($attribs["_itemtemplate"]);
- }
- else
- $content_set=0;
- return $o;
-}
-
-/*
- @description: returns the date format for a language
- @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
-*/
-function m_lang_dateformat($attribs=array())
-{
- global $objLanguages, $objSession;
-
- $lang = $attribs["_lang"];
- if(!strlen($lang))
- {
- $LangId = $objSession->Get("Language");
- $l = $objLanguages->GetItem($LangId);
- }
- else
- {
- $l = $objLanguages->GetItemByField("PackName",$lang);
- }
- $fmt = GetDateFormat($LangId);
- $fmt = GetStdFormat($fmt);
-
- return $fmt;
-}
-
-/*
- @description: returns a language field value
- @attrib: _Field:: Language field to return
- @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
-*/
-function m_lang_field($attribs = array())
-{
- global $objLanguages, $objSession;
-
- if(!strlen($attribs["_field"]))
- return "";
- $lang = $attribs["_lang"];
- if(!strlen($lang))
- {
- $LangId = $objSession->Get("Language");
- $l = $objLanguages->GetItem($LangId);
- }
- else
- {
- $l = $objLanguages->GetItemByField("PackName",$lang);
- }
- if(is_object($l))
- {
- //$ret = $l->Get($attribs["_field"]);
- $e = new clsHtmlTag();
- $e->name=$l->TagPrefix;
- $e->attributes=$attribs;
- $ret = $l->ParseObject($e);
- }
- return $ret;
-}
-
-/*
- @description: Creates a URL used to set the current theme for a user
- @attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index"
-*/
-function m_settheme_link($attribs)
-{
- global $m_var_list_update, $objSession, $objThemes, $CurrentTheme;
-
- $ThemeName = $attribs["_theme"];
-
- if(strlen($ThemeName))
- {
- $t = $objThemes->GetItemByField("Name",$ThemeName);
- if(is_object($t))
- {
- $Id = $t->Get("ThemeId");
- }
- else
- $Id = 0;
- }
- else
- {
- $t = $CurrentTheme;
- $Id = 0;
- }
- $m_var_list_update["theme"] = $Id;
- $ret = GetIndexURL()."?env=".BuildEnv();
- unset($m_var_list_update["theme"]);
- return $ret;
-}
-
-/*
- @description: Initializes categories
-*/
-function m_init_cats($attribs = array())
-{
- // save current & previous category (used in pagination)
- global $objSession, $objCatList;
- global $var_list;
- //echo "SID_INIT: ".$var_list["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].') ';
- $objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') );
- $objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() );
-
- //$last_cat = $objSession->GetVariable('last_category');
- //$prev_cat = $objSession->GetVariable('prev_category');
- //echo "Last CAT: [$last_cat] ";
- //echo "Prev CAT: [$prev_cat] ";
-}
-
-/*
- @description: List all subcategories a user is allowed to view
- @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
- @attrib: _maxlistcount:int: Maximum number of categories to list
- @attrib: _FirstItemTemplate:tpl: Template used for the first category listed
- @attrib: _LastItemTemplate:tpl: Template used for the last category listed
- @attrib: _ItemTemplate:tpl: default template used for category list items
- @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
- @example:
-*/
-function m_list_cats($attribs = array())
-{
- global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache;
-
- $CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv());
- if(strlen($CachedList))
- {
- return $CachedList;
- }
- $cols = $attribs["_columns"];
- if($cols<1)
- $cols =1;
- $CategoryId = $attribs["_catid"];
- if(!is_numeric($CategoryId))
- $CategoryId = $objCatList->CurrentCategoryID();
-
- $cat_count = (int)$attribs["_maxlistcount"];
- /* validation */
- if(strlen($attribs["_itemtemplate"])==0)
- {
- if($attribs["dataexists"])
- $content_set = 0;
- return "";
- }
-
- $GroupList = $objSession->Get("GroupList");
- if(strlen($GroupList))
- {
- $Groups = explode(",",$GroupList);
- }
- $acl_where = "";
- if(@count($Groups)>0 && is_array($Groups))
- {
- $acl_where = array();
- for($i=0;$iClear();
- $OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
- $objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy);
- if ($objCatList->NumItems() == 0)
- {
- if($attribs["_dataexists"])
- $content_set = 0;
- return "";
- }
-
- $html_attr = ExtraAttributes($attribs);
-
- $o="";
- $notable = $attribs["_notable"];
-
- $count=0;
- $row=0;
- $var_list_update["t"] = $var_list["t"];
-
- if(!$notable)
- {
- $per_row = ceil($objCatList->NumItems()/$cols);
- $o = "
\n";
- }
- else
- {
- $CatCount = $objCatList->NumItems();
- foreach($objCatList->Items as $cat)
- {
- if($cat->Get("ParentId")==$CategoryId)
- {
-
- if($row==0 && strlen($attribs["_firstitemtemplate"]))
- {
- //echo 'Saving ID in m_sub_cats[ first ] '.$cat->UniqueId().' ';
- //$GLOBALS['cat_ID'] = $cat->UniqueId();
- $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
- $parsed=1;
- }
- if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
- {
- //echo 'Saving ID in m_sub_cats[ last ] '.$cat->UniqueId().' ';
- //$GLOBALS['cat_ID'] = $cat->UniqueId();
- $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
- $parsed=1;
- }
- if(!$parsed)
- {
- //echo 'Saving ID in m_sub_cats[ each ] '.$cat->UniqueId().' ';
- //$GLOBALS['cat_ID'] = $cat->UniqueId();
- $o .= $cat->ParseTemplate($attribs["_itemtemplate"]);
- }
- $row++;
- $i++;
- $count++;
- if($count>=$cat_count && $cat_count>0)
- break;
- }
- }
- }
- unset($var_list_update["t"]);
- SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o);
- return $o;
-}
-
-function LoadCatSearchResults($attribs)
-{
- global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal;
-
- $GroupList = $objSession->Get("GroupList");
- if(strlen($GroupList))
- $Groups = explode(",",$GroupList);
- $acl_where = "";
- if(@count($Groups)>0 && is_array($Groups))
- {
- $acl_where = array();
- for($i=0;$iGetPermId("CATEGORY.VIEW");
- $ctable = $objCatList->SourceTable;
- $stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable;
- $ptable = GetTablePrefix()."PermCache";
- $sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) ";
- $sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) ";
- $sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY EdPick DESC,Relevance DESC ";
- $objSearchCats->Page = $m_var_list["p"];
- if($objSearchCats->Page<1)
- $objSearchCats->Page=1;
-
- if(is_numeric($objConfig->Get($objSearchCats->PerPageVar)))
- {
- $Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar);
- $limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar);
- }
- else
- $limit = NULL;
-
- if(strlen($limit))
- $sql .= $limit;
-
- // echo "TEST: $sql \n";
- $objSearchCats->Query_Item($sql);
- $where = "ItemType=1";
-
- if(is_numeric($CountVal[1]))
- {
- $objSearchCats->QueryItemCount = $CountVal[1];
- }
- else
- {
- $objSearchCats->QueryItemCount = QueryCount($sql);
- $CountVal[1]= $objSearchCats->QueryItemCount;
- }
-}
-
-/*
- @description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is
- used to switch from a short list to a longer list. The page number is not changed.
- If this tag is called before the list tag, this function will load the category list.
- Generally, it is good practice to duplicate all attributes set for m_search_list_cats.
- Any extra HTML attributes are passed to the anchor tag
- @attrib: _Template:tpl: Template to link to
- @attrib: _text:lang: language tag to include as text for the anchor tag
- @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
- if both are included.
- @attrib: _image:: URL to an image to include inside the anchor tag.
-*/
-function m_search_cat_more($attribs = array())
-{
- global $objSearchCats, $objConfig, $m_var_list_update;
-
- $html_attribs = ExtraAttributes($attribs);
- $DestTemplate = $attribs["_template"];
-
- if($attribs["_shortlist"])
- $objSearchList->PerPageVar = "Perpage_Category_Short";
- if($objSearchCats->NumItems()==0)
- {
- LoadCatSearchResults($attribs);
- }
- $max = $objConfig->Get($objSearchList->PerPageVar);
- $val = $objSearchCats->QueryItemCount;
- if($val > $max)
- {
- if($attribs["_root"])
- $attribs["_category"]=0;
-
- $m_var_list_update["p"]=1;
- $url = m_template_link($attribs);
- unset($m_var_list_update["p"]);
- $o = "";
- $text = $attribs["_text"];
- if(!strlen($text))
- {
- $text = $attribs["_plaintext"];
- if(!strlen($text))
- {
- }
- $o .= $text."";
- }
- else
- $o .= language($text);
- if(strlen($attribs["_image"]))
- {
- $o .= "";
- }
- $o .= "";
- }
- return $o;
-}
-/*
- @description: Used in conjuction with m_search_list_cats. This function generates the page navigation
- for the list. If this tag is called before the list tag, this function will load
- the category list. Generally, it is good practice to duplicate all attributes set for
- m_search_list_cats.
- @attrib: _PagesToList:int: Number of pages to list (default is 10)
- @attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages
- listed, this text will not be included (resulting in an empty output)
-*/
-function m_search_cat_pagenav($attribs = array())
-{
- global $objSearchCats, $objConfig, $objCatList, $objSession;
-
- $DestTemplate = $attribs["_template"];
- $PagesToList = $attribs["_pagestolist"];
- if(!is_numeric($PagesToList))
- $PagesToList = 10;
-
- $CatId = $attribs["_catid"];
- if(!is_numeric($CatId))
- $CatId = $objCatList->CurrentCategoryID();
-
- $objSearchCats->PerPageVar = "Perpage_Category";
- if($attribs["_shortlist"])
- $objSearchCats->PerPageVar = "Perpage_Category_Short";
- if($objSearchCats->NumItems()==0)
- {
- LoadCatSearchResults($attribs);
- }
- $o = $objSearchCats->GetPageLinkList($DestTemplate);
- if(strlen($o) && strlen($attribs["_label"]))
- $o = language($attribs["_label"]).$o;
- return $o;
-}
-
-/*
- @description: List all categories matched in a search
- @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
- @attrib: _maxlistcount:int: Maximum number of categories to list
- @attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category
- @attrib: _FirstItemTemplate:tpl: Template used for the first category listed
- @attrib: _LastItemTemplate:tpl: Template used for the last category listed
- @attrib: _ItemTemplate:tpl: default template used for category list items
- @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
- @example:
-*/
-function m_search_list_cats($attribs = array())
-{
- global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set,
- $objSearchCats, $objPermissions, $m_var_list;
-
- if(!is_object($objSearchCats))
- {
- $objSearchCats = new clsCatList();
- $objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search"
- $objSearchCats->Clear();
- }
- $objSearchCats->PerPageVar = "Perpage_Category";
- if($attribs["_shortlist"])
- {
- $objSearchCats->Page=1;
- $m_var_list["p"] = 1;
- $objSearchCats->PerPageVar = "Perpage_Category_Short";
- }
-
- $keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches
-
- if($objSearchCats->NumItems()==0)
- {
- LoadCatSearchResults($attribs);
- //echo "Cat count: ". $objSearchCats->QueryItemCount;
- $ret = 0;
- if ($keywords) {
- foreach ($objSearchCats->Items as $cat) {
-
- if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($_POST['keywords']))) {
- $ret++;
- }
- }
- }
- else {
- $ret = $objSearchCats->QueryItemCount;
- }
- if ($ret == 0) //if ($objSearchCats->NumItems() == 0)
- {
- $content_set = 0;
- return language("lu_no_categories");
- }
- }
-
- $html_attr = ExtraAttributes($attribs);
- $cols = $attribs["_columns"];
- if($cols<1)
- $cols =1;
- $cat_count = (int)$attribs["_maxlistcount"];
- /* validation */
- if(strlen($attribs["_itemtemplate"])==0)
- {
- $content_set = 0;
- return "ERROR -1";
- }
-
- $o="";
- $notable = $attribs["_notable"];
-
- $count=0;
- $row=0;
- $var_list_update["t"] = $var_list["t"];
-
- if(!$notable)
- {
- $per_row = ceil($objCatList->NumItems()/$cols);
- $o = "
";
- foreach($objSearchCats->Items as $cat)
- {
- //$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
- $keywords_found = strstr( strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords));
- if(!$keywords) $keywords_found = true;
- if ($keywords_found) {
- if($row==0 && strlen($attribs["_firstitemtemplate"]))
- {
- $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
- $parsed=1;
- }
- if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
- {
- $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
- $parsed=1;
- }
- if(!$parsed)
- $o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
- $row++;
- $i++;
- $count++;
- }
- }
- }
- unset($var_list_update["t"]);
- return $o;
-}
-
-/*
- @description: Parse a template based on the current advanced search type
- @attrib:_TypeSelect:tpl:Template to parse if no item type has been selected
- @attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search
-*/
-function m_advsearch_include($attribs)
-{
- global $objTemplate;
-
- $TypeSelectTemplate = $attribs["_typeselect"];
- $ItemTemplate = $attribs["_itemselect"];
- if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search"))
- {
- $o = $objTemplate->ParseTemplate($ItemTemplate);
- }
- else
- $o = $objTemplate->ParseTemplate($TypeSelectTemplate);
- return $o;
-}
-
-/*
- @description: Returns the name of the item type currently being advanced searched
- @attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name])
-*/
-function m_advsearch_type($attribs)
-{
- global $objItemTypes;
-
- if($_GET["Action"]=="m_advsearch_type")
- {
- $ItemType = $_POST["itemtype"];
- }
- elseif($_GET["Action"]=="m_adv_search")
- $ItemType = $_GET["type"];
-
- $o = "";
- if((int)$ItemType>0)
- {
- $Item = $objItemTypes->GetItem($ItemType);
- if(is_object($Item))
- {
- $name = strtolower($Item->Get("ItemName"));
- if($attribs["_plaintext"])
- {
- $o .= $name;
- }
- else
- $o = language("lu_searchtitle_".strtolower($name));
- }
- }
- return $o;
-}
-
-/*
- @description: Lists advanced search fields for the selected item type
- @attrib: _FirstItemTemplate:tpl: Template used for the first field listed
- @attrib: _LastItemTemplate:tpl: Template used for the last field listed
- @attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed
- @attrib: _ItemTemplate:tpl: default template used for field list items
- @attrib: _AltTemplate:tpl: Alternate template used for field list items
-*/
-function m_advsearch_fields($attribs)
-{
- global $objItemTypes, $objTemplate, $objSearchConfig;
-
- if(!is_object($objSearchConfig))
- $objSearchConfig = new clsSearchConfigList();
-
- if($_GET["Action"]=="m_advsearch_type")
- {
- $ItemType = $_POST["itemtype"];
- }
- elseif($_GET["Action"]=="m_adv_search")
- $ItemType = $_GET["type"];
-
- $o = "";
- if((int)$ItemType>0)
- {
- $Item = $objItemTypes->GetItem($ItemType);
- if(is_object($Item))
- {
- $name = strtolower($Item->Get("ItemName"));
-
- $table = $Item->Get("SourceTable");
- $sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder";
- $objSearchConfig->Query_Item($sql);
- $row=0;
- if(is_array($objSearchConfig->Items))
- {
- $ItemCount = count($objSearchConfig->Items);
- foreach($objSearchConfig->Items as $s)
- {
- $even = (($row+1) % 2 == 0);
- $parsed=0;
- if($row==0 && strlen($attribs["_firstitemtemplate"]))
- {
- $o .= $s->ParseTemplate($attribs["_firstitemtemplate"]);
- $parsed=1;
- }
- if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0)
- {
- $o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]);
- $parsed=1;
- }
- if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
- {
- $o .= $s->ParseTemplate($attribs["_lastitemtemplate"]);
- $parsed=1;
- }
- if(!$parsed)
- {
- if($even && strlen($attribs["_altitemtemplate"])>0)
- {
- $o .= $s->ParseTemplate($attribs["_altitemtemplate"]);
- }
- else
- $o .= $s->ParseTemplate($attribs["_itemtemplate"]);
- }
- $row++;
-
- }
- }
- }
- }
- return $o;
-}
-
-/*
- @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
- are passed to the anchor tag created.
- @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
- @attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link)
- @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
- the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
- and the link is created.)
- @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
- attribute. If this attirbute is not included and the user does not have access,
- nothing is returned. (The link is not created.)
- @attrib: _Root:bool: If set, the current category is set to the module's root category
- @attrib: _text:lang: language tag to include as text for the anchor tag
- @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
- if both are included.
- @attrib: _image:: URL to an image to include inside the anchor tag.
- @attrib: _image_actions:: Image events.
-*/
-function m_module_link($attribs = array())
-{
- global $objCatList, $objSession;
-
- $permission = $attribs["_perm"];
- $o = "";
- $tpath = GetModuleArray("template");
- if(strlen($permission))
- {
- $perms = explode(",",$permission);
- $hasperm = FALSE;
- for($x=0;$xHasCatPermission($perms[$x]))
- {
- $hasperm = TRUE;
- break;
- }
- }
- }
- else
- $hasperm = TRUE;
- if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
- {
- $hasperm = TRUE;
- $attribs["_template"]=$attribs["_deniedtemplate"];
- }
- if($hasperm)
- {
- $module = $attribs["_module"];
- if(ModuleEnabled($module))
- {
- $t = $tpath[$attribs["_module"]];
- $t .= $attribs["_template"];
- $attribs["_template"] = $t;
- $html_attr = ExtraAttributes($attribs);
- if($attribs["_root"])
- {
- $func = ModuleTagPrefix($module)."_root_link";
- if(function_exists($func))
- {
- $url = $func($attribs);
- }
- else
- $url = m_template_link($attribs);
- }
- else
- $url = m_template_link($attribs);
- $o = " ";
- $text = $attribs["_text"];
- if(!strlen($text))
- {
- $text = $attribs["_plaintext"];
- if(!strlen($text))
- {
- if(strlen($attribs["_image"]))
- {
- $text = "";
- }
- }
- $o .= $text."";
- }
- else
- $o .= language($text)."";
- }
- else
- {
- $o = "";
- }
- }
- return $o;
-}
-/*
- @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
- are passed to the anchor tag created.
- @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
- @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
- the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
- and the link is created.)
- @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
- attribute. If this attirbute is not included and the user does not have access,
- nothing is returned. (The link is not created.)
- @attrib: _text:lang: language tag to include as text for the anchor tag
- @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
- if both are included.
- @attrib: _image:: URL to an image to include inside the anchor tag.
-*/
-function m_permission_link($attribs = array())
-{
- global $objCatList, $objSession;
-
- $permission = $attribs["_perm"];
- $o = "";
- if(strlen($permission))
- {
- $perms = explode(",",$permission);
- $hasperm = FALSE;
- for($x=0;$xHasCatPermission($perms[$x]))
- {
- $hasperm = TRUE;
- break;
- }
- }
- }
- else
- $hasperm = TRUE;
- if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
- {
- $hasperm = TRUE;
- $attribs["_template"]=$attribs["_deniedtemplate"];
- }
- if($hasperm)
- {
- $url = m_template_link($attribs);
- $o = " ";
- $text = $attribs["_text"];
- if(!strlen($text))
- {
- $text = $attribs["_plaintext"];
- if(!strlen($text))
- {
- if(strlen($attribs["_image"]))
- {
- $text = "";
- }
- }
- $o .= $text."";
- }
- else
- $o .= language($text)."";
- }
- else
- {
- $o = "";
- }
-
- return $o;
-}
-
-/*
- @description: Create a link to a template.
- @attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list")
- @attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test")
- @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
- @attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in )
- @attrib: _Secure:bool:If set, creates an https URL
- @attrib: _Root:bool:If set, gets module root category id
- @attrib: _Module:str:Module Name
- @attrib: _Unsecure:bool: Is set, creates an insecure full url (http://...)
- @example: ">
-*/
-function m_template_link($attribs = array())
-{
- global $var_list, $var_list_update, $m_var_list_update, $objCatList;
-
- $template = $attribs["_template"];
-
- $query = trim($attribs["_query"]);
- $query = !ereg("^&", $query)? "&$query" : $query;
-
- if(!strlen($template))
- $template = $var_list["t"];
- $cat = $attribs["_category"];
- $var_list_update["t"] = $template;
-
- if(strlen($cat))
- {
- if($cat=="NULL")
- {
- $m_var_list_update["cat"]=0;
- }
- else
- {
- $m_var_list_update["cat"] = $cat;
- }
- }
-
- if($attribs["_secure"])
- {
- $ret = GetIndexURL(1)."?env=".BuildEnv().$query;
- }
- elseif($attribs["_unsecure"])
- {
- $ret = GetIndexURL(2)."?env=".BuildEnv().$query;
- }
- else
- $ret = GetIndexURL()."?env=".BuildEnv().$query;
-
- if(strlen($attribs["_anchor"]))
- $ret .= "#".$attribs["_anchor"];
- unset($var_list_update["t"]);
- if(strlen($cat))
- unset($m_var_list_update["cat"]);
- return $ret;
-}
-
-/*
- @description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created.
- @attrib: _Template:tpl: Template to link to if the user has access
- @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
- attribute. If this attirbute is not included and the user does not have access,
- the "login" template is used.
- @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
- the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
- and the link is created.)
- @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
- @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
- @example: ">
-*/
-function m_access_template_link($attribs = array(), $Permission="")
-{
- global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
-
- $cat = $attribs["_category"];
- if(strlen($cat))
- {
- if($cat=="NULL")
- $cat = 0;
- }
- else
- $cat = $objCatList->CurrentCategoryID();
-
- if(!strlen($Permission))
- {
- $Permission = strtoupper($attribs["_perm"]);
- }
-
- $o = "";
- $hasperm = FALSE;
- if(strlen($Permission))
- {
- $perms = explode(",",$Permission);
-
- for($x=0;$xHasCatPermission(trim($perms[$x]),$cat))
- {
- $hasperm = TRUE;
- break;
- }
- }
-
- if(!$hasperm && $attribs["_system"])
- {
- for($x=0;$xHasSystemPermission(trim($perms[$x])))
- {
- $hasperm = TRUE;
- break;
- }
- }
- }
- }
- $access = $attribs["_template"];
- $denied = $attribs["_deniedtemplate"];
- if(!strlen($denied))
- $denied = "login";
-
- $m_var_list_update["cat"] = $cat;
- if($hasperm)
- {
- $template = $access;
- if(!strlen($template))
- $template = $var_list["t"];
- $var_list_update["t"] = $template;
- }
- else
- {
- $template = $denied;
- if(!strlen($template))
- $template = $var_list["t"];
- if($template == "login")
- {
- $dest = $access;
- }
- $var_list_update["t"] = $template;
- }
-
- $ret = GetIndexURL()."?env=".BuildEnv();
- unset($var_list_update["t"]);
- if(strlen($dest))
- $ret .= "&dest=$dest";
- return $ret;
-}
-
-/*
- @description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded.
- @attrib: _Text:lang: Template to link to if the user has access
- @attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used.
- @attrib: _DenyText:lang: Template to link to if the user has access
- @attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set.
- @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated.
- @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
- @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
- @attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used.
- @attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0.
- @example: Some HTML here!
-*/
-function m_perm_text($attribs = array())
-{
- global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
-
- $cat = $attribs["_category"];
- if(strlen($cat))
- {
- if($cat=="NULL")
- $cat = 0;
- }
- else
- $cat = $objCatList->CurrentCategoryID();
-
- if(!strlen($Permission))
- {
- $Permission = strtoupper($attribs["_perm"]);
- }
-
- $o = "";
- $hasperm = FALSE;
-
- $count = 0;
-
- if(strlen($Permission))
- {
- $perms = explode(",",$Permission);
-
- for($x=0;$xHasCatPermission($perms[$x],$cat))
- {
- $hasperm = TRUE;
- $_AllPermsCount[$count] = 1;
-// break;
- }
-
- $count++;
- }
-
- if(!$hasperm && $attribs["_system"])
- {
- for($x=0; $xHasSystemPermission($perms[$x]))
- {
- $hasperm = TRUE;
- $_AllPermsCount[$count] = 1;
-// break;
- }
-
- $count++;
- }
- }
- }
-
- if ((int)$attribs["_matchallperms"])
- {
- if (count($_AllPermsCount) != array_sum($_AllPermsCount))
- $hasperm = FALSE;
- }
-
- $text = $attribs["_text"];
- $plaintext = $attribs["_plaintext"];
- $denytext = $attribs["_denytext"];
- $plaindenytext = $attribs["_plaindenytext"];
- $nopermissions_status = (int)$attribs["_noperm"]? 1 : 0;
-
- if(!strlen($denied))
- $denied = "login";
-
- if (!$nopermissions_status)
- {
- if ($hasperm)
- {
- if (strlen($text) || strlen($plaintext))
- $ret = strlen($text)? language($text) : $plaintext;
- else
- $ret = "1";
- }
- else
- $ret = strlen($denytext)? language($denytext) : $plaindenytext;
- }
- elseif (!$hasperm)
- {
- $ret = "1";
- }
-
- return $ret;
-}
-
-
-/*
- @description: Returns the error string associated with a permission
-*/
-function m_permission_error($attribs = array())
-{
- global $objPermissions;
-
- $ret = "";
- $perm = strtoupper($_GET["error"]);
- if(strlen($perm))
- {
- $ado = &GetADODBConnection();
- $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'";
- $rs = $ado->Execute($sql);
- if($rs && !$rs->EOF)
- {
- $data = $rs->fields;
- $error_tag = $data["ErrorMessage"];
- }
- else
- $error_tag = "lu_unknown_error";
- $ret = language($error_tag);
- }
- return $ret;
-}
-
-/*
- @description: Returns the error text encountered when parsing templates
-*/
-function m_template_error($attribs = array())
-{
- global $objTemplate;
-
- $ret = "";
- if($objTemplate->ErrorNo<0)
- {
- $ret = $objTemplate->ErrorStr;
- }
- return $ret;
-}
-
-/*
- @description: Creates a category navigation bar
- @attrib: _Template:tpl: template to use for navigation links
- @attrib: _RootTemplate:bool: If set, this template is linked to for the root category
- @attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed
- @attrib: _Separator:: text to display between levels of the navigation bar
- @attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used
- @example:
-*/
-function m_navbar($attribs = array())
-{
- global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules;
-
- $separator = GetElem($attribs, '_separator');
- if(!$separator) $separator = " > ";
-
- $admin = (int)GetElem($attribs, 'admin');
-
- $t = GetElem($attribs, '_template');
- $LinkLeafNode = GetElem($attribs, '_linkcurrent');
- $catid = (int)GetElem($attribs, '_catid');
-
- if( GetElem($attribs, '_root') )
- {
- $var = GetElem($attribs, '_root')."_Root";
- $Root = (int)$objConfig->Get($var);
- }
- else
- $Root = 0;
-
- $RootTemplate = GetElem($attribs, '_roottemplate') ? GetElem($attribs, '_roottemplate') : '';
- $Module = GetElem($attribs, '_module');
- $ModuleRootTemplate = '';
- if($Module)
- {
- $ModuleRootCat = $objModules->GetModuleRoot($Module);
- if($ModuleRootCat>0)
- {
- $modkey = "_moduleroottemplate";
- $ModuleRootTemplate = GetElem($attribs, $modkey);
- }
- else
- $ModuleRootTemplate="";
- }
- else
- $ModuleRootCat = 0;
-
- if(!$catid)
- $catid = $objCatList->CurrentCategoryID();
-
- $ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate);
- return $ret;
-}
-
-/*
- @description: Parse a category field and return the value
- @attrib: _Field:: Category field to parse
- @attrib: _CatId:int: Category ID to parse (uses current category if not set)
- @attrib: _StripHTML:bool: if set, all HTML is removed from the output
-*/
-function m_category_field($attribs)
-{
- global $objCatList;
-
- $ret = "";
- $catid = (int)$attribs["_catid"];
- $field = $attribs["_field"];
- if(!$catid)
- $catid = $objCatList->CurrentCategoryID();
-
- if(strlen($field))
- {
- $cat =& $objCatList->GetCategory($catid);
- if(is_object($cat))
- {
- $element = new clsHtmlTag();
- $element->name=$cat->TagPrefix;
- $element->attributes = $attribs;
- $ret = $cat->ParseObject($element);
- }
- }
- if($attribs["_striphtml"])
- $ret = strip_tags($ret);
- return $ret;
-}
-
-/*
- @description: returns the date of the last modification to a category
- @attrib: _Part:: part of the date to display
- @attrib: _Local:bool: If set, only subcategories of the current category is checked
- @example:
-*/
-function m_category_modified($attribs)
-{
- global $objConfig, $objCatList;
-
- $ado = &GetADODBConnection();
-
- if($attribs["_local"] && $objCatList->CurrentCategoryID() != 0)
- {
- $c =& $objCatList->GetItem($objCatList->CurrentCategoryID());
- $catlist = $c->GetSubCatIds();
-
- $catwhere = "CategoryId IN (".explode(",",$catlist).")";
- $sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category ";
- $sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) ";
- $sql .= "WHERE $catwhere LIMIT 1";
- }
- else
- $sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1";
- $rs = $ado->Execute($sql);
- if($rs && ! $rs->EOF)
- {
- $mod = $rs->fields["ModDate"];
- if($mod)
- {
- $part = strtolower($attribs["_part"]);
- if(strlen($part))
- {
- $ret = ExtractDatePart($part,$mod);
- }
- else
- {
- $ret = LangDate($mod);
- }
- }
- }
- return $ret;
-}
-
-/*
- @description: creates LINK tags to include all module style sheets
- @attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin")
- @attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..".
- If a module does not have a *css attribute, the default (style.css) is assumed.
- @example:
-*/
-function m_module_stylesheets($attribs)
-{
- global $TemplateRoot;
-
- $IncludeList = explode(",",trim($attribs["_modules"]));
- $tpath = GetModuleArray("template");
- for($inc=0;$inc\n";
- }
- return $ret;
-}
-
-/*
- @description: lists items related to a category
- @attrib:CatId:int: Category ID of category, or current category if not set
- @attrib:_ListItem: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority.
- Each item should have its own template passed in as an attribute (_{ItemType}Template)
-*/
-function m_related_items($attribs)
-{
- global $objItemTypes, $objCatList, $content_set;
- static $Related;
-
- global $CatRelations;
-
- $cat = $attribs["_catid"];
- if(!is_numeric($cat))
- {
- $cat = $objCatList->CurrentCategoryID();
- }
- $c =& $objCatList->GetCategory($cat);
- $data_sent=0;
- if(is_object($c))
- {
- $ResourceId = $c->Get("ResourceId");
- $IncludeList = explode(",",trim(strtolower($attribs["_listitems"])));
- $o = "";
-
- if(!is_object($CatRelations))
- {
- $CatRelations = new clsMultiTypeList();
- LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId"));
- }
-
- if($CatRelations->NumItems()>0)
- {
- for($inc=0;$incGetTypeByName($item_type);
- if(is_object($objType))
- {
- foreach($CatRelations->Items as $item)
- {
- if(is_object($item))
- {
- if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType"))
- {
- if(strlen($item->BasePermissionName))
- {
- $perm = $item->BasePermissionName.".VIEW";
- $haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId"));
- }
- else
- $hasperm = 1;
-
- if($hasperm)
- {
- $data_sent =1;
- $classname = $objType->Get("ClassName");
- if(strlen($classname))
- {
- $l = new $classname;
- $l->Data = $item->Data;
- $o .= $l->ParseTemplate($t);
- }
- }
- }
- }
- $item = NULL;
- }
- }
- else
- echo $item_type." not found \n";
- }
- }
- if($data_sent)
- {
- return $o;
- }
- else
- {
- $content_set=0;
- return "";
- }
- }
- else
- {
- $content_set = 0;
- return "";
- }
- }
- else
- {
- $content_set = 0;
- return "";
- }
-}
-
-/*
- @description: Returns the number of items related to the current category
- @attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used
- @attrib:_ItemType::Name of item to count. If not set, all related items are counted
-*/
-function m_related_count($attribs)
-{
- global $objItemTypes, $objCatList, $content_set;
-
- $cat = $attribs["_catid"];
-
- if(!is_numeric($cat))
- {
- $cat = $objCatList->CurrentCategoryID();
- }
- $c =& $objCatList->GetCategory($cat);
- $data_sent=0;
- //echo "Category: $cat
"; print_r($c); echo "
";
- if(is_object($c))
- {
- $ResourceId = $c->Get("ResourceId");
- if(!is_object($CatRelations))
- {
- $CatRelations = new clsMultiTypeList();
- LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId"));
- }
-
- $item_type = $attribs["_itemtype"];
- if(strlen($item_type))
- {
- $objType = $objItemTypes->GetTypeByName($item_type);
- if(is_object($objType))
- {
- $TargetType = $objType->Get("ItemType");
- }
- else
- $TargetType="";
- }
-
- if($CatRelations->NumItems()>0)
- {
- for($x=0;$x<$CatRelations->NumItems();$x++)
- {
- $a = $CatRelations->GetItemByIndex($x);
- if($a->type == $TargetType || !strlen($TargetType))
- {
- $count++;
- }
- }
- }
- }
- return $count;
-}
-
-/*
- @description: Returns the MetaKeywords field for a category, or the system MetaKeywords value
- if the category doesn't have a value for MetaKeywords
- @attrib: _CatId:int: Category to use (The current category is used by default)
-*/
-function m_meta_keywords($attribs = array())
-{
- global $objCatList, $objConfig;
- $catid = (int)$attribs["_catid"];
- if(!$catid)
- {
- $catid = $objCatList->CurrentCategoryID();
- }
- if($catid)
- {
- $c = $objCatList->GetItem($catid);
- $keywords = $c->Get("MetaKeywords");
- }
- if(!strlen($keywords))
- {
- $keywords = $objConfig->Get("MetaKeywords");
- }
- return $keywords;
-}
-
-/*
- @description: Returns the MetaDescription field for a category, or the system MetaDescription value
- if the category doesn't have a value for MetaDescription
- @attrib: _CatId:int: Category to use (The current category is used by default)
-*/
-function m_meta_description($attribs = array())
-{
- global $objCatList, $objConfig;
-
- $catid = (int)$attribs["_catid"];
- if(!$catid)
- {
- $catid = $objCatList->CurrentCategoryID();
- }
- if($catid)
- {
- $c = $objCatList->GetItem($catid);
- $desc = $c->Get("MetaDescription");
- }
- if(!strlen($desc))
- {
- $desc = $objConfig->Get("MetaDescription");
- }
- return $desc;
-}
-
-/*
- @description: return the number of items in the database
- @attrib: _ItemType:: Name of item to count
- @attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc)
- @attrib: _CategoryCount:int: Limit scope to the current category
- @attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set)
- @attrib: _Today:bool: Count items added today
- @attrib: _GroupOnly:bool: Only count items the current user can view
- @attrib: _NoCache:bool: Count without using cache
-*/
-function m_itemcount($attribs = array())
-{
- global $objItemTypes, $objCatList, $objSession, $objCountCache;
-
- $Bit_None = 0;
- $Bit_Today = 1;
- $Bit_Owner = 2;
- $Bit_Global = 4;
- $Bit_SubCats=8;
-
- if($attribs["_categorycount"])
- {
- $evar = m_BuildEnv();
- }
- else
- $evar = "";
-
- $cat = $attribs["_catid"];
- if(!is_numeric($cat))
- {
- $cat = $objCatList->CurrentCategoryID();
- }
-
- if((int)$cat>0)
- $c = $objCatList->GetCategory($cat);
-
- if(is_numeric($attribs["_itemtype"]))
- {
- $item = $objItemTypes->GetItem($attribs["_itemtype"]);
- }
- else
- $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
-
- $DoUpdate=0;
-
- //echo "
"; print_r($item); echo "
";
-
- $ExtraId="";
-
- if(is_object($item))
- {
- if($item->Get("ItemType")==1) /* counting categories */
- {
- $ret = $objCatList->CountCategories($attribs);
- }
- else
- {
- $ListVar =& GetItemCollection($attribs["_itemtype"]);
- if(is_object($ListVar))
- {
- $ret = $ListVar->PerformItemCount($attribs);
- }
- }
- }
- else
- $ret = 0;
-
- return !$ret ? 0 : $ret;
-}
-
-/*
- @description: Parse a User field and return the value
- @attrib: _Field:: User field to parse
- @attrib: _UserId:int: Category ID to parse (uses current user if not set)
-*/
-function m_user_field($attribs)
-{
- global $objUsers, $objSession;
-
- $o = "";
- $userid = $attribs["_userid"];
- if(!is_numeric($userid) || $userid=="0")
- $userid = $objSession->Get("PortalUserId");
-
- if($userid)
- {
- $u =& $objUsers->GetItem($userid);
- if(is_object($u))
- {
- $element = new clsHtmlTag();
- $element->name = $u->TagPrefix;
- $element->attributes = $attribs;
- $o = $u->ParseObject($element);
- }
- }
- return $o;
-}
-
-/*
- @description: Parses a user template
- @attrib:_Template:tpl: Template to parse
- @attrib:_UserId:int: User ID to parse. If not set, the current user is used
-*/
-function m_user_detail($attribs = array())
-{
- global $objTemplate, $objUsers, $objSession;
-
- $tname = $attribs["_template"];
- $UserId = (int)$attribs["_userid"];
- if(!$UserId)
- {
- $UserId=$objSession->Get("PortalUserId");
- }
- if($UserId>0)
- {
- $u = $objUsers->GetUser($UserId);
- $o = $u->ParseTemplate($tname);
- }
- else
- {
- $u = new clsPortalUser(NULL);
- $o = $u->ParseTemplate($tname);
- }
-
- return $o;
-}
-
-/*
- @description: returns a user field from the current profile being viewed
- @example:
-*/
-function m_user_profile_field($attribs = array())
-{
- if((int)$_GET["UserId"])
- {
- $attribs["_userid"] = $_GET["UserId"];
- }
-
- $ret = m_user_field($attribs);
-
-/* if ($ret == '') {
- $ret = admin_language("lu_Guest");
- }*/
-
- return $ret;
-}
-
-/*
- @description: Parses a user profile template
- @attrib:_Template:tpl: Template to parse
- @attrib:_UserId:int: User ID to parse. If not set, the current user is used
-*/
-function m_user_profile_detail($attribs)
-{
- if((int)$_GET["UserId"])
- {
- $attribs["_userid"] = $_GET["UserId"];
- }
- $ret = m_user_detail($attribs);
- return $ret;
-}
-
-/*
- @description: Lists all user profile fields the user has indicated to be public
- @attrib: _ItemTemplate:tpl: Template used to list each field
- @example:
-*/
-function m_user_profile($attribs = array())
-{
- global $objTemplate, $objUsers;
-
- $tname = $attribs["_itemtemplate"];
- $t = $objTemplate->GetTemplate($tname);
- if(is_object($t))
- {
- $html = $t->source;
- }
-
- $userid = $_GET["UserId"];
- $o = "";
-
- if((int)$userid>0)
- {
- $u = $objUsers->GetItem($userid);
- $vars = $u->GetAllPersistantVars();
- foreach($vars as $field=>$value)
- {
- if(substr($field,0,3)=="pp_")
- {
- if($value==1)
- {
- $src = $html;
- $src = str_replace("","",$src);
- $src = str_replace("lu_profile_field","lu_".$field,$src);
- $o .= $u->ParseTemplateText($src);
- }
- }
-
- }
- }
-
- return $o;
-}
-
-/*
- @description: List users the current user has marked as 'friend'
- @attrib: _Status:: Determines which online status to list, either "online" or "offline".
- @attrib: _ItemTemplate:tpl: Template used to parse list items
-*/
-function m_list_friends($attribs = array())
-{
- global $objUsers, $objSession;
-
- global $online_friends;
-
- $ado = &GetADODBConnection();
-
- $status = strtolower($attribs["_status"]);
-
- $logedin_user = $objSession->Get("PortalUserId");
- $u =& $objUsers->GetUser($logedin_user);
-
- //echo "
"; print_r($u); echo "
";
- if(!isset($online_friends) || $status=="online")
- {
- $ftable = GetTablePrefix()."Favorites";
- $stable = GetTablePrefix()."UserSession";
- $ptable = GetTablePrefix()."PortalUser";
- if(isset($online_friends))
- {
- foreach($online_friends as $id=>$name)
- {
- $u =& $objUsers->GetUser($id);
- $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
- }
- }
- else
- {
- $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
- $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- //echo $sql;
- $rs = $ado->Execute($sql);
- while($rs && ! $rs->EOF)
- {
- $u =& $objUsers->GetItem($rs->fields["PortalUserId"]);
- if($status=="online")
- {
- $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
- }
- $online_friends[]=$rs->fields["PortalUserId"];
- if(ADODB_EXTENSION>0)
- {
- adodb_movenext($rs);
- }
- else
- $rs->MoveNext();
- }
- }
- }
-
- if($status=="offline")
- {
- $ftable = GetTablePrefix()."Favorites";
- $stable = GetTablePrefix()."UserSession";
- $ptable = GetTablePrefix()."PortalUser";
-
- $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
- if(count($online_friends)>0)
- {
- $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
- $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- }
- else
- {
- $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- }
-
- //echo $sql;
- $rs = $ado->Execute($sql);
- while($rs && ! $rs->EOF)
- {
- $u = $objUsers->GetItem($rs->fields["PortalUserId"]);
- $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
- if(ADODB_EXTENSION>0)
- {
- adodb_movenext($rs);
- }
- else
- $rs->MoveNext();
- }
- }
- $t = $attribs["_itemtemplate"];
- return $o;
-}
-
-/*
- @description: Returns the number of users the current user has marked as 'friend'
- @attrib: _Status:: Determines which online status to count, either "online" or "offline".
-*/
-function m_friend_count($attribs=array())
-{
- global $objUsers, $objSession;
-
- global $online_friends;
-
- $ado = &GetADODBConnection();
-
- $logedin_user = $objSession->Get("PortalUserId");
- $u =& $objUsers->GetUser($logedin_user);
-
- $status = strtolower($attribs["_status"]);
- if(!isset($online_friends) || $status=="online")
- {
- $ftable = GetTablePrefix()."Favorites";
- $stable = GetTablePrefix()."UserSession";
- $ptable = GetTablePrefix()."PortalUser";
- if(isset($online_friends) && $status="online")
- {
- return count($online_friends);
- }
- else
- {
- $online_friends = array();
- $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
- $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- //echo $sql." \n";
- $rs = $ado->Execute($sql);
- while($rs && ! $rs->EOF)
- {
- $online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"];
- if(ADODB_EXTENSION>0)
- {
- adodb_movenext($rs);
- }
- else
- $rs->MoveNext();
- }
- if($status=="online")
- return count($online_friends);
- }
- }
-
- if($status=="offline")
- {
- $ftable = GetTablePrefix()."Favorites";
- $stable = GetTablePrefix()."UserSession";
- $ptable = GetTablePrefix()."PortalUser";
-
- $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
-
- if(count($online_friends)>0)
- {
- $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
- $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- }
- else
- {
- $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
- $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
- }
- $rs = $ado->Execute($sql);
- return $rs->fields["ItemCount"];
- }
-}
-
-/*
- @description: Returns the number of users the current user has marked as 'friend' today
-*/
-function m_friend_count_today($attribs)
-{
- global $objSession;
-
- $logedin_user = $objSession->Get("PortalUserId");
-
- $ret =0;
- $ado = &GetADODBConnection();
- $today = mktime(0,0,0,date("m"),date("d"),date("Y"));
- $sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today";
- $rs = $ado->Execute($sql);
- if($rs && !$rs->EOF)
- $ret = $rs->fields["c"];
- return $ret;
-}
-
-/*
- @description: Returns the number of items in a search result
-
- @Example: ()
-*/
-function m_search_item_count($attribs)
-{
- global $objItemTypes, $objCatList, $objSession, $CountVal;
-
- if(!is_array($CountVal))
- $CountVal=array();
- $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
- if(is_object($item))
- {
- $val = $CountVal[$item->Get("ItemType")];
- if(is_numeric($val))
- return $val;
- $where = "ItemType=".$item->Get("ItemType");
- $table = $objSession->GetSearchTable();
- $ret = TableCount($table,$where,0);
- $CountVal[$item->Get("ItemType")]=(int)$ret;
- }
-
- return $ret;
-}
-/*
- @description: Returns the number of categories in a search result
- @Example: ()
-*/
-function m_search_cat_count($attribs = array())
-{
- global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats;
-
- if(!is_object($objSearchCats))
- {
- $objSearchCats = new clsCatList();
- $objSearchCats->SourceTable = $objSession->GetSearchTable();
- $objSearchCats->Clear();
- }
-
- LoadCatSearchResults($attribs);
- //echo "
"; print_r($objSearchCats->Items); echo "
";
- $ret = 0;
- $keywords = $objSession->GetVariable("Search_Keywords");
-
- if ($keywords) {
- foreach ($objSearchCats->Items as $cat) {
-
- if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords))) {
- $ret++;
- }
- }
- }
- else {
- $ret = $objSearchCats->QueryItemCount;
- }
-
- if ($ret == '') {
- $ret = 0;
- }
-
- //echo $ret;
- //$objSearchCats->QueryItemCount = $ret;
-
- return $ret;
-}
-
-/*
- @description: Returns super global variable by type and name
- @attrib: _Name:: Name of variable
- @attrib: _Type:: Type super global variable Possible Values:
-
-
get: $_GET super variable
-
post: $_POST super variable
-
cookie: $_COOKIE super variable
-
env: $_ENV super variable
-
server: $_SERVER super variable
-
session: $_SESSION super variable
-
- @Example:
-*/
-function m_get_var($attribs = array())
-{
- global $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_SERVER, $_SESSION;
-
- $type = strtolower($attribs['_type']);
- $name = $attribs['_name'];
-
- switch ($type)
- {
- case "get":
- $vars = $_GET;
- break;
- case "cookie":
- $vars = $_COOKIE;
- break;
- case "files":
- $vars = $_FILES;
- break;
- case "server":
- $vars = $_SERVER;
- break;
- case "session":
- $vars = $_SESSION;
- break;
- case "env":
- $vars = $_ENV;
- break;
- case "post":
- $vars = $_POST;
- break;
- default :
- $vars = $_POST;
- break;
- }
- $ret = $vars[$name];
-
- return $ret;
-}
-
-/*
- @description: Returns number of users currently on-line
- @attrib: _LastActive:: Last user/session activity in seconds
- @attrib: _OwnCount:bool: Count user's own session
-*/
-function m_users_online($attribs = array())
-{
- global $objSession;
-
- $LastActive = (int)($attribs['_lastactive']);
- $OwnCount = (int)($attribs['_owncount']);
-
- if ($LastActive && !is_null($LastActive))
- $sql_add = " AND LastAccessed>".(time()-$LastActive);
-
- if (!$OwnCount || is_null($OwnCount))
- $sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'";
-
- $ado = &GetADODBConnection();
- $sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add;
- $rs = $ado->Execute($sql);
- $ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0;
-
- return $ret;
-}
-
-function m_debug_mode($attribs = array())
-{
- $const_name = $attribs['_debugconst'];
- return defined($const_name) && (constant($const_name) == 1) ? 'yes' : '';
-}
-
-function m_info($attribs = array())
-{
- switch ($attribs['_infotype'])
- {
- case 'site':
- global $objConfig;
- $ret = ThisDomain().$objConfig->Get('Site_Path');
- break;
-
- default:
- $ret = '';
- break;
- }
- return $ret;
-}
-
-function m_module_enabled($attribs = array())
-{
- global $objModules;
- $module = $attribs['_module'];
-
- // check if module is installed
- $ModuleItem = $objModules->GetItemByField('Name', $module);
- if( !is_object($ModuleItem) ) return '';
-
- // module is enabled
- $ret = $ModuleItem->Get('Loaded') == 1;
-
- // check if installed module is licensed
- return $ret && _ModuleLicensed($module) ? 'yes' : '';
-}
-
-function m_recall($attribs = array())
-{
- global $objSession;
- return $objSession->GetVariable($attribs['_name']);
-}
-
-?>
+";print_r($pieces);echo "";
+ $m_var_list["cat"] = $pieces[0];
+ $m_var_list["p"] = $pieces[1];
+ $objCatList->Page = $m_var_list["p"];
+
+ $m_var_list["lang"] = $pieces[2];
+ $m_var_list["theme"] = $pieces[3];
+ }
+ else
+ {
+ $m_var_list["cat"]=0;
+ $m_var_list["p"] = 1;
+ $m_var_list["lang"] = $objLanguages->GetPrimary();
+ $m_var_list["theme"]= $objThemes->GetPrimaryTheme();
+ }
+}
+
+function m_BuildEnv()
+{
+ global $m_var_list, $m_var_list_update;
+ $module_vars = Array('cat','p','lang','theme');
+ $ret = GenerateModuleEnv('m', $module_vars);
+ if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']);
+ return $ret;
+}
+
+function m_GetVar($name)
+{
+ // get variable from template variable's list
+ global $m_var_list, $m_var_list_update;
+ return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name];
+}
+
+function &LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId)
+{
+ global $objItemTypes;
+
+ if(!is_object($Relations))
+ {
+ $Relations = new clsRelationshipList();
+ }
+ //$Relations->debuglevel = 2;
+ if ($ResourceId != '') {
+ $sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority,
+ IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId,
+ IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId,
+ IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType,
+ IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType
+ FROM %%s", $ResourceId);
+
+ $where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1";
+ $Relations->LoadRelated($where,"",$sql);
+ $ids = array();
+ if($Relations->NumItems()>0)
+ {
+ foreach($Relations->Items as $r)
+ {
+ if($r->Get("SourceId")==$ResourceId)
+ {
+ $ids[$r->Get("TargetType")][] = $r->Get("TargetId");
+ }
+ if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1)
+ {
+ $ids[$r->Get("SourceType")][] = $ResourceId;
+ }
+ }
+ foreach($ids as $ItemType=>$idlist)
+ {
+ $Item =& $objItemTypes->GetItem($ItemType);
+ $table = GetTablePrefix().$Item->Get("SourceTable");
+ if($ItemType!=1)
+ {
+ $cattable = GetTablePrefix()."CategoryItems";
+ $sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON ";
+ $sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 ";
+ $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
+ }
+ else
+ {
+ $sql = "SELECT *,CategoryId FROM $table ";
+ $sql .="WHERE $table.Status=1 ";
+ $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
+ }
+ // echo $sql." \n";
+ $RelatedItems->Query_Item($sql,-1,-1,$ItemType);
+ }
+ }
+ }
+}
+
+
+/*
+ @description: Inserts the html from a remote source
+ @attrib: _url:: Remote URL to include
+ @attrib: _StartPos:: Numeric start point of text to include, or string match
+ @attrib: _EndPos:: Numeric end point of text to include, or string match
+ @example:
+*/
+function m_insert_url($attribs=array())
+{
+ global $pathtoroot;
+
+ $url = $attribs["_url"];
+ $StartPos = $attribs["_startpos"];
+ $EndPos = $attribs["_endpos"];
+
+ $socket = new Socket($url,0,NULL);
+ $txt = $socket->socket_read_all();
+ $lines = explode("\n",$txt);
+ $txt = substr($txt,strpos($txt,"<"));
+ $tmp = strtolower($txt);
+ $bodypos = strpos($tmp,"0)
+ {
+ $head = substr($txt,0,$bodypos-1);
+ $body = substr($txt,$bodypos);
+ if(substr($tmp,-7)=="")
+ $body = substr($body,0,-7);
+ }
+ else
+ $body = $txt;
+ if(strlen($body))
+ {
+ if(strlen($StartPos))
+ {
+ if(!is_numeric($StartPos))
+ {
+ $start = strpos($body,$StartPos);
+ }
+ else
+ $start = (int)$StartPos;
+ }
+ else
+ $start = 0;
+ if(strlen($EndPos))
+ {
+ if(!is_numeric($EndPos))
+ {
+ $end = strpos($body,$EndPos,$start) + strlen($EndPos);
+ }
+ else
+ $end = (int)$EndPos;
+ }
+ else
+ $end = NULL;
+ $o = substr($body,$start,$end-$start);
+ }
+ return $o;
+}
+
+/*
+ @description: Displays a template depending on the login status of the user
+ @attrib: _logintemplate:tpl: template to display when the user is NOT logged in
+ @attrib: _LoggedinTemplate:tpl: template to display when the user is logged in
+ @example:
+*/
+function m_loginbox($attribs = array())
+{
+ global $var_list, $objSession, $objUsers, $objTemplate;
+
+ $userid = $objSession->Get("PortalUserId");
+ $groupid = $objSession->Get("GroupId");
+ if ($userid == 0)
+ {
+ if (strlen($attribs["_logintemplate"]))
+ $t = $objTemplate->ParseTemplate($attribs["_logintemplate"]);
+ return $t;
+ }
+ else
+ {
+ $user =& $objUsers->GetItem($userid);
+ if (strlen($attribs["_loggedintemplate"]))
+ $t = $user->ParseTemplate($attribs["_loggedintemplate"]);
+ return $t;
+ }
+}
+/*
+ @description: result of suggest site action
+*/
+function m_suggest_result()
+{
+ global $suggest_result;
+
+ return $suggest_result;
+}
+
+/*
+ @description: result of subscribe to mailing list action
+*/
+function m_subscribe_result()
+{
+ global $SubscribeResult;
+
+ if(strlen($SubscribeResult))
+ return language($SubscribeResult);
+ return "";
+}
+
+/*
+ @description: email address of user subscribing to mailing list
+*/
+function m_subscribe_address()
+{
+ global $SubscribeAddress;
+
+ if(strlen($SubscribeAddress))
+ return $SubscribeAddress;
+ return "";
+}
+
+/*
+ @description: Error message of subscribe to mailing list action
+*/
+function m_subscribe_error()
+{
+ global $SubscribeError;
+
+ if(strlen($SubscribeError))
+ return language($SubscribeError);
+ return "";
+}
+
+
+/*
+ @description: Displays a prompt for a form field
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _LangText:lang: Language var to use for field label
+ @attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set)
+ @attrib: _Template:tpl: template used to display the field label (if not set "" is used
+ @attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set
+*/
+function m_form_prompt($attribs = array())
+{
+ global $FormError, $objTemplate, $objConfig;
+
+ $form = strtolower($attribs["_form"]);
+ $field = strtolower($attribs["_field"]);
+
+ if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
+ {
+ $o = "";
+ }
+ else
+ {
+ $t = $attribs["_template"];
+ if(!strlen($t))
+ {
+ $templateText = "";
+ }
+ $e = $attribs["_errortemplate"];
+ if(!strlen($e))
+ $e = $t;
+ if(strlen($attribs["_langtext"]))
+ {
+ $txt = language($attribs["_langtext"]);
+ }
+ else
+ $txt = $attribs["_plaintext"];
+
+ if (strtolower($field) == "dob")
+ {
+ if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")]))
+ $rawtext = $objTemplate->GetTemplate($e, true);
+ }
+
+ if(isset($FormError[strtolower($form)][strtolower($field)]))
+ {
+ $rawtext = $objTemplate->GetTemplate($e);
+ }
+ elseif (strlen($t))
+ $rawtext = $objTemplate->GetTemplate($t);
+
+ if(is_object($rawtext))
+ {
+ $src = $rawtext->source;
+ $o = str_replace("",$txt, $src);
+ }
+ else
+ $o = str_replace("", $txt, $templateText);
+
+ }
+ return $o;
+}
+
+/*
+ @description: Returns text if system is configured to use auto-generated passwords
+ @attrib:_LangText:lang:Language tag to return
+ @attrib:_PlainText::Plain text to return (_LangText takes precedece)
+ @attrib:_Value:bool:Auto Password setting value to match
+*/
+function m_autopassword($attribs = array())
+{
+ global $objConfig;
+ if($attribs["_value"]=="true" || $attribs["_value"]==1)
+ {
+ $IsAuto = $objConfig->Get("User_Password_Auto");
+ }
+ else
+ {
+ $IsAuto = !$objConfig->Get("User_Password_Auto");
+ }
+
+ if($IsAuto)
+ {
+ if(strlen($attribs["_langtext"]))
+ {
+ $ret = language($attribs["_langtext"]);
+ }
+ else
+ $ret = $attribs["_plaintext"];
+ if(!$ret)
+ return "true";
+ }
+ return $ret;
+}
+
+/*
+ @description: checks if field specified is equals to value specified
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Value:: Field value to compare to
+ @example: true
+*/
+function m_field_equals($attribs = array())
+{
+ global $FormValues;
+ //print_pre($attribs);
+ $form = $attribs["_form"];
+ $field = $attribs["_field"];
+ if(isset($_POST[$field]))
+ {
+ $value = $_POST[$field];
+ }
+ else
+ $value = $FormValues[$form][$field];
+ //echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."] ";
+ return $value == $attribs['_value'] ? 1 : '';
+}
+
+/*
+ @description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _ForgetValue:bool: if true, forget value
+ @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
+ @example:
+*/
+function m_form_input($attribs = array())
+{
+ global $FormValues, $objConfig;
+
+ $html_attribs = ExtraAttributes($attribs);
+ $form = $attribs["_form"];
+ $field = strtolower($attribs["_field"]);
+ if(isset($_POST[$field]) && $attribs['_forgetvalue'] != 1)
+ {
+ $value = inp_htmlize($_POST[$field],1);
+ }
+ else {
+ if ($attribs['_forgetvalue'] != 1) {
+ $value = $FormValues[$form][$field];
+ }
+ }
+ //echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']." \n";
+ if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
+ {
+ $ret = "";
+ }
+ else
+ {
+ $ret = "";
+ if($attribs["_required"])
+ $ret .= "";
+ if($attribs["_custom"])
+ $ret .= "";
+ }
+ return $ret;
+}
+
+/*
+ @description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Value:bool: If true, the radio button is CHECKED
+ @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
+ @attrib: _Custom:bool: If set, handled as a custom field
+ @example:
+*/
+function m_form_checkbox($attribs = array())
+{
+ global $FormValues, $objConfig;
+
+ $html_attribs = ExtraAttributes($attribs);
+ $form = $attribs["_form"];
+ $field = strtolower($attribs["_field"]);
+ if(isset($_POST[$field]))
+ {
+ $value = (int)$_POST[$field];
+ if($value==1)
+ $checked = " CHECKED";
+ }
+ else
+ {
+ $value = (int)$FormValues[$form][$field];
+ if($value==1)
+ $checked=" CHECKED";
+ }
+ //echo $form.".".$field."=".$value." \n";
+ $ret = "";
+ if($attribs["_required"])
+ $ret .= "";
+ if($attribs["_custom"])
+ $ret .= "";
+
+ return $ret;
+}
+
+/*
+ @description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED
+ @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
+ @attrib: _Custom:bool: If set, handled as a custom field
+ @example:
+*/
+function m_form_radio($attribs = array())
+{
+ global $FormValues, $objConfig;
+
+ $html_attribs = ExtraAttributes($attribs);
+ $form = $attribs["_form"];
+ $field = strtolower($attribs["_field"]);
+ $val = $attribs["_value"];
+ if(isset($_POST[$field]))
+ {
+ $value = (int)$_POST[$field];
+ if($value==1)
+ $checked = " CHECKED";
+ }
+ else
+ {
+ $value = (int)$FormValues[$form][$field];
+ if($value==$val)
+ $checked=" CHECKED";
+ }
+ //echo $form.".".$field."=".$value." \n";
+ $ret = "";
+ if($attribs["_required"])
+ $ret .= "";
+ if($attribs["_custom"])
+ $ret .= "";
+
+ return $ret;
+}
+/*
+ @description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition)
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @example:
+*/
+function m_form_value($attribs = array())
+{
+ global $FormValues;
+
+ $form = $attribs["_form"];
+ $field = strtolower($attribs["_field"]);
+
+ if(isset($_POST[$field]))
+ {
+ $value = inp_htmlize($_POST[$field],1);
+ }
+ else
+ $value = inp_htmlize($FormValues[$form][$field]);
+ //echo "
"; print_r($FormValues); echo "
";
+ return $value;
+}
+
+/*
+ @description: creates an form OPTION tag for a form SELECT tag.
+ All extra attributes are passed to the OPTION tag.
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select
+ field is the same as this attribute, then this option will be set SELECTED.
+ @attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown
+ @attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext)
+ @example: $txt";
+
+ return $o;
+}
+
+/*
+ @description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
+ @attrib: _Custom:bool: If set, handled as a custom field
+ @example:
+*/
+function m_form_textarea($attribs = array())
+{
+ global $FormValues;
+ $html_attribs = ExtraAttributes($attribs);
+ $field = $attribs["_field"];
+ $form = $attribs["_form"];
+ if(isset($_POST[$field]))
+ {
+ $value = stripslashes($_POST[$field]);
+ }
+ else
+ $value = stripslashes($FormValues[$attribs["_form"]][$field]);
+ $ret = "";
+ if($attribs["_required"])
+ $ret .= "";
+ if($attribs["_custom"])
+ $ret .= "";
+ return $ret;
+}
+
+/*
+ @description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+ @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
+ @attrib: _ImageTypes:: Comma-separated list of file extensions allowed
+ @attrib: _Thumbnail:bool: If true, image is treated as a thumbnail
+ @attrib: _ImageName:: System name of image being uploaded
+ @attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all
+*/
+function m_form_imageupload($attribs = array())
+{
+ $html_attribs = ExtraAttributes($attribs);
+ $field = $attribs["_field"];
+ $form = $attribs["_form"];
+ $TypesAllowed = $attribs["_imagetypes"];
+ $isthumb = (int)$attribs["_thumbnail"];
+ $imgname = $attribs["_imagename"];
+ $maxsize = $attribs["_maxsize"];
+
+ $ret = "";
+ $ret .= "";
+ $ret .= "";
+ $ret .= "";
+ $ret .= "";
+ if($attribs["_required"])
+ $ret .= "";
+ return $ret;
+}
+
+/*
+ @description: Returns the error text for a form field, or nothing if no error exists for the field
+ @attrib: _Form:: Form name for the field
+ @attrib: _Field:: Field Name
+*/
+function m_form_error($attribs = array())
+{
+ global $FormError;
+
+ $form = $attribs["_form"];
+ $field = $attribs["_field"];
+
+ return $FormError[$form][$field];
+}
+
+/**
+ @description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable.
+ @attrib: _Form:: Form name for the field
+*/
+function m_form_has_errors($attribs = array())
+{
+ // shows specified template once if form has error(-s)
+ global $FormError;
+ $f = $attribs["_form"];
+
+ $ret = is_array($FormError[$f]);
+ if(!$ret) return '';
+ return isset($attribs["_asif"]) ? true : language('lu_errors_on_form');
+}
+
+/**
+ @description: Lists form errors for all fields in a form
+ @attrib: _Form:: Form name for the field
+ @attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "" is used)
+*/
+function m_list_form_errors($attribs = array())
+{
+ global $FormError, $content_set, $objTemplate;
+
+ $t = $attribs["_itemtemplate"];
+ if(!strlen($t))
+ $templateText = "";
+ $f = $attribs["_form"];
+ $o = "";
+ if (strlen($t))
+ {
+ $rawtext = $objTemplate->GetTemplate($t, true);
+ $src = $rawtext->source;
+ }
+ else
+ $src = $templateText;
+
+ //echo $f." ";
+ //echo $t." ";
+// echo "
"; print_r($FormError); echo "
";
+ if(is_array($FormError[$f]))
+ {
+ foreach($FormError[$f] as $e)
+ {
+ $o .= str_replace("",$e, $src);
+ }
+ }
+ if(!strlen($o))
+ $content_set = 0;
+ return $o;
+}
+
+function m_form_load_values($FormName,$IdValue)
+{
+ global $FormValues, $objUsers, $objSession, $objConfig;
+
+ switch($FormName)
+ {
+ case "m_acctinfo":
+ $u =& $objUsers->GetItem($IdValue);
+ $FormValues[$FormName]["username"] = $u->Get("Login");
+ //$FormValues[$FormName]["password"] = $u->Get("Password");
+ //$FormValues[$FormName]["passwordverify"] = $u->Get("Password");
+
+ $FormValues[$FormName]["password"] = "";
+ $FormValues[$FormName]["passwordverify"] = "";
+
+ $FormValues[$FormName]["firstname"] = $u->Get("FirstName");
+ $FormValues[$FormName]["lastname"] = $u->Get("LastName");
+ $FormValues[$FormName]["email"] = $u->Get("Email");
+ $FormValues[$FormName]["phone"] = $u->Get("Phone");
+ $FormValues[$FormName]["street"] = $u->Get("Street");
+ $FormValues[$FormName]["city"] = $u->Get("City");
+ $FormValues[$FormName]["state"] = $u->Get("State");
+ $FormValues[$FormName]["zip"] = $u->Get("Zip");
+ $FormValues[$FormName]["country"] = $u->Get("Country");
+
+// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob"));
+ $FormValues[$FormName]["dob_day"] = date("d", $u->Get("dob"));
+ $FormValues[$FormName]["dob_year"] = date("Y", $u->Get("dob"));
+ $FormValues[$FormName]["dob_month"] = date("m", $u->Get("dob"));
+
+ $u->LoadCustomFields();
+ if(is_array($u->CustomFields->Items))
+ {
+ foreach($u->CustomFields->Items as $f)
+ {
+ $FormValues[$FormName][$f->Get("FieldName")] = $f->Get("Value");
+ }
+ }
+ break;
+ case "m_profile":
+ $u =& $objUsers->GetItem($IdValue);
+ if(is_object($u))
+ {
+ $FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname");
+ $FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname");
+ $FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob");
+ $FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email");
+ $FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone");
+ $FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street");
+ $FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city");
+ $FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state");
+ $FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip");
+ $FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country");
+ }
+ break;
+ case "m_simplesearch":
+ $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
+ break;
+ case "m_simple_subsearch":
+ $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
+ break;
+
+ }
+}
+
+/*
+ @description: Generates the ACTTION property for a FORM tag used by In-Portal
+ @attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template)
+ @attrib: _Form:: The form name Possible Values:
+
+
login: user login
+
logout: user logout
+
forgotpw: Form to prompt the user for forgotten password information
+
forgotpw_confirm: confirmation form for forgotpw
+
suggest: form to suggest the site to a friend
+
suggest_confirm: form to confirm suggestion of the site to a friend
+
m_subscribe: form to subscribe to the mailing list
+
subscribe_confirm: form to confirm subscription to the mailing list
+
m_unsubscribe: form to unsubscribe from the mailing list
+
unsubscribe_confirm: form to confirm un-subscription from the mailing list
+
m_acctinfo: user account information
+
m_profile: system-level profile information
+
m_register: New User registration form
+
m_addcat: Suggest Category form
+
m_addcat_confirm: Confirmation for add category
+
m_simplesearch: Perform a simple search
+
m_simple_subsearch: Search within results
+
m_adv_searchtype: Form to select type of advanced search
+
m_adv_subsearch: Advanced Search
+
error_access: form displayed on the access denied template
+
error_template: Form displayed on the template error page
+
m_set_theme: Form displayed for theme selection
+
+ @attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed.
+ @attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed.
+ @attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed.
+ @attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed.
+ @attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error.
+ @attrib: _Referer:bool: The destination template will be taken from referer page we can from.
+
+ @example: ">
+*/
+function m_form_action($attribs = array())
+{
+ global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList;
+
+ $target_template = $attribs["_template"];
+ if(strlen($target_template))
+ {
+ $var_list_update["t"] = $target_template;
+ }
+ else
+ $var_list_update["t"] = $var_list["t"];
+
+ $ret = "";
+ $form = strtolower($attribs["_form"]);
+ switch($form)
+ {
+ case "login":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_login";
+ if($attribs["_successtemplate"])
+ {
+ $ret .= "&dest=".$attribs["_successtemplate"];
+ }
+ else
+ if(strlen($var_list["dest"]))
+ $ret .= "&dest=".$var_list["dest"];
+ }
+ break;
+ case "logout":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_logout";
+ break;
+ case "forgotpw":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ if(strlen($attribs["_errortemplate"]))
+ {
+ $err = $attribs["_errortemplate"];
+ }
+ else
+ $err = $var_list["t"];
+ $ret = GetIndexURL(2)."?env=".BuildEnv()."&Action=m_forgotpw&error=$err";
+ }
+ break;
+ case "forgotpw_confirm":
+ $ret = GetIndexURL(2)."?env=".BuildEnv();
+ break;
+ case "suggest":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_suggest_email";
+ if(strlen($attribs["_confirmtemplate"])>0)
+ {
+ $ret .= "&Confirm=".$attribs["_confirmtemplate"];
+ }
+ if(strlen($Dest))
+ {
+ $ret .= "&DestTemplate=$Dest";
+ }
+ else
+ {
+ if(strlen($attribs["_confirmtemplate"])>0)
+ $ret .="&DestTemplate=".$var_list["t"];
+ }
+
+ if(strlen($attribs["_errortemplate"])>0)
+ {
+ $ret .= "&Error=".$attribs["_errortemplate"];
+ }
+ }
+ break;
+ case "suggest_confirm":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ if(strlen($_GET["DestTemplate"]))
+ {
+ $var_list_update["t"] = $_GET["DestTemplate"];
+ }
+ else
+ $var_list_update["t"] = "index";
+
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ break;
+ case "m_subscribe":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe_confirm";
+ if(strlen($attribs["_subscribetemplate"]))
+ {
+ $ret .="&Subscribe=".$attribs["_subscribetemplate"];
+ }
+
+ if(strlen($attribs["_unsubscribetemplate"])>0)
+ {
+ $ret .= "&Unsubscribe=".$attribs["_unsubscribetemplate"];
+ }
+ if(strlen($attribs["_errortemplate"])>0)
+ {
+ $ret .= "&Error=".$attribs["_errortemplate"];
+ }
+ }
+ break;
+
+ case "subscribe_confirm":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe";
+ if($attribs["_subscribetemplate"])
+ $ret .= "&Subscribe=".$attribs["_subscribetemplate"];
+ break;
+ case "unsubscribe_confirm":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe";
+ if($attribs["_subscribetemplate"])
+ $ret .= "&Subscribe=".$attribs["_subscribetemplate"];
+ break;
+ case "m_unsubscribe":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe";
+ if(strlen($attribs["_confirmtemplate"])>0)
+ {
+ $ret .= "&Confirm=".$attribs["_confirmtemplate"];
+ }
+ if(strlen($Dest))
+ {
+ $ret .= "&DestTemplate=$Dest";
+ }
+ else
+ {
+ if(strlen($attribs["_confirmtemplate"])>0)
+ $ret .="&DestTemplate=".$var_list["t"];
+ }
+ }
+
+ if(strlen($attribs["_confirmtemplate"])>0)
+ {
+ $ret .="&ErrorTemplate=".$attribs["_confirmtemplate"];
+ }
+
+
+ break;
+ case "m_unsubscribe_confirm":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ break;
+ case "m_acctinfo":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_acctinfo&UserId=".$objSession->Get("PortalUserId");
+ m_form_load_values($form, $objSession->Get("PortalUserId"));
+ break;
+ case "m_profile":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_profile&UserId=".$objSession->Get("PortalUserId");
+ m_form_load_values($form,$objSession->Get("PortalUserId"));
+ break;
+
+ case "m_set_theme":
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_set_theme";
+ break;
+
+ case "m_register":
+
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_register";
+
+ switch ($objConfig->Get("User_Allow_New"))
+ {
+ case "1":
+ if(strlen($attribs["_confirmtemplate"]) && $objConfig->Get("User_Password_Auto"))
+ $_dest = "&dest=".$attribs["_confirmtemplate"];
+ else
+ $_dest = "&dest=".$attribs["_logintemplate"];
+ break;
+
+ case "2":
+ if(strlen($attribs["_notallowedtemplate"]))
+ $_dest = "&dest=".$attribs["_notallowedtemplate"];
+ break;
+
+ case "3":
+ if(strlen($attribs["_pendingtemplate"]))
+ $_dest = "&dest=".$attribs["_pendingtemplate"];
+ break;
+ }
+
+ if (strlen($_dest))
+ $ret .= $_dest;
+ }
+ break;
+
+ case "register_confirm":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ break;
+ case "m_addcat":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $action = "m_add_cat";
+ if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING"))
+ {
+ if(strlen($attribs["_confirmpending"]))
+ {
+ $ConfirmTemplate = $attribs["_confirmpending"];
+ }
+ else
+ $ConfirmTemplate = $attribs["_confirm"];
+ $action="m_add_cat_confirm";
+ }
+
+ if ($objSession->HasCatPermission("CATEGORY.ADD"))
+ {
+ $ConfirmTemplate = $attribs["_confirm"];
+ $action="m_add_cat_confirm";
+ }
+
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=$action";
+ if(strlen($ConfirmTemplate))
+ $ret .= "&Confirm=$ConfirmTemplate";
+
+ if (strlen($attribs["_mod_finishtemplate"])) {
+
+ $CurrentCat = $objCatList->CurrentCategoryID();
+ if((int)$CurrentCat>0)
+ {
+ $c = $objCatList->GetCategory($CurrentCat);
+
+ //will prefix the template with module template root path depending on category
+ $ids = $c->GetParentIds();
+ $tpath = GetModuleArray("template");
+ $roots = GetModuleArray("rootcat");
+
+ // get template path of module, by searching for moudle name
+ // in this categories first parent category
+ // and then using found moudle name as a key for module template paths array
+ $path = $tpath[array_search ($ids[0], $roots)];
+ $t = $path . $attribs["_mod_finishtemplate"];
+ }
+ else {
+ $t = $attribs["_mod_finishtemplate"]; //Just in case
+ }
+ }
+ else {
+ $t = $attribs["_finishtemplate"];
+ }
+
+ $ret .="&DestTemplate=".$t;
+ }
+ break;
+ case "m_addcat_confirm":
+ $target_template = $_GET["DestTemplate"];
+ if(strlen($target_template))
+ {
+ $var_list_update["t"] = $target_template;
+ }
+ else
+ $var_list_update["t"] = $var_list["t"];
+ $ret = GetIndexURL(2)."?env=".BuildEnv();
+ break;
+ case "m_simplesearch":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_search";
+
+ if(strlen($attribs["_errortemplate"]))
+ $ret.= "&Error=".$attribs["_errortemplate"];
+
+ m_form_load_values($form, 0);
+ }
+ break;
+ case "m_simple_subsearch":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_subsearch";
+ m_form_load_values($form,0);
+ }
+ break;
+ case "m_adv_search_type":
+ if(!$objSession->SessionEnabled())
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_advsearch_type";
+ m_form_load_values($form,0);
+ }
+ break;
+ case "m_adv_search":
+ $SearchType = $_GET["type"];
+ if(!is_numeric($SearchType))
+ $SearchType = $_POST["itemtype"];
+ if(!$objSession->SessionEnabled() && !strlen($SearchType))
+ {
+ $var_list_update["t"] = "error_session";
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ }
+ else
+ {
+ $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_adv_search&type=$SearchType";
+ m_form_load_values($form,0);
+ }
+ break;
+
+ case "error_access":
+ $target_template = $_GET["DestTemplate"];
+ if(!strlen($target_template))
+ $target_template="login";
+ $var_list_update["t"] = $target_template;
+
+ $ret = GetIndexURL(2)."?env=" . BuildEnv();
+ break;
+
+ case "error_template":
+
+ $target_template = $_GET["DestTemplate"];
+
+ if($attribs["_referer"] == 1)
+ {
+ $target_template = "_referer_";
+ }
+ elseif (!strlen($target_template))
+ {
+ $target_template = "index";
+ }
+
+ $var_list_update["t"] = $target_template;
+
+// $m_var_list_update["cat"]=0;
+
+ $ret = GetIndexURL(2)."?env=".BuildEnv();
+
+ break;
+
+ }
+ return $ret;
+}
+
+/*
+ @description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link
+
+*/
+function m_logout_link($attribs)
+{
+ $ret = m_template_link($attribs)."&Action=m_logout";
+ return $ret;
+}
+
+/*
+ @description: returns a URL to the current theme
+ @attrib: _page:: Additional address to be added to the end of the theme URL
+*/
+function m_theme_url($attribs=array())
+{
+ global $objConfig,$objSession, $objThemes, $CurrentTheme;
+
+ if(!is_object($CurrentTheme))
+ $CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
+
+ $theme_url = "http://". ThisDomain().$objConfig->Get("Site_Path")."themes/".$CurrentTheme->Get("Name")."/";
+ if($attribs["_page"])
+ {
+ if ($attribs["_page"] != 'current')
+ {
+ $theme_url .= $attribs["_page"];
+ }
+ else
+ {
+ $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
+ }
+ }
+ return $theme_url;
+}
+
+/*
+ @description: returns a URL to the current theme
+*/
+function m_current_page_url($attribs=array())
+{
+ global $objConfig,$objSession;
+
+ $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
+
+ return $theme_url;
+}
+
+/*
+ @description: returns a URL to the current theme
+ @attrib: _fullpath:bool: Append the title with the full path of the current category
+ @attrib: _currentcategory:bool: Append the title with the current category
+ @attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name
+*/
+function m_page_title($attribs = array())
+{
+ global $objConfig, $objCatList;
+
+ $ret = $objConfig->Get("Site_Name");
+ if($attribs["_fullpath"] || $attribs["_currentcategory"])
+ {
+ $CurrentCat = $objCatList->CurrentCategoryID();
+ if((int)$CurrentCat>0)
+ {
+ $c = $objCatList->GetCategory($CurrentCat);
+ if($attribs["_fullpath"])
+ {
+ $path = $c->Get("CachedNavbar");
+
+ if(strlen($path))
+ $ret .= " - ".$path;
+ }
+ else
+ {
+ if($attribs["_currentcategory"])
+ {
+ $f = $attribs["_catfield"];
+ if(!strlen($f))
+ $f = "Name";
+ $ret .= " - ".$c->Get($f);
+ }
+ }
+ }
+ }
+ $ret = stripslashes($ret);
+ return $ret;
+}
+
+/*
+ @description: list all active themes
+ @attrib: _ItemTemplate:tpl: Template to display each theme in the list
+*/
+function m_list_themes($attribs=array())
+{
+ global $objThemes;
+
+ $t = $attribs["_itemtemplate"];
+ if(strlen($t))
+ {
+ $objThemes->Clear();
+ $objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC");
+
+ foreach($objThemes->Items as $theme)
+ {
+ $o .= $theme->ParseTemplate($t);
+ }
+ }
+ return $o;
+}
+
+/*
+ @description: display text based on the user's language
+ @attrib: _Phrase:lang: label to replace with language-specific text
+ @example:
+*/
+function m_language($attribs)
+{
+ global $objSession, $objLanguages, $ForceLanguage;
+
+ $phrase = $attribs["_phrase"];
+ $LangId = (int)$ForceLanguage;
+ if(strlen($phrase))
+ {
+ $lang = $attribs["_language"];
+ if(strlen($lang))
+ {
+ $l = $objLanguages->GetItemByField("PackName",$lang);
+ if(is_object($l))
+ {
+ $LangId = $l->Get("LanguageId");
+ }
+ }
+ return language($phrase,$LangId);
+ }
+ else
+ return "";
+}
+
+/*
+ @description: Creates a URL used to set the current language for a user
+ @attrib: _language:: Language to set (this value should be the language Pack Name)
+*/
+function m_setlang_link($attribs)
+{
+ global $m_var_list_update, $objSession,$objLanguages;
+
+ $lang = $attribs["_language"];
+ if(strlen($lang))
+ {
+ $l = $objLanguages->GetItemByField("PackName",$lang);
+ if(is_object($l))
+ $LangId = $l->Get("LanguageId");
+ }
+ else
+ $LangId=$objSession->Get("Language");
+ if($LangId)
+ {
+ $m_var_list_update["lang"] = $LangId;
+ $ret = GetIndexURL()."?env=".BuildEnv();
+ unset($m_var_list_update["lang"]);
+ }
+ else
+ $ret = "";
+ return $ret;
+}
+
+/*
+ @description: list all active languages
+ @attrib: _ItemTemplate:tpl: Template to display each language in the list
+*/
+function m_list_languages($attribs)
+{
+ global $objLanguages, $content_set;
+
+ $sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1";
+ $objLanguages->Clear();
+ $objLanguages->Query_Item($sql);
+
+ if($objLanguages->NumItems()>0)
+ {
+ foreach($objLanguages->Items as $l)
+ $o .= $l->ParseTemplate($attribs["_itemtemplate"]);
+ }
+ else
+ $content_set=0;
+ return $o;
+}
+
+/*
+ @description: returns the date format for a language
+ @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
+*/
+function m_lang_dateformat($attribs=array())
+{
+ global $objLanguages, $objSession;
+
+ $lang = $attribs["_lang"];
+ if(!strlen($lang))
+ {
+ $LangId = $objSession->Get("Language");
+ $l = $objLanguages->GetItem($LangId);
+ }
+ else
+ {
+ $l = $objLanguages->GetItemByField("PackName",$lang);
+ }
+ $fmt = GetDateFormat($LangId);
+ $fmt = GetStdFormat($fmt);
+
+ return $fmt;
+}
+
+/*
+ @description: returns a language field value
+ @attrib: _Field:: Language field to return
+ @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
+*/
+function m_lang_field($attribs = array())
+{
+ global $objLanguages, $objSession;
+
+ if(!strlen($attribs["_field"]))
+ return "";
+ $lang = $attribs["_lang"];
+ if(!strlen($lang))
+ {
+ $LangId = $objSession->Get("Language");
+ $l = $objLanguages->GetItem($LangId);
+ }
+ else
+ {
+ $l = $objLanguages->GetItemByField("PackName",$lang);
+ }
+ if(is_object($l))
+ {
+ //$ret = $l->Get($attribs["_field"]);
+ $e = new clsHtmlTag();
+ $e->name=$l->TagPrefix;
+ $e->attributes=$attribs;
+ $ret = $l->ParseObject($e);
+ }
+ return $ret;
+}
+
+/*
+ @description: Creates a URL used to set the current theme for a user
+ @attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index"
+*/
+function m_settheme_link($attribs)
+{
+ global $m_var_list_update, $objSession, $objThemes, $CurrentTheme;
+
+ $ThemeName = $attribs["_theme"];
+
+ if(strlen($ThemeName))
+ {
+ $t = $objThemes->GetItemByField("Name",$ThemeName);
+ if(is_object($t))
+ {
+ $Id = $t->Get("ThemeId");
+ }
+ else
+ $Id = 0;
+ }
+ else
+ {
+ $t = $CurrentTheme;
+ $Id = 0;
+ }
+ $m_var_list_update["theme"] = $Id;
+ $ret = GetIndexURL()."?env=".BuildEnv();
+ unset($m_var_list_update["theme"]);
+ return $ret;
+}
+
+/*
+ @description: Initializes categories
+*/
+function m_init_cats($attribs = array())
+{
+ // save current & previous category (used in pagination)
+ global $objSession, $objCatList;
+ global $var_list;
+ //echo "SID_INIT: ".$var_list["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].') ';
+ $objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') );
+ $objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() );
+
+ //$last_cat = $objSession->GetVariable('last_category');
+ //$prev_cat = $objSession->GetVariable('prev_category');
+ //echo "Last CAT: [$last_cat] ";
+ //echo "Prev CAT: [$prev_cat] ";
+}
+
+/*
+ @description: List all subcategories a user is allowed to view
+ @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
+ @attrib: _maxlistcount:int: Maximum number of categories to list
+ @attrib: _FirstItemTemplate:tpl: Template used for the first category listed
+ @attrib: _LastItemTemplate:tpl: Template used for the last category listed
+ @attrib: _ItemTemplate:tpl: default template used for category list items
+ @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
+ @example:
+*/
+function m_list_cats($attribs = array())
+{
+ global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache;
+
+ $CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv());
+ if(strlen($CachedList))
+ {
+ return $CachedList;
+ }
+ $cols = $attribs["_columns"];
+ if($cols<1)
+ $cols =1;
+ $CategoryId = $attribs["_catid"];
+ if(!is_numeric($CategoryId))
+ $CategoryId = $objCatList->CurrentCategoryID();
+
+ $cat_count = (int)$attribs["_maxlistcount"];
+ /* validation */
+ if(strlen($attribs["_itemtemplate"])==0)
+ {
+ if($attribs["dataexists"])
+ $content_set = 0;
+ return "";
+ }
+
+ $GroupList = $objSession->Get("GroupList");
+ if(strlen($GroupList))
+ {
+ $Groups = explode(",",$GroupList);
+ }
+ $acl_where = "";
+ if(@count($Groups)>0 && is_array($Groups))
+ {
+ $acl_where = array();
+ for($i=0;$iClear();
+ $OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
+ $objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy);
+ if ($objCatList->NumItems() == 0)
+ {
+ if($attribs["_dataexists"])
+ $content_set = 0;
+ return "";
+ }
+
+ $html_attr = ExtraAttributes($attribs);
+
+ $o="";
+ $notable = $attribs["_notable"];
+
+ $count=0;
+ $row=0;
+ $var_list_update["t"] = $var_list["t"];
+
+ if(!$notable)
+ {
+ $per_row = ceil($objCatList->NumItems()/$cols);
+ $o = "
\n";
+ }
+ else
+ {
+ $CatCount = $objCatList->NumItems();
+ foreach($objCatList->Items as $cat)
+ {
+ if($cat->Get("ParentId")==$CategoryId)
+ {
+
+ if($row==0 && strlen($attribs["_firstitemtemplate"]))
+ {
+ //echo 'Saving ID in m_sub_cats[ first ] '.$cat->UniqueId().' ';
+ //$GLOBALS['cat_ID'] = $cat->UniqueId();
+ $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
+ $parsed=1;
+ }
+ if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
+ {
+ //echo 'Saving ID in m_sub_cats[ last ] '.$cat->UniqueId().' ';
+ //$GLOBALS['cat_ID'] = $cat->UniqueId();
+ $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
+ $parsed=1;
+ }
+ if(!$parsed)
+ {
+ //echo 'Saving ID in m_sub_cats[ each ] '.$cat->UniqueId().' ';
+ //$GLOBALS['cat_ID'] = $cat->UniqueId();
+ $o .= $cat->ParseTemplate($attribs["_itemtemplate"]);
+ }
+ $row++;
+ $i++;
+ $count++;
+ if($count>=$cat_count && $cat_count>0)
+ break;
+ }
+ }
+ }
+ unset($var_list_update["t"]);
+ SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o);
+ return $o;
+}
+
+function LoadCatSearchResults($attribs)
+{
+ global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal;
+
+ $GroupList = $objSession->Get("GroupList");
+ if(strlen($GroupList))
+ $Groups = explode(",",$GroupList);
+ $acl_where = "";
+ if(@count($Groups)>0 && is_array($Groups))
+ {
+ $acl_where = array();
+ for($i=0;$iGetPermId("CATEGORY.VIEW");
+ $ctable = $objCatList->SourceTable;
+ $stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable;
+ $ptable = GetTablePrefix()."PermCache";
+ $sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) ";
+ $sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) ";
+ $sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY EdPick DESC,Relevance DESC ";
+ $objSearchCats->Page = $m_var_list["p"];
+ if($objSearchCats->Page<1)
+ $objSearchCats->Page=1;
+
+ if(is_numeric($objConfig->Get($objSearchCats->PerPageVar)))
+ {
+ $Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar);
+ $limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar);
+ }
+ else
+ $limit = NULL;
+
+ if(strlen($limit))
+ $sql .= $limit;
+
+ // echo "TEST: $sql \n";
+ $objSearchCats->Query_Item($sql);
+ $where = "ItemType=1";
+
+ if(is_numeric($CountVal[1]))
+ {
+ $objSearchCats->QueryItemCount = $CountVal[1];
+ }
+ else
+ {
+ $objSearchCats->QueryItemCount = QueryCount($sql);
+ $CountVal[1]= $objSearchCats->QueryItemCount;
+ }
+}
+
+/*
+ @description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is
+ used to switch from a short list to a longer list. The page number is not changed.
+ If this tag is called before the list tag, this function will load the category list.
+ Generally, it is good practice to duplicate all attributes set for m_search_list_cats.
+ Any extra HTML attributes are passed to the anchor tag
+ @attrib: _Template:tpl: Template to link to
+ @attrib: _text:lang: language tag to include as text for the anchor tag
+ @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
+ if both are included.
+ @attrib: _image:: URL to an image to include inside the anchor tag.
+*/
+function m_search_cat_more($attribs = array())
+{
+ global $objSearchCats, $objConfig, $m_var_list_update;
+
+ $html_attribs = ExtraAttributes($attribs);
+ $DestTemplate = $attribs["_template"];
+
+ if($attribs["_shortlist"])
+ $objSearchList->PerPageVar = "Perpage_Category_Short";
+ if($objSearchCats->NumItems()==0)
+ {
+ LoadCatSearchResults($attribs);
+ }
+ $max = $objConfig->Get($objSearchList->PerPageVar);
+ $val = $objSearchCats->QueryItemCount;
+ if($val > $max)
+ {
+ if($attribs["_root"])
+ $attribs["_category"]=0;
+
+ $m_var_list_update["p"]=1;
+ $url = m_template_link($attribs);
+ unset($m_var_list_update["p"]);
+ $o = "";
+ $text = $attribs["_text"];
+ if(!strlen($text))
+ {
+ $text = $attribs["_plaintext"];
+ if(!strlen($text))
+ {
+ }
+ $o .= $text."";
+ }
+ else
+ $o .= language($text);
+ if(strlen($attribs["_image"]))
+ {
+ $o .= "";
+ }
+ $o .= "";
+ }
+ return $o;
+}
+/*
+ @description: Used in conjuction with m_search_list_cats. This function generates the page navigation
+ for the list. If this tag is called before the list tag, this function will load
+ the category list. Generally, it is good practice to duplicate all attributes set for
+ m_search_list_cats.
+ @attrib: _PagesToList:int: Number of pages to list (default is 10)
+ @attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages
+ listed, this text will not be included (resulting in an empty output)
+*/
+function m_search_cat_pagenav($attribs = array())
+{
+ global $objSearchCats, $objConfig, $objCatList, $objSession;
+
+ $DestTemplate = $attribs["_template"];
+ $PagesToList = $attribs["_pagestolist"];
+ if(!is_numeric($PagesToList))
+ $PagesToList = 10;
+
+ $CatId = $attribs["_catid"];
+ if(!is_numeric($CatId))
+ $CatId = $objCatList->CurrentCategoryID();
+
+ $objSearchCats->PerPageVar = "Perpage_Category";
+ if($attribs["_shortlist"])
+ $objSearchCats->PerPageVar = "Perpage_Category_Short";
+ if($objSearchCats->NumItems()==0)
+ {
+ LoadCatSearchResults($attribs);
+ }
+ $o = $objSearchCats->GetPageLinkList($DestTemplate);
+ if(strlen($o) && strlen($attribs["_label"]))
+ $o = language($attribs["_label"]).$o;
+ return $o;
+}
+
+/*
+ @description: List all categories matched in a search
+ @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
+ @attrib: _maxlistcount:int: Maximum number of categories to list
+ @attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category
+ @attrib: _FirstItemTemplate:tpl: Template used for the first category listed
+ @attrib: _LastItemTemplate:tpl: Template used for the last category listed
+ @attrib: _ItemTemplate:tpl: default template used for category list items
+ @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
+ @example:
+*/
+function m_search_list_cats($attribs = array())
+{
+ global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set,
+ $objSearchCats, $objPermissions, $m_var_list;
+
+ if(!is_object($objSearchCats))
+ {
+ $objSearchCats = new clsCatList();
+ $objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search"
+ $objSearchCats->Clear();
+ }
+ $objSearchCats->PerPageVar = "Perpage_Category";
+ if($attribs["_shortlist"])
+ {
+ $objSearchCats->Page=1;
+ $m_var_list["p"] = 1;
+ $objSearchCats->PerPageVar = "Perpage_Category_Short";
+ }
+
+ $keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches
+
+ if($objSearchCats->NumItems()==0)
+ {
+ LoadCatSearchResults($attribs);
+ //echo "Cat count: ". $objSearchCats->QueryItemCount;
+ $ret = 0;
+ if ($keywords) {
+ foreach ($objSearchCats->Items as $cat) {
+
+ if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($_POST['keywords']))) {
+ $ret++;
+ }
+ }
+ }
+ else {
+ $ret = $objSearchCats->QueryItemCount;
+ }
+ if ($ret == 0) //if ($objSearchCats->NumItems() == 0)
+ {
+ $content_set = 0;
+ return language("lu_no_categories");
+ }
+ }
+
+ $html_attr = ExtraAttributes($attribs);
+ $cols = $attribs["_columns"];
+ if($cols<1)
+ $cols =1;
+ $cat_count = (int)$attribs["_maxlistcount"];
+ /* validation */
+ if(strlen($attribs["_itemtemplate"])==0)
+ {
+ $content_set = 0;
+ return "ERROR -1";
+ }
+
+ $o="";
+ $notable = $attribs["_notable"];
+
+ $count=0;
+ $row=0;
+ $var_list_update["t"] = $var_list["t"];
+
+ if(!$notable)
+ {
+ $per_row = ceil($objCatList->NumItems()/$cols);
+ $o = "
";
+ foreach($objSearchCats->Items as $cat)
+ {
+ //$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
+ $keywords_found = strstr( strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords));
+ if(!$keywords) $keywords_found = true;
+ if ($keywords_found) {
+ if($row==0 && strlen($attribs["_firstitemtemplate"]))
+ {
+ $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
+ $parsed=1;
+ }
+ if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
+ {
+ $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
+ $parsed=1;
+ }
+ if(!$parsed)
+ $o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
+ $row++;
+ $i++;
+ $count++;
+ }
+ }
+ }
+ unset($var_list_update["t"]);
+ return $o;
+}
+
+/*
+ @description: Parse a template based on the current advanced search type
+ @attrib:_TypeSelect:tpl:Template to parse if no item type has been selected
+ @attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search
+*/
+function m_advsearch_include($attribs)
+{
+ global $objTemplate;
+
+ $TypeSelectTemplate = $attribs["_typeselect"];
+ $ItemTemplate = $attribs["_itemselect"];
+ if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search"))
+ {
+ $o = $objTemplate->ParseTemplate($ItemTemplate);
+ }
+ else
+ $o = $objTemplate->ParseTemplate($TypeSelectTemplate);
+ return $o;
+}
+
+/*
+ @description: Returns the name of the item type currently being advanced searched
+ @attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name])
+*/
+function m_advsearch_type($attribs)
+{
+ global $objItemTypes;
+
+ if($_GET["Action"]=="m_advsearch_type")
+ {
+ $ItemType = $_POST["itemtype"];
+ }
+ elseif($_GET["Action"]=="m_adv_search")
+ $ItemType = $_GET["type"];
+
+ $o = "";
+ if((int)$ItemType>0)
+ {
+ $Item = $objItemTypes->GetItem($ItemType);
+ if(is_object($Item))
+ {
+ $name = strtolower($Item->Get("ItemName"));
+ if($attribs["_plaintext"])
+ {
+ $o .= $name;
+ }
+ else
+ $o = language("lu_searchtitle_".strtolower($name));
+ }
+ }
+ return $o;
+}
+
+/*
+ @description: Lists advanced search fields for the selected item type
+ @attrib: _FirstItemTemplate:tpl: Template used for the first field listed
+ @attrib: _LastItemTemplate:tpl: Template used for the last field listed
+ @attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed
+ @attrib: _ItemTemplate:tpl: default template used for field list items
+ @attrib: _AltTemplate:tpl: Alternate template used for field list items
+*/
+function m_advsearch_fields($attribs)
+{
+ global $objItemTypes, $objTemplate, $objSearchConfig;
+
+ if(!is_object($objSearchConfig))
+ $objSearchConfig = new clsSearchConfigList();
+
+ if($_GET["Action"]=="m_advsearch_type")
+ {
+ $ItemType = $_POST["itemtype"];
+ }
+ elseif($_GET["Action"]=="m_adv_search")
+ $ItemType = $_GET["type"];
+
+ $o = "";
+ if((int)$ItemType>0)
+ {
+ $Item = $objItemTypes->GetItem($ItemType);
+ if(is_object($Item))
+ {
+ $name = strtolower($Item->Get("ItemName"));
+
+ $table = $Item->Get("SourceTable");
+ $sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder";
+ $objSearchConfig->Query_Item($sql);
+ $row=0;
+ if(is_array($objSearchConfig->Items))
+ {
+ $ItemCount = count($objSearchConfig->Items);
+ foreach($objSearchConfig->Items as $s)
+ {
+ $even = (($row+1) % 2 == 0);
+ $parsed=0;
+ if($row==0 && strlen($attribs["_firstitemtemplate"]))
+ {
+ $o .= $s->ParseTemplate($attribs["_firstitemtemplate"]);
+ $parsed=1;
+ }
+ if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0)
+ {
+ $o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]);
+ $parsed=1;
+ }
+ if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
+ {
+ $o .= $s->ParseTemplate($attribs["_lastitemtemplate"]);
+ $parsed=1;
+ }
+ if(!$parsed)
+ {
+ if($even && strlen($attribs["_altitemtemplate"])>0)
+ {
+ $o .= $s->ParseTemplate($attribs["_altitemtemplate"]);
+ }
+ else
+ $o .= $s->ParseTemplate($attribs["_itemtemplate"]);
+ }
+ $row++;
+
+ }
+ }
+ }
+ }
+ return $o;
+}
+
+/*
+ @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
+ are passed to the anchor tag created.
+ @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
+ @attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link)
+ @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
+ the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
+ and the link is created.)
+ @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
+ attribute. If this attirbute is not included and the user does not have access,
+ nothing is returned. (The link is not created.)
+ @attrib: _Root:bool: If set, the current category is set to the module's root category
+ @attrib: _text:lang: language tag to include as text for the anchor tag
+ @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
+ if both are included.
+ @attrib: _image:: URL to an image to include inside the anchor tag.
+ @attrib: _image_actions:: Image events.
+*/
+function m_module_link($attribs = array())
+{
+ global $objCatList, $objSession;
+
+ $permission = $attribs["_perm"];
+ $o = "";
+ $tpath = GetModuleArray("template");
+ if(strlen($permission))
+ {
+ $perms = explode(",",$permission);
+ $hasperm = FALSE;
+ for($x=0;$xHasCatPermission($perms[$x]))
+ {
+ $hasperm = TRUE;
+ break;
+ }
+ }
+ }
+ else
+ $hasperm = TRUE;
+ if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
+ {
+ $hasperm = TRUE;
+ $attribs["_template"]=$attribs["_deniedtemplate"];
+ }
+ if($hasperm)
+ {
+ $module = $attribs["_module"];
+ if(ModuleEnabled($module))
+ {
+ $t = $tpath[$attribs["_module"]];
+ $t .= $attribs["_template"];
+ $attribs["_template"] = $t;
+ $html_attr = ExtraAttributes($attribs);
+ if($attribs["_root"])
+ {
+ $func = ModuleTagPrefix($module)."_root_link";
+ if(function_exists($func))
+ {
+ $url = $func($attribs);
+ }
+ else
+ $url = m_template_link($attribs);
+ }
+ else
+ $url = m_template_link($attribs);
+ $o = " ";
+ $text = $attribs["_text"];
+ if(!strlen($text))
+ {
+ $text = $attribs["_plaintext"];
+ if(!strlen($text))
+ {
+ if(strlen($attribs["_image"]))
+ {
+ $text = "";
+ }
+ }
+ $o .= $text."";
+ }
+ else
+ $o .= language($text)."";
+ }
+ else
+ {
+ $o = "";
+ }
+ }
+ return $o;
+}
+/*
+ @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
+ are passed to the anchor tag created.
+ @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
+ @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
+ the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
+ and the link is created.)
+ @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
+ attribute. If this attirbute is not included and the user does not have access,
+ nothing is returned. (The link is not created.)
+ @attrib: _text:lang: language tag to include as text for the anchor tag
+ @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
+ if both are included.
+ @attrib: _image:: URL to an image to include inside the anchor tag.
+*/
+function m_permission_link($attribs = array())
+{
+ global $objCatList, $objSession;
+
+ $permission = $attribs["_perm"];
+ $o = "";
+ if(strlen($permission))
+ {
+ $perms = explode(",",$permission);
+ $hasperm = FALSE;
+ for($x=0;$xHasCatPermission($perms[$x]))
+ {
+ $hasperm = TRUE;
+ break;
+ }
+ }
+ }
+ else
+ $hasperm = TRUE;
+ if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
+ {
+ $hasperm = TRUE;
+ $attribs["_template"]=$attribs["_deniedtemplate"];
+ }
+ if($hasperm)
+ {
+ $url = m_template_link($attribs);
+ $o = " ";
+ $text = $attribs["_text"];
+ if(!strlen($text))
+ {
+ $text = $attribs["_plaintext"];
+ if(!strlen($text))
+ {
+ if(strlen($attribs["_image"]))
+ {
+ $text = "";
+ }
+ }
+ $o .= $text."";
+ }
+ else
+ $o .= language($text)."";
+ }
+ else
+ {
+ $o = "";
+ }
+
+ return $o;
+}
+
+/*
+ @description: Create a link to a template.
+ @attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list")
+ @attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test")
+ @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
+ @attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in )
+ @attrib: _Secure:bool:If set, creates an https URL
+ @attrib: _Root:bool:If set, gets module root category id
+ @attrib: _Module:str:Module Name
+ @attrib: _Unsecure:bool: Is set, creates an insecure full url (http://...)
+ @example: ">
+*/
+function m_template_link($attribs = array())
+{
+ global $var_list, $var_list_update, $m_var_list_update, $objCatList;
+
+ $template = $attribs["_template"];
+
+ $query = trim($attribs["_query"]);
+ $query = !ereg("^&", $query)? "&$query" : $query;
+
+ if(!strlen($template))
+ $template = $var_list["t"];
+ $cat = $attribs["_category"];
+ $var_list_update["t"] = $template;
+
+ if(strlen($cat))
+ {
+ if($cat=="NULL")
+ {
+ $m_var_list_update["cat"]=0;
+ }
+ else
+ {
+ $m_var_list_update["cat"] = $cat;
+ }
+ }
+
+ if($attribs["_secure"])
+ {
+ $ret = GetIndexURL(1)."?env=".BuildEnv().$query;
+ }
+ elseif($attribs["_unsecure"])
+ {
+ $ret = GetIndexURL(2)."?env=".BuildEnv().$query;
+ }
+ else
+ $ret = GetIndexURL()."?env=".BuildEnv().$query;
+
+ if(strlen($attribs["_anchor"]))
+ $ret .= "#".$attribs["_anchor"];
+ unset($var_list_update["t"]);
+ if(strlen($cat))
+ unset($m_var_list_update["cat"]);
+ return $ret;
+}
+
+/*
+ @description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created.
+ @attrib: _Template:tpl: Template to link to if the user has access
+ @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
+ attribute. If this attirbute is not included and the user does not have access,
+ the "login" template is used.
+ @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
+ the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
+ and the link is created.)
+ @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
+ @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
+ @example: ">
+*/
+function m_access_template_link($attribs = array(), $Permission="")
+{
+ global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
+
+ $cat = $attribs["_category"];
+ if(strlen($cat))
+ {
+ if($cat=="NULL")
+ $cat = 0;
+ }
+ else
+ $cat = $objCatList->CurrentCategoryID();
+
+ if(!strlen($Permission))
+ {
+ $Permission = strtoupper($attribs["_perm"]);
+ }
+
+ $o = "";
+ $hasperm = FALSE;
+ if(strlen($Permission))
+ {
+ $perms = explode(",",$Permission);
+
+ for($x=0;$xHasCatPermission(trim($perms[$x]),$cat))
+ {
+ $hasperm = TRUE;
+ break;
+ }
+ }
+
+ if(!$hasperm && $attribs["_system"])
+ {
+ for($x=0;$xHasSystemPermission(trim($perms[$x])))
+ {
+ $hasperm = TRUE;
+ break;
+ }
+ }
+ }
+ }
+ $access = $attribs["_template"];
+ $denied = $attribs["_deniedtemplate"];
+ if(!strlen($denied))
+ $denied = "login";
+
+ $m_var_list_update["cat"] = $cat;
+ if($hasperm)
+ {
+ $template = $access;
+ if(!strlen($template))
+ $template = $var_list["t"];
+ $var_list_update["t"] = $template;
+ }
+ else
+ {
+ $template = $denied;
+ if(!strlen($template))
+ $template = $var_list["t"];
+ if($template == "login")
+ {
+ $dest = $access;
+ }
+ $var_list_update["t"] = $template;
+ }
+
+ $ret = GetIndexURL()."?env=".BuildEnv();
+ unset($var_list_update["t"]);
+ if(strlen($dest))
+ $ret .= "&dest=$dest";
+ return $ret;
+}
+
+/*
+ @description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded.
+ @attrib: _Text:lang: Template to link to if the user has access
+ @attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used.
+ @attrib: _DenyText:lang: Template to link to if the user has access
+ @attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set.
+ @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated.
+ @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
+ @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
+ @attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used.
+ @attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0.
+ @example: Some HTML here!
+*/
+function m_perm_text($attribs = array())
+{
+ global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
+
+ $cat = $attribs["_category"];
+ if(strlen($cat))
+ {
+ if($cat=="NULL")
+ $cat = 0;
+ }
+ else
+ $cat = $objCatList->CurrentCategoryID();
+
+ if(!strlen($Permission))
+ {
+ $Permission = strtoupper($attribs["_perm"]);
+ }
+
+ $o = "";
+ $hasperm = FALSE;
+
+ $count = 0;
+
+ if(strlen($Permission))
+ {
+ $perms = explode(",",$Permission);
+
+ for($x=0;$xHasCatPermission($perms[$x],$cat))
+ {
+ $hasperm = TRUE;
+ $_AllPermsCount[$count] = 1;
+// break;
+ }
+
+ $count++;
+ }
+
+ if(!$hasperm && $attribs["_system"])
+ {
+ for($x=0; $xHasSystemPermission($perms[$x]))
+ {
+ $hasperm = TRUE;
+ $_AllPermsCount[$count] = 1;
+// break;
+ }
+
+ $count++;
+ }
+ }
+ }
+
+ if ((int)$attribs["_matchallperms"])
+ {
+ if (count($_AllPermsCount) != array_sum($_AllPermsCount))
+ $hasperm = FALSE;
+ }
+
+ $text = $attribs["_text"];
+ $plaintext = $attribs["_plaintext"];
+ $denytext = $attribs["_denytext"];
+ $plaindenytext = $attribs["_plaindenytext"];
+ $nopermissions_status = (int)$attribs["_noperm"]? 1 : 0;
+
+ if(!strlen($denied))
+ $denied = "login";
+
+ if (!$nopermissions_status)
+ {
+ if ($hasperm)
+ {
+ if (strlen($text) || strlen($plaintext))
+ $ret = strlen($text)? language($text) : $plaintext;
+ else
+ $ret = "1";
+ }
+ else
+ $ret = strlen($denytext)? language($denytext) : $plaindenytext;
+ }
+ elseif (!$hasperm)
+ {
+ $ret = "1";
+ }
+
+ return $ret;
+}
+
+
+/*
+ @description: Returns the error string associated with a permission
+*/
+function m_permission_error($attribs = array())
+{
+ global $objPermissions;
+
+ $ret = "";
+ $perm = strtoupper($_GET["error"]);
+ if(strlen($perm))
+ {
+ $ado = &GetADODBConnection();
+ $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'";
+ $rs = $ado->Execute($sql);
+ if($rs && !$rs->EOF)
+ {
+ $data = $rs->fields;
+ $error_tag = $data["ErrorMessage"];
+ }
+ else
+ $error_tag = "lu_unknown_error";
+ $ret = language($error_tag);
+ }
+ return $ret;
+}
+
+/*
+ @description: Returns the error text encountered when parsing templates
+*/
+function m_template_error($attribs = array())
+{
+ global $objTemplate;
+
+ $ret = "";
+ if($objTemplate->ErrorNo<0)
+ {
+ $ret = $objTemplate->ErrorStr;
+ }
+ return $ret;
+}
+
+/*
+ @description: Creates a category navigation bar
+ @attrib: _Template:tpl: template to use for navigation links
+ @attrib: _RootTemplate:bool: If set, this template is linked to for the root category
+ @attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed
+ @attrib: _Separator:: text to display between levels of the navigation bar
+ @attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used
+ @example:
+*/
+function m_navbar($attribs = array())
+{
+ global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules;
+
+ $separator = GetElem($attribs, '_separator');
+ if(!$separator) $separator = " > ";
+
+ $admin = (int)GetElem($attribs, 'admin');
+
+ $t = GetElem($attribs, '_template');
+ $LinkLeafNode = GetElem($attribs, '_linkcurrent');
+ $catid = (int)GetElem($attribs, '_catid');
+
+ if( GetElem($attribs, '_root') )
+ {
+ $var = GetElem($attribs, '_root')."_Root";
+ $Root = (int)$objConfig->Get($var);
+ }
+ else
+ $Root = 0;
+
+ $RootTemplate = GetElem($attribs, '_roottemplate') ? GetElem($attribs, '_roottemplate') : '';
+ $Module = GetElem($attribs, '_module');
+ $ModuleRootTemplate = '';
+ if($Module)
+ {
+ $ModuleRootCat = $objModules->GetModuleRoot($Module);
+ if($ModuleRootCat>0)
+ {
+ $modkey = "_moduleroottemplate";
+ $ModuleRootTemplate = GetElem($attribs, $modkey);
+ }
+ else
+ $ModuleRootTemplate="";
+ }
+ else
+ $ModuleRootCat = 0;
+
+ if(!$catid)
+ $catid = $objCatList->CurrentCategoryID();
+
+ $ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate);
+ return $ret;
+}
+
+/*
+ @description: Parse a category field and return the value
+ @attrib: _Field:: Category field to parse
+ @attrib: _CatId:int: Category ID to parse (uses current category if not set)
+ @attrib: _StripHTML:bool: if set, all HTML is removed from the output
+*/
+function m_category_field($attribs)
+{
+ global $objCatList;
+
+ $ret = "";
+ $catid = (int)$attribs["_catid"];
+ $field = $attribs["_field"];
+ if(!$catid)
+ $catid = $objCatList->CurrentCategoryID();
+
+ if(strlen($field))
+ {
+ $cat =& $objCatList->GetCategory($catid);
+ if(is_object($cat))
+ {
+ $element = new clsHtmlTag();
+ $element->name=$cat->TagPrefix;
+ $element->attributes = $attribs;
+ $ret = $cat->ParseObject($element);
+ }
+ }
+ if($attribs["_striphtml"])
+ $ret = strip_tags($ret);
+ return $ret;
+}
+
+/*
+ @description: returns the date of the last modification to a category
+ @attrib: _Part:: part of the date to display
+ @attrib: _Local:bool: If set, only subcategories of the current category is checked
+ @example:
+*/
+function m_category_modified($attribs)
+{
+ global $objConfig, $objCatList;
+
+ $ado = &GetADODBConnection();
+
+ if($attribs["_local"] && $objCatList->CurrentCategoryID() != 0)
+ {
+ $c =& $objCatList->GetItem($objCatList->CurrentCategoryID());
+ $catlist = $c->GetSubCatIds();
+
+ $catwhere = "CategoryId IN (".explode(",",$catlist).")";
+ $sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category ";
+ $sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) ";
+ $sql .= "WHERE $catwhere LIMIT 1";
+ }
+ else
+ $sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1";
+ $rs = $ado->Execute($sql);
+ if($rs && ! $rs->EOF)
+ {
+ $mod = $rs->fields["ModDate"];
+ if($mod)
+ {
+ $part = strtolower($attribs["_part"]);
+ if(strlen($part))
+ {
+ $ret = ExtractDatePart($part,$mod);
+ }
+ else
+ {
+ $ret = LangDate($mod);
+ }
+ }
+ }
+ return $ret;
+}
+
+/*
+ @description: creates LINK tags to include all module style sheets
+ @attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin")
+ @attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..".
+ If a module does not have a *css attribute, the default (style.css) is assumed.
+ @example:
+*/
+function m_module_stylesheets($attribs)
+{
+ global $TemplateRoot;
+
+ $IncludeList = explode(",",trim($attribs["_modules"]));
+ $tpath = GetModuleArray("template");
+ for($inc=0;$inc\n";
+ }
+ return $ret;
+}
+
+/*
+ @description: lists items related to a category
+ @attrib:CatId:int: Category ID of category, or current category if not set
+ @attrib:_ListItem: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority.
+ Each item should have its own template passed in as an attribute (_{ItemType}Template)
+*/
+function m_related_items($attribs)
+{
+ global $objItemTypes, $objCatList, $content_set;
+ static $Related;
+
+ global $CatRelations;
+
+ $cat = $attribs["_catid"];
+ if(!is_numeric($cat))
+ {
+ $cat = $objCatList->CurrentCategoryID();
+ }
+ $c =& $objCatList->GetCategory($cat);
+ $data_sent=0;
+ if(is_object($c))
+ {
+ $ResourceId = $c->Get("ResourceId");
+ $IncludeList = explode(",",trim(strtolower($attribs["_listitems"])));
+ $o = "";
+
+ if(!is_object($CatRelations))
+ {
+ $CatRelations = new clsMultiTypeList();
+ LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId"));
+ }
+
+ if($CatRelations->NumItems()>0)
+ {
+ for($inc=0;$incGetTypeByName($item_type);
+ if(is_object($objType))
+ {
+ foreach($CatRelations->Items as $item)
+ {
+ if(is_object($item))
+ {
+ if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType"))
+ {
+ if(strlen($item->BasePermissionName))
+ {
+ $perm = $item->BasePermissionName.".VIEW";
+ $haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId"));
+ }
+ else
+ $hasperm = 1;
+
+ if($hasperm)
+ {
+ $data_sent =1;
+ $classname = $objType->Get("ClassName");
+ if(strlen($classname))
+ {
+ $l = new $classname;
+ $l->Data = $item->Data;
+ $o .= $l->ParseTemplate($t);
+ }
+ }
+ }
+ }
+ $item = NULL;
+ }
+ }
+ else
+ echo $item_type." not found \n";
+ }
+ }
+ if($data_sent)
+ {
+ return $o;
+ }
+ else
+ {
+ $content_set=0;
+ return "";
+ }
+ }
+ else
+ {
+ $content_set = 0;
+ return "";
+ }
+ }
+ else
+ {
+ $content_set = 0;
+ return "";
+ }
+}
+
+/*
+ @description: Returns the number of items related to the current category
+ @attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used
+ @attrib:_ItemType::Name of item to count. If not set, all related items are counted
+*/
+function m_related_count($attribs)
+{
+ global $objItemTypes, $objCatList, $content_set;
+
+ $cat = $attribs["_catid"];
+
+ if(!is_numeric($cat))
+ {
+ $cat = $objCatList->CurrentCategoryID();
+ }
+ $c =& $objCatList->GetCategory($cat);
+ $data_sent=0;
+ //echo "Category: $cat
"; print_r($c); echo "
";
+ if(is_object($c))
+ {
+ $ResourceId = $c->Get("ResourceId");
+ if(!is_object($CatRelations))
+ {
+ $CatRelations = new clsMultiTypeList();
+ LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId"));
+ }
+
+ $item_type = $attribs["_itemtype"];
+ if(strlen($item_type))
+ {
+ $objType = $objItemTypes->GetTypeByName($item_type);
+ if(is_object($objType))
+ {
+ $TargetType = $objType->Get("ItemType");
+ }
+ else
+ $TargetType="";
+ }
+
+ if($CatRelations->NumItems()>0)
+ {
+ for($x=0;$x<$CatRelations->NumItems();$x++)
+ {
+ $a = $CatRelations->GetItemByIndex($x);
+ if($a->type == $TargetType || !strlen($TargetType))
+ {
+ $count++;
+ }
+ }
+ }
+ }
+ return $count;
+}
+
+/*
+ @description: Returns the MetaKeywords field for a category, or the system MetaKeywords value
+ if the category doesn't have a value for MetaKeywords
+ @attrib: _CatId:int: Category to use (The current category is used by default)
+*/
+function m_meta_keywords($attribs = array())
+{
+ global $objCatList, $objConfig;
+ $catid = (int)$attribs["_catid"];
+ if(!$catid)
+ {
+ $catid = $objCatList->CurrentCategoryID();
+ }
+ if($catid)
+ {
+ $c = $objCatList->GetItem($catid);
+ $keywords = $c->Get("MetaKeywords");
+ }
+ if(!strlen($keywords))
+ {
+ $keywords = $objConfig->Get("MetaKeywords");
+ }
+ return $keywords;
+}
+
+/*
+ @description: Returns the MetaDescription field for a category, or the system MetaDescription value
+ if the category doesn't have a value for MetaDescription
+ @attrib: _CatId:int: Category to use (The current category is used by default)
+*/
+function m_meta_description($attribs = array())
+{
+ global $objCatList, $objConfig;
+
+ $catid = (int)$attribs["_catid"];
+ if(!$catid)
+ {
+ $catid = $objCatList->CurrentCategoryID();
+ }
+ if($catid)
+ {
+ $c = $objCatList->GetItem($catid);
+ $desc = $c->Get("MetaDescription");
+ }
+ if(!strlen($desc))
+ {
+ $desc = $objConfig->Get("MetaDescription");
+ }
+ return $desc;
+}
+
+/*
+ @description: return the number of items in the database
+ @attrib: _ItemType:: Name of item to count
+ @attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc)
+ @attrib: _CategoryCount:int: Limit scope to the current category
+ @attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set)
+ @attrib: _Today:bool: Count items added today
+ @attrib: _GroupOnly:bool: Only count items the current user can view
+ @attrib: _NoCache:bool: Count without using cache
+*/
+function m_itemcount($attribs = array())
+{
+ global $objItemTypes, $objCatList, $objSession, $objCountCache;
+
+ $Bit_None = 0;
+ $Bit_Today = 1;
+ $Bit_Owner = 2;
+ $Bit_Global = 4;
+ $Bit_SubCats=8;
+
+ if($attribs["_categorycount"])
+ {
+ $evar = m_BuildEnv();
+ }
+ else
+ $evar = "";
+
+ $cat = $attribs["_catid"];
+ if(!is_numeric($cat))
+ {
+ $cat = $objCatList->CurrentCategoryID();
+ }
+
+ if((int)$cat>0)
+ $c = $objCatList->GetCategory($cat);
+
+ if(is_numeric($attribs["_itemtype"]))
+ {
+ $item = $objItemTypes->GetItem($attribs["_itemtype"]);
+ }
+ else
+ $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
+
+ $DoUpdate=0;
+
+ //echo "
"; print_r($item); echo "
";
+
+ $ExtraId="";
+
+ if(is_object($item))
+ {
+ if($item->Get("ItemType")==1) /* counting categories */
+ {
+ $ret = $objCatList->CountCategories($attribs);
+ }
+ else
+ {
+ $ListVar =& GetItemCollection($attribs["_itemtype"]);
+ if(is_object($ListVar))
+ {
+ $ret = $ListVar->PerformItemCount($attribs);
+ }
+ }
+ }
+ else
+ $ret = 0;
+
+ return !$ret ? 0 : $ret;
+}
+
+/*
+ @description: Parse a User field and return the value
+ @attrib: _Field:: User field to parse
+ @attrib: _UserId:int: Category ID to parse (uses current user if not set)
+*/
+function m_user_field($attribs)
+{
+ global $objUsers, $objSession;
+
+ $o = "";
+ $userid = $attribs["_userid"];
+ if(!is_numeric($userid) || $userid=="0")
+ $userid = $objSession->Get("PortalUserId");
+
+ if($userid)
+ {
+ $u =& $objUsers->GetItem($userid);
+ if(is_object($u))
+ {
+ $element = new clsHtmlTag();
+ $element->name = $u->TagPrefix;
+ $element->attributes = $attribs;
+ $o = $u->ParseObject($element);
+ }
+ }
+ return $o;
+}
+
+/*
+ @description: Parses a user template
+ @attrib:_Template:tpl: Template to parse
+ @attrib:_UserId:int: User ID to parse. If not set, the current user is used
+*/
+function m_user_detail($attribs = array())
+{
+ global $objTemplate, $objUsers, $objSession;
+
+ $tname = $attribs["_template"];
+ $UserId = (int)$attribs["_userid"];
+ if(!$UserId)
+ {
+ $UserId=$objSession->Get("PortalUserId");
+ }
+ if($UserId>0)
+ {
+ $u = $objUsers->GetUser($UserId);
+ $o = $u->ParseTemplate($tname);
+ }
+ else
+ {
+ $u = new clsPortalUser(NULL);
+ $o = $u->ParseTemplate($tname);
+ }
+
+ return $o;
+}
+
+/*
+ @description: returns a user field from the current profile being viewed
+ @example:
+*/
+function m_user_profile_field($attribs = array())
+{
+ if((int)$_GET["UserId"])
+ {
+ $attribs["_userid"] = $_GET["UserId"];
+ }
+
+ $ret = m_user_field($attribs);
+
+/* if ($ret == '') {
+ $ret = admin_language("lu_Guest");
+ }*/
+
+ return $ret;
+}
+
+/*
+ @description: Parses a user profile template
+ @attrib:_Template:tpl: Template to parse
+ @attrib:_UserId:int: User ID to parse. If not set, the current user is used
+*/
+function m_user_profile_detail($attribs)
+{
+ if((int)$_GET["UserId"])
+ {
+ $attribs["_userid"] = $_GET["UserId"];
+ }
+ $ret = m_user_detail($attribs);
+ return $ret;
+}
+
+/*
+ @description: Lists all user profile fields the user has indicated to be public
+ @attrib: _ItemTemplate:tpl: Template used to list each field
+ @example:
+*/
+function m_user_profile($attribs = array())
+{
+ global $objTemplate, $objUsers;
+
+ $tname = $attribs["_itemtemplate"];
+ $t = $objTemplate->GetTemplate($tname);
+ if(is_object($t))
+ {
+ $html = $t->source;
+ }
+
+ $userid = $_GET["UserId"];
+ $o = "";
+
+ if((int)$userid>0)
+ {
+ $u = $objUsers->GetItem($userid);
+ $vars = $u->GetAllPersistantVars();
+ foreach($vars as $field=>$value)
+ {
+ if(substr($field,0,3)=="pp_")
+ {
+ if($value==1)
+ {
+ $src = $html;
+ $src = str_replace("","",$src);
+ $src = str_replace("lu_profile_field","lu_".$field,$src);
+ $o .= $u->ParseTemplateText($src);
+ }
+ }
+
+ }
+ }
+
+ return $o;
+}
+
+/*
+ @description: List users the current user has marked as 'friend'
+ @attrib: _Status:: Determines which online status to list, either "online" or "offline".
+ @attrib: _ItemTemplate:tpl: Template used to parse list items
+*/
+function m_list_friends($attribs = array())
+{
+ global $objUsers, $objSession;
+
+ global $online_friends;
+
+ $ado = &GetADODBConnection();
+
+ $status = strtolower($attribs["_status"]);
+
+ $logedin_user = $objSession->Get("PortalUserId");
+ $u =& $objUsers->GetUser($logedin_user);
+
+ //echo "
"; print_r($u); echo "
";
+ if(!isset($online_friends) || $status=="online")
+ {
+ $ftable = GetTablePrefix()."Favorites";
+ $stable = GetTablePrefix()."UserSession";
+ $ptable = GetTablePrefix()."PortalUser";
+ if(isset($online_friends))
+ {
+ foreach($online_friends as $id=>$name)
+ {
+ $u =& $objUsers->GetUser($id);
+ $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
+ }
+ }
+ else
+ {
+ $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
+ $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ //echo $sql;
+ $rs = $ado->Execute($sql);
+ while($rs && ! $rs->EOF)
+ {
+ $u =& $objUsers->GetItem($rs->fields["PortalUserId"]);
+ if($status=="online")
+ {
+ $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
+ }
+ $online_friends[]=$rs->fields["PortalUserId"];
+ if(ADODB_EXTENSION>0)
+ {
+ adodb_movenext($rs);
+ }
+ else
+ $rs->MoveNext();
+ }
+ }
+ }
+
+ if($status=="offline")
+ {
+ $ftable = GetTablePrefix()."Favorites";
+ $stable = GetTablePrefix()."UserSession";
+ $ptable = GetTablePrefix()."PortalUser";
+
+ $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
+ if(count($online_friends)>0)
+ {
+ $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
+ $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ }
+ else
+ {
+ $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ }
+
+ //echo $sql;
+ $rs = $ado->Execute($sql);
+ while($rs && ! $rs->EOF)
+ {
+ $u = $objUsers->GetItem($rs->fields["PortalUserId"]);
+ $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
+ if(ADODB_EXTENSION>0)
+ {
+ adodb_movenext($rs);
+ }
+ else
+ $rs->MoveNext();
+ }
+ }
+ $t = $attribs["_itemtemplate"];
+ return $o;
+}
+
+/*
+ @description: Returns the number of users the current user has marked as 'friend'
+ @attrib: _Status:: Determines which online status to count, either "online" or "offline".
+*/
+function m_friend_count($attribs=array())
+{
+ global $objUsers, $objSession;
+
+ global $online_friends;
+
+ $ado = &GetADODBConnection();
+
+ $logedin_user = $objSession->Get("PortalUserId");
+ $u =& $objUsers->GetUser($logedin_user);
+
+ $status = strtolower($attribs["_status"]);
+ if(!isset($online_friends) || $status=="online")
+ {
+ $ftable = GetTablePrefix()."Favorites";
+ $stable = GetTablePrefix()."UserSession";
+ $ptable = GetTablePrefix()."PortalUser";
+ if(isset($online_friends) && $status="online")
+ {
+ return count($online_friends);
+ }
+ else
+ {
+ $online_friends = array();
+ $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
+ $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ //echo $sql." \n";
+ $rs = $ado->Execute($sql);
+ while($rs && ! $rs->EOF)
+ {
+ $online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"];
+ if(ADODB_EXTENSION>0)
+ {
+ adodb_movenext($rs);
+ }
+ else
+ $rs->MoveNext();
+ }
+ if($status=="online")
+ return count($online_friends);
+ }
+ }
+
+ if($status=="offline")
+ {
+ $ftable = GetTablePrefix()."Favorites";
+ $stable = GetTablePrefix()."UserSession";
+ $ptable = GetTablePrefix()."PortalUser";
+
+ $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
+
+ if(count($online_friends)>0)
+ {
+ $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
+ $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ }
+ else
+ {
+ $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
+ $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
+ }
+ $rs = $ado->Execute($sql);
+ return $rs->fields["ItemCount"];
+ }
+}
+
+/*
+ @description: Returns the number of users the current user has marked as 'friend' today
+*/
+function m_friend_count_today($attribs)
+{
+ global $objSession;
+
+ $logedin_user = $objSession->Get("PortalUserId");
+
+ $ret =0;
+ $ado = &GetADODBConnection();
+ $today = mktime(0,0,0,date("m"),date("d"),date("Y"));
+ $sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today";
+ $rs = $ado->Execute($sql);
+ if($rs && !$rs->EOF)
+ $ret = $rs->fields["c"];
+ return $ret;
+}
+
+/*
+ @description: Returns the number of items in a search result
+
+ @Example: ()
+*/
+function m_search_item_count($attribs)
+{
+ global $objItemTypes, $objCatList, $objSession, $CountVal;
+
+ if(!is_array($CountVal))
+ $CountVal=array();
+ $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
+ if(is_object($item))
+ {
+ $val = $CountVal[$item->Get("ItemType")];
+ if(is_numeric($val))
+ return $val;
+ $where = "ItemType=".$item->Get("ItemType");
+ $table = $objSession->GetSearchTable();
+ $ret = TableCount($table,$where,0);
+ $CountVal[$item->Get("ItemType")]=(int)$ret;
+ }
+
+ return $ret;
+}
+/*
+ @description: Returns the number of categories in a search result
+ @Example: ()
+*/
+function m_search_cat_count($attribs = array())
+{
+ global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats;
+
+ if(!is_object($objSearchCats))
+ {
+ $objSearchCats = new clsCatList();
+ $objSearchCats->SourceTable = $objSession->GetSearchTable();
+ $objSearchCats->Clear();
+ }
+
+ LoadCatSearchResults($attribs);
+ //echo "
"; print_r($objSearchCats->Items); echo "
";
+ $ret = 0;
+ $keywords = $objSession->GetVariable("Search_Keywords");
+
+ if ($keywords) {
+ foreach ($objSearchCats->Items as $cat) {
+
+ if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords))) {
+ $ret++;
+ }
+ }
+ }
+ else {
+ $ret = $objSearchCats->QueryItemCount;
+ }
+
+ if ($ret == '') {
+ $ret = 0;
+ }
+
+ //echo $ret;
+ //$objSearchCats->QueryItemCount = $ret;
+
+ return $ret;
+}
+
+/*
+ @description: Returns super global variable by type and name
+ @attrib: _Name:: Name of variable
+ @attrib: _Type:: Type super global variable Possible Values:
+
+
get: $_GET super variable
+
post: $_POST super variable
+
cookie: $_COOKIE super variable
+
env: $_ENV super variable
+
server: $_SERVER super variable
+
session: $_SESSION super variable
+
+ @Example:
+*/
+function m_get_var($attribs = array())
+{
+ global $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_SERVER, $_SESSION;
+
+ $type = strtolower($attribs['_type']);
+ $name = $attribs['_name'];
+
+ switch ($type)
+ {
+ case "get":
+ $vars = $_GET;
+ break;
+ case "cookie":
+ $vars = $_COOKIE;
+ break;
+ case "files":
+ $vars = $_FILES;
+ break;
+ case "server":
+ $vars = $_SERVER;
+ break;
+ case "session":
+ $vars = $_SESSION;
+ break;
+ case "env":
+ $vars = $_ENV;
+ break;
+ case "post":
+ $vars = $_POST;
+ break;
+ default :
+ $vars = $_POST;
+ break;
+ }
+ $ret = $vars[$name];
+
+ return $ret;
+}
+
+/*
+ @description: Returns number of users currently on-line
+ @attrib: _LastActive:: Last user/session activity in seconds
+ @attrib: _OwnCount:bool: Count user's own session
+*/
+function m_users_online($attribs = array())
+{
+ global $objSession;
+
+ $LastActive = (int)($attribs['_lastactive']);
+ $OwnCount = (int)($attribs['_owncount']);
+
+ if ($LastActive && !is_null($LastActive))
+ $sql_add = " AND LastAccessed>".(time()-$LastActive);
+
+ if (!$OwnCount || is_null($OwnCount))
+ $sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'";
+
+ $ado = &GetADODBConnection();
+ $sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add;
+ $rs = $ado->Execute($sql);
+ $ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0;
+
+ return $ret;
+}
+
+function m_debug_mode($attribs = array())
+{
+ $const_name = $attribs['_debugconst'];
+ return defined($const_name) && (constant($const_name) == 1) ? 'yes' : '';
+}
+
+function m_info($attribs = array())
+{
+ switch ($attribs['_infotype'])
+ {
+ case 'site':
+ global $objConfig;
+ $ret = ThisDomain().$objConfig->Get('Site_Path');
+ break;
+
+ default:
+ $ret = '';
+ break;
+ }
+ return $ret;
+}
+
+function m_module_enabled($attribs = array())
+{
+ global $objModules;
+ $module = $attribs['_module'];
+
+ // check if module is installed
+ $ModuleItem = $objModules->GetItemByField('Name', $module);
+ if( !is_object($ModuleItem) ) return '';
+
+ // module is enabled
+ $ret = $ModuleItem->Get('Loaded') == 1;
+
+ // check if installed module is licensed
+ return $ret && _ModuleLicensed($module) ? 'yes' : '';
+}
+
+function m_recall($attribs = array())
+{
+ global $objSession;
+ return $objSession->GetVariable($attribs['_name']);
+}
+
+?>
Index: trunk/admin/install/inportal_schema.sql
===================================================================
diff -u -r431 -r642
--- trunk/admin/install/inportal_schema.sql (.../inportal_schema.sql) (revision 431)
+++ trunk/admin/install/inportal_schema.sql (.../inportal_schema.sql) (revision 642)
@@ -1,523 +1,523 @@
-CREATE TABLE BanRules (
- RuleId int(11) NOT NULL auto_increment,
- RuleType tinyint(4) NOT NULL default '0',
- ItemField varchar(255) default NULL,
- ItemVerb tinyint(4) NOT NULL default '0',
- ItemValue varchar(255) NOT NULL default '',
- ItemType int(11) NOT NULL default '0',
- Priority int(11) NOT NULL default '0',
- Status tinyint(4) NOT NULL default '1',
- ErrorTag varchar(255) default NULL,
- PRIMARY KEY (RuleId)
-)
-# --------------------------------------------------------
-CREATE TABLE Category (
- CategoryId int(11) NOT NULL auto_increment,
- Type int(11) NOT NULL default '0',
- ParentId int(11) NOT NULL default '0',
- Name varchar(255) NOT NULL default '',
- Description text NOT NULL,
- CreatedOn double NOT NULL default '0',
- EditorsPick tinyint(4) default NULL,
- Status tinyint(4) NOT NULL default '0',
- Pop tinyint(4) default NULL,
- Priority int(11) default NULL,
- MetaKeywords varchar(255) default NULL,
- CachedDescendantCatsQty int(11) default NULL,
- CachedNavbar text NOT NULL,
- CreatedById int(11) NOT NULL default '0',
- ResourceId int(11) default NULL,
- ParentPath text NOT NULL,
- MetaDescription varchar(255) default NULL,
- HotItem int(11) NOT NULL default '2',
- NewItem int(11) NOT NULL default '2',
- PopItem int(11) NOT NULL default '2',
- Modified double NOT NULL default '0',
- ModifiedById int(11) NOT NULL default '0',
- PRIMARY KEY (CategoryId),
- KEY ParentId (ParentId),
- KEY ResourceId (ResourceId),
- KEY Modified (Modified),
- KEY Priority (Priority),
- KEY sorting (Name,Priority)
-)
-# --------------------------------------------------------
-CREATE TABLE CategoryItems (
- CategoryId int(11) NOT NULL default '0',
- ItemResourceId int(11) NOT NULL default '0',
- PrimaryCat tinyint(4) NOT NULL default '0',
- PRIMARY KEY (CategoryId,ItemResourceId),
- KEY ItemResourceId (ItemResourceId),
- KEY PrimaryCat (PrimaryCat)
-)
-# --------------------------------------------------------
-CREATE TABLE ConfigurationAdmin (
- VariableName varchar(80) NOT NULL default '',
- heading varchar(255) default NULL,
- prompt varchar(255) default NULL,
- element_type varchar(20) NOT NULL default '',
- validation varchar(255) default NULL,
- ValueList varchar(255) default NULL,
- DisplayOrder int(11) NOT NULL default '0',
- Install int(11) NOT NULL default '1',
- PRIMARY KEY (VariableName)
-)
-# --------------------------------------------------------
-CREATE TABLE ConfigurationValues (
- VariableName varchar(255) NOT NULL default '',
- VariableValue varchar(255) default NULL,
- ModuleOwner varchar(20) default 'In-Portal',
- Section varchar(255) NOT NULL default '',
- PRIMARY KEY (VariableName)
-)
-# --------------------------------------------------------
-CREATE TABLE CountCache (
- ListType int(11) NOT NULL default '0',
- ItemType int(11) NOT NULL default '-1',
- Value int(11) NOT NULL default '0',
- CountCacheId int(11) NOT NULL auto_increment,
- LastUpdate int(11) NOT NULL default '0',
- ExtraId varchar(50) default NULL,
- TodayOnly tinyint(4) NOT NULL default '0',
- PRIMARY KEY (CountCacheId)
-)
-# --------------------------------------------------------
-CREATE TABLE CustomField (
- CustomFieldId int(11) NOT NULL auto_increment,
- Type int(11) NOT NULL default '0',
- FieldName varchar(255) NOT NULL default '',
- FieldLabel varchar(40) default NULL,
- Heading varchar(60) default NULL,
- Prompt varchar(60) default NULL,
- ElementType varchar(50) NOT NULL default '',
- ValueList varchar(255) default NULL,
- DisplayOrder int(11) NOT NULL default '0',
- OnGeneralTab tinyint(4) NOT NULL default '0',
- PRIMARY KEY (CustomFieldId),
- KEY Type (Type)
-)
-# --------------------------------------------------------
-CREATE TABLE CustomMetaData (
- CustomDataId int(11) NOT NULL auto_increment,
- ResourceId int(11) NOT NULL default '0',
- CustomFieldId int(11) NOT NULL default '0',
- Value text NOT NULL,
- PRIMARY KEY (CustomDataId)
-)
-# --------------------------------------------------------
-CREATE TABLE EmailMessage (
- EmailMessageId int(10) NOT NULL auto_increment,
- Template longtext,
- MessageType enum('html','text') NOT NULL default 'text',
- LanguageId int(11) NOT NULL default '0',
- EventId int(11) NOT NULL default '0',
- PRIMARY KEY (EmailMessageId)
-)
-# --------------------------------------------------------
-CREATE TABLE EmailQueue (
- Subject text NOT NULL,
- toaddr text NOT NULL,
- fromaddr text NOT NULL,
- message blob,
- headers blob,
- queued timestamp NOT NULL
-)
-# --------------------------------------------------------
-CREATE TABLE EmailSubscribers (
- EmailMessageId int(11) NOT NULL default '0',
- PortalUserId int(11) NOT NULL default '0'
-)
-# --------------------------------------------------------
-CREATE TABLE Events (
- EventId int(11) NOT NULL auto_increment,
- Event varchar(40) NOT NULL default '',
- Enabled int(11) NOT NULL default '1',
- FromUserId int(11) NOT NULL default '0',
- Module varchar(40) NOT NULL default '',
- Description varchar(255) NOT NULL default '',
- Type int(11) NOT NULL default '0',
- PRIMARY KEY (EventId)
-)
-# --------------------------------------------------------
-CREATE TABLE Favorites (
- FavoriteId int(11) NOT NULL auto_increment,
- PortalUserId int(11) NOT NULL default '0',
- ResourceId int(11) NOT NULL default '0',
- ItemTypeId int(11) NOT NULL default '0',
- Modified int(11) NOT NULL default '0',
- PRIMARY KEY (FavoriteId),
- UNIQUE KEY main (PortalUserId,ResourceId)
-)
-# --------------------------------------------------------
-CREATE TABLE IdGenerator (
- lastid int(11) default NULL
-)
-# --------------------------------------------------------
-CREATE TABLE Images (
- ImageId int(11) NOT NULL auto_increment,
- ResourceId int(11) NOT NULL default '0',
- Url varchar(255) NOT NULL default '',
- Name varchar(255) NOT NULL default '',
- AltName varchar(255) default NULL,
- ImageIndex int(11) NOT NULL default '0',
- LocalImage tinyint(4) NOT NULL default '1',
- LocalPath varchar(240) NOT NULL default '',
- Enabled int(11) NOT NULL default '1',
- DefaultImg int(11) NOT NULL default '0',
- ThumbUrl varchar(255) default NULL,
- Priority int(11) NOT NULL default '0',
- ThumbPath varchar(255) default NULL,
- LocalThumb tinyint(4) NOT NULL default '0',
- SameImages tinyint(4) NOT NULL default '0',
- PRIMARY KEY (ImageId),
- KEY ResourceId (ResourceId)
-)
-# --------------------------------------------------------
-CREATE TABLE ItemRating (
- RatingId int(11) NOT NULL auto_increment,
- IPAddress varchar(255) NOT NULL default '',
- CreatedOn double NOT NULL default '0',
- RatingValue int(11) NOT NULL default '0',
- ItemId int(11) NOT NULL default '0',
- PRIMARY KEY (RatingId)
-)
-# --------------------------------------------------------
-CREATE TABLE ItemReview (
- ReviewId int(11) NOT NULL auto_increment,
- CreatedOn double NOT NULL default '0',
- ReviewText longtext NOT NULL,
- IPAddress varchar(255) NOT NULL default '',
- ItemId int(11) NOT NULL default '0',
- CreatedById int(11) NOT NULL default '0',
- ItemType tinyint(4) NOT NULL default '0',
- Priority int(11) NOT NULL default '0',
- Status tinyint(4) NOT NULL default '0',
- TextFormat int(11) NOT NULL default '0',
- Module varchar(255) NOT NULL default '',
- PRIMARY KEY (ReviewId)
-)
-# --------------------------------------------------------
-CREATE TABLE ItemTypes (
- ItemType int(11) NOT NULL default '0',
- Module varchar(50) NOT NULL default '',
- SourceTable varchar(100) NOT NULL default '',
- TitleField varchar(50) default NULL,
- CreatorField varchar(255) NOT NULL default '',
- PopField varchar(255) default NULL,
- RateField varchar(255) default NULL,
- LangVar varchar(255) NOT NULL default '',
- PrimaryItem int(11) NOT NULL default '0',
- EditUrl varchar(255) NOT NULL default '',
- ClassName varchar(40) NOT NULL default '',
- ItemName varchar(50) NOT NULL default '',
- PRIMARY KEY (ItemType),
- KEY Module (Module)
-)
-# --------------------------------------------------------
-CREATE TABLE Language (
- LanguageId int(11) NOT NULL auto_increment,
- PackName varchar(40) NOT NULL default '',
- LocalName varchar(40) NOT NULL default '',
- Enabled int(11) NOT NULL default '0',
- PrimaryLang int(11) NOT NULL default '0',
- IconURL varchar(255) default NULL,
- DateFormat varchar(50) NOT NULL default '',
- TimeFormat varchar(50) NOT NULL default '',
- DecimalPoint char(2) NOT NULL default '.',
- ThousandSep char(1) NOT NULL default ',',
- PRIMARY KEY (LanguageId)
-)
-# --------------------------------------------------------
-CREATE TABLE Modules (
- Name varchar(255) NOT NULL default '',
- Path varchar(255) NOT NULL default '',
- Var varchar(10) NOT NULL default '',
- Version varchar(10) NOT NULL default '',
- Loaded tinyint(4) NOT NULL default '1',
- LoadOrder tinyint(4) NOT NULL default '0',
- TemplatePath varchar(255) NOT NULL default '',
- RootCat int(11) NOT NULL default '0',
- BuildDate double NOT NULL default '0',
- PRIMARY KEY (Name)
-)
-# --------------------------------------------------------
-CREATE TABLE PermCache (
- PermCacheId int(11) NOT NULL auto_increment,
- CategoryId int(11) NOT NULL default '0',
- PermId int(11) NOT NULL default '0',
- ACL varchar(255) NOT NULL default '',
- DACL varchar(255) NOT NULL default '',
- PRIMARY KEY (PermCacheId),
- KEY CategoryId (CategoryId),
- KEY PermId (PermId)
-)
-# --------------------------------------------------------
-CREATE TABLE PermissionConfig (
- PermissionConfigId int(11) NOT NULL auto_increment,
- PermissionName varchar(30) NOT NULL default '',
- Description varchar(255) NOT NULL default '',
- ErrorMessage varchar(255) NOT NULL default '',
- ModuleId varchar(20) NOT NULL default '0',
- PRIMARY KEY (PermissionConfigId),
- KEY PermissionName (PermissionName)
-)
-# --------------------------------------------------------
-CREATE TABLE Permissions (
- PermissionId int(11) NOT NULL auto_increment,
- Permission varchar(30) NOT NULL default '',
- GroupId int(11) default '0',
- PermissionValue int(11) NOT NULL default '0',
- Type tinyint(4) NOT NULL default '0',
- CatId int(11) NOT NULL default '0',
- PRIMARY KEY (PermissionId)
-)
-# --------------------------------------------------------
-CREATE TABLE PersistantSessionData (
- PortalUserId int(11) NOT NULL default '0',
- VariableName varchar(255) NOT NULL default '',
- VariableValue text NOT NULL,
- KEY UserId (PortalUserId),
- KEY VariableName (VariableName)
-)
-# --------------------------------------------------------
-CREATE TABLE Phrase (
- Phrase varchar(255) NOT NULL default '',
- Translation varchar(255) NOT NULL default '',
- PhraseType int(11) NOT NULL default '0',
- PhraseId int(11) NOT NULL auto_increment,
- LanguageId int(11) NOT NULL default '0',
- PRIMARY KEY (PhraseId),
- INDEX Phrase_Index (Phrase)
-)
-# --------------------------------------------------------
-CREATE TABLE PhraseCache (
- Template varchar(40) NOT NULL default '',
- PhraseList text NOT NULL,
- CacheDate int(11) NOT NULL default '0',
- ThemeId int(11) NOT NULL default '0',
- PRIMARY KEY (Template)
-)
-# --------------------------------------------------------
-CREATE TABLE PortalGroup (
- GroupId int(11) NOT NULL auto_increment,
- Name varchar(255) NOT NULL default '',
- Description varchar(255) default NULL,
- CreatedOn double NOT NULL default '0',
- System tinyint(4) NOT NULL default '0',
- Personal tinyint(4) NOT NULL default '0',
- Enabled tinyint(4) NOT NULL default '1',
- ResourceId int(11) NOT NULL default '0',
- PRIMARY KEY (GroupId),
- UNIQUE KEY Name (Name),
- KEY ResourceId (ResourceId),
- KEY Personal (Personal),
- KEY Enabled (Enabled)
-)
-# --------------------------------------------------------
-CREATE TABLE PortalUser (
- PortalUserId int(11) NOT NULL auto_increment,
- Login varchar(255) default NULL,
- Password varchar(255) default NULL,
- FirstName varchar(255) default NULL,
- LastName varchar(255) default NULL,
- Email varchar(255) NOT NULL default '',
- CreatedOn double NOT NULL default '0',
- Phone varchar(20) default NULL,
- Street varchar(255) default NULL,
- City varchar(20) default NULL,
- State varchar(20) default NULL,
- Zip varchar(20) default NULL,
- Country varchar(20) NOT NULL default '',
- ResourceId int(11) NOT NULL default '0',
- Status tinyint(4) NOT NULL default '2',
- Modified int(11) NOT NULL default '0',
- dob double NOT NULL default '0',
- tz int(11) default NULL,
- ip varchar(20) default NULL,
- IsBanned tinyint(1) NOT NULL default '0',
- PRIMARY KEY (PortalUserId),
- UNIQUE KEY Login (Login),
- KEY ResourceId (ResourceId),
- KEY CreatedOn (CreatedOn)
-)
-# --------------------------------------------------------
-CREATE TABLE Relationship (
- RelationshipId int(11) NOT NULL auto_increment,
- SourceId int(11) default NULL,
- TargetId int(11) default NULL,
- SourceType tinyint(4) NOT NULL default '0',
- TargetType tinyint(4) NOT NULL default '0',
- Type int(11) NOT NULL default '0',
- Enabled int(11) NOT NULL default '1',
- Priority int(11) NOT NULL default '0',
- PRIMARY KEY (RelationshipId),
- KEY RelSource (SourceId),
- KEY RelTarget (TargetId)
-)
-# --------------------------------------------------------
-CREATE TABLE SearchConfig (
- TableName varchar(40) NOT NULL default '',
- FieldName varchar(40) NOT NULL default '',
- SimpleSearch tinyint(4) NOT NULL default '0',
- AdvancedSearch tinyint(4) NOT NULL default '0',
- Description varchar(255) default NULL,
- DisplayName varchar(80) default NULL,
- ModuleName varchar(20) default NULL,
- ConfigHeader varchar(255) default NULL,
- DisplayOrder int(11) NOT NULL default '0',
- SearchConfigId int(11) NOT NULL auto_increment,
- Priority int(11) NOT NULL default '0',
- FieldType varchar(20) NOT NULL default 'text',
- ForeignField varchar(255) default NULL,
- JoinClause varchar(255) default NULL,
- IsWhere text,
- IsNotWhere text,
- ContainsWhere text,
- NotContainsWhere text,
- CustomFieldId int(11) NOT NULL default '0',
- PRIMARY KEY (SearchConfigId)
-)
-# --------------------------------------------------------
-CREATE TABLE SearchLog (
- SearchLogId int(11) NOT NULL auto_increment,
- Keyword varchar(255) NOT NULL default '',
- Indices bigint(20) NOT NULL default '0',
- SearchType int(11) NOT NULL default '0',
- PRIMARY KEY (SearchLogId)
-)
-# --------------------------------------------------------
-CREATE TABLE SessionData (
- SessionKey varchar(50) NOT NULL default '',
- VariableName varchar(255) NOT NULL default '',
- VariableValue text NOT NULL,
- KEY SessionKey (SessionKey),
- KEY VariableName (VariableName)
-)
-# --------------------------------------------------------
-CREATE TABLE SpamControl (
- ItemResourceId int(11) NOT NULL default '0',
- IPaddress varchar(20) NOT NULL default '',
- Expire double NOT NULL default '0',
- PortalUserId int(11) NOT NULL default '0',
- DataType varchar(20) default NULL
-)
-# --------------------------------------------------------
-CREATE TABLE StatItem (
- StatItemId int(11) NOT NULL auto_increment,
- Module varchar(20) NOT NULL default '',
- ValueSQL varchar(255) default NULL,
- ResetSQL varchar(255) default NULL,
- ListLabel varchar(255) NOT NULL default '',
- Priority int(11) NOT NULL default '0',
- AdminSummary int(11) NOT NULL default '0',
- PRIMARY KEY (StatItemId)
-)
-# --------------------------------------------------------
-CREATE TABLE Theme (
- ThemeId int(11) NOT NULL auto_increment,
- Name varchar(40) NOT NULL default '',
- Enabled int(11) NOT NULL default '1',
- Description varchar(255) default NULL,
- PrimaryTheme int(11) NOT NULL default '0',
- CacheTimeout int(11) NOT NULL default '0',
- PRIMARY KEY (ThemeId)
-)
-# --------------------------------------------------------
-CREATE TABLE ThemeFiles (
- FileId int(11) NOT NULL auto_increment,
- ThemeId int(11) NOT NULL default '0',
- FileName varchar(255) NOT NULL default '',
- FilePath varchar(255) NOT NULL default '',
- Description varchar(255) default NULL,
- FileType int(11) NOT NULL default '0',
- PRIMARY KEY (FileId),
- KEY theme (ThemeId)
-)
-# --------------------------------------------------------
-CREATE TABLE UserGroup (
- PortalUserId int(11) NOT NULL default '0',
- GroupId int(11) NOT NULL default '0',
- PrimaryGroup tinyint(4) NOT NULL default '1',
- PRIMARY KEY (PortalUserId,GroupId),
- KEY GroupId (GroupId),
- KEY PrimaryGroup (PrimaryGroup)
-)
-# --------------------------------------------------------
-
-CREATE TABLE UserSession (
- SessionKey varchar(50) NOT NULL default '',
- CurrentTempKey varchar(50) default NULL,
- PrevTempKey varchar(50) default NULL,
- LastAccessed double NOT NULL default '0',
- PortalUserId varchar(255) NOT NULL default '',
- Language varchar(255) NOT NULL default '',
- Theme varchar(255) NOT NULL default '',
- GroupId int(11) NOT NULL default '0',
- IpAddress varchar(20) NOT NULL default '0.0.0.0',
- Status int(11) NOT NULL default '1',
- GroupList varchar(255) default NULL,
- tz int(11) default NULL,
- PRIMARY KEY (SessionKey),
- KEY UserId (PortalUserId),
- KEY LastAccessed (LastAccessed)
-)
-# --------------------------------------------------------
-CREATE TABLE SuggestMail (
- email varchar(255) NOT NULL default '',
- sent double,
- PRIMARY KEY (email)
-)
-# --------------------------------------------------------
-CREATE TABLE SysCache (
- SysCacheId int(11) NOT NULL auto_increment,
- Name varchar(255) NOT NULL default '',
- Value mediumtext,
- Expire double NOT NULL default '0',
- Module varchar(20) default NULL,
- Context varchar(255) default NULL,
- GroupList varchar(255) NOT NULL default '',
- PRIMARY KEY (SysCacheId),
- KEY Name (Name)
-)
-# --------------------------------------------------------
-CREATE TABLE TagLibrary (
- TagId int(11) NOT NULL auto_increment,
- name varchar(255) NOT NULL default '',
- description text,
- example text,
- scope varchar(20) NOT NULL default 'global',
- PRIMARY KEY (TagId)
-)
-# --------------------------------------------------------
-CREATE TABLE TagAttributes (
- AttrId int(11) NOT NULL auto_increment,
- TagId int(11) NOT NULL default '0',
- Name varchar(255) NOT NULL default '',
- AttrType varchar(20) default NULL,
- DefValue varchar(255) default NULL,
- Description TEXT,
- Required int(11) NOT NULL default '0',
- PRIMARY KEY (AttrId)
-)
-# --------------------------------------------------------
-CREATE TABLE EmailLog (
- EmailLogId int(11) NOT NULL auto_increment,
- fromuser varchar(200) default NULL,
- addressto varchar(255) default NULL,
- subject varchar(255) default NULL,
- timestamp bigint(20) default '0',
- event varchar(100) default NULL,
- PRIMARY KEY (EmailLogId)
-)
-# --------------------------------------------------------
-CREATE TABLE ImportScripts (
- is_id smallint(5) unsigned NOT NULL auto_increment,
- is_Module varchar(50) NOT NULL default '',
- is_string_id varchar(10) NOT NULL default '',
- is_script varchar(100) NOT NULL default '',
- is_label varchar(255) NOT NULL default '',
- is_field_prefix varchar(50) NOT NULL default '',
- is_requred_fields varchar(255) NOT NULL default '',
- is_enabled tinyint(1) unsigned NOT NULL default '0',
- PRIMARY KEY (is_id)
+CREATE TABLE BanRules (
+ RuleId int(11) NOT NULL auto_increment,
+ RuleType tinyint(4) NOT NULL default '0',
+ ItemField varchar(255) default NULL,
+ ItemVerb tinyint(4) NOT NULL default '0',
+ ItemValue varchar(255) NOT NULL default '',
+ ItemType int(11) NOT NULL default '0',
+ Priority int(11) NOT NULL default '0',
+ Status tinyint(4) NOT NULL default '1',
+ ErrorTag varchar(255) default NULL,
+ PRIMARY KEY (RuleId)
+)
+# --------------------------------------------------------
+CREATE TABLE Category (
+ CategoryId int(11) NOT NULL auto_increment,
+ Type int(11) NOT NULL default '0',
+ ParentId int(11) NOT NULL default '0',
+ Name varchar(255) NOT NULL default '',
+ Description text NOT NULL,
+ CreatedOn double NOT NULL default '0',
+ EditorsPick tinyint(4) default NULL,
+ Status tinyint(4) NOT NULL default '0',
+ Pop tinyint(4) default NULL,
+ Priority int(11) default NULL,
+ MetaKeywords varchar(255) default NULL,
+ CachedDescendantCatsQty int(11) default NULL,
+ CachedNavbar text NOT NULL,
+ CreatedById int(11) NOT NULL default '0',
+ ResourceId int(11) default NULL,
+ ParentPath text NOT NULL,
+ MetaDescription varchar(255) default NULL,
+ HotItem int(11) NOT NULL default '2',
+ NewItem int(11) NOT NULL default '2',
+ PopItem int(11) NOT NULL default '2',
+ Modified double NOT NULL default '0',
+ ModifiedById int(11) NOT NULL default '0',
+ PRIMARY KEY (CategoryId),
+ KEY ParentId (ParentId),
+ KEY ResourceId (ResourceId),
+ KEY Modified (Modified),
+ KEY Priority (Priority),
+ KEY sorting (Name,Priority)
+)
+# --------------------------------------------------------
+CREATE TABLE CategoryItems (
+ CategoryId int(11) NOT NULL default '0',
+ ItemResourceId int(11) NOT NULL default '0',
+ PrimaryCat tinyint(4) NOT NULL default '0',
+ PRIMARY KEY (CategoryId,ItemResourceId),
+ KEY ItemResourceId (ItemResourceId),
+ KEY PrimaryCat (PrimaryCat)
+)
+# --------------------------------------------------------
+CREATE TABLE ConfigurationAdmin (
+ VariableName varchar(80) NOT NULL default '',
+ heading varchar(255) default NULL,
+ prompt varchar(255) default NULL,
+ element_type varchar(20) NOT NULL default '',
+ validation varchar(255) default NULL,
+ ValueList text default NULL,
+ DisplayOrder int(11) NOT NULL default '0',
+ Install int(11) NOT NULL default '1',
+ PRIMARY KEY (VariableName)
+)
+# --------------------------------------------------------
+CREATE TABLE ConfigurationValues (
+ VariableName varchar(255) NOT NULL default '',
+ VariableValue varchar(255) default NULL,
+ ModuleOwner varchar(20) default 'In-Portal',
+ Section varchar(255) NOT NULL default '',
+ PRIMARY KEY (VariableName)
+)
+# --------------------------------------------------------
+CREATE TABLE CountCache (
+ ListType int(11) NOT NULL default '0',
+ ItemType int(11) NOT NULL default '-1',
+ Value int(11) NOT NULL default '0',
+ CountCacheId int(11) NOT NULL auto_increment,
+ LastUpdate int(11) NOT NULL default '0',
+ ExtraId varchar(50) default NULL,
+ TodayOnly tinyint(4) NOT NULL default '0',
+ PRIMARY KEY (CountCacheId)
+)
+# --------------------------------------------------------
+CREATE TABLE CustomField (
+ CustomFieldId int(11) NOT NULL auto_increment,
+ Type int(11) NOT NULL default '0',
+ FieldName varchar(255) NOT NULL default '',
+ FieldLabel varchar(40) default NULL,
+ Heading varchar(60) default NULL,
+ Prompt varchar(60) default NULL,
+ ElementType varchar(50) NOT NULL default '',
+ ValueList varchar(255) default NULL,
+ DisplayOrder int(11) NOT NULL default '0',
+ OnGeneralTab tinyint(4) NOT NULL default '0',
+ PRIMARY KEY (CustomFieldId),
+ KEY Type (Type)
+)
+# --------------------------------------------------------
+CREATE TABLE CustomMetaData (
+ CustomDataId int(11) NOT NULL auto_increment,
+ ResourceId int(11) NOT NULL default '0',
+ CustomFieldId int(11) NOT NULL default '0',
+ Value text NOT NULL,
+ PRIMARY KEY (CustomDataId)
+)
+# --------------------------------------------------------
+CREATE TABLE EmailMessage (
+ EmailMessageId int(10) NOT NULL auto_increment,
+ Template longtext,
+ MessageType enum('html','text') NOT NULL default 'text',
+ LanguageId int(11) NOT NULL default '0',
+ EventId int(11) NOT NULL default '0',
+ PRIMARY KEY (EmailMessageId)
+)
+# --------------------------------------------------------
+CREATE TABLE EmailQueue (
+ Subject text NOT NULL,
+ toaddr text NOT NULL,
+ fromaddr text NOT NULL,
+ message blob,
+ headers blob,
+ queued timestamp NOT NULL
+)
+# --------------------------------------------------------
+CREATE TABLE EmailSubscribers (
+ EmailMessageId int(11) NOT NULL default '0',
+ PortalUserId int(11) NOT NULL default '0'
+)
+# --------------------------------------------------------
+CREATE TABLE Events (
+ EventId int(11) NOT NULL auto_increment,
+ Event varchar(40) NOT NULL default '',
+ Enabled int(11) NOT NULL default '1',
+ FromUserId int(11) NOT NULL default '0',
+ Module varchar(40) NOT NULL default '',
+ Description varchar(255) NOT NULL default '',
+ Type int(11) NOT NULL default '0',
+ PRIMARY KEY (EventId)
+)
+# --------------------------------------------------------
+CREATE TABLE Favorites (
+ FavoriteId int(11) NOT NULL auto_increment,
+ PortalUserId int(11) NOT NULL default '0',
+ ResourceId int(11) NOT NULL default '0',
+ ItemTypeId int(11) NOT NULL default '0',
+ Modified int(11) NOT NULL default '0',
+ PRIMARY KEY (FavoriteId),
+ UNIQUE KEY main (PortalUserId,ResourceId)
+)
+# --------------------------------------------------------
+CREATE TABLE IdGenerator (
+ lastid int(11) default NULL
+)
+# --------------------------------------------------------
+CREATE TABLE Images (
+ ImageId int(11) NOT NULL auto_increment,
+ ResourceId int(11) NOT NULL default '0',
+ Url varchar(255) NOT NULL default '',
+ Name varchar(255) NOT NULL default '',
+ AltName varchar(255) default NULL,
+ ImageIndex int(11) NOT NULL default '0',
+ LocalImage tinyint(4) NOT NULL default '1',
+ LocalPath varchar(240) NOT NULL default '',
+ Enabled int(11) NOT NULL default '1',
+ DefaultImg int(11) NOT NULL default '0',
+ ThumbUrl varchar(255) default NULL,
+ Priority int(11) NOT NULL default '0',
+ ThumbPath varchar(255) default NULL,
+ LocalThumb tinyint(4) NOT NULL default '0',
+ SameImages tinyint(4) NOT NULL default '0',
+ PRIMARY KEY (ImageId),
+ KEY ResourceId (ResourceId)
+)
+# --------------------------------------------------------
+CREATE TABLE ItemRating (
+ RatingId int(11) NOT NULL auto_increment,
+ IPAddress varchar(255) NOT NULL default '',
+ CreatedOn double NOT NULL default '0',
+ RatingValue int(11) NOT NULL default '0',
+ ItemId int(11) NOT NULL default '0',
+ PRIMARY KEY (RatingId)
+)
+# --------------------------------------------------------
+CREATE TABLE ItemReview (
+ ReviewId int(11) NOT NULL auto_increment,
+ CreatedOn double NOT NULL default '0',
+ ReviewText longtext NOT NULL,
+ IPAddress varchar(255) NOT NULL default '',
+ ItemId int(11) NOT NULL default '0',
+ CreatedById int(11) NOT NULL default '0',
+ ItemType tinyint(4) NOT NULL default '0',
+ Priority int(11) NOT NULL default '0',
+ Status tinyint(4) NOT NULL default '0',
+ TextFormat int(11) NOT NULL default '0',
+ Module varchar(255) NOT NULL default '',
+ PRIMARY KEY (ReviewId)
+)
+# --------------------------------------------------------
+CREATE TABLE ItemTypes (
+ ItemType int(11) NOT NULL default '0',
+ Module varchar(50) NOT NULL default '',
+ SourceTable varchar(100) NOT NULL default '',
+ TitleField varchar(50) default NULL,
+ CreatorField varchar(255) NOT NULL default '',
+ PopField varchar(255) default NULL,
+ RateField varchar(255) default NULL,
+ LangVar varchar(255) NOT NULL default '',
+ PrimaryItem int(11) NOT NULL default '0',
+ EditUrl varchar(255) NOT NULL default '',
+ ClassName varchar(40) NOT NULL default '',
+ ItemName varchar(50) NOT NULL default '',
+ PRIMARY KEY (ItemType),
+ KEY Module (Module)
+)
+# --------------------------------------------------------
+CREATE TABLE Language (
+ LanguageId int(11) NOT NULL auto_increment,
+ PackName varchar(40) NOT NULL default '',
+ LocalName varchar(40) NOT NULL default '',
+ Enabled int(11) NOT NULL default '0',
+ PrimaryLang int(11) NOT NULL default '0',
+ IconURL varchar(255) default NULL,
+ DateFormat varchar(50) NOT NULL default '',
+ TimeFormat varchar(50) NOT NULL default '',
+ DecimalPoint char(2) NOT NULL default '.',
+ ThousandSep char(1) NOT NULL default ',',
+ PRIMARY KEY (LanguageId)
+)
+# --------------------------------------------------------
+CREATE TABLE Modules (
+ Name varchar(255) NOT NULL default '',
+ Path varchar(255) NOT NULL default '',
+ Var varchar(10) NOT NULL default '',
+ Version varchar(10) NOT NULL default '',
+ Loaded tinyint(4) NOT NULL default '1',
+ LoadOrder tinyint(4) NOT NULL default '0',
+ TemplatePath varchar(255) NOT NULL default '',
+ RootCat int(11) NOT NULL default '0',
+ BuildDate double NOT NULL default '0',
+ PRIMARY KEY (Name)
+)
+# --------------------------------------------------------
+CREATE TABLE PermCache (
+ PermCacheId int(11) NOT NULL auto_increment,
+ CategoryId int(11) NOT NULL default '0',
+ PermId int(11) NOT NULL default '0',
+ ACL varchar(255) NOT NULL default '',
+ DACL varchar(255) NOT NULL default '',
+ PRIMARY KEY (PermCacheId),
+ KEY CategoryId (CategoryId),
+ KEY PermId (PermId)
+)
+# --------------------------------------------------------
+CREATE TABLE PermissionConfig (
+ PermissionConfigId int(11) NOT NULL auto_increment,
+ PermissionName varchar(30) NOT NULL default '',
+ Description varchar(255) NOT NULL default '',
+ ErrorMessage varchar(255) NOT NULL default '',
+ ModuleId varchar(20) NOT NULL default '0',
+ PRIMARY KEY (PermissionConfigId),
+ KEY PermissionName (PermissionName)
+)
+# --------------------------------------------------------
+CREATE TABLE Permissions (
+ PermissionId int(11) NOT NULL auto_increment,
+ Permission varchar(30) NOT NULL default '',
+ GroupId int(11) default '0',
+ PermissionValue int(11) NOT NULL default '0',
+ Type tinyint(4) NOT NULL default '0',
+ CatId int(11) NOT NULL default '0',
+ PRIMARY KEY (PermissionId)
+)
+# --------------------------------------------------------
+CREATE TABLE PersistantSessionData (
+ PortalUserId int(11) NOT NULL default '0',
+ VariableName varchar(255) NOT NULL default '',
+ VariableValue text NOT NULL,
+ KEY UserId (PortalUserId),
+ KEY VariableName (VariableName)
+)
+# --------------------------------------------------------
+CREATE TABLE Phrase (
+ Phrase varchar(255) NOT NULL default '',
+ Translation varchar(255) NOT NULL default '',
+ PhraseType int(11) NOT NULL default '0',
+ PhraseId int(11) NOT NULL auto_increment,
+ LanguageId int(11) NOT NULL default '0',
+ PRIMARY KEY (PhraseId),
+ INDEX Phrase_Index (Phrase)
+)
+# --------------------------------------------------------
+CREATE TABLE PhraseCache (
+ Template varchar(40) NOT NULL default '',
+ PhraseList text NOT NULL,
+ CacheDate int(11) NOT NULL default '0',
+ ThemeId int(11) NOT NULL default '0',
+ PRIMARY KEY (Template)
+)
+# --------------------------------------------------------
+CREATE TABLE PortalGroup (
+ GroupId int(11) NOT NULL auto_increment,
+ Name varchar(255) NOT NULL default '',
+ Description varchar(255) default NULL,
+ CreatedOn double NOT NULL default '0',
+ System tinyint(4) NOT NULL default '0',
+ Personal tinyint(4) NOT NULL default '0',
+ Enabled tinyint(4) NOT NULL default '1',
+ ResourceId int(11) NOT NULL default '0',
+ PRIMARY KEY (GroupId),
+ UNIQUE KEY Name (Name),
+ KEY ResourceId (ResourceId),
+ KEY Personal (Personal),
+ KEY Enabled (Enabled)
+)
+# --------------------------------------------------------
+CREATE TABLE PortalUser (
+ PortalUserId int(11) NOT NULL auto_increment,
+ Login varchar(255) default NULL,
+ Password varchar(255) default NULL,
+ FirstName varchar(255) default NULL,
+ LastName varchar(255) default NULL,
+ Email varchar(255) NOT NULL default '',
+ CreatedOn double NOT NULL default '0',
+ Phone varchar(20) default NULL,
+ Street varchar(255) default NULL,
+ City varchar(20) default NULL,
+ State varchar(20) default NULL,
+ Zip varchar(20) default NULL,
+ Country varchar(20) NOT NULL default '',
+ ResourceId int(11) NOT NULL default '0',
+ Status tinyint(4) NOT NULL default '2',
+ Modified int(11) NOT NULL default '0',
+ dob double NOT NULL default '0',
+ tz int(11) default NULL,
+ ip varchar(20) default NULL,
+ IsBanned tinyint(1) NOT NULL default '0',
+ PRIMARY KEY (PortalUserId),
+ UNIQUE KEY Login (Login),
+ KEY ResourceId (ResourceId),
+ KEY CreatedOn (CreatedOn)
+)
+# --------------------------------------------------------
+CREATE TABLE Relationship (
+ RelationshipId int(11) NOT NULL auto_increment,
+ SourceId int(11) default NULL,
+ TargetId int(11) default NULL,
+ SourceType tinyint(4) NOT NULL default '0',
+ TargetType tinyint(4) NOT NULL default '0',
+ Type int(11) NOT NULL default '0',
+ Enabled int(11) NOT NULL default '1',
+ Priority int(11) NOT NULL default '0',
+ PRIMARY KEY (RelationshipId),
+ KEY RelSource (SourceId),
+ KEY RelTarget (TargetId)
+)
+# --------------------------------------------------------
+CREATE TABLE SearchConfig (
+ TableName varchar(40) NOT NULL default '',
+ FieldName varchar(40) NOT NULL default '',
+ SimpleSearch tinyint(4) NOT NULL default '0',
+ AdvancedSearch tinyint(4) NOT NULL default '0',
+ Description varchar(255) default NULL,
+ DisplayName varchar(80) default NULL,
+ ModuleName varchar(20) default NULL,
+ ConfigHeader varchar(255) default NULL,
+ DisplayOrder int(11) NOT NULL default '0',
+ SearchConfigId int(11) NOT NULL auto_increment,
+ Priority int(11) NOT NULL default '0',
+ FieldType varchar(20) NOT NULL default 'text',
+ ForeignField varchar(255) default NULL,
+ JoinClause varchar(255) default NULL,
+ IsWhere text,
+ IsNotWhere text,
+ ContainsWhere text,
+ NotContainsWhere text,
+ CustomFieldId int(11) NOT NULL default '0',
+ PRIMARY KEY (SearchConfigId)
+)
+# --------------------------------------------------------
+CREATE TABLE SearchLog (
+ SearchLogId int(11) NOT NULL auto_increment,
+ Keyword varchar(255) NOT NULL default '',
+ Indices bigint(20) NOT NULL default '0',
+ SearchType int(11) NOT NULL default '0',
+ PRIMARY KEY (SearchLogId)
+)
+# --------------------------------------------------------
+CREATE TABLE SessionData (
+ SessionKey varchar(50) NOT NULL default '',
+ VariableName varchar(255) NOT NULL default '',
+ VariableValue text NOT NULL,
+ KEY SessionKey (SessionKey),
+ KEY VariableName (VariableName)
+)
+# --------------------------------------------------------
+CREATE TABLE SpamControl (
+ ItemResourceId int(11) NOT NULL default '0',
+ IPaddress varchar(20) NOT NULL default '',
+ Expire double NOT NULL default '0',
+ PortalUserId int(11) NOT NULL default '0',
+ DataType varchar(20) default NULL
+)
+# --------------------------------------------------------
+CREATE TABLE StatItem (
+ StatItemId int(11) NOT NULL auto_increment,
+ Module varchar(20) NOT NULL default '',
+ ValueSQL varchar(255) default NULL,
+ ResetSQL varchar(255) default NULL,
+ ListLabel varchar(255) NOT NULL default '',
+ Priority int(11) NOT NULL default '0',
+ AdminSummary int(11) NOT NULL default '0',
+ PRIMARY KEY (StatItemId)
+)
+# --------------------------------------------------------
+CREATE TABLE Theme (
+ ThemeId int(11) NOT NULL auto_increment,
+ Name varchar(40) NOT NULL default '',
+ Enabled int(11) NOT NULL default '1',
+ Description varchar(255) default NULL,
+ PrimaryTheme int(11) NOT NULL default '0',
+ CacheTimeout int(11) NOT NULL default '0',
+ PRIMARY KEY (ThemeId)
+)
+# --------------------------------------------------------
+CREATE TABLE ThemeFiles (
+ FileId int(11) NOT NULL auto_increment,
+ ThemeId int(11) NOT NULL default '0',
+ FileName varchar(255) NOT NULL default '',
+ FilePath varchar(255) NOT NULL default '',
+ Description varchar(255) default NULL,
+ FileType int(11) NOT NULL default '0',
+ PRIMARY KEY (FileId),
+ KEY theme (ThemeId)
+)
+# --------------------------------------------------------
+CREATE TABLE UserGroup (
+ PortalUserId int(11) NOT NULL default '0',
+ GroupId int(11) NOT NULL default '0',
+ PrimaryGroup tinyint(4) NOT NULL default '1',
+ PRIMARY KEY (PortalUserId,GroupId),
+ KEY GroupId (GroupId),
+ KEY PrimaryGroup (PrimaryGroup)
+)
+# --------------------------------------------------------
+
+CREATE TABLE UserSession (
+ SessionKey varchar(50) NOT NULL default '',
+ CurrentTempKey varchar(50) default NULL,
+ PrevTempKey varchar(50) default NULL,
+ LastAccessed double NOT NULL default '0',
+ PortalUserId varchar(255) NOT NULL default '',
+ Language varchar(255) NOT NULL default '',
+ Theme varchar(255) NOT NULL default '',
+ GroupId int(11) NOT NULL default '0',
+ IpAddress varchar(20) NOT NULL default '0.0.0.0',
+ Status int(11) NOT NULL default '1',
+ GroupList varchar(255) default NULL,
+ tz int(11) default NULL,
+ PRIMARY KEY (SessionKey),
+ KEY UserId (PortalUserId),
+ KEY LastAccessed (LastAccessed)
+)
+# --------------------------------------------------------
+CREATE TABLE SuggestMail (
+ email varchar(255) NOT NULL default '',
+ sent double,
+ PRIMARY KEY (email)
+)
+# --------------------------------------------------------
+CREATE TABLE SysCache (
+ SysCacheId int(11) NOT NULL auto_increment,
+ Name varchar(255) NOT NULL default '',
+ Value mediumtext,
+ Expire double NOT NULL default '0',
+ Module varchar(20) default NULL,
+ Context varchar(255) default NULL,
+ GroupList varchar(255) NOT NULL default '',
+ PRIMARY KEY (SysCacheId),
+ KEY Name (Name)
+)
+# --------------------------------------------------------
+CREATE TABLE TagLibrary (
+ TagId int(11) NOT NULL auto_increment,
+ name varchar(255) NOT NULL default '',
+ description text,
+ example text,
+ scope varchar(20) NOT NULL default 'global',
+ PRIMARY KEY (TagId)
+)
+# --------------------------------------------------------
+CREATE TABLE TagAttributes (
+ AttrId int(11) NOT NULL auto_increment,
+ TagId int(11) NOT NULL default '0',
+ Name varchar(255) NOT NULL default '',
+ AttrType varchar(20) default NULL,
+ DefValue varchar(255) default NULL,
+ Description TEXT,
+ Required int(11) NOT NULL default '0',
+ PRIMARY KEY (AttrId)
+)
+# --------------------------------------------------------
+CREATE TABLE EmailLog (
+ EmailLogId int(11) NOT NULL auto_increment,
+ fromuser varchar(200) default NULL,
+ addressto varchar(255) default NULL,
+ subject varchar(255) default NULL,
+ timestamp bigint(20) default '0',
+ event varchar(100) default NULL,
+ PRIMARY KEY (EmailLogId)
+)
+# --------------------------------------------------------
+CREATE TABLE ImportScripts (
+ is_id smallint(5) unsigned NOT NULL auto_increment,
+ is_Module varchar(50) NOT NULL default '',
+ is_string_id varchar(10) NOT NULL default '',
+ is_script varchar(100) NOT NULL default '',
+ is_label varchar(255) NOT NULL default '',
+ is_field_prefix varchar(50) NOT NULL default '',
+ is_requred_fields varchar(255) NOT NULL default '',
+ is_enabled tinyint(1) unsigned NOT NULL default '0',
+ PRIMARY KEY (is_id)
)
\ No newline at end of file
Index: trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql
===================================================================
diff -u -r616 -r642
--- trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql (.../inportal_upgrade_v1.0.8.sql) (revision 616)
+++ trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql (.../inportal_upgrade_v1.0.8.sql) (revision 642)
@@ -1,4 +1,7 @@
-UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Name' AND TableName = 'Category';
-UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Description' AND TableName = 'Category';
-
+UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Name' AND TableName = 'Category';
+UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Description' AND TableName = 'Category';
+ALTER TABLE ConfigurationAdmin CHANGE ValueList ValueList TEXT;
+UPDATE ConfigurationAdmin SET ValueList='Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0' WHERE VariableName='Category_Sortfield';
+UPDATE ConfigurationAdmin SET ValueList='Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0' WHERE VariableName='Category_Sortfield2';
+
UPDATE Modules SET Version = '1.0.8' WHERE Name = 'In-Portal';
\ No newline at end of file
Index: trunk/admin/browse.php
===================================================================
diff -u -r547 -r642
--- trunk/admin/browse.php (.../browse.php) (revision 547)
+++ trunk/admin/browse.php (.../browse.php) (revision 642)
@@ -1,472 +1,472 @@
-