示例#1
0
文件: Database.php 项目: gorvic/L11
 /**
  * Constructor 
  */
 private function __construct()
 {
     $connection = DbSimple_Generic::connect('mysqli://' . DB_USER . ':' . DB_PASS . '@' . DB_SERVER . '/' . DB_NAME);
     $connection->query("SET names utf8");
     $connection->setErrorHandler('dbErrorHandler');
     $connection->setLogger('dbLogger');
 }
示例#2
0
 public function __construct()
 {
     global $g_config;
     // Подключаем модули для работы с DbSimple (не по подгрузится автолоудером)
     $path = dirname(__FILE__) . '/DbSimple/';
     require_once $path . 'Generic.php';
     require_once $path . 'Mysql.php';
     require_once $path . 'Postgresql.php';
     require_once $path . 'my/MyDataBaseLog.php';
     $dbs = $g_config['dbSimple']['databases'];
     // Собираем все объекты в $o
     $o = new stdClass();
     foreach ($dbs as $db => $conn) {
         $dsn = $conn['dsn'];
         $cacheFunc = isset($conn['pCacheFunc']) ? $conn['pCacheFunc'] : NULL;
         $o->{$db} = DbSimple_Generic::connect($dsn);
         if ($g_config['dbSimple']['logDbError']) {
             MyDataBaseLog::SetFuncOnError(array(__CLASS__, 'DbSimpleError'));
             $o->{$db}->setLogger(array('MyDataBaseLog', 'Log'));
             $o->{$db}->setErrorHandler(array('MyDataBaseLog', 'Error'));
         }
         if ($cacheFunc) {
             $o->{$db}->setCacher($cacheFunc);
         }
     }
     // Регистрируем все базы данных как объект $g_databases
     $GLOBALS['g_databases'] = $o;
 }
 public function __construct($config)
 {
     include_once "core/dbsimple/Generic.php";
     $this->rDB = DbSimple_Generic::connect($config['rdb']);
     $this->rDB->setErrorHandler("databaseErrorHandler");
     $this->rDB->query("SET NAMES ? ", $config['db_encoding']);
 }
示例#4
0
 function __construct()
 {
     require_once "dbsimple/config.php";
     require_once "dbsimple/DbSimple/Generic.php";
     require_once "data_connection.php";
     $this->db = @DbSimple_Generic::connect('mysqli://' . $UserName . ':' . $Password . '@' . $ServerName . '/' . $Database);
 }
 function __construct($file = null)
 {
     global $db_config;
     include_once 'dbsimple/Generic.php';
     // including simple conecting for DB
     $this->DB = DbSimple_Generic::connect($db_config['dbc_dns']);
     $this->DB->setErrorHandler("databaseErrorHandler");
     // $this->DB->setLogger("databaseLogHandler");
     // $this->DB->setIdentPrefix($db_config['db_prefix']);
     $this->initDB();
     if ($file == null) {
         return;
     }
     if ($this->file = fopen(self::$_dir . $file, "rb")) {
         $ex = explode('.', $file);
         $this->name = $ex[0];
         $this->dom = new DOMDocument();
         $this->dom->preserveWhiteSpace = false;
         $this->dom->substituteEntities = true;
         $xmlfile = 'xml/' . $this->name . '.xml';
         if (file_exists($xmlfile)) {
             $this->dom->Load($xmlfile);
             $this->XML = $this->dom->getElementsByTagName('file')->item(0);
             $this->format = $this->XML->getAttribute('format');
             return;
         }
     } else {
         $this->error = sprintf($this->_STR['FILE_NOT_EXISTS'], $file);
     }
 }
