Example #1
0
 /**
  * Session garbage collection handler
  *
  * @access protected
  * @return boolean
  */
 function _gc()
 {
     if (!$this->_db->Execute('DELETE FROM sessions WHERE expire < ' . $this->_db->DBTimeStamp(time() - $this->sessionLife)) && AK_DEBUG) {
         trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE);
     }
     return (bool) $this->_db->Affected_Rows();
 }
Example #2
0
 /**
  * Increment the counter
  * @return nothing
  * @access public
  */
 function incrementCounter()
 {
     // increment in the same table
     if ($this->table != '' && count($this->pk) > 0 && $this->counterField != '') {
         $fileHash = $this->downloadHash;
         $this->pk['value'] = $fileHash['pk'];
         $sql = 'UPDATE ' . $this->table . ' SET ' . KT_escapeFieldName($this->counterField) . ' = ' . KT_escapeFieldName($this->counterField) . '+ 1 WHERE ' . KT_escapeFieldName($this->pk['field']) . ' = ' . KT_escapeForSql($this->pk['value'], $this->pk['type'], false);
         $ret = $this->conn->Execute($sql);
         if ($ret === false) {
             $this->setError(new tNG_error('INCREMENTER_ERROR', array(), array($this->conn->ErrorMsg(), $sql)));
             return;
         }
     }
     // increment in the MTM table
     if ($this->counterFieldMtm != '' && $this->tableMtm != '' && count($this->fkMtm) > 0 && count($this->pkMtm) > 0) {
         $fileHash = $this->downloadHash;
         if (!isset($fileHash['fkMtm']) || $fileHash['fkMtm'] == '') {
             $this->setError(new tNG_error('INCREMENTER_ERROR_FK', array(), array($this->fkMtm['field'])));
             return;
         }
         $this->fkMtm['value'] = $fileHash['fkMtm'];
         if (!isset($fileHash['pkMtm']) || $fileHash['pkMtm'] == '') {
             $this->setError(new tNG_error('INCREMENTER_ERROR_FK', array(), array($this->pkMtm['field'])));
             return;
         }
         $this->pkMtm['value'] = $fileHash['pkMtm'];
         $sql = 'UPDATE ' . $this->tableMtm . ' SET ' . KT_escapeFieldName($this->counterFieldMtm) . ' = ' . KT_escapeFieldName($this->counterFieldMtm) . '+ 1 WHERE ' . KT_escapeFieldName($this->pkMtm['field']) . ' = ' . KT_escapeForSql($this->pkMtm['value'], $this->pkMtm['type'], false) . ' AND ' . KT_escapeFieldName($this->fkMtm['field']) . ' = ' . KT_escapeForSql($this->fkMtm['value'], $this->fkMtm['type'], false);
         $ret = $this->conn->Execute($sql);
         if ($ret === false) {
             $this->setError(new tNG_error('INCREMENTER_ERROR', array(), array($this->conn->ErrorMsg(), $sql)));
             return;
         }
     }
     return null;
 }
Example #3
0
 /**
  * Inserts $message to the currently open database.  Calls open(),
  * if necessary.  Also passes the message along to any Log_observer
  * instances that are observing this Log.
  *
  * @param mixed  $message  String or object containing the message to log.
  * @param string $priority The priority of the message.  Valid
  *                  values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT,
  *                  PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING,
  *                  PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG.
  * @return boolean  True on success or false on failure.
  * @access public     
  */
 function log($message, $priority = null)
 {
     /* If a priority hasn't been specified, use the default value. */
     if ($priority === null) {
         $priority = $this->_priority;
     }
     /* Abort early if the priority is above the maximum logging level. */
     if (!$this->_isMasked($priority)) {
         return false;
     }
     /* If the connection isn't open and can't be opened, return failure. */
     if (!$this->_opened && !$this->open()) {
         return false;
     }
     /* Extract the string representation of the message. */
     $message = $this->_extractMessage($message);
     /* Build the SQL query for this log entry insertion. */
     $q = sprintf('insert into %s (logtime, ident, priority, message)' . 'values(%s, %s, %d, %s)', $this->_table, $this->_db->DBTimeStamp(time()), $this->_db->Quote($this->_ident), $priority, $this->_db->Quote($message));
     $result = $this->_db->Execute($q);
     if ($this->_db->ErrorMsg() != '') {
         return false;
     }
     $this->_announce(array('priority' => $priority, 'message' => $message));
     return true;
 }
