Exemple #1
0
 public function get($key)
 {
     $object = $this->db->select('*')->from(':cache')->where(['file_name' => $key])->get();
     if (isset($object['cache_id'])) {
         return $this->_build($object);
     }
     return null;
 }
Exemple #2
0
 public function initDb($name)
 {
     $config = App::conf('app', 'database');
     if (!isset($config[$name])) {
         throw new \InvalidArgumentException("数据配置不存在: {$name}");
     }
     $db = new Db($config[$name]);
     $db->setLogger(App::logger());
     return $db;
 }
    public static function createAdoption($adoptionObj)
    {
        $user_id_adopter = \Core\Db::escape($adoptionObj->getUserIdAdopter());
        $user_id_poster = \Core\Db::escape($adoptionObj->getUserIdPoster());
        $pet_id = \Core\Db::escape($adoptionObj->getPetId());
        $created = $adoptionObj->getCreated();
        $updated = $adoptionObj->getUpdated();
        $visibility = $adoptionObj->getVisibility();
        $sql = <<<q
INSERT INTO `adoption`(
`id`,
`user_id_adopter`, 
`user_id_poster`,
`pet_id`,
`created`,
`updated`,
`visibility`) 
VALUES (
DEFAULT,
'{$user_id_adopter}',
'{$user_id_poster}',
'{$pet_id}',
{$created},
{$updated},
'{$visibility}');
q;
        $res = \Core\Db::execute($sql);
        return $res === false ? false : \Core\Db::insertId();
    }
Exemple #4
0
 public static function save($user_data)
 {
     $dbh = Db::get();
     try {
         $query = $dbh->prepare('INSERT INTO ' . static::tableName() . ' (login, password, email, sex, birth_date, other_info, picture) VALUES (:login, :password, :email, :sex, :birth_date, :other_info, :picture)');
     } catch (\PDOException $e) {
         echo "PDO Exception: ";
         var_dump($e->getMessage());
         die;
     }
     $query->bindValue(':login', $user_data['login']);
     $query->bindValue(':password', static::bcrypt($user_data['password']));
     $query->bindValue(':email', $user_data['email']);
     $query->bindValue(':sex', $user_data['sex']);
     $query->bindValue(':birth_date', $user_data['birth_date_year'] . '-' . $user_data['birth_date_month'] . '-' . $user_data['birth_date_day']);
     $query->bindValue(':other_info', $user_data['other_info']);
     $query->bindValue(':picture', isset($user_data['picture']) ? $user_data['picture'] : null);
     try {
         $query->execute();
     } catch (\PDOException $e) {
         echo "Error while saving user info: " . $e->getMessage();
     }
     $user_data['password'] = static::bcrypt($user_data['password']);
     return new UserModel($user_data);
 }
Exemple #5
0
 public function setDefault()
 {
     $this->_db->update(':theme', ['is_default' => 0], ['is_default' => 1]);
     $this->_db->update(':theme_style', ['is_default' => 0], ['is_default' => 1]);
     $this->_db->update(':theme', ['is_default' => 1], ['theme_id' => $this->theme_id]);
     $this->_db->update(':theme_style', ['is_default' => 1], ['style_id' => $this->flavor_id]);
     return true;
 }
Exemple #6
0
 static function findAll($condition)
 {
     //Выборка записей;
     $table = static::getTable();
     $sql = "Select * from " . $table;
     if ($condition) {
         $sql .= " {$condition}";
     }
     return Db::getInstance()->query($sql, \PDO::FETCH_ASSOC);
 }
Exemple #7
0
 public function initDb($name)
 {
     $config = App::conf('app', 'database');
     if (!isset($config[$name])) {
         throw new \InvalidArgumentException("数据配置不存在: {$name}");
     }
     $config = $config[$name];
     $db = new Db($config);
     if (isset($config['slow_log']) && $config['slow_log']) {
         // 慢查询日志
         $db->addHook(Db::TAG_AFTER_QUERY, function ($data) use($config) {
             if ($data['time'] > $config['slow_log']) {
                 $logger = App::logger('database');
                 $logger->debug("\nROUTE: " . CUR_ROUTE . "\nSQL: {$data['sql']}\nDATA: " . json_encode($data['data']) . "\nTIME: {$data['time']}\nMETHOD: {$data['method']}\n");
             }
         });
     }
     return $db;
 }