示例#6
0
function db_connect($hostName, $userName, $dbPassword, $dbName)
{
    // Подключаемся к БД.
    $dbc = DbSimple_Generic::connect('mysqli://' . $userName . ':' . $dbPassword . '@' . $hostName . '/' . $dbName);
    $dbc->query('set names ?', 'utf8');
    return $dbc;
}
示例#7
0
 /**
  * Initialize database & template handlers, sets up sql/site configs
  * @category Main system functions
  * @example Connector::__construct()
  * @return bool
  **/
 public function __construct()
 {
     include 'configuration.php';
     require_once 'libs/DbSimple/Generic.php';
     require_once 'libs/Smarty-2.6.26/Smarty.class.php';
     $this->mysqlconfig = $ArmoryConfig['mysql'];
     $this->armoryconfig = $ArmoryConfig['settings'];
     $this->aDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_armory'] . ':' . $this->mysqlconfig['pass_armory'] . '@' . $this->mysqlconfig['host_armory'] . '/' . $this->mysqlconfig['name_armory']);
     $this->cDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_characters'] . ':' . $this->mysqlconfig['pass_characters'] . '@' . $this->mysqlconfig['host_characters'] . '/' . $this->mysqlconfig['name_characters']);
     $this->rDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_realmd'] . ':' . $this->mysqlconfig['pass_realmd'] . '@' . $this->mysqlconfig['host_realmd'] . '/' . $this->mysqlconfig['name_realmd']);
     $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']);
     /*
     temporary disabled
     // Test connection
     if(!$this->aDB->selectCell("SELECT `id` FROM `classes` LIMIT 1")) {
         $this->databaseError('Can not execute query to armory database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_armory']);
     }
     if(!$this->cDB->selectCell("SELECT `guid` FROM `characters` LIMIT 1")) {
         $this->databaseError('Can not execute query to characters database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_characters']);
     }
     if(!$this->rDB->selectCell("SELECT `name` FROM `realmlist` LIMIT 1")) {
         $this->databaseError('Can not execute query to realmd database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_realmd']);
     }
     if(!$this->wDB->selectCell("SELECT `entry` FROM `item_template` LIMIT 1")) {
         $this->databaseError('Can not execute query to mangos database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_mangos']);
     }
     */
     $this->aDB->query("SET NAMES ?", $this->mysqlconfig['charset_armory']);
     $this->cDB->query("SET NAMES ?", $this->mysqlconfig['charset_characters']);
     $this->rDB->query("SET NAMES ?", $this->mysqlconfig['charset_realmd']);
     $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']);
     $this->tpl = new Smarty();
     return true;
 }
示例#8
0
 function BDConnect()
 {
     $db = DbSimple_Generic::connect("mysqli://{$this->user}:{$this->pass}@{$this->host}/{$this->bd_name}");
     $db->query("SET NAMES utf8");
     $db->setErrorHandler('databaseErrorHandler');
     $db->setLogger('myLogger');
     return $db;
 }
示例#9
0
 public function connectDB()
 {
     // Подключаемся к БД.
     $db = DbSimple_Generic::connect("mysqli://{$this->db_user}:{$this->db_password}@{$this->db_host}/{$this->db_name}");
     $db->query("SET NAMES utf8");
     // Устанавливаем обработчик ошибок.
     $db->setErrorHandler('installErrorHandler');
     $db->setLogger('myLogger');
     return $db;
 }
示例#10
0
 public function __construct($ini_file_name)
 {
     if (!($ini_array = $this->get_params_from_ini_file($ini_file_name))) {
         echo 'Отсутствует ' . $this->ini_file_name . ' файл. Перейдите к <a href="install.php">установке</a>';
         exit;
     }
     $this->db = DbSimple_Generic::connect('mysqli://' . $ini_array['UserName'] . ':' . $ini_array['Password'] . '@' . $ini_array['ServerName'] . '/' . $ini_array['Database']);
     $this->db->setErrorHandler('databaseErrorHandler');
     $this->db->setLogger('myLogger');
 }
示例#11
0
function &connectMysql($conf)
{
    global $config;
    require_once $config['root_dir'] . '/includes/dbsimple/Generic.php';
    require_once $config['root_dir'] . '/includes/dbsimple/Mysql.php';
    extract($conf);
    $database =& DbSimple_Generic::connect(array('scheme' => 'mysql', 'user' => $user, 'pass' => $pass, 'host' => $host, 'path' => $db));
    $database->setErrorHandler('defaultDatabaseErrorHandler');
    $database->setIdentPrefix($prefix);
    return $database;
}
示例#12
0
 /**
  * Получает объект БД
  *
  * @param array $aConfig - конфиг подключения к БД(хост, логин, пароль, тип бд, имя бд)
  * @return DbSimple
  */
 public function GetConnect($aConfig = null)
 {
     /**
      * Если конфиг не передан то используем главный конфиг БД из config.php
      */
     if (is_null($aConfig)) {
         $aConfig = Config::Get('db.params');
     }
     $sDSN = $aConfig['type'] . 'wrapper://' . $aConfig['user'] . ':' . $aConfig['pass'] . '@' . $aConfig['host'] . ':' . $aConfig['port'] . '/' . $aConfig['dbname'];
     /**
      * Создаём хеш подключения, уникальный для каждого конфига
      */
     $sDSNKey = md5($sDSN);
     /**
      * Проверяем создавали ли уже коннект с такими параметрами подключения(DSN)
      */
     if (isset($this->aInstance[$sDSNKey])) {
         return $this->aInstance[$sDSNKey];
     } else {
         /**
          * Если такого коннекта еще не было то создаём его
          */
         $oDbSimple = DbSimple_Generic::connect($sDSN);
         /**
          * Устанавливаем хук на перехват ошибок при работе с БД
          */
         $oDbSimple->setErrorHandler('databaseErrorHandler');
         /**
          * Если нужно логировать все SQL запросы то подключаем логгер
          */
         if (Config::Get('sys.logs.sql_query')) {
             $oDbSimple->setLogger('databaseLogger');
         }
         /**
          * Устанавливаем настройки соединения, по хорошему этого здесь не должно быть :)
          * считайте это костылём
          */
         $oDbSimple->query("set character_set_client='utf8'");
         $oDbSimple->query("set character_set_results='utf8'");
         $oDbSimple->query("set collation_connection='utf8_bin'");
         /**
          * Сохраняем коннект
          */
         $this->aInstance[$sDSNKey] = $oDbSimple;
         /**
          * Возвращаем коннект
          */
         return $oDbSimple;
     }
 }
