/** * see crypt::decrypt(); */ public function decrypt($data) { $this->send_key_to_db(); $db = new db($this->db_link); $result = $db->query("SELECT sm.decrypt('" . pg_escape_bytea($data) . "') AS decrypted;"); return $result['rows'][0]['decrypted'] ?? false; }
protected function GetBlobFieldValueAsSQL($value) { if (is_array($value)) { return '\'' . pg_escape_bytea(file_get_contents($value[0])) . '\''; } else { return '\'' . pg_escape_bytea($value) . '\''; } }
function binary_sql($bin) { if (DB::connection() instanceof \Illuminate\Database\PostgresConnection) { $bin = pg_escape_bytea($bin); $bin = str_replace("''", "'", $bin); } return $bin; }
/** * * @param mixed $blob Blob object or string containing data. * @return string */ protected function getBlobSql($blob) { // they took magic __toString() out of PHP5.0.0; this sucks if (is_object($blob)) { $blob = $blob->__toString(); } return "'" . pg_escape_bytea($blob) . "'"; }
function _quote($s) { if (USE_BYTEA) { return pg_escape_bytea($s); } else { // pg_escape_string() is broken return base64_encode($s); } }
/** * @param String str * @return String */ public function addSlashesBinary($str) { if ($this->postgreDbVersion < 9) { return "'" . pg_escape_bytea($str) . "'"; } if (!strlen($str)) { return "''"; } return "E'\\\\x" . bin2hex($str) . "'"; }
public function AddRegistro($datos) { extract($datos); $data = file_get_contents('imagenes/' . $imagen); $image = pg_escape_bytea($data); $sql = "INSERT INTO imagen(nombre, rutaim, imagen, tipoim, tamima, idimag) VALUES ('{$nombre}', '{$ruta}', '{$image}', '{$tipo}', '{$taman}',{$idimagen})"; pg_query($conn, $sql); pg_close($conn); return true; }
/** * @since 1.8 * * {@inheritDoc} */ public function getInsertValues(DataItem $dataItem) { $serialization = rawurldecode($dataItem->getSerialization()); $text = mb_strlen($serialization) <= self::MAX_LENGTH ? null : $serialization; // bytea type handling if ($text !== null && $GLOBALS['wgDBtype'] === 'postgres') { $text = pg_escape_bytea($text); } return array('o_blob' => $text, 'o_serialized' => $serialization); }
function _quote($s) { if (USE_BYTEA) { return pg_escape_bytea($s); } if (function_exists('pg_escape_string')) { return pg_escape_string($s); } else { return base64_encode($s); } }
function db_addslashesbinary($str) { global $postgreDbVersion; if( $postgreDbVersion < 9 ) return "'".pg_escape_bytea($str)."'"; if(!strlen($str)) return "''"; return "E'\\\\x".bin2hex($str)."'"; }
public function GetFieldValueAsSQL($fieldInfo, $value) { if ($fieldInfo->FieldType == ftBlob) { if (is_array($value)) { return '\'' . pg_escape_bytea(file_get_contents($value[0])) . '\''; } else { return '\'' . pg_escape_bytea($value) . '\''; } } else { return parent::GetFieldValueAsSQL($fieldInfo, $value); } }
public function quoteBinary($data) { $esc = pg_escape_bytea($this->getLink(), $data); if (mb_strpos($esc, '\\x') === 0) { // http://www.postgresql.org/docs/9.1/static/datatype-binary.html // if pg_escape_bytea use postgres 9.1+ it's return value like '\x00aabb' (new bytea hex format), // but must return '\\x00aabb'. So we use this fix:' return "E'\\" . $esc . "'"; } else { //if function escape value like '\\000\\123' - all ok return "E'" . $esc . "'"; } }
public function execute() { try { if (request::getInstance()->isMethod('POST')) { $ruta = configClass::getUrlBase() . 'objeto'; $foto = $_FILES[datosUsuarioTableClass::getNameField(datosUsuarioTableClass::FOTO, true)]['tmp_name']; $nombreArchivo = $_FILES[datosUsuarioTableClass::getNameField(datosUsuarioTableClass::FOTO, true)]['name']; move_uploaded_file($foto, $ruta . "/" . $nombreArchivo); $ruta = $ruta . "/" . $nombreArchivo; $dataImg = file_get_contents($foto); $img = pg_escape_bytea($dataImg); // echo $dataImg; // exit(); //usuario $id = request::getInstance()->getPost(usuarioTableClass::getNameField(usuarioTableClass::ID, true)); $usuario = request::getInstance()->getPost(usuarioTableClass::getNameField(usuarioTableClass::USER, true)); $password = request::getInstance()->getPost(usuarioTableClass::getNameField(usuarioTableClass::PASSWORD, true)); $recuperar = request::getInstance()->getPost(usuarioTableClass::getNameField(usuarioTableClass::RESTAURAR_ID, true)); $respuesta_secreta = request::getInstance()->getPost(usuarioTableClass::getNameField(usuarioTableClass::RESPUESTA_SECRETA, true)); $idUser = array(usuarioTableClass::ID => $id); $data = array(usuarioTableClass::USER => $usuario, usuarioTableClass::PASSWORD => md5($password), usuarioTableClass::RESTAURAR_ID => $recuperar, usuarioTableClass::RESPUESTA_SECRETA => $respuesta_secreta); usuarioTableClass::update($idUser, $data); $dataUser = array(usuarioTableClass::USER => $usuario, usuarioTableClass::PASSWORD => md5($password), usuarioTableClass::RESTAURAR_ID => $recuperar, usuarioTableClass::RESPUESTA_SECRETA => $respuesta_secreta); //datos usuario $nombre = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::NOMBRE, true)); $apellidos = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::APELLIDOS, true)); $tipoDocumento = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::TIPO_DOC, true)); $numeroDocumento = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::NUMERO_DOCUMENTO, true)); $direccion = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::DIRECCION, true)); $idCiudad = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::CIUDAD_ID, true)); $telefono = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::TELEFONO, true)); $correo = request::getInstance()->getPost(datosUsuarioTableClass::getNameField(datosUsuarioTableClass::CORREO, true)); $datosUsuario = array(datosUsuarioTableClass::NOMBRE => $nombre, datosUsuarioTableClass::APELLIDOS => $apellidos, datosUsuarioTableClass::TIPO_DOC => $tipoDocumento, datosUsuarioTableClass::NUMERO_DOCUMENTO => $numeroDocumento, datosUsuarioTableClass::DIRECCION => $direccion, datosUsuarioTableClass::CIUDAD_ID => $idCiudad, datosUsuarioTableClass::TELEFONO => $telefono, datosUsuarioTableClass::CORREO => $correo); $idData = array(datosUsuarioTableClass::USUARIO_ID => $id); // usuarioTableClass::validatUpdate($usuario, $password); datosUsuarioTableClass::update($idData, $datosUsuario); usuarioTableClass::update($idUser, $dataUser); session::getInstance()->setSuccess(i18n::__('succesUpdate', null, 'default')); log::register(i18n::__('update'), usuarioTableClass::getNameTable()); routing::getInstance()->redirect('usuario', 'indexUsuario'); } else { log::register(i18n::__('update'), usuarioTableClass::getNameTable(), i18n::__('errorUpdateBitacora')); session::getInstance()->setError(i18n::__('errorUpdate', null, 'default')); routing::getInstance()->redirect('usuario', 'indexUsuario'); } } catch (PDOException $exc) { session::getInstance()->setFlash('exc', $exc); routing::getInstance()->forward('shfSecurity', 'exception'); } }
public function esc($data, $mode = self::STRING) { switch ($mode) { case "literal": $data = pg_escape_literal($this->connection, $data); break; case "bytea": $data = pg_escape_bytea($this->connection, $data); break; default: $data = pg_escape_string($this->connection, $data); break; } return $data; }
function test_postgis($name, $type, $geom, $connection, $format) { global $table; // Let's insert into the database using GeomFromWKB $insert_string = pg_escape_bytea($geom->out($format)); pg_query($connection, "INSERT INTO {$table} (name, type, geom) values ('{$name}', '{$type}', GeomFromWKB('{$insert_string}'))"); // SELECT using asBinary PostGIS $result = pg_fetch_all(pg_query($connection, "SELECT asBinary(geom) as geom FROM {$table} WHERE name='{$name}'")); foreach ($result as $item) { $wkb = pg_unescape_bytea($item['geom']); // Make sure to unescape the hex blob $geom = geoPHP::load($wkb, $format); // We now a full geoPHP Geometry object } // SELECT and INSERT directly, with no wrapping functions $result = pg_fetch_all(pg_query($connection, "SELECT geom as geom FROM {$table} WHERE name='{$name}'")); foreach ($result as $item) { $wkb = pack('H*', $item['geom']); // Unpacking the hex blob $geom = geoPHP::load($wkb, $format); // We now have a geoPHP Geometry // Let's re-insert directly into postGIS // We need to unpack the WKB $unpacked = unpack('H*', $geom->out($format)); $insert_string = $unpacked[1]; pg_query($connection, "INSERT INTO {$table} (name, type, geom) values ('{$name}', '{$type}', '{$insert_string}')"); } // SELECT and INSERT using as EWKT (ST_GeomFromEWKT and ST_AsEWKT) $result = pg_fetch_all(pg_query($connection, "SELECT ST_AsEWKT(geom) as geom FROM {$table} WHERE name='{$name}'")); foreach ($result as $item) { $wkt = $item['geom']; // Make sure to unescape the hex blob $geom = geoPHP::load($wkt, 'ewkt'); // We now a full geoPHP Geometry object // Let's re-insert directly into postGIS $insert_string = $geom->out('ewkt'); pg_query($connection, "INSERT INTO {$table} (name, type, geom) values ('{$name}', '{$type}', ST_GeomFromEWKT('{$insert_string}'))"); } }
public function Inserta() { session_start(); $especies = new EspeciesModel(); $directorio = $_SERVER['DOCUMENT_ROOT'] . '/uploads/'; if (isset($_POST["nombre_especies"])) { $_nombre_especies = strtoupper($_POST["nombre_especies"]); $nombre = $_FILES['logo_especies']['name']; $tipo = $_FILES['logo_especies']['type']; $tamano = $_FILES['logo_especies']['size']; // temporal al directorio definitivo move_uploaded_file($_FILES['logo_especies']['tmp_name'], $directorio . $nombre); $data = file_get_contents($directorio . $nombre); $logo_especies = pg_escape_bytea($data); $funcion = "ins_especies"; $parametros = " '{$_nombre_especies}' ,'{$logo_especies}' "; $especies->setFuncion($funcion); $especies->setParametros($parametros); $resultado = $especies->Insert(); $this->redirect("Especies", "index"); } }
public function geometryToDatabaseValue(\Geometry $value = null) { return $value === null ? null : pg_escape_bytea($value->out('ewkt')); }
/** * Format value to it can be used in sql query * * Type of value is one of: * "n" - number (int or float) * "N" - number (int or float) - allow NULL values * "s" - string * "S" - string - allow NULL values * "b" - bool * "B" - bool - allow NULL values * "i" - image (binary data) * "I" - image (binary data) - allow NULL values * "t" - datetime * "T" - datetime - allow NULL values * * @param mixed $val * @param string $type * @return string */ function sql_format($val, $type) { switch ($type) { case "S": if (is_null($val)) { return "NULL"; } case "s": return "'" . addslashes($val) . "'"; case "N": if (is_null($val)) { return "NULL"; } case "n": return (int) $val; case "B": if (is_null($val)) { return "NULL"; } case "b": if ($this->db_host['parsed']['phptype'] == 'mysql') { return $val ? "1" : "0"; } else { return $val ? "true" : "false"; } case "I": if (is_null($val)) { return "NULL"; } case "i": if ($this->db_host['parsed']['phptype'] == 'pgsql') { return "'" . pg_escape_bytea($val) . "'::bytea"; } else { return "'" . $this->db->escapeSimple($val) . "'"; } case "T": if (is_null($val)) { return "NULL"; } case "t": return "'" . gmdate("Y-m-d H:i:s", $val) . "'"; default: return ""; } }
function encodeBlob($b) { return new Blob(pg_escape_bytea($b)); }
protected function _quote($text, $binary) { if ($binary) { return pg_escape_bytea($this->_connection, $text); } else { return pg_escape_string($this->_connection, $text); } }
/** * get the string to use in the SQL statement from a blob of binary data * ** Suppots only blob->postgres::bytea * * @param int $to Type (DB_DATAOBJECT_* * @param object $db DB Connection Object * * * @return string * @access public */ function toStringFromBlob($to, $db) { // first weed out invalid casts.. // in blobs can only be cast to blobs.! // perhaps we should support TEXT fields??? if (!($to & DB_DATAOBJECT_BLOB)) { return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::blob to something other than a blob!'); } switch ($db->dsn["phptype"]) { case 'pgsql': return "'" . pg_escape_bytea($this->value) . "'::bytea"; case 'mysql': return "'" . mysql_real_escape_string($this->value, $db->connection) . "'"; case 'mysqli': // this is funny - the parameter order is reversed ;) return "'" . mysqli_real_escape_string($db->connection, $this->value) . "'"; case 'sqlite': // this is funny - the parameter order is reversed ;) return "'" . sqlite_escape_string($this->value) . "'"; case 'mssql': if (is_numeric($this->value)) { return $this->value; } $unpacked = unpack('H*hex', $this->value); return '0x' . $unpacked['hex']; default: return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:{$db->dsn['phptype']} Yet"); } }
/** * Returns a quoted and escaped string of $data for use in an SQL statement. * * @param string $data String to be prepared for use in an SQL statement * @param string $column The column into which this data will be inserted * @param boolean $read Value to be used in READ or WRITE context * @return string Quoted and escaped * @todo Add logic that formats/escapes data based on column type */ function value($data, $column = null, $read = true) { $parent = parent::value($data, $column); if ($parent != null) { return $parent; } if ($data === null) { return 'NULL'; } if (empty($column)) { $column = $this->introspectType($data); } switch ($column) { case 'inet': case 'float': case 'integer': case 'date': case 'datetime': case 'timestamp': case 'time': if ($data === '') { return $read ? 'NULL' : 'DEFAULT'; } case 'binary': $data = pg_escape_bytea($data); break; case 'boolean': if ($data === true || $data === 't' || $data === 'true') { return 'TRUE'; } elseif ($data === false || $data === 'f' || $data === 'false') { return 'FALSE'; } return !empty($data) ? 'TRUE' : 'FALSE'; break; default: $data = pg_escape_string($data); break; } return "'" . $data . "'"; }
function Backup($uiFilename = NULL) { if (!$this->Connected) { return false; } if (is_null($uiFilename)) { $this->Filename = $this->Database . ".sql"; } else { $this->Filename = $uiFilename; } // Fix incompatible flags $this->_FixOptions(); //---[ PASS 1: Opening SQL File for writing $this->fpSQL = @fopen($this->Filename, "w"); if (!$this->fpSQL) { $this->Error("Can't open " . $this->Filename . " for writing!", true); } // Writes header to file if string Header is not empty if (!empty($this->Header)) { $this->writeSQL($this->Header . "\n"); } //---[ PASS 1.1: Set default options $this->commentSQL("Default options\n"); $this->writeSQL("SET client_encoding = '{$this->Encoding}';\n"); $this->writeSQL("SET standard_conforming_strings = off;\n"); $this->writeSQL("SET check_function_bodies = false;\n"); $this->writeSQL("SET client_min_messages = warning;\n"); $this->writeSQL("SET escape_string_warning = off;\n"); $this->writeSQL("\n"); //---[ PASS 2: Obtaining table list from database // If the tables array is not empy, it means that // the method $this->BackupOnlyTables was used if (empty($this->Tables)) { $SQL = "SELECT relname AS tablename\n" . "FROM pg_class WHERE relkind IN ('r')\n" . "AND relname NOT LIKE 'pg_%' AND relname NOT LIKE 'sql_%' ORDER BY tablename\n"; $this->query($SQL); // Checks if the current table is in the exclude array. while ($this->next_record()) { $Table = $this->get("tablename"); if (!in_array($Table, $this->ExcludeTables)) { $this->Tables[] = $this->escape_keyword($Table); } } } //---[ PASS 3: Generating structure for each table foreach ($this->Tables as $Table) { // Use DROP TABLE statement before INSERT ? if ($this->UseDropTable) { $this->writeSQL("DROP TABLE IF EXISTS {$Table} CASCADE;\n"); } elseif ($this->UseTruncateTable) { $this->writeSQL("TRUNCATE TABLE {$Table};\n"); } if (!$this->DataOnly) { $_sequences = array(); $this->commentSQL("Structure for table '{$Table}'\n"); $strSQL .= "CREATE TABLE {$Table} ("; $SQL = "SELECT attnum, attname, typname, atttypmod-4 AS atttypmod, attnotnull, atthasdef, adsrc AS def\n" . "FROM pg_attribute, pg_class, pg_type, pg_attrdef\n" . "WHERE pg_class.oid=attrelid\n" . "AND pg_type.oid=atttypid AND attnum>0 AND pg_class.oid=adrelid AND adnum=attnum\n" . "AND atthasdef='t' AND lower(relname)='{$Table}' UNION\n" . "SELECT attnum, attname, typname, atttypmod-4 AS atttypmod, attnotnull, atthasdef, '' AS def\n" . "FROM pg_attribute, pg_class, pg_type WHERE pg_class.oid=attrelid\n" . "AND pg_type.oid=atttypid AND attnum>0 AND atthasdef='f' AND lower(relname)='{$Table}'\n"; $this->query($SQL); while ($this->next_record()) { $_attnum = $this->get('attnum'); $_attname = $this->escape_keyword($this->get('attname')); $_typname = $this->get('typname'); $_atttypmod = $this->get('atttypmod'); $_attnotnull = $this->get('attnotnull'); $_atthasdef = $this->get('atthasdef'); $_def = $this->get('def'); if (preg_match("/^nextval/", $_def)) { $_t = explode("'", $_def); $_sequences[] = $_t[1]; } $strSQL .= "{$_attname} {$_typname}"; if ($_typname == "varchar") { $strSQL .= "({$_atttypmod})"; } if ($_attnotnull == "t") { $strSQL .= " NOT NULL"; } if ($_atthasdef == "t") { $strSQL .= " DEFAULT {$_def}"; } $strSQL .= ","; } $strSQL = rtrim($strSQL, ","); $strSQL .= ");\n"; //--[ PASS 3.1: Creating sequences if ($_sequences) { foreach ($_sequences as $_seq_name) { $SQL = "SELECT * FROM {$_seq_name}\n"; $this->query($SQL); $this->next_record(); $_incrementby = $this->get('increment_by'); $_minvalue = $this->get('min_value'); $_maxvalue = $this->get('max_value'); $_lastvalue = $this->get('last_value'); $_cachevalue = $this->get('cache_value'); $this->writeSQL("CREATE SEQUENCE {$_seq_name} INCREMENT {$_incrementby} MINVALUE {$_minvalue} " . "MAXVALUE {$_maxvalue} START {$_lastvalue} CACHE {$_cachevalue};\n"); } } $this->writeSQL($strSQL); } if (!$this->StructureOnly || $this->DataOnly) { $field_attribs = array(); //---[ PASS 4: Generating INSERTs for data $this->commentSQL("Data for table '{$Table}'\n"); //---[ PASS 4.1: Get field attributes to check if it's null or bytea (to be escaped) $SQL = "SELECT * FROM {$Table} LIMIT 0;\n"; $this->query($SQL); $fields = $this->field_names(); foreach ($fields as $Field) { $field_attribs[$Field] = $this->GetFieldInfo($Table, $Field); } //---| END PASS 4.1 $SQL = "SELECT * FROM {$Table}\n"; $this->query($SQL); while ($this->next_record()) { $Record = array(); foreach ($fields as $f) { $data = $this->get($f); if ($field_attribs[$f]['is_binary']) { // Binary Data $Record[$f] = addcslashes(pg_escape_bytea($data), "\$"); } else { // Strings $data = preg_replace("/\n/", "", $data); $data = preg_replace("/\r/", "\r", $data); $Record[$f] = pg_escape_string(trim($data)); } } $FieldNames = $this->UseCompleteInsert ? "(" . implode(",", $fields) . ")" : ""; $strSQL = "INSERT INTO {$Table}{$FieldNames} VALUES({" . implode("},{", $fields) . "});"; foreach ($fields as $f) { if ($Record[$f] != '') { $str = sprintf("'%s'", $Record[$f]); } else { $str = $field_attribs[$f]['not_null'] ? "''" : "NULL"; } $strSQL = preg_replace("/{" . $f . "}/", $str, $strSQL); } $this->writeSQL($strSQL . "\n"); unset($strSQL); } } if (!$this->DataOnly) { //---[ PASS 5: Generating data indexes (Primary) $this->commentSQL("Indexes for table '{$Table}'\n"); $SQL = "SELECT pg_index.indisprimary, pg_catalog.pg_get_indexdef(pg_index.indexrelid)\n" . "FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index AS pg_index\n" . "WHERE c.relname = '{$Table}'\n" . "AND c.oid = pg_index.indrelid\n" . "AND pg_index.indexrelid = c2.oid\n"; $this->query($SQL); while ($this->next_record()) { $_pggetindexdef = $this->get('pg_get_indexdef'); $_indisprimary = $this->get('indisprimary'); if (eregi("^CREATE UNIQUE INDEX", $_pggetindexdef)) { $_keyword = $_indisprimary == 't' ? 'PRIMARY KEY' : 'UNIQUE'; $strSQL = str_replace("CREATE UNIQUE INDEX", "", $this->get('pg_get_indexdef')); $strSQL = str_replace("USING btree", "|", $strSQL); $strSQL = str_replace("ON", "|", $strSQL); $strSQL = str_replace(" ", "", $strSQL); list($_pkey, $_tablename, $_fieldname) = explode("|", $strSQL); $this->writeSQL("ALTER TABLE ONLY {$_tablename} ADD CONSTRAINT {$_pkey} {$_keyword} {$_fieldname};\n"); unset($strSQL); } else { $this->writeSQL("{$_pggetindexdef};\n"); } } //---[ PASS 6: Generating relationships $this->commentSQL("Relationships for table '{$Table}'\n"); $SQL = "SELECT cl.relname AS table, ct.conname, pg_get_constraintdef(ct.oid)\n" . "FROM pg_catalog.pg_attribute a\n" . "JOIN pg_catalog.pg_class cl ON (a.attrelid = cl.oid AND cl.relkind = 'r')\n" . "JOIN pg_catalog.pg_namespace n ON (n.oid = cl.relnamespace)\n" . "JOIN pg_catalog.pg_constraint ct ON (a.attrelid = ct.conrelid AND ct.confrelid != 0 AND ct.conkey[1] = a.attnum)\n" . "JOIN pg_catalog.pg_class clf ON (ct.confrelid = clf.oid AND clf.relkind = 'r')\n" . "JOIN pg_catalog.pg_namespace nf ON (nf.oid = clf.relnamespace)\n" . "JOIN pg_catalog.pg_attribute af ON (af.attrelid = ct.confrelid AND af.attnum = ct.confkey[1]) order by cl.relname\n"; $this->query($SQL); while ($this->next_record()) { $_table = $this->get('table'); $_conname = $this->get('conname'); $_constraintdef = $this->get('pg_get_constraintdef'); $this->writeSQL("ALTER TABLE ONLY {$_table} ADD CONSTRAINT {$_conname} {$_constraintdef};\n"); } } } //---[ PASS 7: Closing SQL File fclose($this->fpSQL); return filesize($this->Filename) > 0 ? true : false; }
/** * Returns a cleaned-up binary string BLOG for storing in ByteA fields * * @param $string The string to clean up * @return The cleaned-up string */ function escapeBinaryString($string) { return pg_escape_bytea($string); }
/** * Escape a bytefield. Most databases consider these strings, so we'll try * handling it as a string by default. * * @param string $bf Bytefield to escape * @return string **/ public function escape_bytefield($bf) { return "E'" . pg_escape_bytea($this->dbh, (string) $string) . "'::bytea"; }
/** * @param $b * @return Blob */ function encodeBlob($b) { return new Blob(pg_escape_bytea($this->mConn, $b)); }
/** Update the content of the file */ function Update($buildid) { if (!is_numeric($buildid) || $buildid == 0) { return; } include "cdash/config.php"; // Compute the crc32 of the file (before compression for backward compatibility) $this->Crc32 = crc32($this->FullPath . $this->File); $this->FullPath = pdo_real_escape_string($this->FullPath); if ($CDASH_USE_COMPRESSION) { $file = gzcompress($this->File); if ($file === false) { $file = $this->File; } else { if ($CDASH_DB_TYPE == "pgsql") { if (strlen($this->File) < 2000) { $file = $this->File; } $file = pg_escape_bytea(base64_encode($file)); // hopefully does the escaping correctly } } } else { $file = $this->File; if ($CDASH_DB_TYPE == "pgsql") { $file = pg_escape_bytea($file); } } $file = pdo_real_escape_string($file); $coveragefile = pdo_query("SELECT id FROM coveragefile WHERE crc32=" . qnum($this->Crc32)); add_last_sql_error("CoverageFile:Update"); if (pdo_num_rows($coveragefile) > 0) { $coveragefile_array = pdo_fetch_array($coveragefile); $this->Id = $coveragefile_array["id"]; // Update the current coverage.fileid $coverage = pdo_query("SELECT c.fileid FROM coverage AS c,coveragefile AS cf \n WHERE c.fileid=cf.id AND c.buildid=" . qnum($buildid) . "\n AND cf.fullpath='{$this->FullPath}'"); $coverage_array = pdo_fetch_array($coverage); $prevfileid = $coverage_array["fileid"]; pdo_query("UPDATE coverage SET fileid=" . qnum($this->Id) . " WHERE buildid=" . qnum($buildid) . " AND fileid=" . qnum($prevfileid)); add_last_sql_error("CoverageFile:Update"); $row = pdo_single_row_query("SELECT COUNT(*) AS c FROM label2coveragefile WHERE buildid=" . qnum($buildid) . " AND coveragefileid=" . qnum($prevfileid)); if (isset($row['c']) && $row['c'] > 0) { pdo_query("UPDATE label2coveragefile SET coveragefileid=" . qnum($this->Id) . " WHERE buildid=" . qnum($buildid) . " AND coveragefileid=" . qnum($prevfileid)); add_last_sql_error("CoverageFile:Update"); } // Remove the file if the crc32 is NULL pdo_query("DELETE FROM coveragefile WHERE id=" . qnum($prevfileid) . " AND file IS NULL and crc32 IS NULL"); add_last_sql_error("CoverageFile:Update"); } else { // We find the current fileid based on the name and the file should be null $coveragefile = pdo_query("SELECT cf.id,cf.file FROM coverage AS c,coveragefile AS cf \n WHERE c.fileid=cf.id AND c.buildid=" . qnum($buildid) . "\n AND cf.fullpath='{$this->FullPath}' ORDER BY cf.id ASC"); $coveragefile_array = pdo_fetch_array($coveragefile); // The GcovTarHandler creates coveragefiles before coverages // so we need a simpler query in this case. if (empty($coveragefile_array)) { $coveragefile = pdo_query("SELECT id, file FROM coveragefile\n WHERE fullpath='{$this->FullPath}' AND file IS NULL\n ORDER BY id ASC"); $coveragefile_array = pdo_fetch_array($coveragefile); } $this->Id = $coveragefile_array["id"]; pdo_query("UPDATE coveragefile SET file='{$file}',crc32='{$this->Crc32}' WHERE id=" . qnum($this->Id)); add_last_sql_error("CoverageFile:Update"); } return true; }
function BlobEncode($blob) { if (ADODB_PHPVER >= 0x5200) { return pg_escape_bytea($this->_connectionID, $blob); } if (ADODB_PHPVER >= 0x4200) { return pg_escape_bytea($blob); } /*92=backslash, 0=null, 39=single-quote*/ $badch = array(chr(92), chr(0), chr(39)); # \ null ' $fixch = array('\\\\134', '\\\\000', '\\\\047'); return adodb_str_replace($badch, $fixch, $blob); // note that there is a pg_escape_bytea function only for php 4.2.0 or later }
/** * @param null|bool|Blob $s * @return int|string */ function addQuotes($s) { if (is_null($s)) { return 'NULL'; } elseif (is_bool($s)) { return intval($s); } elseif ($s instanceof Blob) { if ($s instanceof PostgresBlob) { $s = $s->fetch(); } else { $s = pg_escape_bytea($this->mConn, $s->fetch()); } return "'{$s}'"; } return "'" . pg_escape_string($this->mConn, $s) . "'"; }
/** * Encodes data for use in an SQL statement. * * @param string value * @param string type (dibi::FIELD_TEXT, dibi::FIELD_BOOL, ...) * @return string encoded value * @throws InvalidArgumentException */ public function escape($value, $type) { switch ($type) { case dibi::FIELD_TEXT: if ($this->escMethod) { return "'" . pg_escape_string($this->connection, $value) . "'"; } else { return "'" . pg_escape_string($value) . "'"; } case dibi::FIELD_BINARY: if ($this->escMethod) { return "'" . pg_escape_bytea($this->connection, $value) . "'"; } else { return "'" . pg_escape_bytea($value) . "'"; } case dibi::IDENTIFIER: $a = strrpos($value, '.'); if ($a === FALSE) { return '"' . str_replace('"', '""', $value) . '"'; } else { // table.col delimite as table."col" return substr($value, 0, $a) . '."' . str_replace('"', '""', substr($value, $a + 1)) . '"'; } case dibi::FIELD_BOOL: return $value ? 'TRUE' : 'FALSE'; case dibi::FIELD_DATE: return date("'Y-m-d'", $value); case dibi::FIELD_DATETIME: return date("'Y-m-d H:i:s'", $value); default: throw new InvalidArgumentException('Unsupported type.'); } }