Exemple #8
0
 public function initDatabase()
 {
     $this->db = \Core\Db::create("mysql");
     // create table (demo pour mysql)
     $sql = "\n            CREATE TABLE IF NOT EXISTS `role` (\n              `idrole` int(11) NOT NULL AUTO_INCREMENT,\n              `role` varchar(45) DEFAULT NULL,\n              PRIMARY KEY (`idrole`)\n            )\n        ";
     $this->db->query($sql);
     $sql = "\n            CREATE TABLE IF NOT EXISTS `countries` (\n                `id` int(11) NOT NULL auto_increment,\n                `country_code` varchar(2) NOT NULL default '',\n                `country_name` varchar(100) NOT NULL default '',\n                PRIMARY KEY (`id`)\n            )\n        ";
     $this->db->query($sql);
     $sql = "\n            CREATE TABLE IF NOT EXISTS `user` (\n              `iduser` int(11) NOT NULL AUTO_INCREMENT,\n              `nom` varchar(45) NOT NULL,\n              `password` varchar(45) DEFAULT NULL,\n              `role` int(11) DEFAULT NULL,\n              `datetime` datetime DEFAULT NULL,\n              `date` date DEFAULT NULL,\n              `time` time DEFAULT NULL,\n              `float` float DEFAULT NULL,\n              `description` text,\n              `pays` int(11) DEFAULT NULL,\n              PRIMARY KEY (`iduser`),\n              UNIQUE KEY `nom_UNIQUE` (`nom`),\n              KEY `fk_user_role` (`role`),\n              KEY `fk_user_pays` (`pays`),\n              CONSTRAINT `fk_user_pays` FOREIGN KEY (`pays`) REFERENCES `countries` (`id`),\n              CONSTRAINT `fk_user_role` FOREIGN KEY (`role`) REFERENCES `role` (`idrole`)\n            )\n        ";
     $this->db->query($sql);
 }
Exemple #9
0
 /**
  * 将数组解析成SQL
  *
  * @param array $filter
  * @return string
  */
 protected function parseFilter(array $filter)
 {
     $where = array();
     foreach ($filter as $field => $val) {
         if (($pos = strrpos($field, '__')) > 0) {
             $op = substr($field, $pos + 2);
             $field = substr($field, 0, $pos);
             switch ($op) {
                 case 'gt':
                     //大于
                     $where[] = "`{$field}` > " . $this->db->quote($val);
                     break;
                 case 'gte':
                     //大于等于
                     $where[] = "`{$field}` >= " . $this->db->quote($val);
                     break;
                 case 'lt':
                     //小于
                     $where[] = "`{$field}` < " . $this->db->quote($val);
                     break;
                 case 'lte':
                     //小于等于
                     $where[] = "`{$field}` <= " . $this->db->quote($val);
                     break;
                 case 'like':
                     //LIKE ‘%%’
                     $where[] = "`{$field}` LIKE " . $this->db->quote("%{$val}%");
                     break;
                 case 'startswith':
                     //LIKE 'xxx%'
                     $where[] = "`{$field}` LIKE " . $this->db->quote("{$val}%");
                     break;
                 case 'endswith':
                     //LIKE '%xxx'
                     $where[] = "`{$field}` LIKE " . $this->db->quote("%{$val}");
                     break;
                 case 'between':
                     //between 'a' AND 'b'
                     $where[] = "`{$field}` BETWEEN " . $this->db->quote($val[0]) . " AND " . $this->db->quote($val[1]);
                     break;
             }
         } elseif (is_array($val)) {
             foreach ($val as $k => $v) {
                 $val[$k] = $this->db->quote($v);
             }
             $where[] = "`{$field}` IN (" . implode(',', $val) . ")";
         } else {
             $where[] = "`{$field}` = " . $this->db->quote($val);
         }
     }
     return implode(' AND ', $where);
 }