示例#13
0
 private function _boot()
 {
     session_start();
     ob_start();
     $this->_oConfig = new Config($this->_sConfigFile);
     setlocale(LC_ALL, $this->config->project->locale);
     require_once $_SERVER['DOCUMENT_ROOT'] . $this->config->db->lib_path . '/Generic.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . $this->config->db->lib_path . '/Mysql.php';
     $this->_oDb = \DbSimple_Generic::connect("mysql://" . $this->config->db->user . ($this->config->db->password ? ":" . $this->config->db->password : '') . "@" . $this->config->db->host . "/" . $this->config->db->database);
     $this->db->setIdentPrefix($this->config->db->table_prefix);
     $this->db->query("SET NAMES utf8");
     $oRoutesConfig = new Config($_SERVER['DOCUMENT_ROOT'] . $this->config->router->path);
     $this->_oRequest = new Request($oRoutesConfig->routes);
     $this->_oView = new View($this->config->templates->path, $this->_oRequest->lang);
     $this->_oDirector = new Director($this->options);
 }
 function __construct()
 {
     global $config;
     include_once dirname(__FILE__) . '/dbsimple/Generic.php';
     $this->cDB = DbSimple_Generic::connect($config['cdb']);
     $this->cDB->setErrorHandler("databaseErrorHandler");
     $this->cDB->query("SET NAMES ? ", $config['db_encoding']);
     $this->rDB = DbSimple_Generic::connect($config['rdb']);
     $this->rDB->setErrorHandler("databaseErrorHandler");
     $this->rDB->query("SET NAMES ? ", $config['db_encoding']);
     $this->wDB = DbSimple_Generic::connect($config['wdb']);
     $this->wDB->setErrorHandler("databaseErrorHandler");
     $this->wDB->query("SET NAMES ? ", $config['db_encoding']);
     if ($config['buildClient'] < 11723) {
         print "Некорректно настроен конфиг. Неизвесная сборка клиента (" . $config['buildClient'] . ")";
     }
 }
