Разработка библиотеки для осуществления адаптивного поиска в базах данных Web-приложений (бакалаврская работа) (544459), страница 6
Текст из файла (страница 6)
{
if(empty($this->userinfo))
{
$this->userinfo = $info;
}
else
{
$this->userinfo .= " ** $info";
}
}
public function __toString()
{
return $this->getMessage();
}
public function toString()
{
$modes = array();
$levels = array(
E_USER_NOTICE => 'notice',
E_USER_WARNING => 'warning',
E_USER_ERROR => 'error'
);
if($this->mode & DB_ERROR_CALLBACK)
{
if(is_array($this->callback))
{
$callback = (is_object($this->callback[0]) ?
strtolower(get_class($this->callback[0])) :
$this->callback[0]) . '::' .
$this->callback[1];
}
else
{
$callback = $this->callback;
}
return sprintf('[%s: message="%s" code=%d mode=callback ' .
'callback=%s prefix="%s" info="%s"]',
strtolower(get_class($this)), $this->message, $this->code,
$callback, $this->error_message_prefix, $this->userinfo);
}
if($this->mode & ERROR_PRINT)
$modes[] = 'print';
if($this->mode & ERROR_TRIGGER)
$modes[] = 'trigger';
if($this->mode & ERROR_DIE)
$modes[] = 'die';
if($this->mode & ERROR_RETURN)
$modes[] = 'return';
return sprintf('[%s: message="%s" code=%d mode=%s level=%s ' .
'prefix="%s" info="%s"]', strtolower(get_class($this)),
$this->message, $this->code, implode("|", $modes),
$levels[$this->level], $this->error_message_prefix,
$this->userinfo);
}
}
class DB_result
{
var $autofree;
var $dbh;
var $fetchmode;
var $fetchmode_object_class;
var $limit_count = null;
var $limit_from = null;
var $parameters;
var $query;
var $result;
var $row_counter = null;
var $statement;
function __construct(&$dbh, $result, $options = array())
{
$this->autofree = $dbh->options['autofree'];
$this->dbh = &$dbh;
$this->fetchmode = $dbh->fetchmode;
$this->fetchmode_object_class = $dbh->fetchmode_object_class;
$this->parameters = $dbh->last_parameters;
$this->query = $dbh->last_query;
$this->result = $result;
$this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
foreach($options as $key => $value)
$this->setOption($key, $value);
}
function setOption($key, $value = null)
{
switch($key)
{
case 'limit_from':
$this->limit_from = $value;
break;
case 'limit_count':
$this->limit_count = $value;
}
}
function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
{
if($fetchmode === DB_FETCHMODE_DEFAULT)
{
$fetchmode = $this->fetchmode;
}
if($fetchmode === DB_FETCHMODE_OBJECT)
{
$fetchmode = DB_FETCHMODE_ASSOC;
$object_class = $this->fetchmode_object_class;
}
if(is_null($rownum) && $this->limit_from !== null)
{
if($this->row_counter === null)
{
$this->row_counter = $this->limit_from;
if($this->dbh->features['limit'] === false)
{
$i = 0;
while($i++ < $this->limit_from)
{
$this->dbh->fetchInto($this->result, $arr, $fetchmode);
}
}
}
if($this->row_counter >= ($this->limit_from + $this->limit_count))
{
if($this->autofree)
{
$this->free();
}
$tmp = null;
return $tmp;
}
if($this->dbh->features['limit'] === 'emulate')
{
$rownum = $this->row_counter;
}
$this->row_counter++;
}
$res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
if($res === DB_OK)
{
if(isset($object_class))
{
if($object_class == 'stdClass')
{
$arr = (object) $arr;
}
else
{
$arr = new $object_class($arr);
}
}
return $arr;
}
if($res == null && $this->autofree)
{
$this->free();
}
return $res;
}
function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
{
if($fetchmode === DB_FETCHMODE_DEFAULT)
{
$fetchmode = $this->fetchmode;
}
if($fetchmode === DB_FETCHMODE_OBJECT)
{
$fetchmode = DB_FETCHMODE_ASSOC;
$object_class = $this->fetchmode_object_class;
}
if(is_null($rownum) && $this->limit_from !== null)
{
if($this->row_counter === null)
{
$this->row_counter = $this->limit_from;
if($this->dbh->features['limit'] === false)
{
$i = 0;
while($i++ < $this->limit_from)
{
$this->dbh->fetchInto($this->result, $arr, $fetchmode);
}
}
}
if($this->row_counter >= (
$this->limit_from + $this->limit_count))
{
if($this->autofree)
{
$this->free();
}
return null;
}
if($this->dbh->features['limit'] === 'emulate')
{
$rownum = $this->row_counter;
}
$this->row_counter++;
}
$res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
if($res === DB_OK)
{
if(isset($object_class))
{
if($object_class == 'stdClass')
{
$arr = (object)$arr;
}
else
{
$arr = new $object_class($arr);
}
}
return DB_OK;
}
if($res == null && $this->autofree)
{
$this->free();
}
return $res;
}
function numCols()
{
return $this->dbh->numCols($this->result);
}
function numRows()
{
if($this->dbh->features['numrows'] === 'emulate'
&& $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
{
if($this->dbh->features['prepare'])
$res = $this->dbh->query($this->query, $this->parameters);
else
$res = $this->dbh->query($this->query);
if(DB::isError($res))
return $res;
$count = 0;
while($res->fetchInto($tmp, DB_FETCHMODE_ORDERED))
$count++;
}
else
$count = $this->dbh->numRows($this->result);
if(($this->dbh->features['limit'] === 'emulate' && $this->limit_from !== null)
|| $this->dbh->phptype == 'fbsql')
{
$limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
if($count < $this->limit_from)
$count = 0;
elseif($count < ($this->limit_from + $limit_count))
$count -= $this->limit_from;
else
$count = $limit_count;
}
return $count;
}
function nextResult()
{
return $this->dbh->nextResult($this->result);
}
function free()
{
$err = $this->dbh->freeResult($this->result);
if(DB::isError($err))
return $err;
$this->result = false;
$this->statement = false;
return true;
}
function getQuery()
{
return $this->query;
}
function getRowCounter()
{
return $this->row_counter;
}
}
class DB_row
{
function __construct(&$arr)
{
foreach($arr as $key => $value)
$this->$key = &$arr[$key];
}
}
class DB_common
{
var $fetchmode = DB_FETCHMODE_ORDERED;
var $fetchmode_object_class = 'stdClass';
var $was_connected = null;
var $last_query = '';
var $options = array(
// Имя таблицы для хранения ключевых слов
'users_words_table_name' => 'adaptive_search_users_words',
// Кодировка таблицы для хранения ключевых слов пользователей
'users_words_table_charset' => 'utf8',
// Идентификатор текущего пользователя
'user_id' => NULL,
// Максимальная длина индексируемого слова
'max_word_length' => 30,
// Время жизни индексируемых слов (в секундах)
'words_lifetime' => NULL,
// Лимит на число ключевых слов для одного пользователя
'words_limit' => 8,
// Имя Cookie для хранения идентификатора пользователя
'cookie_user_id_name' => 'adaptive_search_user_id',
// Время жизни идентификатора пользователя
'cookie_user_id_lifetime' => 2592000,
// Алгоритм хеширования данных пользователя
'cookie_hash_algo' => 'sha256',
// Переключатель адаптации для поиска
'adaptive' => true,
// Подсветка результатов
'highlight' => true,
'result_buffering' => 500,
'persistent' => false,
'ssl' => false,
'debug' => 0,
'seqname_format' => '%s_seq',
'autofree' => false,
'portability' => DB_PORTABILITY_NONE,
);
var $last_parameters = array();
var $prepare_tokens = array();
var $prepare_types = array();
var $prepared_queries = array();
var $_last_query_manip = false;
var $_next_query_manip = false;
function DB_common()
{
$this->DB('DB_Error');
}
function __sleep()
{
if ($this->connection) {
$this->was_connected = true;
} else {
$this->was_connected = false;
}
if (isset($this->autocommit)) {
return array('autocommit',
'dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
} else {
return array('dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
}
}
function __wakeup()
{
if ($this->was_connected) {
$this->connect($this->dsn, $this->options['persistent']);
}
}
function __toString()
{
$info = strtolower(get_class($this));
$info .= ': (phptype=' . $this->phptype .
', dbsyntax=' . $this->dbsyntax .
')';
if ($this->connection) {
$info .= ' [connected]';
}
return $info;
}
function toString()
{
return $this->__toString();
}
function quoteString($string)
{
$string = $this->quote($string);
if ($string{0} == "'") {
return substr($string, 1, -1);
}
return $string;
}
function quote($string = null)
{
return ($string === null) ? 'NULL'
: "'" . str_replace("'", "''", $string) . "'";
}
function setFetchMode($fetchmode, $object_class = 'stdClass')
{
switch ($fetchmode) {
case DB_FETCHMODE_OBJECT:
$this->fetchmode_object_class = $object_class;
case DB_FETCHMODE_ORDERED:
case DB_FETCHMODE_ASSOC:
$this->fetchmode = $fetchmode;
break;
default:
return $this->raiseError('invalid fetchmode mode');
}
}
public function setOption($option, $value)
{
if(array_key_exists($option, $this->options))
{
$this->options[$option] = $value;
return DB_OK;
}
return $this->raiseError("Неизвестный параметр '{$option}'");
}
public function checkOptions()
{
// Проверка существования таблицы ключевых слов
$result = $this->query('SHOW TABLES LIKE ?',
array($this->options['users_words_table_name']));
if(DB::isError($result))
return $result;
// Создание таблицы ключевых слов, если не существует
if(!$result->numRows())
{
if(!is_int($this->options['max_word_length'])
|| $this->options['max_word_length'] <= 0)
return $this->raiseError(DB_ERROR_MAX_WORD_LENGTH);
$sql_filename =
"./DB/sql/{$this->phptype}/adaptive_search_users_words.sql";
$sql = file_get_contents($sql_filename, FILE_USE_INCLUDE_PATH);
if($sql === false)
return DB::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
"Файл '{$sql_filename}' не найден", 'DB_Error', true);
$data = array($this->options['users_words_table_name'],
$this->options['max_word_length'],
$this->options['users_words_table_charset']);
$result = $this->query($sql, $data);
if(DB::isError($result))
return $this->raiseError(DB_ERROR_WORDS_TABLE_CREATE);
}
// Получение идентификатора для текущего пользователя
$ckey = $this->options['cookie_user_id_name'];
$ctime = $this->options['cookie_user_id_lifetime'];
if(is_null($this->options['user_id'])
&& isset($this->options['cookie_hash_algo']))
{