Example #4
0
/**
 *  获取文档
 *
 * @param     object  $dsql
 * @param     string  $ordertype  排序类型
 * @return    string
 */
function GetArchives($dsql, $ordertype)
{
    $starttime = time() - 24 * 3600 * 30;
    if ($ordertype == 'monthFeedback' || $ordertype == 'monthHot') {
        $swhere = " where senddate>{$starttime} ";
    } else {
        $swhere = "";
    }
    if (preg_match("#feedback#", $ordertype)) {
        $ordersql = " ORDER BY scores DESC ";
    } else {
        $ordersql = " ORDER BY click DESC ";
    }
    $query = "SELECT id,title,click,scores FROM #@__archives {$swhere} {$ordersql} LIMIT 0,20 ";
    $dsql->SetQuery($query);
    $dsql->Execute('ga');
    while ($row = $dsql->GetObject('ga')) {
        if (preg_match("#feedback#i", $ordertype)) {
            $moreinfo = "[<a target='_blank' href='" . $GLOBALS['cfg_phpurl'] . "/feedback.php?aid={$row->id}'><u>评论:{$row->scores}</u></a>]";
        } else {
            $moreinfo = "[点击:{$row->click}]";
        }
        echo "·<a href='archives_do.php?aid={$row->id}&dopost=viewArchives' target='_blank'>";
        echo cn_substr($row->title, 30) . "</a>{$moreinfo}<br/>\r\n";
    }
}
Example #5
0
 /**
  * Query
  *
  * @param mixed $sql
  * @param mixed $inputarr
  * @param mixed $numrows
  * @param mixed $offset
  * @access public
  * @return void
  */
 public function Query($sql, $inputarr = false, $numrows = -1, $offset = -1)
 {
     // auto add $dbprefix where we have {table}
     $sql = $this->_add_prefix($sql);
     // remove conversions for MySQL
     if (strcasecmp($this->dbtype, 'pgsql') != 0) {
         $sql = str_replace('::int', '', $sql);
         $sql = str_replace('::text', '', $sql);
     }
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     if ($numrows >= 0 or $offset >= 0) {
         /* adodb drivers are inconsisent with the casting of $numrows and $offset so WE
          * cast to integer here anyway */
         $result = $this->dblink->SelectLimit($sql, (int) $numrows, (int) $offset, $inputarr);
     } else {
         $result = $this->dblink->Execute($sql, $inputarr);
     }
     if (!$result) {
         if (function_exists("debug_backtrace") && defined('DEBUG_SQL')) {
             echo "<pre style='text-align: left;'>";
             var_dump(debug_backtrace());
             echo "</pre>";
         }
         $query_params = '';
         if (is_array($inputarr) && count($inputarr)) {
             $query_params = implode(',', array_map(array('Filters', 'noXSS'), $inputarr));
         }
         die(sprintf("Query {%s} with params {%s} Failed! (%s)", Filters::noXSS($sql), $query_params, Filters::noXSS($this->dblink->ErrorMsg())));
     }
     return $result;
 }