示例#15
0
 /**
  * Возвращает экземпляр класса для подключения к бд
  *
  * @param string  $dbAlias
  * @return DbSimple_Generic
  */
 public static function get($dbAlias)
 {
     if (!isset(self::$_instances[$dbAlias])) {
         $db = DbSimple_Generic::connect(self::$_configs[$dbAlias]['connectUri']);
         if (self::$_configs[$dbAlias]['initSQL']) {
             $db->query(self::$_configs[$dbAlias]['initSQL']);
         }
         $db->setErrorHandler(array(__CLASS__, 'databaseErrorHandler'));
         $db->addIgnoreInTrace(__CLASS__ . '::databaseErrorHandler');
         if (self::$_configs[$dbAlias]['debug']) {
             $db->setLogger(array(__CLASS__, 'databaseLogger'));
             $db->addIgnoreInTrace(__CLASS__ . '::databaseLogger');
         }
         self::$_instances[$dbAlias] = $db;
     }
     return self::$_instances[$dbAlias];
 }
 /**
  * Получает объект БД
  *
  * @param array|null $aConfig - конфиг подключения к БД(хост, логин, пароль, тип бд, имя бд), если null, то используются параметры из конфига Config::Get('db.params')
  * @param bool $bForce Создавать принудительно новый коннект, даже если он уже существует
  * @return DbSimple_Generic_Database DbSimple
  */
 public function GetConnect($aConfig = null, $bForce = false)
 {
     /**
      * Получаем DSN
      */
     $sDSN = $this->GetDSNByConfig($aConfig);
     /**
      * Создаём хеш подключения, уникальный для каждого конфига
      */
     $sDSNKey = md5($sDSN);
     /**
      * Проверяем создавали ли уже коннект с такими параметрами подключения(DSN)
      */
     if (isset($this->aInstance[$sDSNKey]) and !$bForce) {
         return $this->aInstance[$sDSNKey];
     } else {
         /**
          * Если такого коннекта еще не было то создаём его
          */
         $oDbSimple = DbSimple_Generic::connect($sDSN);
         /**
          * Устанавливаем хук на перехват ошибок при работе с БД
          */
         $oDbSimple->setErrorHandler(array($this, 'CallbackError'));
         /**
          * Если нужно логировать все SQL запросы то подключаем логгер
          */
         if (Config::Get('sys.logs.sql_query')) {
             $oDbSimple->setLogger(array($this, 'CallbackQuery'));
         }
         /**
          * Устанавливаем настройки соединения, по хорошему этого здесь не должно быть :)
          * считайте это костылём
          */
         $oDbSimple->query("set character_set_client='utf8', character_set_results='utf8', collation_connection='utf8_bin' ");
         /**
          * Сохраняем коннект
          */
         $this->aInstance[$sDSNKey] = $oDbSimple;
         /**
          * Возвращаем коннект
          */
         return $oDbSimple;
     }
 }
示例#17
0
 public static function connect($idx)
 {
     if (self::isConnected($idx)) {
         return;
     }
     $options =& self::$optionsCache[$idx];
     $interface = DbSimple_Generic::connect(self::createConnectSyntax($options));
     if (!$interface || $interface->error) {
         die('Failed to connect to database.');
     }
     $interface->setErrorHandler(['DB', 'errorHandler']);
     $interface->query('SET NAMES ?', 'utf8');
     if ($options['prefix']) {
         $interface->setIdentPrefix($options['prefix']);
     }
     self::$interfaceCache[$idx] =& $interface;
     self::$connectionCache[$idx] = true;
 }
示例#18
0
文件: DB.php 项目: slimko/test
 private function __construct()
 {
     require_once "./lib/dbsimple/config.php";
     require_once "./lib/dbsimple/DbSimple/Generic.php";
     //проверим заполнен ли конфигурационный файл с подключением к БД в случае ошибки перенаправим на установку
     if (!file_get_contents('base.conf')) {
         header('Location: http://' . $_SERVER['HTTP_HOST'] . '/install');
         exit;
     }
     $this->getConfig();
     //получаем конфиг к подключению к базе данных
     $this->db = DbSimple_Generic::connect("mysql://{$this->_conf['user_name']}:{$this->_conf['password']}@{$this->_conf['server_name']}/{$this->_conf['database']}");
     //в случае возникновения ошибки
     if (!empty($this->db->error)) {
         $this->db = $this->databaseError($this->db->error['code'], $this->db->error['message']);
         return $this->db;
     }
     $this->db->query("SET NAMES UTF8");
 }
 protected function _getDbConnect($sDsn)
 {
     if (Config::Get('db.params.lazy')) {
         // lazy connection
         //F::IncludeLib('DbSimple3/lib/DbSimple/Connect.php');
         $oDbSimple = new DbSimple_Connect($sDsn);
         foreach ($this->aInitSql as $sSql) {
             $oDbSimple->addInit($sSql);
         }
     } else {
         // immediate connection
         //F::IncludeLib('DbSimple3/lib/DbSimple/Generic.php');
         $oDbSimple = DbSimple_Generic::connect($sDsn);
         foreach ($this->aInitSql as $sSql) {
             $oDbSimple->query($sSql);
         }
     }
     return $oDbSimple;
 }