Exemple #10
0
 public function __construct($select = false)
 {
     $config = (require $this->config);
     $this->configure($config);
     $this->db = Db::getInstance()->connect($this);
     $modelName = get_class($this);
     $arrExp = explode('\\', $modelName);
     $tableName = strtolower($arrExp[1]);
     $this->table = $tableName;
     $sql = $this->_getSelect($select);
     if ($sql) {
         $this->_getResult("SELECT * FROM {$this->table}" . $sql);
     }
 }
Exemple #11
0
 function connect()
 {
     include "db-conf.php";
     try {
         if (Db::$_db) {
             return Db::$_db;
         }
         $opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
         $db = new PDO('mysql:host=localhost;dbname=' . $dbConfig["dbname"], $dbConfig["user"], $dbConfig["password"], $opt);
         //TODO: move to config
         Db::$_db = $db;
         return $db;
     } catch (PDOException $e) {
         echo $e->getMessage();
     }
 }
Exemple #12
0
 public function __construct($params = array())
 {
     parent::__construct($params);
     $db = null;
     if (isset($this->params["database"])) {
         $db = $this->params["database"];
     }
     $this->db = \Core\Db::create($db);
     $this->table = $this->params["table"];
     $this->describe = $this->db->describe($this->table);
     $this->primaryKey = null;
     foreach ($this->describe as $desc) {
         if ($desc["primaryKey"]) {
             $this->primaryKey = $desc["name"];
         }
     }
     if ($this->primaryKey === null) {
         throw new \Core\CException("TableManager : Table " . $this->table . " have no primary key");
     }
     $this->SetColumns();
 }
Exemple #13
0
 public static function findOneByField($fieldName = 'id', $fieldValue)
 {
     $pdo = Db::get();
     try {
         $query = $pdo->prepare('SELECT * FROM ' . static::tableName() . ' AS tbl WHERE tbl.' . $fieldName . ' = :fieldvalue');
     } catch (\PDOException $e) {
         echo "PDO Exception: ";
         var_dump($e->getMessage());
         die;
     }
     $query->bindValue(':fieldvalue', $fieldValue);
     $query->execute();
     $user_row = $query->fetch(\PDO::FETCH_ASSOC);
     if (!$user_row) {
         return null;
         //no entries with this restrictions
     }
     foreach ($user_row as $index => $value) {
         $user_row[$index] = htmlentities($value);
     }
     return new static($user_row);
 }
Exemple #14
0
 public function __construct()
 {
     parent::__construct('test', true);
 }
 public function getUsersConfig()
 {
     $db = \Core\Db::create($this->getUserParams("database"));
     return array("db" => $db, "database" => $this->getUserParams("database"), "userTable" => $this->getUserParams("userTable", "table"), "idField" => $this->getUserParams("userTable", "idField"), "loginField" => $this->getUserParams("userTable", "loginField"), "passwordField" => $this->getUserParams("userTable", "passwordField"), "passwordFn" => $this->getUserParams("userTable", "passwordFn"), "nameField" => $this->getUserParams("userTable", "nameField"), "roleTable" => $this->getUserParams("roleTable", "table"), "roleId" => $this->getUserParams("roleTable", "idField"), "roleField" => $this->getUserParams("roleTable", "roleField"), "linkTable" => $this->getUserParams("linkTable", "table"), "linkUser" => $this->getUserParams("linkTable", "userId"), "linkRole" => $this->getUserParams("linkTable", "roleId"));
 }
