Example #1
20
 /**
  * Quote a value for use in a query.
  * @param  $value
  * @return string
  */
 public function quote($value)
 {
     if (is_array($value)) {
         $result = [];
         foreach ($value as $single) {
             $result[] = $this->quote($single);
         }
         return sprintf('(%s)', implode(', ', $result));
     } else {
         return $this->pdo->quote($value);
     }
 }
Example #2
0
 /**
  * Override the template-fetching-function of the Parser
  *
  * @global string $IP
  * @global string $wgTemplatePath
  * @global string $wgTemplateExtension
  * @global string $wgTemplatePrefix
  * @param Title $title
  * @return array
  */
 function fetchTemplateAndTitle($title)
 {
     #echo "\n--- Trying to find offline template: $title ---\n";
     global $wgTemplateDB, $wgTemplateFileID;
     $finalTitle = $title;
     $template_text = null;
     # $$$ need to fix later for all languages
     # We pad the title with '~' to force the database to import strings
     $title_orig = '~' . $wgTemplateFileID . '~' . strtolower($title);
     $db = new PDO('sqlite:' . $wgTemplateDB);
     $tl = $db->quote($title_orig);
     #echo "\n--- ($title_orig) --- \n";
     $result = $db->query("SELECT body FROM templates WHERE title = {$tl} LIMIT 1");
     $data = $result->fetchAll();
     $max_loop_count = 25;
     while ($max_loop_count && sizeof($data) == 0) {
         $result = $db->query("SELECT redirect FROM redirects WHERE title = {$tl} LIMIT 1");
         $data = $result->fetchAll();
         if (sizeof($data) == 0) {
             break;
         }
         $redirect = $db->quote($data[0]['redirect']);
         $result = $db->query("SELECT body FROM templates WHERE title = {$redirect} LIMIT 1");
         $data = $result->fetchAll();
         --$max_loop_count;
     }
     if (sizeof($data) > 0) {
         $template_text = substr($data[0]['body'], 1);
         #echo "\n--- TT:($template_text):TT --- \n";
     } else {
         $template_text = '';
     }
     $ret = array($template_text, $finalTitle);
     return $ret;
 }
Example #3
0
 public function quote($str)
 {
     if (!$this->link) {
         return false;
     }
     return $this->link->quote($str);
 }
Example #4
0
 /**
  * @param $field
  * @param $operator
  * @param $value
  * @return $this
  */
 public function where($field, $operator, $value)
 {
     $value = is_numeric($value) ? $value : $this->pdo->quote($value);
     if (in_array($operator, $this->operators)) {
         $this->whereAnd[] = "`{$field}` {$operator} {$value}";
         return $this;
     }
     die(sprintf('unsupported operator %s', $operator));
 }
Example #5
0
function generate_insert_query($line, $places, $table, PDO $db, $v_ids)
{
    global $salt;
    foreach ($places as $field => $place) {
        $fields[] = $field;
        if ($field == 'password') {
            $values[] = $db->quote(md5($salt . $line[$place]));
        } else {
            $values[] = $db->quote($line[$place]);
        }
    }
    $username = $line[$places['username']];
    switch ($table) {
        case 'v_users':
            if (empty($username) || $username == 'NULL') {
                return false;
            }
            // we'll assume that every user should be able to login
            if (!in_array('password', $fields)) {
                $fields[] = 'password';
                $values[] = $db->quote(md5($salt . $username));
            }
            break;
        case 'v_extensions':
            $ext = $line[$places['extension']];
            if (empty($ext) || $ext == 'NULL') {
                return false;
            }
            // let's also assume every extension should also have a vm pin
            if (!in_array('vm_password', $fields)) {
                $fields[] = 'vm_password';
                $values[] = $db->quote($ext);
            }
            /* if we have a username but no user_list,
             * let's assume we want the extension tied to the current user
             */
            if (!in_array('user_list', $fields) && $username) {
                $fields[] = 'user_list';
                $values[] = $db->quote(sprintf('|%s|', $username));
            }
            $idx = array_search('username', $fields);
            unset($fields[$idx]);
            unset($values[$idx]);
            break;
        default:
            break;
    }
    if (!in_array('v_id')) {
        //print "v_id not found, adding one for localhost<br>\n";
        //printf('<pre>%s</pre>', print_r($v_ids, true));
        $fields[] = 'v_id';
        $values[] = $v_ids['localhost'];
    }
    $query = sprintf('INSERT INTO %s (%s) VALUES (%s);', $table, join(', ', $fields), join(', ', $values));
    return $query;
}
Example #6
0
 public function authenticate($login, $password)
 {
     $query = "\n\t\t\tSELECT  *\n\t\t\tFROM\t`user`\n\t\t\tWHERE\t`user_login` = " . $this->_oDbAdapter->quote($login) . "\n\t\t\t\tAND `user_password` = " . $this->_oDbAdapter->quote(sha1($password)) . "\n\t\t";
     $mResult = $this->_oDbAdapter->query($query)->fetch();
     if ($mResult) {
         trigger_error('User #' . $mResult->user_id . ' authenticated', E_USER_NOTICE);
         $this->setIdentity($mResult);
         return true;
     }
     trigger_error('Could not authenticate user `' . $login . '` authenticated', E_USER_NOTICE);
     return false;
 }