示例#20
0
 function initialize(IConfigParameter $configuration)
 {
     $dsn = $configuration->get('DSN');
     if (!$dsn) {
         $connection_file = $configuration->get('connection_file');
         if (!$connection_file) {
             throw new DbException("Connection file not defined");
         }
         $p = pathinfo($connection_file);
         $dir = Project::NS()->path($p['dirname']);
         $f = $dir . $p['basename'];
         if (!file_exists($f) || !is_file($f)) {
             throw new DbException("Connection file not exists");
         }
         $config = new ConfigParameter(file_get_contents($f));
         $dsn = $config->get('DSN');
         if (!$dsn) {
             throw new DbException("DSN not exitsts at connection file");
         }
     }
     $this->_caching = $configuration->get('caching');
     if ($configuration->get('cache_prefix')) {
         $this->_cache_prefix = $configuration->get('cache_prefix');
     }
     if ($configuration->get('cache_module_id')) {
         $this->_cache_module_id = $configuration->get('cache_module_id');
     } else {
         // No cache module defined
         // TODO:: write NOTICE to log
         $this->_caching = false;
     }
     $this->_DSN = $dsn;
     $this->_common_config($configuration);
     $this->_driver = DbSimple_Generic::connect($this->_DSN);
     if (!is_object($this->_driver)) {
         throw new DbException("No connection to database");
     }
     $this->_driver->query("SET NAMES utf8");
     $this->_driver->setLogger($configuration->get('native_logger'));
     //$this -> _driver -> setLogger('myLogger');
     Project::setDatabase($this);
 }
示例#21
0
 public static function connect($idx)
 {
     if (self::isConnected($idx)) {
         return;
     }
     $options =& self::$optionsCache[$idx];
     $interface = DbSimple_Generic::connect(self::createConnectSyntax($options));
     if (!$interface || $interface->error) {
         die('Failed to connect to database.');
     }
     $interface->setErrorHandler(['DB', 'errorHandler']);
     $interface->query('SET NAMES ?', 'utf8');
     if ($options['prefix']) {
         $interface->setIdentPrefix($options['prefix']);
     }
     // kill STRICT_TRANS_TABLES and STRICT_ALL_TABLES off. It prevents usage of implicit default values.
     if ($idx == DB_AOWOW) {
         $interface->query('SET SESSION sql_mode = \'NO_ENGINE_SUBSTITUTION\'');
     }
     self::$interfaceCache[$idx] =& $interface;
     self::$connectionCache[$idx] = true;
 }
示例#22
0
文件: misc.php 项目: sandrain/hangee
 function c()
 {
     global $conn;
     if (self::$conn) {
         return self::$conn;
     }
     self::$conn = DbSimple_Generic::connect(sprintf("mysql://%s:%s@%s/%s", Z::config("db_user"), Z::config("db_password"), Z::config("db_host"), Z::config("db_database")));
     /* Set error handler */
     if (!function_exists("databaseErrorHandler")) {
         function databaseErrorHandler($message, $info)
         {
             // 	Если использовалась @, ничего не делать.
             if (!error_reporting()) {
                 return;
             }
             // Выводим подробную информацию об ошибке.
             var_dump($message);
             var_dump($info);
             //	debug($message);
             //	debug($info);
             exit;
         }
     }
     self::$conn->setErrorHandler('databaseErrorHandler');
     /*$conn->setLogger('myLogger');
       function myLogger($db, $sql) {
         // Находим контекст вызова этого запроса.
       //  $caller = $db->findLibraryCaller();
       //  $tip = "at ".@$caller['file'].' line '.@$caller['line'];
         // Печатаем запрос (конечно, Debug_HackerConsole лучше).
       //  echo "<xmp title=\"$tip\">"; 
       //  print_r($sql); 
       //  echo "</xmp>";
         debug($sql);
       }
         */
     self::$conn->query("SET names utf8");
 }