Exemple #16
0
 /**
  * 切换当前的数据库连接
  * @access public
  * @param integer $linkNum  连接序号
  * @param mixed $config  数据库连接信息
  * @param boolean $force 强制重新连接
  * @return Model
  */
 public function db($linkNum = '', $config = '', $force = false)
 {
     if ('' === $linkNum && $this->db) {
         return $this->db;
     }
     if (!isset($this->_db[$linkNum]) || $force) {
         // 创建一个新的实例
         if (!empty($config) && is_string($config) && false === strpos($config, '/')) {
             // 支持读取配置参数
             $config = Config::get($config);
         }
         $this->_db[$linkNum] = \Core\Db::getInstance($config);
     } elseif (NULL === $config) {
         $this->_db[$linkNum]->close();
         // 关闭数据库连接
         unset($this->_db[$linkNum]);
         return;
     }
     // 切换数据库连接
     $this->db = $this->_db[$linkNum];
     $this->_after_db();
     // 字段检测
     if (!empty($this->name) && $this->autoCheckFields) {
         $this->_checkTableInfo();
     }
     return $this;
 }
Exemple #17
0
 public function updateViews()
 {
     $this->_db->query("update #__ams_pages set views = views + 1 where ams_page_id = '" . $this->id . "'");
 }
Exemple #18
0
 public static function getPetByApproved($petApprove)
 {
     //$cleanPetName = \Core\Db::escape($petName);
     $sql = "SELECT * FROM pet WHERE `approved`='{$petApprove}';";
     $res = \Core\Db::execute($sql);
     return $res;
 }
Exemple #19
0
 public function __construct()
 {
     $this->conn = \Core\Db::getInstance();
 }
Exemple #20
0
<?php

$params = $self->getUsersConfig();
$table = $params["roleTable"];
$database = $params["database"];
$db = \Core\Db::create($database);
$fields = $db->describe($table);
$tblParams = array();
foreach ($fields as $field => $aField) {
    $tblParams[$field] = array("showInTable" => false);
}
$tblParams[$params["roleId"]] = array("alias" => "", "link" => true);
$tblParams[$params["roleField"]] = array("alias" => "Role", "link" => true);
echo \Core\Module::create("core/Admin/TableManager", array("database" => $database, "table" => $table, "columns" => $tblParams))->render();
 public static function getImagesByPetId($petId)
 {
     return \Core\Db::execute("SELECT * FROM image WHERE `pet_id`='{$petId}';");
 }
Exemple #22
0
 /**
  * Select a row from the user table by username
  * @param type $userName   email to select on
  * @return type  mixed      false on failure, array of results otherwise - see http://php.net/manual/en/mysqli.query.php
  * @throws Exception     
  */
 public static function getUserByUsername($userName)
 {
     $userName = \Core\Db::escape($userName);
     return \Core\Db::execute("SELECT * FROM `user` WHERE `username`='{$userName}';");
 }