Example #7
0
 /**
  * Экранирует значение
  * @param  string|array $value
  * @param  int          $type
  * @return string
  */
 public function quote($value, $type = \PDO::PARAM_STR)
 {
     if (is_array($value)) {
         foreach ($value as $key => $val) {
             $value[$key] = $this->db->quote($val, $type);
         }
         $quoted_value = implode(', ', $value);
     } else {
         $quoted_value = $this->db->quote($value, $type);
     }
     return $quoted_value;
 }
Example #8
0
 function quote($Param)
 {
     $args = func_get_args();
     if (count($args) > 1) {
         foreach ($args as &$arg) {
             if ($x = $this->DB->quote($arg)) {
                 $arg = $x;
             }
         }
     } else {
         return $this->DB->quote($args[0]);
     }
 }
Example #9
0
function news_add($catid, $title, $text)
{
    try {
        $db = new PDO("sqlite:D:\\OpenServer\\domains\\test.git\\news.db");
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $title = $db->quote($title);
        $text = $db->quote($text);
        $time = time();
        $sql = "INSERT INTO news(catid,title,text,time) VALUES({$catid},{$title},{$text},{$time})";
        $db->exec($sql);
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
    $db = null;
}
Example #10
0
 /**
  * 备份数据库
  * @param string|array $table 表名或表名数组,为空时备份所有表
  * @return bool
  */
 public function backup($table = null)
 {
     $tables = empty($table) ? $this->getTables() : (is_array($table) ? $table : array($table));
     $filePre = $this->dataDir . '/' . date('Ymd', time());
     $tablesStructure = '';
     $i = 0;
     $dataTemp = array();
     $dataHead = '';
     $backupData = '';
     $file = '';
     foreach ($tables as $table) {
         $tablesStructure .= '------------------------------------------' . PHP_EOL . '-- 表名:' . $table . PHP_EOL . '--------' . PHP_EOL . 'DROP TABLE IF EXISTS ' . $table . ';' . PHP_EOL;
         $createtable = $this->query('SHOW CREATE TABLE ' . $table)->fetchAll();
         $createtable = end($createtable[0]);
         $createtable = preg_replace('/AUTO_INCREMENT=\\d*/i', 'AUTO_INCREMENT=0', $createtable);
         $tablesStructure .= $createtable . ';' . PHP_EOL;
         $data = $this->query('SELECT * FROM ' . $table)->fetchAll();
         $dataHead = 'INSERT INTO ' . $table . ' VALUES' . PHP_EOL;
         foreach ($data as $rowIndex => $row) {
             foreach ($row as $colKey => $colValue) {
                 $row[$colKey] = $this->db->quote($colValue);
             }
             $dataTemp[] = '(' . implode(', ', $row) . ')';
             $data[$rowIndex] = '';
             if ($i < 200) {
                 $i++;
             } else {
                 $backupData .= $dataHead . implode(',' . PHP_EOL, $dataTemp) . ';' . PHP_EOL;
                 $dataTemp = array();
                 $i = 0;
             }
         }
         if (!empty($dataTemp)) {
             $backupData .= $dataHead . implode(',' . PHP_EOL, $dataTemp) . ';' . PHP_EOL;
         }
         $file = $filePre . '/' . $table . $this->dataFix;
         dir_check(dirname($file));
         file_put_contents($file, $backupData, LOCK_EX);
         $i = 0;
         $dataTemp = array();
         $dataHead = null;
         $backupData = '';
     }
     $file = $filePre . '/' . $this->structureFile;
     dir_check(dirname($file));
     file_put_contents($file, $tablesStructure, LOCK_EX);
     return true;
 }
 /** @return string */
 public function Quote($string)
 {
     if (!$this->connected) {
         $this->Connect();
     }
     return $this->Conn->quote($string);
 }
Example #12
0
 function quote($str, $parameter_type = PDO::PARAM_STR)
 {
     if ($str === null) {
         return 'NULL';
     }
     return parent::quote($str, $parameter_type);
 }
Example #13
0
 public function quote($string, $parameterType = null)
 {
     if (!$this->pdo) {
         $this->connect();
     }
     return $this->pdo->quote($string, $parameterType);
 }
Example #14
0
 /**
  * Quotes a value for insertion into a query.
  *
  * @param mixed $value
  * @return string
  */
 function transform($value)
 {
     if (strlen($value) == 0) {
         return 'NULL';
     }
     return $this->pdo->quote($value);
 }
Example #15
0
 /**
  * 用引号引用内容
  *
  * @param mixed $value to quote
  * @return string
  */
 public function quote($value)
 {
     if (!$this->pdo) {
         $this->connect();
     }
     return $this->pdo->quote($value);
 }
Example #16
0
 /**
  * Allow a value to be escaped
  *
  * @param $str
  * @return string
  */
 function escape($str)
 {
     if (!$this->isConnected()) {
         $this->connect();
     }
     return $this->unquote_outer($this->pdo->quote((string) $str));
 }
Example #17
0
 public function getRecent($tp)
 {
     $db = new PDO('mysql:host=localhost;dbname=saddahaq_facebook_apps', 'root', 'vivenfarms');
     $tmp = $db->query("SELECT _ID_ id FROM table_free_basics_saddahaq WHERE _Typ_ = " . $db->quote($tp) . " ORDER BY _Tme_ DESC LIMIT 0,42");
     $res = $tmp->fetchAll(PDO::FETCH_ASSOC);
     return $res[0];
 }
Example #18
0
 /**
  * Prepara valor segun tipo especificado.
  *
  * @param mixed $valor Valor a preparar
  * @param string $tipo Tipo de valor pasado: bol, txt, num, def
  * @param bool $permiteVacio Define si permite cadena de texto vacio en vez de nulo
  *
  * @return string Retorna valor escapado para MySQL
  */
 public function prepararValor($valor, $tipo = 'txt', $permiteVacio = false)
 {
     if (is_array($valor)) {
         if (empty($valor)) {
             return 'NULL';
         }
         foreach ($valor as $llave => $v) {
             $valor[$llave] = $this->prepararValor($v, $tipo);
         }
         return $valor;
     }
     // Retornamos valor boleano según el tipo
     if ($tipo == 'bol' || $tipo == 'bool') {
         return $valor ? '1' : '0';
     }
     // Detectamos y retornamos valor nulo
     if ($valor === null || $valor === false) {
         return 'NULL';
     }
     if (!$permiteVacio && $valor === '') {
         return 'NULL';
     }
     // Retornamos valor numerico según el tipo
     if ($tipo == 'num' || $tipo == 'int') {
         if ($valor === '') {
             return 'NULL';
         }
         return strval(floatval($valor));
     }
     // Retornamos valor textual como valor predeterminado
     return $this->pdo->quote($valor);
 }
Example #19
0
 /**
  * @param string $str
  * @return string
  */
 public static function esc($str)
 {
     if (!_db::connected()) {
         _db::reconnect();
     }
     return _db::$con->quote($str);
 }
 /**
  * Helper function to generate the SQL for a given entity field
  * @param string $name the name of the field to generate SQL for
  * @param array $spec the entity spec array for the field
  * @param boolean $alias whether to also generate an "AS" alias for the field - defaults to false
  * @param string|null $func the function to call against the field (count, avg, sum, max, min)
  * @param array|null $pivot if there was a pivot for this query, this should be an array of values that uniquely identify this field
  * @param array|null $pivot_fields if there was a pivot for this query, this should be an array of the specs for the pivoted fields
  * @return string the SQL string for this field, with an op
  */
 protected function getFieldSQL($name, $spec, $alias = false, $func = null, $pivot = null, $pivot_fields = null)
 {
     $sql = $spec['field'];
     $q = $this->getFieldQuote();
     if ($func !== null) {
         if ($pivot === null) {
             $sql = strtoupper($func) . '(' . $sql . ')';
             if ($alias) {
                 $sql .= ' AS ' . $q . $func . '-' . $name . $q;
             }
         } else {
             $casewhen = array();
             foreach ($pivot as $key => $val) {
                 $pivot_field = $pivot_fields[$key];
                 $casewhen[] = $pivot_field['field'] . '=' . $this->db->quote($val);
             }
             $sql = strtoupper($func) . '(CASE WHEN ' . implode(' AND ', $casewhen) . ' THEN ' . $sql . ' ELSE NULL END)';
             if ($alias) {
                 $sql .= ' AS ' . $q . implode(',', $pivot) . ' ' . $func . '-' . $name . $q;
             }
         }
     } elseif ($alias) {
         $sql .= ' AS ' . $name;
     }
     return $sql;
 }
Example #21
0
 /**
  * Quote Trusted Value
  *
  * The ability to quote values without notices
  *
  * @param $value
  * @return mixed
  */
 public function quoteTrustedValue($value)
 {
     if ($this->resource instanceof \PDO) {
         return $this->resource->quote($value);
     }
     return '\'' . addcslashes($value, "\n\r\\'\"") . '\'';
 }
 public function quote($value, $type = null)
 {
     if (is_array($value) || is_object($value)) {
         return "''";
     }
     return parent::quote($value, $type ? $type : $this->_getPdoDataType(gettype($value)));
 }
 /**
  * Returns the quoted version of the specified value.
  *
  * Do not use this function to quote data in a query, use the bound parameters instead. {@see self::query()}
  *
  * @param mixed $value   The value to quote.
  *
  * @return string   The quoted value.
  *
  * @throws DatabaseException   If no database connection is established.
  */
 public function quote($value)
 {
     if (empty($this->connection)) {
         throw new DatabaseException('Connection to the database is not established');
     }
     return $this->connection->quote($value, $this->getParamType($value));
 }
Example #24
0
 public function selectDB($dbname)
 {
     if ($this->conn->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
         return $this->conn->exec("use " . PDO::quote($dbname));
     }
     return false;
 }
Example #25
0
 /**
  * Escapes SQL string
  *
  * @param string $string
  * @return string
  */
 public function escapeString($string)
 {
     $quotedString = $this->connection->quote($string);
     // real_escape_string( $string );
     return mb_substr($quotedString, 1, mb_strlen($quotedString) - 2);
     //dirty hack to delete quotes
 }
Example #26
0
 /**
  * Executes the generated query.
  * @return boolean Was query successfull or not.
  */
 public function execute()
 {
     $this->queryStr = $this->buildQuery();
     // Connect and execute
     $this->connect();
     if ($this->prepared && $this->tokenCount > 0) {
         // Prepare tokenised values.
         $this->sth = $this->dbh->prepare($this->queryStr);
         foreach ($this->tokens as $token) {
             $this->sth->bindParam($token['token'], $token['value']);
         }
         if (!$this->sth->execute()) {
             $this->reset();
             return false;
         }
     } else {
         foreach ($this->tokens as $token) {
             $this->queryStr = str_replace($token['token'], $this->dbh->quote($token['value']), $this->queryStr);
         }
         $this->sth = $this->dbh->query($this->queryStr);
         if ($this->sth === false) {
             $this->reset();
             return false;
         }
         $this->dbh->errorInfo();
     }
     $this->lastQuery = $this->queryStr;
     $this->reset();
     return true;
 }
Example #27
0
 /**
  * @param string $string
  * @return string
  */
 public function quoteString($string)
 {
     if (!$this->_dbHandler) {
         $this->connect();
     }
     return $this->_dbHandler->quote($string);
 }
Example #28
0
 /**
  * Quote Trusted Value
  *
  * The ability to quote values without notices
  *
  * @param $value
  * @return mixed
  */
 public function quoteTrustedValue($value)
 {
     if ($this->resource instanceof \PDO) {
         return $this->resource->quote($value);
     }
     return '\'' . str_replace('\'', '\'\'', $value) . '\'';
 }
Example #29
-1
 private function buildInsertQuery($tablename, array $fields)
 {
     $columns = $values = array();
     foreach ($fields as $field => $value) {
         $columns[] = $field;
         $values[] = $this->db->quote($value);
     }
     $columns = implode(',', $columns);
     $values = implode(',', $values);
     return "INSERT INTO {$tablename} ({$columns}) VALUES ({$values})";
 }
Example #30
-1
 /**
  * Write a message to the log
  *
  * @param array $messages
  * @throws \RuntimeException
  */
 public function write(array $messages)
 {
     $stmt = $this->dbh->prepare("INSERT INTO " . $this->dbh->quote($this->tableName) . " (level, level_name, message, creation_time)" . " VALUES (:level, :level_name, :message, :creation_time)");
     foreach ($messages as $record) {
         list($datetime, $level, $levelCode, $message) = $record;
         $stmt->bindParam(':creation_time', $datetime->getTimestamp(), \PDO::PARAM_INT);
         $stmt->bindParam(':level', $levelCode, \PDO::PARAM_INT);
         $stmt->bindParam(':level_name', $level, \PDO::PARAM_STR);
         $stmt->bindParam(':message', $message, \PDO::PARAM_STR);
         $stmt->execute();
     }
 }