示例#23
0
 /**
  * Initialize database & template handlers, sets up sql/site configs
  * @category Main system functions
  * @example Connector::__construct()
  * @return bool
  **/
 public function Connector()
 {
     if (!@(include 'configuration.php')) {
         die('<b>Error</b>: unable to load configuration file!');
     }
     if (!@(require_once 'libs/DbSimple/Generic.php')) {
         die('<b>Error</b>: unable to load database class!');
     }
     $this->mysqlconfig = $ArmoryConfig['mysql'];
     $this->armoryconfig = $ArmoryConfig['settings'];
     $this->realmData = $ArmoryConfig['multiRealm'];
     $this->aDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_armory'] . ':' . $this->mysqlconfig['pass_armory'] . '@' . $this->mysqlconfig['host_armory'] . '/' . $this->mysqlconfig['name_armory']);
     $this->aDB->query("SET NAMES ?", $this->mysqlconfig['charset_armory']);
     $this->rDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_realmd'] . ':' . $this->mysqlconfig['pass_realmd'] . '@' . $this->mysqlconfig['host_realmd'] . '/' . $this->mysqlconfig['name_realmd']);
     if (isset($_GET['r'])) {
         $realmName = urldecode($_GET['r']);
         $realm_info = $this->aDB->selectRow("SELECT `id`, `version` FROM `armory_realm_data` WHERE `name`=?", $realmName);
         if (!$realm_info) {
             $this->cDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_characters'] . ':' . $this->mysqlconfig['pass_characters'] . '@' . $this->mysqlconfig['host_characters'] . '/' . $this->mysqlconfig['name_characters']);
             $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']);
             $this->cDB->query("SET NAMES ?", $this->mysqlconfig['charset_characters']);
             $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']);
         } elseif (isset($this->realmData[$realm_info['id']])) {
             $this->connectionData = $this->realmData[$realm_info['id']];
             $this->cDB = DbSimple_Generic::connect('mysql://' . $this->connectionData['user_characters'] . ':' . $this->connectionData['pass_characters'] . '@' . $this->connectionData['host_characters'] . '/' . $this->connectionData['name_characters']);
             $this->cDB->query("SET NAMES ?", $this->connectionData['charset_characters']);
             $this->currentRealmInfo = array('name' => $this->connectionData['name'], 'id' => $realm_info['id'], 'version' => $realm_info['version'], 'connected' => true);
             if (isset($this->connectionData['name_mangos'])) {
                 $this->wDB = DbSimple_Generic::connect('mysql://' . $this->connectionData['user_mangos'] . ':' . $this->connectionData['pass_mangos'] . '@' . $this->connectionData['host_mangos'] . '/' . $this->connectionData['name_mangos']);
                 $this->wDB->query("SET NAMES ?", $this->connectionData['charset_mangos']);
             } else {
                 $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']);
                 $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']);
             }
         } else {
             $this->cDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_characters'] . ':' . $this->mysqlconfig['pass_characters'] . '@' . $this->mysqlconfig['host_characters'] . '/' . $this->mysqlconfig['name_characters']);
             $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']);
             $this->cDB->query("SET NAMES ?", $this->mysqlconfig['charset_characters']);
             $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']);
         }
     } else {
         $this->cDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_characters'] . ':' . $this->mysqlconfig['pass_characters'] . '@' . $this->mysqlconfig['host_characters'] . '/' . $this->mysqlconfig['name_characters']);
         $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']);
         $this->cDB->query("SET NAMES ?", $this->mysqlconfig['charset_characters']);
         $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']);
     }
     if (!$this->currentRealmInfo) {
         $this->currentRealmInfo = array('name' => $this->realmData[1]['name'], 'id' => 1, 'version' => $this->armoryconfig['server_version'], 'connected' => true);
     }
     if (!$this->connectionData) {
         $this->connectionData = $this->realmData[1];
     }
     $this->rDB->query("SET NAMES ?", $this->mysqlconfig['charset_realmd']);
     $user_locale = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
     if ($user_locale && ($http_locale = self::IsAllowedLocale($user_locale))) {
         $this->_locale = isset($_SESSION['armoryLocale']) ? $_SESSION['armoryLocale'] : $http_locale;
     } else {
         $this->_locale = isset($_SESSION['armoryLocale']) ? $_SESSION['armoryLocale'] : $this->armoryconfig['defaultLocale'];
     }
     $this->_locale = isset($_SESSION['armoryLocale']) ? $_SESSION['armoryLocale'] : $this->armoryconfig['defaultLocale'];
     switch ($this->_locale) {
         case 'en_gb':
         case 'en_us':
             $this->_loc = 0;
             break;
             /*
             case 'ko_kr':
                 $this->_loc = 1;
                 break;
             */
         /*
         case 'ko_kr':
             $this->_loc = 1;
             break;
         */
         case 'fr_fr':
             $this->_loc = 2;
             break;
         case 'de_de':
             $this->_loc = 3;
             break;
             /*
             case 'zh_cn':
                 $this->_loc = 4; // China
                 break;
             case 'zh_tw':
                 $this->_loc = 5; // Taiwan
                 break;
             */
         /*
         case 'zh_cn':
             $this->_loc = 4; // China
             break;
         case 'zh_tw':
             $this->_loc = 5; // Taiwan
             break;
         */
         case 'es_es':
             $this->_loc = 6;
             break;
         case 'es_mx':
             $this->_loc = 7;
             break;
         case 'ru_ru':
             $this->_loc = 8;
             break;
     }
 }
示例#24
0
{
	$mangos['db_port'] = ( int )$MW->getConfig->generic->use_alternate_mangosdb_port ;
}