Exemple #23
0
 protected function loginAction($options = array())
 {
     // Default option value
     // passwordEncrypt = true
     $options["passwordEncrypt"] = isset($options["passwordEncrypt"]) ? $options["passwordEncrypt"] : true;
     // force l'envoi de la clé
     $this->testKey(true);
     if (empty($_REQUEST->login) || empty($_REQUEST->password)) {
         throw new \Core\CException("Login failed");
     }
     $db = \Core\Db::create($this->getParams("database"));
     $userTable = $db->quoteTable($this->getParams("userTable", "table"));
     $idField = $db->quoteField($this->getParams("userTable", "idField"));
     $loginField = $db->quoteField($this->getParams("userTable", "loginField"));
     $passwordField = $db->quoteField($this->getParams("userTable", "passwordField"));
     $passwordFn = $this->getParams("userTable", "passwordFn");
     $nameField = $db->quoteField($this->getParams("userTable", "nameField"));
     $roleTable = $db->quoteTable($this->getParams("roleTable", "table"));
     $roleId = $db->quoteField($this->getParams("roleTable", "idField"));
     $roleField = $db->quoteField($this->getParams("roleTable", "roleField"));
     $linkTable = $db->quoteTable($this->getParams("linkTable", "table"));
     $linkUser = $db->quoteField($this->getParams("linkTable", "userId"));
     $linkRole = $db->quoteField($this->getParams("linkTable", "roleId"));
     //if(! \Core\CString::isValidMd5($_REQUEST->password)) {
     if ($options["passwordEncrypt"] === true && !empty($passwordFn)) {
         $_REQUEST->password = call_user_func($passwordFn, $_REQUEST->password);
     }
     $randId = strtolower(\Core\CString::rand(5));
     $sql = "\n            SELECT\n                {$idField} as userid_{$randId},\n                {$loginField} as userlogin_{$randId},\n                {$nameField} as username_{$randId},\n                u.*\n            FROM\n                {$userTable} u\n            WHERE\n                u.{$loginField} = :user\n                AND u.{$passwordField} = :Login\n        ";
     $res = $db->selectRow($sql, array(":user" => $_REQUEST->login, ":Login" => $_REQUEST->password));
     if (!empty($res)) {
         \Core\Security::setUserId($res["userid_" . $randId]);
         \Core\Security::setUserLogin($res["userlogin_" . $randId]);
         \Core\Security::setUserName($res["username_" . $randId]);
         $resUser = $res;
         unset($resUser["userid_" . $randId]);
         unset($resUser["userlogin_" . $randId]);
         unset($resUser["username_" . $randId]);
         \Core\Security::setUser($resUser);
         // Reccup role
         $sql = "\n                SELECT \n                    r.{$roleField} as role\n                FROM\n                    {$roleTable} r\n               JOIN\n                    {$linkTable} l\n                        ON r.{$roleId} = l.{$linkRole}\n               JOIN\n                    {$userTable} u\n                        ON u.{$idField} = l.{$linkUser}\n               WHERE\n                    u.{$idField} = :userid\n            ";
         $resRole = $db->select($sql, array(":userid" => $res["userid_" . $randId]));
         if (!empty($resRole)) {
             foreach ($resRole as $role) {
                 \Core\Security::AddRole($role["role"]);
             }
         }
         // St cookie for Autologin
         if (isset($_REQUEST->autologin) && $_REQUEST->autologin == "1") {
             $c = array($_REQUEST->login, $_REQUEST->password);
             $c = serialize($c);
             $c = \Core\CString::encrypt($c, $this->cookieName);
             setcookie($this->cookieName, $c, time() + $this->cookieTime, "/");
         }
     } else {
         $this->logout(new \Core\Request());
         throw new \Core\CException("Login failed");
     }
 }
 public static function getNextThread()
 {
     $sql = "SELECT MAX(thread_id) FROM message;";
     $res = \Core\Db::execute($sql);
     return isset($res[0]['MAX(thread_id)']) ? $res[0]['MAX(thread_id)'] + 1 : null;
 }
<?php

session_start();
require_once "Core/App.php";
use Core\Db;
use Config\DbConfig;
use Core\App;
spl_autoload_register(function ($class) {
    $classPath = str_replace('\\', '/', $class);
    require_once $classPath . '.php';
});
Db::SetInstance(DbConfig::DB_INSTANCE, DbConfig::DB_DRIVER, DbConfig::DB_USER, DbConfig::DB_PASS, DbConfig::DB_NAME, DbConfig::DB_HOST);
$app = new App(Db::getInstance(DbConfig::DB_INSTANCE));
function loadTemplate($templateName, $data = null)
{
    require_once 'Templates/' . $templateName . '.php';
}
 function __construct()
 {
     $dataBase = new Db();
     $this->db = $dataBase->connect();
 }
 public function run()
 {
     \Core\Db::dbClose();
 }
 /**
  * Remove a pet from a user's PetBasket
  * @param mixed $userId
  * @param mixed $petId
  * @return type
  */
 public static function remove($userId, $petId)
 {
     $userId = \Core\Db::escape($userId);
     $petId = \Core\Db::escape($petId);
     $sql = "DELETE FROM `basket` WHERE `user_id`='user:{$userId}' AND `pet_id`='pet:{$petId}';";
     return \Core\Db::execute($sql);
 }