Example #6
0
 public function UpdateLevelById($category_id, $level, $level_name)
 {
     $category_id = $this->db->Quote($category_id);
     $level = $this->db->Quote($level);
     $level_name = $this->db->Quote($level_name);
     $sql = 'UPDATE ' . _DB_PREFIX_ . 'category_tags SET tag_level_name = ' . $level_name . ' WHERE tag_level = ' . $level . ' AND id_category = ' . $category_id;
     $this->db->StartTrans();
     if ($this->db->Execute($sql)) {
         $this->db->CompleteTrans();
         return true;
     } else {
         $this->db->FailTrans();
         return false;
     }
 }
Example #7
0
/**
 * 获得特定的Tag列表
 *
 * @param object $dsql
 * @param int $pageno
 * @param int $pagesize
 * @param string $orderby
 */
function GetTagList($dsql, $pageno, $pagesize, $orderby = 'aid')
{
    global $cfg_phpurl, $addsql;
    $start = ($pageno - 1) * $pagesize;
    $printhead = "<table width='98%' border='0' cellpadding='1' cellspacing='1' align='center'  class='tbtitle' style='background:#cfcfcf;margin-bottom:5px;'>\n        <tr align='center' bgcolor='#FBFCE2'>\n          <td width='5%' class='tbsname'><a href='#' onclick=\"ReloadPage('aid')\"><u>ID</u></a></td>\n          <td width='20%' class='tbsname'>列表名称</td>\n          <td width='20%' class='tbsname'>模板文件</td>\n          <td width='5%' class='tbsname'><a href='#' onclick=\"ReloadPage('click')\"><u>点击</u></a></td>\n          <td width='15%' class='tbsname'>创建时间</td>\n          <td class='tbsname'>管理</td>\n            </tr>\r\n";
    echo $printhead;
    $dsql->SetQuery("Select aid,title,templet,click,edtime,namerule,listdir,defaultpage,nodefault From #@__freelist {$addsql} order by {$orderby} desc limit {$start},{$pagesize} ");
    $dsql->Execute();
    while ($row = $dsql->GetArray()) {
        $listurl = GetFreeListUrl($row['aid'], $row['namerule'], $row['listdir'], $row['defaultpage'], $row['nodefault']);
        $line = "\n    <tr align='center' bgcolor='#FFFFFF' onMouseMove=\"javascript:this.bgColor='#FCFDEE';\" onMouseOut=\"javascript:this.bgColor='#FFFFFF';\">\n        <td>{$row['aid']}</td>\n        <td> <a href='{$listurl}' target='_blank'>{$row['title']}</a> </td>\n        <td> {$row['templet']} </td>\n        <td> {$row['click']} </td>\n        <td>" . MyDate("y-m-d", $row['edtime']) . "</td>\n        <td> <a href='#' onclick='EditNote({$row['aid']})'>更改</a> |\n        <a href='#' onclick='CreateNote({$row['aid']})'>更新</a> |\n         <a href='#' onclick='DelNote({$row['aid']})'>删除</a>\n    </td>\n  </tr>";
        echo $line;
    }
    echo "</table>\r\n";
}
 /**
  * Get user information from database
  *
  * This function uses the given username to fetch
  * the corresponding login data from the database
  * table. If an account that matches the passed username
  * and password is found, the function returns true.
  * Otherwise it returns false.
  *
  * @param   string Username
  * @param   string Password
  * @return  mixed  Error object or boolean
  */
 function fetchData($username, $password)
 {
     // Prepare for a database query
     $err = $this->_prepare();
     if ($err !== true) {
         return PEAR::raiseError($err->getMessage(), $err->getCode());
     }
     // Find if db_fields contains a *, i so assume all col are selected
     if (strstr($this->options['db_fields'], '*')) {
         $sql_from = "*";
     } else {
         $sql_from = $this->options['usernamecol'] . ", " . $this->options['passwordcol'] . $this->options['db_fields'];
     }
     $query = "SELECT " . $sql_from . " FROM " . $this->options['table'] . " WHERE " . $this->options['usernamecol'] . " = " . $this->db->Quote($username);
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     $rset = $this->db->Execute($query);
     $res = $rset->fetchRow();
     if (DB::isError($res)) {
         return PEAR::raiseError($res->getMessage(), $res->getCode());
     }
     if (!is_array($res)) {
         $this->activeUser = '';
         return false;
     }
     if ($this->verifyPassword(trim($password, "\r\n"), trim($res[$this->options['passwordcol']], "\r\n"), $this->options['cryptType'])) {
         // Store additional field values in the session
         foreach ($res as $key => $value) {
             if ($key == $this->options['passwordcol'] || $key == $this->options['usernamecol']) {
                 continue;
             }
             // Use reference to the auth object if exists
             // This is because the auth session variable can change so a static call to setAuthData does not make sence
             if (is_object($this->_auth_obj)) {
                 $this->_auth_obj->setAuthData($key, $value);
             } else {
                 Auth::setAuthData($key, $value);
             }
         }
         return true;
     }
     $this->activeUser = $res[$this->options['usernamecol']];
     return false;
 }