// Connects to WORLD DB
$WSDB = DbSimple_Generic::connect( "" . $mangos['db_type'] . "://" . $mangos['db_username'] .
	":" . $mangos['db_password'] . "@" . $mangos['db_host'] . ":" . $mangos['db_port'] .
	"/" . $mangos['db_name'] . "" ) ;
if ( $WSDB )
	$WSDB->setErrorHandler( 'databaseErrorHandler' ) ;
if ( $WSDB )
	$WSDB->query( "SET NAMES " . $mangos['db_encoding'] ) ;

// Connects to CHARACTERS DB
$CHDB = DbSimple_Generic::connect( "" . $mangos['db_type'] . "://" . $mangos['db_username'] .
	":" . $mangos['db_password'] . "@" . $mangos['db_host'] . ":" . $mangos['db_port'] .
	"/" . $mangos['db_char'] . "" ) ;
if ( $CHDB )
	$CHDB->setErrorHandler( 'databaseErrorHandler' ) ;
if ( $CHDB )
	$CHDB->query( "SET NAMES " . $mangos['db_encoding'] ) ;

//Load characters list
if ( isset( $user['id'] ) && $user['id'] > 0 )
{
	$characters = $CHDB->select( 'SELECT guid,name FROM `characters` WHERE account=?d',
		$user['id'] ) ;
	if ( isset( $_COOKIE['cur_selected_character'] ) )
	{
		foreach ( $characters as $character )
		{
示例#25
0
 if (!$realmid) {
     $strErrorMsg = 'Not realmid';
     $bResult = false;
 }
 if ($bResult) {
     $realm_info = get_realm_byid($realmid);
     if (!$realm_info['CharacterDatabaseInfo']) {
         $strErrorMsg = 'Check field <u>CharacterDatabaseInfo</u> in table `realmlist` for realm id=' . $realm_info['id'];
         $bResult = false;
     }
 }
 AddMangosFields($realm_info['Version']);
 $charinfo_link = $realm_info['WowdCharInfoLink'];
 if ($bResult) {
     $wsdb_info = parse_worlddb_info($realm_info['CharacterDatabaseInfo']);
     $WSDB = DbSimple_Generic::connect("" . $config['db_type'] . "://" . $wsdb_info['user'] . ":" . $wsdb_info['password'] . "@" . $wsdb_info['host'] . ":" . $wsdb_info['port'] . "/" . $wsdb_info['db'] . "");
     if (!$WSDB) {
         $strErrorMsg = 'Not Connect';
         $bResult = false;
     }
 }
 $action = $_GET['action'];
 $guid = $_GET['guid'];
 $char_online = false;
 if ($bResult) {
     $WSDB->setErrorHandler('databaseErrorHandler');
     $WSDB->query("SET NAMES " . $config['db_encoding']);
     $query = $WSDB->selectrow("SELECT * FROM `characters` WHERE `account`=?d and `guid`=?d ORDER BY `name`", $user['id'], $guid);
     $my_char;
     if (!$query) {
         $strErrorMsg = 'Персонаж на вашем аккаунте не обнаружен';
示例#26
0
include 'RepositoryAds.php';
include 'Advertisement.php';
include 'AdvCompany.php';
include 'AdvPrivate.php';
//include 'AdvertisementFactory.php';
// загрузка данных из фала server_name,user_name, password, database
$filename = './User.txt';
if (file_exists($filename)) {
    $temp_str = file_get_contents('./User.txt');
    if (isset($temp_str)) {
        $user = unserialize(file_get_contents('./User.txt'));
        // действие в случае удачи
    } else {
        ?>
<a href="instal.php">Проверьте введенные данные</a><?php 
        exit('Ошибка чтения файла');
        // или другое действие при неудачном чтении файла
    }
} else {
    ?>
<a href="instal.php">Проверьте введенные данные</a><?php 
    exit('Ошибка чтения файла');
}
//подключение к серверу SQL
$bd = DbSimple_Generic::connect("mysqli://{$user['user_name']}:{$user['password']}@{$user['server_name']}/{$user['database']}");
// Устанавливаем обработчик ошибок.
$bd->setErrorHandler('databaseErrorHandler');
$bd->setLogger('myLogger');
$bd->query('SET NAMES utf8');
//установка кодировки utf8
$location = basename($_SERVER['PHP_SELF']);
示例#27
0
<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', 1);
require_once "settings.php";
require_once "functions.php";
require_once "FirePHPCore/FirePHP.class.php";
require_once MY_DBSIMPLE_DIR . "DbSimple/Generic.php";
require_once MY_DBSIMPLE_DIR . "config.php";
require_once MY_SMARTY_DIR . '/libs/Smarty.class.php';
$firePHP = FirePHP::getInstance(true);
$firePHP->setEnabled(true);
$smarty = new Smarty();
$smarty->compile_check = true;
$smarty->template_dir = MY_SMARTY_DIR . 'templates';
$smarty->compile_dir = MY_SMARTY_DIR . 'templates_c';
$smarty->cache_dir = MY_SMARTY_DIR . 'cache';
$smarty->config_dir = MY_SMARTY_DIR . 'configs';
if (!($iniArray = getParamsFromIniFile(INI_FILE_NAME))) {
    echo 'Отсутствует ' . INI_FILE_NAME . ' файл. Перейдите к <a href="install.php">установке</a>';
    exit;
}
$db = DbSimple_Generic::connect('mysqli://' . $iniArray['UserName'] . ':' . $iniArray['Password'] . '@' . $iniArray['ServerName'] . '/' . $iniArray['Database']);
$db->setErrorHandler('databaseErrorHandler');
$db->setLogger('myLogger');
示例#28
0
$users_online = array();
$guests_online = 0;
$messages = '';
$redirect = '';
$sidebarmessages = '';
$context_menu = array();
// Connetcts to DB
// DB layer documentation at http://en.dklab.ru/lib/DbSimple/
function databaseErrorHandler($message, $info)
{
    if (!error_reporting()) {
        return;
    }
    output_message('alert', "SQL Error: {$message}<br><pre>" . print_r($info, true) . "</pre>");
}
$DB = DbSimple_Generic::connect("" . $config['db_type'] . "://" . $config['db_username'] . ":" . $config['db_password'] . "@" . $config['db_host'] . ":" . $config['db_port'] . "/" . $config['db_name'] . "");
$DB->setErrorHandler('databaseErrorHandler');
$DB->query("SET NAMES " . $config['db_encoding']);
// Load settings from db or cache //
loadSettings();
// Build path vars //
$config['site_href'] = str_replace('//', '/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']) . '/'));
$config['site_domain'] = $_SERVER['HTTP_HOST'];
$config['base_href'] = 'http://' . $config['site_domain'] . '' . $config['site_href'];
$config['template_href'] = $config['site_href'] . 'templates/' . $config['template'] . '/';
// Check lang ======================================
if (isset($_COOKIE['Language'])) {
    $config['lang'] = $_COOKIE['Language'];
}
loadLanguages();
// ================================================
示例#29
0
ini_set('display_errors', 1);
require_once "../dbsimple/config.php";
require_once "../dbsimple/DbSimple/Generic.php";
require_once '../FirePHPCore/lib/FirePHPCore/FirePHP.class.php';
$firePHP = FirePHP::getInstance(true);
$firePHP->setEnabled(true);
require '../smarty/libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->compile_check = true;
//$smarty->debugging = true;
$smarty->template_dir = '../smarty/templates';
$smarty->compile_dir = '../smarty/templates_c';
$smarty->cache_dir = '../smarty/cache';
$smarty->config_dir = '../smarty/configs';
// Подключаемся к БД.
$db = DbSimple_Generic::connect('mysqli://*****:*****@127.0.0.1/ads');
//DNS
$db->setErrorHandler('databaseErrorHandler');
$db->setLogger('myLogger');
function databaseErrorHandler($message, $info)
{
    if (!error_reporting()) {
        return;
    }
    echo "SQL Error: {$message}<br><pre>";
    print_r($info);
    echo "</pre>";
    exit;
}
function myLogger($db, $sql, $caller)
{
示例#30
0
文件: init.php 项目: Sarjuuk/DbSimple
                continue;
            }
            if ($dsnOwn != '*' && strtolower($e) != strtolower($dsnOwn)) {
                continue;
            }
            $dsn = trim(@join("", file("{$full}/{$dsnFile}")));
            if ($dsn) {
                $DSN = array_merge($DSN, preg_split('/\\s+/s', $dsn));
            }
        }
    } else {
        $DSN[] = $dsnOwn;
    }
}
foreach ($DSN as $dsn) {
    $DB =& DbSimple_Generic::connect($dsn);
    $DB->setLogger('queryLogger');
    $DB->setErrorHandler('errorHandler');
    main($DB);
}
function queryLogger(&$DB, $query)
{
    if (preg_match('/^\\s*--\\s+(\\d|error)/', $query)) {
        return;
    }
    printr($query, "Query");
}
function errorHandler($msg, $error)
{
    if (!error_reporting()) {
        return;