Разработка библиотеки для осуществления адаптивного поиска в базах данных Web-приложений (бакалаврская работа) (544459), страница 7
Текст из файла (страница 7)
if(!in_array($this->options['cookie_hash_algo'], hash_algos(), true))
return $this->raiseError(DB_ERROR_KEY_CREATE);
// Проверка существования таблицы идентификационных ключей пользователей
$result = $this->query('SHOW TABLES LIKE ?',
array('adaptive_search_users_keys'));
if(DB::isError($result))
return $result;
if(!$result->numRows())
{
$sql_filename =
"./DB/sql/{$this->phptype}/adaptive_search_users_keys.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);
$result = $this->query($sql, array());
if(DB::isError($result))
return $this->raiseError(DB_ERROR_USERS_KEYS_CREATE);
}
// Пробуем идентифицировать пользователя
elseif(isset($_COOKIE[$ckey]))
{
$sql = 'SELECT * FROM `adaptive_search_users_keys` WHERE `user_id` = ? AND `key` = ?';
$udata = unserialize(base64_decode($_COOKIE[$ckey]));
$result = $this->query($sql, array($udata[0], $udata[1]));
if(DB::isError($result))
return $result;
if($result->numRows() == 1
&& $udata[2] == hash_hmac($this->options['cookie_hash_algo'],
$udata[0], $udata[1]))
$this->options['user_id'] = $udata[0];
}
// Регистрируем новый идентификатор для пользователя
if(is_null($this->options['user_id']))
{
$user_key = md5(mt_rand());
$sql = 'INSERT INTO `adaptive_search_users_keys` (`key`) VALUES (?)';
$result = $this->query($sql, array($user_key));
if(DB::isError($result))
return $this->raiseError(DB_ERROR_KEY_CREATE);
$sql = 'SELECT `user_id`, `key` FROM `adaptive_search_users_keys`
WHERE `key` = ? ORDER BY `user_id` DESC LIMIT 1';
$udata = $this->getRow($sql, array($user_key), DB_FETCHMODE_ORDERED);
if(DB::isError($udata))
return $udata;
$this->options['user_id'] = $udata[0];
$udata[] = hash_hmac($this->options['cookie_hash_algo'],
$this->options['user_id'], $udata[1]);
}
// Сохраняем идентификатор пользователя в Cookie
setcookie($ckey, base64_encode(serialize($udata)), time() + $ctime, '/');
}
elseif(isset($_COOKIE[$ckey]))
setcookie($ckey, 0, time(), '/');
return DB_OK;
}
public function getOption($option)
{
if(array_key_exists($option, $this->options))
return $this->options[$option];
return $this->raiseError("Неизвестный параметр '{$option}'");
}
function prepare($query)
{
$tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
PREG_SPLIT_DELIM_CAPTURE);
$token = 0;
$types = array();
$newtokens = array();
foreach ($tokens as $val) {
switch ($val) {
case '?':
$types[$token++] = DB_PARAM_SCALAR;
break;
case '&':
$types[$token++] = DB_PARAM_OPAQUE;
break;
case '!':
$types[$token++] = DB_PARAM_MISC;
break;
default:
$newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val);
}
}
$this->prepare_tokens[] = &$newtokens;
end($this->prepare_tokens);
$k = key($this->prepare_tokens);
$this->prepare_types[$k] = $types;
$this->prepared_queries[$k] = implode(' ', $newtokens);
return $k;
}
function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT,
$where = false)
{
$query = $this->buildManipSQL($table, $table_fields, $mode, $where);
if (DB::isError($query)) {
return $query;
}
return $this->prepare($query);
}
function &execute($stmt, $data = array())
{
$realquery = $this->executeEmulateQuery($stmt, $data);
if (DB::isError($realquery)) {
return $realquery;
}
$result = $this->simpleQuery($realquery);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp = new DB_result($this, $result);
return $tmp;
}
}
function &query($query, $params = array())
{
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$ret = $this->execute($sth, $params);
$this->freePrepared($sth, false);
return $ret;
} else {
$this->last_parameters = array();
$result = $this->simpleQuery($query);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp = new DB_result($this, $result);
return $tmp;
}
}
}
function &getOne($query, $params = array())
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res = $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res = $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, DB_FETCHMODE_ORDERED);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row[0];
}
function &getRow($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res = $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res = $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, $fetchmode);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row;
}
function &getCol($query, $col = 0, $params = array())
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res = $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res = $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC;
if (!is_array($row = $res->fetchRow($fetchmode))) {
$ret = array();
} else {
if (!array_key_exists($col, $row)) {
$ret = $this->raiseError(DB_ERROR_NOSUCHFIELD);
} else {
$ret = array($row[$col]);
while (is_array($row = $res->fetchRow($fetchmode))) {
$ret[] = $row[$col];
}
}
}
$res->free();
if (DB::isError($row)) {
$ret = $row;
}
return $ret;
}
function &getAssoc($query, $force_array = false, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res = $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res = $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
if ($fetchmode == DB_FETCHMODE_DEFAULT) {
$fetchmode = $this->fetchmode;
}
$cols = $res->numCols();
if ($cols < 2) {
$tmp = $this->raiseError(DB_ERROR_TRUNCATED);
return $tmp;
}
$results = array();
if ($cols > 2 || $force_array) {
if ($fetchmode == DB_FETCHMODE_ASSOC) {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) {
reset($row);
$key = current($row);
unset($row[key($row)]);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} elseif ($fetchmode == DB_FETCHMODE_OBJECT) {
while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
$arr = get_object_vars($row);
$key = current($arr);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} else {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
$key = array_shift($row);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
}
if (DB::isError($row)) {
$results = $row;
}
} else {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
if ($group) {
$results[$row[0]][] = $row[1];
} else {
$results[$row[0]] = $row[1];
}
}
if (DB::isError($row)) {
$results = $row;
}
}
$res->free();
return $results;
}
function &getAll($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res = $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res = $this->query($query);
}
if ($res === DB_OK || DB::isError($res)) {
return $res;
}
$results = array();
while (DB_OK === $res->fetchInto($row, $fetchmode)) {
if ($fetchmode & DB_FETCHMODE_FLIPPED) {
foreach ($row as $key => $val) {
$results[$key][] = $val;
}
} else {
$results[] = $row;
}
}
$res->free();
if (DB::isError($row)) {
$tmp = $this->raiseError($row);
return $tmp;
}
return $results;
}
function numRows($result)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
function &raiseError($code = DB_ERROR, $mode = null, $options = null,
$userinfo = null, $nativecode = null, $dummy1 = null,
$dummy2 = null)
{
if (is_object($code)) {
if ($mode === null && !empty($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
}
$tmp = DB::raiseError($code, null, $mode, $options,
null, null, true);
return $tmp;
}
if ($userinfo === null) {
$userinfo = $this->last_query;
}
if ($nativecode) {
$userinfo .= ' [nativecode=' . trim($nativecode) . ']';
} else {
$userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']';
}
$tmp = DB::raiseError(null, $code, $mode, $options, $userinfo,
'DB_Error', true);
return $tmp;
}
public function prepareWords(&$words)
{
if(is_string($words))
$words = array($words);
if(!is_array($words) && count($words))
return $this->raiseError(DB_ERROR_WORDS);
$words = array_unique($words);
// Удаляем слова превышающие максимально допустимую длину
foreach($words as $i => $word)
{
if(mb_strlen($word) > $this->options['max_word_length'])