Example #9
0
/**
 *  获得特定的关键字列表
 *
 * @access    public
 * @param     object  $dsql  数据库操作类
 * @param     int  $pageno  页面数
 * @param     int  $pagesize  页面尺寸
 * @return    string
 */
function GetList(&$dsql, $pageno, $pagesize)
{
    global $cfg_phpurl, $cfg_ml;
    $pagesize = intval($pagesize);
    $pageno = intval($pageno);
    $start = ($pageno - 1) * $pagesize;
    $dsql->SetQuery("SELECT * FROM `#@__member_guestbook` WHERE mid='" . $cfg_ml->M_ID . "' ORDER BY aid DESC LIMIT {$start},{$pagesize} ");
    $dsql->Execute();
    $line = '';
    while ($row = $dsql->GetArray()) {
        $line .= "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='list'>\r\n          <thead>\r\n            <tr>\r\n              <th colspan='6'><strong class='fLeft' style='padding-left: 5px;'>留言标题:" . $row['title'] . "</strong><span class='fRight'>\r\n              <input name=\"ids\" type=\"checkbox\" id=\"ids\" value=\"" . $row['aid'] . "\" />\r\n              <a href='#' onclick='DelNote(" . $row['aid'] . ")' style='color:#29A5C9;'>删除</a></span></th>\r\n            </tr>\r\n          </thead>\r\n          <tbody>\r\n            <tr>\r\n              <td width='18%' style='padding-left: 10px;'>用户称呼:" . $row['uname'] . "</td>\r\n              <td>时间:" . MyDate("Y-m-d H:i", $row['dtime']) . "&nbsp;IP地址:" . $row['ip'] . "&nbsp;";
        if (!empty($row['gid'])) {
            $line .= " <a href='index.php?uid={$row['uname']}&action=infos' target='_blank'>资料</a> <a href='index.php?uid={$row['uname']}' target='_blank'>空间</a> <a href='index.php?uid={$row['uname']}&action=guestbook' target='_blank'>回复</a> ";
        }
        $line .= "</td>\r\n            </tr>\r\n            <tr>\r\n              <td colspan='2' style='padding-left: 10px;'>" . Text2Html($row['msg']) . "</td>\r\n            </tr>\r\n          </tbody>\r\n        </table>";
    }
    $line = $line == '' ? '暂无留言' : $line;
    echo $line;
}
Example #10
0
 /**
  * Clean the cache
  *
  * If no group is specified all cache items  will be removed
  * from the database else only cache items of the specified
  * group will be destroyed
  *
  * @access public
  * @param    string    $group    If no group is specified all cache items  will be
  * removed from the database else only cache items
  * of the specified group will be destroyed
  * @param    string    $mode    Flush cache mode. Options are:
  *
  * - old
  * - ingroup
  * - notingroup
  * @return boolean True if no problem
  */
 function clean($group = false, $mode = 'ingroup')
 {
     switch ($mode) {
         case 'ingroup':
             if (!$this->_db->Execute('DELETE FROM cache WHERE cache_group = ' . $this->_db->qstr($group)) && AK_DEBUG) {
                 trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE);
             }
             return (bool) $this->_db->Affected_Rows();
         case 'notingroup':
             if (!$this->_db->Execute('DELETE FROM cache WHERE cache_group NOT LIKE ' . $this->_db->qstr($group)) && AK_DEBUG) {
                 trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE);
             }
             return (bool) $this->_db->Affected_Rows();
         case 'old':
             if (!$this->_db->Execute('DELETE FROM cache WHERE expire < ' . $this->_db->DBTimeStamp(time())) && AK_DEBUG) {
                 trigger_error($this->_db->ErrorMsg(), E_USER_NOTICE);
             }
             return (bool) $this->_db->Affected_Rows();
         default:
             return true;
     }
 }
Example #11
0
/**
 *	get or set artist id for the specified artist name
 *
 *	this functions searches the database for an entry with the specified name,
 *  if there is any, its 'artistid' is returned, otherwise a new entry is
 *  created and its 'artistid' returned alike.
 *  if this fails, 'false' is returned
 *
 *	@access		public
 *	@param 		string	$artist_name
 *	@param 		object	$db
 *	@param 		string	$db_prefix
 *	@return		int
 *
 */
function migrate_get_or_set_artistid($artist_name, $db, $db_prefix)
{
    $sql = "SELECT id FROM " . $db_prefix . "artist WHERE name=" . $db->qstr($artist_name);
    $artist_id = $db->GetOne($sql);
    // echo ($sql."\n<br>\n");
    if (!$artist_id) {
        $sql = "INSERT INTO " . $db_prefix . "artist (`src`, `name`, `preferred_name_id`, `sounds`) VALUES (" . $db->qstr('dilps') . "," . $db->qstr($artist_name) . "," . $db->qstr(0) . "," . $db->qstr(migrate_get_sounds_string($artist_name)) . ")";
        $rs = $db->Execute($sql);
        // echo ($sql."\n<br>\n");
        if (!$rs) {
            return false;
        } else {
            $sql = "SELECT id FROM " . $db_prefix . "artist WHERE name=" . $db->qstr($artist_name);
            $artist_id = $db->GetOne($sql);
            // echo ($sql."\n<br>\n");
            if (!$artist_id) {
                return false;
            }
            echo "New artist entry ({$artist_id}, {$artist_name})! \n<br>\n";
        }
    }
    return $artist_id;
}
Example #12
0
/**
 *  获取链接列表
 *
 * @access    public
 * @param     object  $dsql  数据库操作类
 * @return    string
 */
function GetLinkList(&$dsql)
{
    global $cfg_ml;
    $dsql->SetQuery("SELECT * FROM `#@__member_flink` WHERE mid='" . $cfg_ml->M_ID . "' ORDER BY aid DESC");
    $dsql->Execute();
    $j = 0;
    while ($row = $dsql->GetArray()) {
        $j++;
        $line = "\n<div class='item flink'>\n  <div class='itemHead' >\n    <div class='fRight'>\n      <span class='itemDigg'><a href='#' onclick='UpdateType({$row['aid']})'>[更新]</a></span>\n      <span class='itemManage'><a href='#' onclick='DelType({$row['aid']})'>[删除]</a></span>\n    </div>\n    <span class='itemTitle'>名称:<input name='title{$row['aid']}' type='text' id='title{$row['aid']}' value='{$row['title']}' class='intxt' /></span>\n    <div class='mt5'>网址:<input name='url{$row['aid']}' type='text' id='url{$row['aid']}' value='{$row['url']}' class='intxt' /></div>\n  </div>\n</div>\n<hr class='dotted' />";
        echo $line;
    }
    if ($j == 0) {
        echo "尚无任何链接";
    }
}
Example #13
0
/**
 *  优化数据
 *
 * @access    public
 * @param     object  $dsql  数据库对象
 * @return    void
 */
function OptimizeData($dsql)
{
    global $cfg_dbprefix;
    $tptables = array("{$cfg_dbprefix}archives", "{$cfg_dbprefix}arctiny");
    $dsql->SetQuery("SELECT maintable,addtable FROM `#@__channeltype` ");
    $dsql->Execute();
    while ($row = $dsql->GetObject()) {
        $addtable = str_replace('#@__', $cfg_dbprefix, $row->addtable);
        if ($addtable != '' && !in_array($addtable, $tptables)) {
            $tptables[] = $addtable;
        }
    }
    $tptable = '';
    foreach ($tptables as $t) {
        $tptable .= $tptable == '' ? "`{$t}`" : ",`{$t}`";
    }
    $dsql->ExecuteNoneQuery(" OPTIMIZE TABLE {$tptable}; ");
}
 public function Execute($sql, $params, $varMarker = NULL)
 {
     return $this->mrDbEngine->Execute($sql, $params, $varMarker);
 }
Example #15
0
 /**
  * Returns whether or not our db connection was made, and tables exist
  * @return boolean
  * @access public
  */
 public function checkDbConnection()
 {
     if ($this->db) {
         if ($this->db->Execute('SHOW TABLES')) {
             return true;
         }
     } else {
         return false;
     }
 }
Example #16
0
 public function DbReConnect($agi)
 {
     $res = $this->DBHandle->Execute("select 1");
     if (!$res) {
         $this->debug(DEBUG, $agi, __FILE__, __LINE__, "[DB CONNECTION LOST] - RECONNECT ATTEMPT");
         $this->DBHandle->Close();
         if ($this->config['database']['dbtype'] == "postgres") {
             $datasource = 'pgsql://' . $this->config['database']['user'] . ':' . $this->config['database']['password'] . '@' . $this->config['database']['hostname'] . '/' . $this->config['database']['dbname'];
         } else {
             $datasource = 'mysqli://' . $this->config['database']['user'] . ':' . $this->config['database']['password'] . '@' . $this->config['database']['hostname'] . '/' . $this->config['database']['dbname'];
         }
         $count = 1;
         $sleep = 1;
         while (!$res && $count < 5) {
             $this->DBHandle = NewADOConnection($datasource);
             if (!$this->DBHandle) {
                 $this->debug(DEBUG, $agi, __FILE__, __LINE__, "[DB CONNECTION LOST]- RECONNECT FAILED ,ATTEMPT {$count} sleep for {$sleep} ");
                 $count += 1;
                 $sleep = $sleep * 2;
                 sleep($sleep);
             } else {
                 break;
             }
         }
         if (!$this->DBHandle) {
             $this->debug(FATAL, $agi, __FILE__, __LINE__, "[DB CONNECTION LOST] CDR NOT POSTED");
             die("Reconnection failed");
         }
         if ($this->config['database']['dbtype'] == "mysqli") {
             $this->DBHandle->Execute('SET AUTOCOMMIT = 1');
         }
         $this->debug(DEBUG, $agi, __FILE__, __LINE__, "[NO DB CONNECTION] - RECONNECT OK]");
     } else {
         $res->Close();
     }
     return true;
 }
Example #17
0
 /**
  * Metodo que elimina registros dados según la consulta construida
  * 
  * @param object $lobCon Objeto de conexión
  * @param string $query consulta
  * @return int
  */
 public static function delete($lobCon, $query)
 {
     if ($lobCon->Execute($query) === false) {
         return 0;
     } else {
         self::$affectedRows = $lobCon->Affected_Rows();
         return self::$affectedRows;
     }
 }
Example #18
0
/**
 *	modified version of get_groupid_where_clause
 *
 *	this version is working without the query array
 *
 *	@access		public
 *	@param 		int		$groupid
 *	@param 		object	$db
 *	@param 		string	$db_prefix
 *	@param 		bool	$subgroups
 *	@return		string
 *
 */
function get_groupid_where($groupid, &$db, $db_prefix, $subgroups = true)
{
    $where = '';
    if (!empty($groupid)) {
        // our result
        $groups = array();
        // first id is the give one
        $groups[] = $groupid;
        $db->SetFetchMode(ADODB_FETCH_ASSOC);
        $sql = "SELECT id FROM " . $db_prefix . "group WHERE " . "parentid = " . $db->qstr($groupid) . " ORDER BY id";
        $rs = $db->Execute($sql);
        if (!$rs || !$subgroups) {
            // we have no subgroups (or we do not use them), just query one id
            $where .= " AND {$db_prefix}img_group.groupid = " . $db->qstr($groupid);
        } else {
            // get next sublevel
            while (!$rs->EOF) {
                // add group to result array
                $groups[] = $rs->fields['id'];
                // get next but one sublevel, if available
                $sql2 = "SELECT id FROM " . $db_prefix . "group WHERE " . "parentid = " . $db->qstr($rs->fields['id']) . " ORDER BY id";
                $rs2 = $db->Execute($sql2);
                while (!$rs2->EOF) {
                    $groups[] = $rs2->fields['id'];
                    $rs2->MoveNext();
                }
                $rs->MoveNext();
            }
            $where .= " AND (0 ";
            foreach ($groups as $gid) {
                $where .= " OR {$db_prefix}img_group.groupid = " . $db->qstr($gid);
            }
            $where .= ") ";
        }
    }
    return $where;
}
 /**
  * Writes to file the $table's structure
  * 
  * @param string $table The table name
  * @access private
  * @return boolean|string return false when table not exists or return table schema
  */
 private function getSqlKeysTable($table)
 {
     $primary = "";
     $unique = $index = $fulltext = array();
     $objResult = $this->db->Execute("SHOW KEYS FROM `{$table}`");
     if ($objResult->RecordCount() == 0) {
         return false;
     }
     while (!$objResult->EOF) {
         if ($objResult->fields['Key_name'] == 'PRIMARY' && $objResult->fields['Index_type'] == 'BTREE') {
             if ($primary == '') {
                 $primary = "  PRIMARY KEY  (`{$objResult->fields['Column_name']}`";
             } else {
                 $primary .= ", `{$objResult->fields['Column_name']}`";
             }
         }
         if ($objResult->fields['Key_name'] != 'PRIMARY' && $objResult->fields['Non_unique'] == '0' && $objResult->fields['Index_type'] == 'BTREE') {
             if (!is_array($unique) || $unique[$objResult->fields['Key_name']] == "") {
                 $unique[$objResult->fields['Key_name']] = "  UNIQUE KEY `{$objResult->fields['Key_name']}` (`{$objResult->fields['Column_name']}`";
             } else {
                 $unique[$objResult->fields['Key_name']] .= ", `{$objResult->fields['Column_name']}`";
             }
         }
         if ($objResult->fields['Key_name'] != 'PRIMARY' && $objResult->fields['Non_unique'] == '1' && $objResult->fields['Index_type'] == 'BTREE') {
             if (!is_array($index) or $index[$objResult->fields['Key_name']] == "") {
                 $index[$objResult->fields['Key_name']] = "  KEY `{$objResult->fields['Key_name']}` (`{$objResult->fields['Column_name']}`";
             } else {
                 $index[$objResult->fields['Key_name']] .= ", `{$objResult->fields['Column_name']}`";
             }
         }
         if ($objResult->fields['Key_name'] != 'PRIMARY' && $objResult->fields['Non_unique'] == '1' && $objResult->fields['Index_type'] == 'FULLTEXT') {
             if (!is_array($fulltext) || $fulltext[$objResult->fields['Key_name']] == "") {
                 $fulltext[$objResult->fields['Key_name']] = "  FULLTEXT `{$objResult->fields['Key_name']}` (`{$objResult->fields['Column_name']}`";
             } else {
                 $fulltext[$objResult->fields['Key_name']] .= ", `{$objResult->fields['Column_name']}`";
             }
         }
         $objResult->MoveNext();
     }
     $sqlKeyStatement = '';
     // generate primary, unique, key and fulltext
     if ($primary != "") {
         $sqlKeyStatement .= ",\n";
         $primary .= ")";
         $sqlKeyStatement .= $primary;
     }
     foreach ($unique as $keyName => $keyDef) {
         $sqlKeyStatement .= ",\n";
         $keyDef .= ")";
         $sqlKeyStatement .= $keyDef;
     }
     foreach ($index as $keyName => $keyDef) {
         $sqlKeyStatement .= ",\n";
         $keyDef .= ")";
         $sqlKeyStatement .= $keyDef;
     }
     foreach ($fulltext as $keyName => $keyDef) {
         $sqlKeyStatement .= ",\n";
         $keyDef .= ")";
         $sqlKeyStatement .= $keyDef;
     }
     return $sqlKeyStatement;
 }
Example #20
0
 /**
  *Executes a query
  *
  *Executes a query, manage errors and returns a recordset to work on
  *
  *@param string $sql SQL to execute
  *@return object
  */
 function ExecSQL($sql)
 {
     $rs = $this->conn->Execute($sql);
     if ($this->conn->ErrorNo() != 0) {
         $this->lasterror = 3;
         $this->lasterrmsg = $this->conn->ErrorMsg();
     } else {
         $this->lasterror = 0;
         $this->lasterrmsg = '';
     }
     return $rs;
 }
Example #21
0
/**
 *	formats a datespring according the DILPS-rules
 *
 *	formats a given datestring according to the rules
 *	in the DILPS database, returns the result in datelist
 *
 *	@access		public
 *	@param		object	$db
 *	@param		string	$datestring
 *	@param		array	$datelist
 *	@return		void
 *
 */
function dating($db, &$datestring, &$datelist)
{
    global $db_prefix;
    static $dating_match = NULL;
    static $dating_replacement = NULL;
    static $dating_pattern = NULL;
    if ($dating_match == NULL) {
        $sql = "SELECT * FROM {$db_prefix}dating_rules WHERE `type`='match' ORDER BY seq ASC";
        $dating_match = $db->GetArray($sql);
        for ($i = 0; $i < sizeof($dating_match); $i++) {
            $dating_match[$i]['regexp'] = strtolower(stripslashes($dating_match[$i]['regexp']));
        }
    }
    if ($dating_replacement == NULL) {
        $sql = "SELECT * FROM {$db_prefix}dating_rules WHERE `type`='replace' ORDER BY seq ASC";
        $rs = $db->Execute($sql);
        $dating_pattern = array();
        $dating_replacement = array();
        while (!$rs->EOF) {
            $dating_pattern[] = strtolower(stripslashes($rs->fields['from']));
            $dating_replacement[] = strtolower(stripslashes($rs->fields['to']));
            $rs->MoveNext();
        }
        $rs->Close();
    }
    $datelist = array();
    //	echo "[$datestring] --> ";
    $datestring = trim(preg_replace($dating_pattern, $dating_replacement, strtolower($datestring)));
    //	echo "[$datestring]\n";
    $dates = explode(';', $datestring);
    //    print_r( $dates );
    foreach ($dates as $date) {
        for ($i = 0; $i < sizeof($dating_match); $i++) {
            $matches = array();
            if (preg_match($dating_match[$i]['regexp'], $date, $match)) {
                $result = array('from' => eval($dating_match[$i]['from']), 'to' => eval($dating_match[$i]['to']));
                $datelist[] = $result;
                break;
            }
        }
    }
    return true;
}