Exemplo n.º 1
0
 function _performGetBlobFieldNames($result)
 {
     $blobFields = array();
     for ($i = mssql_num_fields($result) - 1; $i >= 0; $i--) {
         $type = mssql_field_type($result, $i);
         if (strpos($type, "BLOB") !== false) {
             $blobFields[] = mssql_field_name($result, $i);
         }
     }
     return $blobFields;
 }
Exemplo n.º 2
0
 /**
  * Returns information about a table or a result set.
  *
  * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  * is a table name.
  *
  * @param object|string  $result  MDB2_result object from a query or a
  *                                string containing the name of a table
  * @param int            $mode    a valid tableInfo mode
  * @return array  an associative array with the information requested
  *                or an error object if something is wrong
  * @access public
  * @internal
  * @see MDB2_Driver_Common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
     if ($db->options['portability'] & MDB2_PORTABILITY_LOWERCASE) {
         $case_func = 'strtolower';
     } else {
         $case_func = 'strval';
     }
     if (is_string($result)) {
         /*
          * Probably received a table name.
          * Create a result resource identifier.
          */
         if (MDB2::isError($connect = $db->connect())) {
             return $connect;
         }
         $id = @mssql_query("SELECT * FROM {$result} WHERE 1=0", $db->connection);
         $got_string = true;
     } else {
         /*
          * Probably received a result object.
          * Extract the result resource identifier.
          */
         $id = $result->getResource();
         if (empty($id)) {
             return $db->raiseError();
         }
         $got_string = false;
     }
     if (!is_resource($id)) {
         return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA);
     }
     $count = @mssql_num_fields($id);
     // made this IF due to performance (one if is faster than $count if's)
     if (!$mode) {
         for ($i = 0; $i < $count; $i++) {
             $res[$i]['table'] = $got_string ? $case_func($result) : '';
             $res[$i]['name'] = $case_func(@mssql_field_name($id, $i));
             $res[$i]['type'] = @mssql_field_type($id, $i);
             $res[$i]['len'] = @mssql_field_length($id, $i);
             // We only support flags for tables
             $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : '';
         }
     } else {
         // full
         $res['num_fields'] = $count;
         for ($i = 0; $i < $count; $i++) {
             $res[$i]['table'] = $got_string ? $case_func($result) : '';
             $res[$i]['name'] = $case_func(@mssql_field_name($id, $i));
             $res[$i]['type'] = @mssql_field_type($id, $i);
             $res[$i]['len'] = @mssql_field_length($id, $i);
             // We only support flags for tables
             $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : '';
             if ($mode & MDB2_TABLEINFO_ORDER) {
                 $res['order'][$res[$i]['name']] = $i;
             }
             if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
             }
         }
     }
     // free the result only if we were called on a table
     if ($got_string) {
         @mssql_free_result($id);
     }
     return $res;
 }
Exemplo n.º 3
0
function copy_table_data($db, $table, $keys, $filter)
{
    global $gp;
    global $con;
    /*
     if($db == "dynamics")
    mssql_select_db("dynamics");
     else 
    mssql_select_db("cpj");
    */
    mssql_select_db($db);
    echo "Pulling data for table {$db}_{$table}...\n";
    $table = strtolower($table);
    $filter = strtolower($filter);
    $field_names = "";
    $field_values = "";
    #$key_id = 0;
    $xkeys = !empty($keys["primary"]) ? explode(", ", strtolower($keys["primary"])) : [];
    $primary = [];
    foreach ($xkeys as $value) {
        $primary[$value] = -1;
    }
    if (!table_exists($db, $table)) {
        echo "Table {$db}_{$table} does not exist.\nCopying table structure.\n";
        copy_table_structure($db, $table, $keys);
    }
    $result = mysqli_query($con, "select coalesce(max(modified), '01/10/1970') modified from sync_log where db = '{$db}' and tbl = '{$table}';");
    if ($result === false) {
        die("Error can not get last modified date. " . mysqli_error($con));
    }
    $row = mysqli_fetch_assoc($result);
    $mysql_modified = $row["modified"];
    mysqli_free_result($result);
    $result = mssql_query("select convert(varchar(23), modify_date, 121) modify_date from {$db}.sys.tables where name = '{$table}';", $gp);
    if ($result === false) {
        die("Error can not get last modified date. " . mssql_get_last_message());
    }
    $row = mssql_fetch_assoc($result);
    $mssql_modified = $row["modify_date"];
    mssql_free_result($result);
    echo "\n\n\n######################\n\n{$mssql_modified} == {$mysql_modified}\n\n#######################\n\n\n";
    if ($mssql_modified == $mysql_modified) {
        return;
    }
    $where = "";
    switch ($filter) {
        case "dex_row_id":
            $result = mysqli_query($con, "select coalesce(max(dex_row_id), 0) modified from {$db}_{$table};");
            if ($result === false) {
                die("Error can not get last modified date. " . mysqli_error($con));
            }
            $row = mysqli_fetch_assoc($result);
            $where = " where dex_row_id > '" . $row["modified"] . "'";
            mysqli_free_result($result);
            break;
        case "dex_row_ts":
            $result = mysqli_query($con, "select coalesce(max(dex_row_ts), '01/10/1970') modified from {$db}_{$table};");
            if ($result === false) {
                die("Error can not get last modified date. " . mysqli_error($con));
            }
            $row = mysqli_fetch_assoc($result);
            $where = " where dex_row_ts > '" . $row["modified"] . "'";
            mysqli_free_result($result);
            break;
        case "active":
            $where = " where active = 1";
            mysqli_query($con, utf8_encode("truncate table {$db}_{$table};"));
            break;
        default:
            mysqli_query($con, utf8_encode("truncate table {$db}_{$table};"));
            break;
    }
    $sql = "select * from {$table} {$where}";
    $rset = mssql_query($sql, $gp, 5000);
    if (!$rset) {
        die('MSSQL error: ' . mssql_get_last_message() . "\n\n {$sql} \n\n\n");
    }
    $cnt = mssql_num_fields($rset);
    for ($inc = 0; $inc < $cnt; $inc++) {
        if ($field_names == "") {
            $field_names = mssql_field_name($rset, $inc);
        } else {
            $field_names .= ", " . mssql_field_name($rset, $inc);
        }
        $ykey = trim(strtolower(mssql_field_name($rset, $inc)));
        if (isset($primary[$ykey])) {
            $primary[$ykey] = $inc;
        }
    }
    $zkey = "";
    foreach ($primary as $key => $value) {
        if ($zkey != "") {
            $zkey .= ":{$key}";
        } else {
            $zkey .= "{$key}";
        }
    }
    $p_sql = "";
    $radix = 0;
    $counter = 0;
    $xdata = "";
    echo "\n\n";
    do {
        while ($line = mssql_fetch_row($rset)) {
            $field_values = "";
            $vkey = "";
            foreach ($primary as $key => $value) {
                if ($vkey != "") {
                    $vkey .= ":" . $line[$value];
                } else {
                    $vkey .= $line[$value];
                }
            }
            echo "Importing ({$zkey} " . $vkey . ")\r";
            for ($inc = 0; $inc < $cnt; $inc++) {
                if (mssql_field_type($rset, $inc) == "datetime") {
                    $xdata = "'" . date(DATE_ATOM, strtotime($line[$inc])) . "'";
                } else {
                    $xdata = "'" . sanitize($line[$inc]) . "'";
                }
                if ($field_values == "") {
                    $field_values = "{$xdata}";
                } else {
                    $field_values .= ", {$xdata}";
                }
            }
            if ($p_sql != "") {
                $p_sql .= ", ({$field_values})";
            } else {
                $p_sql .= "({$field_values})";
            }
            if ($radix == 500) {
                mysqli_query($con, utf8_encode("insert into {$db}_{$table} ({$field_names}) values {$p_sql};"));
                $radix = 0;
                $p_sql = "";
            }
            $radix++;
            $counter++;
            #echo "$p_sql\n";
            #mysqli_query($con, utf8_encode($p_sql));
        }
    } while (mssql_fetch_batch($rset));
    if ($p_sql != "") {
        mysqli_query($con, utf8_encode("insert into {$db}_{$table} ({$field_names}) values {$p_sql};"));
        $radix = 0;
        $p_sql = "";
    }
    $p_sql = "insert into sync_log (db, tbl, modified, synced, rows) values ('{$db}', '{$table}', '{$mssql_modified}', now(), '{$counter}');";
    mysqli_query($con, utf8_encode($p_sql));
    echo "\n\nTable {$db}_{$table} completed.\n\n";
}
 function IsTimestamp($vField)
 {
     return $this->res > 0 && mssql_field_type($this->res, $vField) == 'datetime';
 }
Exemplo n.º 5
0
 /**
  * Returns information about a table or a result set
  *
  * NOTE: doesn't support table name and flags if called from a db_result
  *
  * @param  mixed $resource SQL Server result identifier or table name
  * @param  int $mode A valid tableInfo mode (DB_TABLEINFO_ORDERTABLE or
  *                   DB_TABLEINFO_ORDER)
  *
  * @return array An array with all the information
  */
 function tableInfo($result, $mode = null)
 {
     $count = 0;
     $id = 0;
     $res = array();
     /*
      * depending on $mode, metadata returns the following values:
      *
      * - mode is false (default):
      * $result[]:
      *   [0]["table"]  table name
      *   [0]["name"]   field name
      *   [0]["type"]   field type
      *   [0]["len"]    field length
      *   [0]["flags"]  field flags
      *
      * - mode is DB_TABLEINFO_ORDER
      * $result[]:
      *   ["num_fields"] number of metadata records
      *   [0]["table"]  table name
      *   [0]["name"]   field name
      *   [0]["type"]   field type
      *   [0]["len"]    field length
      *   [0]["flags"]  field flags
      *   ["order"][field name]  index of field named "field name"
      *   The last one is used, if you have a field name, but no index.
      *   Test:  if (isset($result['meta']['myfield'])) { ...
      *
      * - mode is DB_TABLEINFO_ORDERTABLE
      *    the same as above. but additionally
      *   ["ordertable"][table name][field name] index of field
      *      named "field name"
      *
      *      this is, because if you have fields from different
      *      tables with the same field name * they override each
      *      other with DB_TABLEINFO_ORDER
      *
      *      you can combine DB_TABLEINFO_ORDER and
      *      DB_TABLEINFO_ORDERTABLE with DB_TABLEINFO_ORDER |
      *      DB_TABLEINFO_ORDERTABLE * or with DB_TABLEINFO_FULL
      */
     // if $result is a string, then we want information about a
     // table without a resultset
     if (is_string($result)) {
         $id = mssql_query("SELECT * FROM {$result}", $this->connection);
         if (empty($id)) {
             return $this->mssqlRaiseError();
         }
     } else {
         // else we want information about a resultset
         $id = $result;
         if (empty($id)) {
             return $this->mssqlRaiseError();
         }
     }
     $count = @mssql_num_fields($id);
     // made this IF due to performance (one if is faster than $count if's)
     if (empty($mode)) {
         for ($i = 0; $i < $count; $i++) {
             $res[$i]['table'] = is_string($result) ? $result : '';
             $res[$i]['name'] = @mssql_field_name($id, $i);
             $res[$i]['type'] = @mssql_field_type($id, $i);
             $res[$i]['len'] = @mssql_field_length($id, $i);
             $res[$i]['flags'] = '';
         }
     } else {
         // full
         $res['num_fields'] = $count;
         for ($i = 0; $i < $count; $i++) {
             $res[$i]['table'] = is_string($result) ? $result : '';
             $res[$i]['name'] = @mssql_field_name($id, $i);
             $res[$i]['type'] = @mssql_field_type($id, $i);
             $res[$i]['len'] = @mssql_field_length($id, $i);
             $res[$i]['flags'] = '';
             if ($mode & DB_TABLEINFO_ORDER) {
                 $res['order'][$res[$i]['name']] = $i;
             }
             if ($mode & DB_TABLEINFO_ORDERTABLE) {
                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
             }
         }
     }
     // free the result only if we were called on a table
     if (is_string($result)) {
         @mssql_free_result($id);
     }
     return $res;
 }
Exemplo n.º 6
0
 function write_data_mssql($table_name)
 {
     global $db;
     $ary_type = $ary_name = array();
     $ident_set = false;
     $sql_data = '';
     // Grab all of the data from current table.
     $sql = "SELECT *\n\t\t\tFROM {$table_name}";
     $result = $db->sql_query($sql);
     $retrieved_data = mssql_num_rows($result);
     $i_num_fields = mssql_num_fields($result);
     for ($i = 0; $i < $i_num_fields; $i++) {
         $ary_type[$i] = mssql_field_type($result, $i);
         $ary_name[$i] = mssql_field_name($result, $i);
     }
     if ($retrieved_data) {
         $sql = "SELECT 1 as has_identity\n\t\t\t\tFROM INFORMATION_SCHEMA.COLUMNS\n\t\t\t\tWHERE COLUMNPROPERTY(object_id('{$table_name}'), COLUMN_NAME, 'IsIdentity') = 1";
         $result2 = $db->sql_query($sql);
         $row2 = $db->sql_fetchrow($result2);
         if (!empty($row2['has_identity'])) {
             $sql_data .= "\nSET IDENTITY_INSERT {$table_name} ON\nGO\n";
             $ident_set = true;
         }
         $db->sql_freeresult($result2);
     }
     while ($row = $db->sql_fetchrow($result)) {
         $schema_vals = $schema_fields = array();
         // Build the SQL statement to recreate the data.
         for ($i = 0; $i < $i_num_fields; $i++) {
             $str_val = $row[$ary_name[$i]];
             if (preg_match('#char|text|bool|varbinary#i', $ary_type[$i])) {
                 $str_quote = '';
                 $str_empty = "''";
                 $str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
             } else {
                 if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                     if (empty($str_val)) {
                         $str_quote = '';
                     } else {
                         $str_quote = "'";
                     }
                 } else {
                     $str_quote = '';
                     $str_empty = 'NULL';
                 }
             }
             if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val))) {
                 $str_val = $str_empty;
             }
             $schema_vals[$i] = $str_quote . $str_val . $str_quote;
             $schema_fields[$i] = $ary_name[$i];
         }
         // Take the ordered fields and their associated data and build it
         // into a valid sql statement to recreate that field in the data.
         $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
         $this->flush($sql_data);
         $sql_data = '';
     }
     $db->sql_freeresult($result);
     if ($retrieved_data && $ident_set) {
         $sql_data .= "\nSET IDENTITY_INSERT {$table_name} OFF\nGO\n";
     }
     $this->flush($sql_data);
 }
Exemplo n.º 7
0
 /**
  * mysql_field_type() wrapper
  */
 function fieldType($res, $index)
 {
     if ($res instanceof ResultWrapper) {
         $res = $res->result;
     }
     return mssql_field_type($res, $index);
 }
Exemplo n.º 8
0
function db_field_type($result, $i)
{
    global $_josh;
    db_open();
    if ($_josh["db"]["language"] == "mysql") {
        return mysql_field_type($result, $i);
    } elseif ($_josh["db"]["language"] == "mssql") {
        return mssql_field_type($result, $i);
    }
}
 function query($query)
 {
     // For reg expressions
     $query = trim($query);
     // Flush cached values..
     $this->flush();
     // Log how the function was called
     $this->func_call = "\$db->query(\"{$query}\")";
     // Keep track of the last query for debug..
     $this->last_query = $query;
     // Perform the query via std mssql_query function..
     $this->result = @mssql_query($query, $this->dbh);
     $this->num_queries++;
     // Unfortunately, PHP fuctions for MS SQL currently don't offer a decent way
     // to retrieve errors from MS SQL
     // Make sure not to run a query between the actual query and this one !
     $get_errorcode = "SELECT @@ERROR as errorcode";
     $error_res = @mssql_query($get_errorcode, $this->dbh);
     $errorcode = @mssql_result($error_res, 0, "errorcode");
     // If there was an insert, delete or update see how many rows were affected
     // (Also, If there there was an insert take note of the last OID
     $query_type = array("insert", "delete", "update", "replace");
     // loop through the above array
     foreach ($query_type as $word) {
         // This is true if the query starts with insert, delete or update
         if (preg_match("/^{$word}\\s+/i", $query)) {
             $this->rows_affected = @mssql_rows_affected($this->dbh);
             // This gets the insert ID
             if ($word == "insert" || $word == "replace") {
                 $get_last_ident = "SELECT @@IDENTITY as id";
                 $last_res = @mssql_query($get_last_ident, $this->dbh);
                 $this->insert_id = @mssql_result($last_res, 0, "id");
                 // If insert id then return it - true evaluation
                 return $this->insert_id;
             }
             // Set to false if there was no insert id
             $this->result = false;
         }
     }
     if ($errorcode != 0) {
         // there is an error
         $this->print_error();
     } else {
         // =======================================================
         // Take note of column info
         $i = 0;
         while ($i < @mssql_num_fields($this->result)) {
             $this->col_info[$i]->name = @mssql_field_name($this->result, $i);
             $this->col_info[$i]->type = @mssql_field_type($this->result, $i);
             $this->col_info[$i]->size = @mssql_field_length($this->result, $i);
             $i++;
         }
         // =======================================================
         // Store Query Results
         $i = 0;
         while ($row = @mssql_fetch_object($this->result)) {
             // Store relults as an objects within main array
             $this->last_result[$i] = $row;
             $i++;
         }
         // Log number of rows the query returned
         $this->num_rows = $i;
         //}
         @mssql_free_result($this->result);
         // If this was a select..
         if (preg_match("/^(select|show|desc)\\s+/i", $query)) {
             // If debug ALL queries
             $this->debug_all ? $this->debug() : null;
             // If there were results then return true for $db->query
             if ($i) {
                 return true;
             } else {
                 return false;
             }
         } else {
             // If debug ALL queries
             $this->debug_all ? $this->debug() : null;
             // Update insert etc. was good..
             return true;
         }
     }
 }
Exemplo n.º 10
0
 /**
  * Get the rows returned from a SELECT query.
  *
  * @param  resource		The query result pointer
  * @param  ?integer		Whether to start reading from (NULL: irrelevant for this forum driver)
  * @return array			A list of row maps
  */
 function db_get_query_rows($results, $start = NULL)
 {
     $out = array();
     if (!function_exists('sqlsrv_num_fields')) {
         $num_fields = mssql_num_fields($results);
         $types = array();
         $names = array();
         for ($x = 1; $x <= $num_fields; $x++) {
             $types[$x - 1] = mssql_field_type($results, $x - 1);
             $names[$x - 1] = strtolower(mssql_field_name($results, $x - 1));
         }
         $i = 0;
         while (($row = mssql_fetch_row($results)) !== false) {
             $j = 0;
             $newrow = array();
             foreach ($row as $v) {
                 $type = strtoupper($types[$j]);
                 $name = $names[$j];
                 if ($type == 'SMALLINT' || $type == 'INT' || $type == 'INTEGER' || $type == 'UINTEGER' || $type == 'BYTE' || $type == 'COUNTER') {
                     if (!is_null($v)) {
                         $newrow[$name] = intval($v);
                     } else {
                         $newrow[$name] = NULL;
                     }
                 } else {
                     if ($v == ' ') {
                         $v = '';
                     }
                     $newrow[$name] = $v;
                 }
                 $j++;
             }
             $out[] = $newrow;
             $i++;
         }
     } else {
         if (function_exists('sqlsrv_fetch_array')) {
             while (($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) !== NULL) {
                 $out[] = $row;
             }
         } else {
             while (($row = mssql_fetch_row($results)) !== false) {
                 $out[] = $row;
             }
         }
     }
     if (function_exists('sqlsrv_free_stmt')) {
         sqlsrv_free_stmt($results);
     } else {
         mssql_free_result($results);
     }
     return $out;
 }
Exemplo n.º 11
0
	public function __construct($result_id, $x, $value)
	{
		try
		{
			$this->name = @mssql_field_name($result_id, $x);

			//If can't read field name			
			if (!$this->name) throw new TException(TCustomMessage::GetMessage(5008), 5008);

			$this->size = @mssql_field_length($result_id, $x);
			
			//If can't read field size
			if (!$this->size) throw new TException(TCustomMessage::GetMessage(5008), 5008);
			
			$this->type = @mssql_field_type($result_id, $x);	
			
			//If can't read field type
			if (!$this->type) throw new TException(TCustomMessage::GetMessage(5008), 5008);
			
			$this->value = $value;
			
		}
		catch (TException $e)
		{
			//...
		}
	}
Exemplo n.º 12
0
 function FieldType($result, $offset)
 {
     switch ($this->dbType) {
         case "mssql":
             $r = mssql_field_type($result, $offset);
             break;
         case "mysql":
             $r = mysql_field_type($result, $offset);
             break;
         case "pg":
             $r = pg_fieldtype($result, $offset);
             break;
         default:
             $r = False;
             break;
     }
     return $r;
 }
Exemplo n.º 13
0
 /**
  * Returns information about a table or a result set
  *
  * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  * is a table name.
  *
  * @param object|string  $result  MDB2_result object from a query or a
  *                                 string containing the name of a table.
  *                                 While this also accepts a query result
  *                                 resource identifier, this behavior is
  *                                 deprecated.
  * @param int            $mode    a valid tableInfo mode
  *
  * @return array  an associative array with the information requested.
  *                 A MDB2_Error object on failure.
  *
  * @see MDB2_Driver_Common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     $db =& $this->getDBInstance();
     if (PEAR::isError($db)) {
         return $db;
     }
     if (is_string($result)) {
         /*
          * Probably received a table name.
          * Create a result resource identifier.
          */
         $query = 'SELECT TOP 0 * FROM ' . $db->quoteIdentifier($result);
         $id =& $db->_doQuery($query, false);
         if (PEAR::isError($id)) {
             return $id;
         }
         $got_string = true;
     } elseif (MDB2::isResultCommon($result)) {
         /*
          * Probably received a result object.
          * Extract the result resource identifier.
          */
         $id = $result->getResource();
         $got_string = false;
     } else {
         /*
          * Probably received a result resource identifier.
          * Copy it.
          * Deprecated.  Here for compatibility only.
          */
         $id = $result;
         $got_string = false;
     }
     if (!is_resource($id)) {
         return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA);
     }
     if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
         if ($db->options['field_case'] == CASE_LOWER) {
             $case_func = 'strtolower';
         } else {
             $case_func = 'strtoupper';
         }
     } else {
         $case_func = 'strval';
     }
     $count = @mssql_num_fields($id);
     $res = array();
     if ($mode) {
         $res['num_fields'] = $count;
     }
     $db->loadModule('Datatype', null, true);
     for ($i = 0; $i < $count; $i++) {
         $res[$i] = array('table' => $got_string ? $case_func($result) : '', 'name' => $case_func(@mssql_field_name($id, $i)), 'type' => @mssql_field_type($id, $i), 'length' => @mssql_field_length($id, $i), 'flags' => $got_string ? $this->_mssql_field_flags($result, @mssql_field_name($id, $i)) : '');
         $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
         if (PEAR::isError($mdb2type_info)) {
             return $mdb2type_info;
         }
         $res[$i]['mdb2type'] = $mdb2type_info[0][0];
         if ($mode & MDB2_TABLEINFO_ORDER) {
             $res['order'][$res[$i]['name']] = $i;
         }
         if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
             $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
         }
     }
     // free the result only if we were called on a table
     if ($got_string) {
         @mssql_free_result($id);
     }
     return $res;
 }
Exemplo n.º 14
0
 public function run_inquirydetail($criteria)
 {
     //select the database
     mssql_select_db($this->dbname, $this->dbcon);
     //SQL Select statement
     $xml = new XMLHandler(XML_DIR . "inquiry.xml");
     $sql_from_xml = $xml->getNode("inquiry");
     $sqlselect = str_replace("FILTER_BY_PROGRAM", " WHERE SPK.NO_SPK = '" . $criteria . "' ", $sql_from_xml);
     //Run the SQL query
     $result = mssql_query($sqlselect);
     $numfields = mssql_num_fields($result);
     $string_result = "";
     while ($row = mssql_fetch_row($result)) {
         for ($i = 0; $i < $numfields; $i++) {
             $fieldType = mssql_field_type($result, $i);
             if ($fieldType == "datetime") {
                 if ($row[$i] != null) {
                     $dateVal = strtotime($row[$i]);
                     $string_result .= "<tr><th scope=\"row\">" . mssql_field_name($result, $i) . "</th><td>:</td><td>" . date('d-m-Y', $dateVal) . "</td></tr>";
                 } else {
                     $string_result .= "<tr><th scope=\"row\">" . mssql_field_name($result, $i) . "</th><td>:</td><td>-</td></tr>";
                 }
             } else {
                 if ($i == 0) {
                     $string_result .= "<tr><th scope=\"row\">" . mssql_field_name($result, $i) . "</th><td>:</td><td>" . $row[$i] . " <a href='loadspk_" . $criteria . "'><button type=\"button\" class=\"btn btn-info btn-xs\">edit</button></a></td></tr>";
                 } else {
                     $string_result .= "<tr><th scope=\"row\">" . mssql_field_name($result, $i) . "</th><td>:</td><td>" . $row[$i] . "</td></tr>";
                 }
             }
         }
     }
     $string_result .= "<tr><th scope=\"row\" colspan=3><a href='loadspk_" . $criteria . "'><button type=\"button\" class=\"btn btn-info\">edit mode</button></a></th></tr>";
     return $string_result;
 }
Exemplo n.º 15
0
function vty_field_type($list,$i){
        switch($this->vtAdi){
        case 'mysql': return mysql_field_type($list,$i); break;
        case 'odbc': return odbc_field_type($list,$i); break;
        case 'mssql': return mssql_field_type($list,$i); break;
        case 'postgresql': pg_fieldtype($list,$i); break;
        }
}
Exemplo n.º 16
0
 public function get_spk($no_spk)
 {
     //select the database
     mssql_select_db($this->dbname, $this->dbcon);
     //SQL Select statement
     $xml = new XMLHandler(XML_DIR . "web_request_spk.xml");
     $sql_from_xml = $xml->getNode("browsepo");
     $sqlselect = str_replace("FILTER_BY_PROGRAM", " AND TR_SALE_SPK.NO_SPK='{$no_spk}'", $sql_from_xml);
     //echo $sqlselect."<br>";
     //Run the SQL query
     $result = mssql_query($sqlselect);
     $numfields = mssql_num_fields($result);
     $jsonString = "{\"dt_objectTable\": [{\"dt_fieldsCollection\":[@fieldsCollection@],\"tableName\":\"SPK\",\"modify_status\":\"ORI\"}]}";
     $fieldsCollection = "";
     $cust_beli = "";
     $cust_stnk = "";
     $cust_kirim = "";
     while ($row = mssql_fetch_row($result)) {
         for ($i = 0; $i < $numfields; $i++) {
             if ($fieldsCollection != "") {
                 $fieldsCollection .= ",";
             }
             $fieldType = mssql_field_type($result, $i);
             if ($fieldType == "datetime") {
                 $dateVal = strtotime($row[$i]);
                 $fieldsCollection .= "{\"fieldName\":\"" . mssql_field_name($result, $i) . "\",\"fieldValue\":\"" . date('m/d/Y', $dateVal) . "\"}";
             } else {
                 $fieldsCollection .= "{\"fieldName\":\"" . mssql_field_name($result, $i) . "\",\"fieldValue\":\"" . $row[$i] . "\"}";
             }
         }
     }
     $jsonString = str_replace("@fieldsCollection@", $fieldsCollection, $jsonString);
     return $jsonString;
 }
Exemplo n.º 17
0
    function main($id, $mode)
    {
        global $db, $user, $auth, $template, $table_prefix;
        global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;
        $user->add_lang('acp/database');
        $this->tpl_name = 'acp_database';
        $this->page_title = 'ACP_DATABASE';
        $action = request_var('action', '');
        $submit = isset($_POST['submit']) ? true : false;
        $template->assign_vars(array('MODE' => $mode));
        switch ($mode) {
            case 'backup':
                switch ($action) {
                    case 'download':
                        $type = request_var('type', '');
                        $table = request_var('table', array(''));
                        $format = request_var('method', '');
                        $where = request_var('where', '');
                        $store = $download = $structure = $schema_data = false;
                        if ($where == 'store_and_download' || $where == 'store') {
                            $store = true;
                        }
                        if ($where == 'store_and_download' || $where == 'download') {
                            $download = true;
                        }
                        if ($type == 'full' || $type == 'structure') {
                            $structure = true;
                        }
                        if ($type == 'full' || $type == 'data') {
                            $schema_data = true;
                        }
                        @set_time_limit(1200);
                        $filename = time();
                        // We set up the info needed for our on-the-fly creation :D
                        switch ($format) {
                            case 'text':
                                $ext = '.sql';
                                $open = 'fopen';
                                $write = 'fwrite';
                                $close = 'fclose';
                                $oper = '';
                                $mimetype = 'text/x-sql';
                                break;
                            case 'bzip2':
                                $ext = '.sql.bz2';
                                $open = 'bzopen';
                                $write = 'bzwrite';
                                $close = 'bzclose';
                                $oper = 'bzcompress';
                                $mimetype = 'application/x-bzip2';
                                break;
                            case 'gzip':
                                $ext = '.sql.gz';
                                $open = 'gzopen';
                                $write = 'gzwrite';
                                $close = 'gzclose';
                                $oper = 'gzencode';
                                $mimetype = 'application/x-gzip';
                                break;
                        }
                        // We write the file to "store" first (and then compress the file) to not use too much
                        // memory. The server process can be easily killed by storing too much data at once.
                        if ($store == true) {
                            $file = $phpbb_root_path . 'store/' . $filename . $ext;
                            $fp = $open($file, 'w');
                            if (!$fp) {
                                trigger_error('Unable to write temporary file to storage folder');
                            }
                        }
                        if ($download == true) {
                            $name = $filename . $ext;
                            header('Pragma: no-cache');
                            header("Content-Type: {$mimetype}; name=\"{$name}\"");
                            header("Content-disposition: attachment; filename={$name}");
                        }
                        // All of the generated queries go here
                        $sql_data = '';
                        $sql_data .= "#\n";
                        $sql_data .= "# phpBB Backup Script\n";
                        $sql_data .= "# Dump of tables for {$table_prefix}\n";
                        $sql_data .= "# DATE : " . gmdate("d-m-Y H:i:s", $filename) . " GMT\n";
                        $sql_data .= "#\n";
                        switch (SQL_LAYER) {
                            case 'sqlite':
                                $sql_data .= "BEGIN TRANSACTION;\n";
                                break;
                            case 'postgres':
                                $sql_data .= "BEGIN;\n";
                                break;
                            case 'mssql':
                            case 'mssql_odbc':
                                $sql_data .= "BEGIN TRANSACTION\nGO\n";
                                break;
                        }
                        foreach ($table as $table_name) {
                            // Get the table structure
                            if ($structure) {
                                switch (SQL_LAYER) {
                                    case 'mysqli':
                                    case 'mysql4':
                                    case 'mysql':
                                    case 'sqlite':
                                        $sql_data .= '# Table: ' . $table_name . "\n";
                                        $sql_data .= "DROP TABLE IF EXISTS {$table_name};\n";
                                        break;
                                    case 'oracle':
                                        $sql_data .= '# Table: ' . $table_name . "\n";
                                        $sql_data .= "DROP TABLE {$table_name};\n\\\n";
                                        break;
                                    case 'postgres':
                                    case 'firebird':
                                        $sql_data .= '# Table: ' . $table_name . "\n";
                                        $sql_data .= "DROP TABLE {$table_name};\n";
                                        break;
                                    case 'mssql':
                                    case 'mssql_odbc':
                                        $sql_data .= '# Table: ' . $table_name . "\n";
                                        $sql_data .= "IF OBJECT_ID(N'{$table_name}', N'U') IS NOT NULL\n";
                                        $sql_data .= "DROP TABLE {$table_name};\nGO\n";
                                        break;
                                }
                                $sql_data .= $this->get_table_structure($table_name);
                            }
                            // Now write the data for the first time. :)
                            if ($store == true) {
                                $write($fp, $sql_data);
                            }
                            if ($download == true) {
                                if (!empty($oper)) {
                                    echo $oper($sql_data);
                                } else {
                                    echo $sql_data;
                                }
                            }
                            $sql_data = '';
                            // Data
                            if ($schema_data) {
                                $sql_data .= "\n";
                                switch (SQL_LAYER) {
                                    case 'mysqli':
                                        $sql = "SELECT * FROM {$table_name}";
                                        $result = mysqli_query($db->db_connect_id, $sql, MYSQLI_USE_RESULT);
                                        if ($result != false) {
                                            $fields_cnt = mysqli_num_fields($result);
                                            // Get field information
                                            $field = mysqli_fetch_fields($result);
                                            $field_set = array();
                                            for ($j = 0; $j < $fields_cnt; $j++) {
                                                $field_set[$j] = $field[$j]->name;
                                            }
                                            $search = array('\\', "'", "", "\n", "\r", "");
                                            $replace = array('\\\\\\\\', "''", '\\0', '\\n', '\\r', '\\Z');
                                            $fields = implode(', ', $field_set);
                                            $values = array();
                                            $schema_insert = 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES (';
                                            while ($row = mysqli_fetch_row($result)) {
                                                for ($j = 0; $j < $fields_cnt; $j++) {
                                                    if (!isset($row[$j]) || is_null($row[$j])) {
                                                        $values[$j] = 'NULL';
                                                    } else {
                                                        if ($field[$j]->flags & 32768 && !($field[$j]->flags & 1024)) {
                                                            $values[$j] = $row[$j];
                                                        } else {
                                                            $values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
                                                        }
                                                    }
                                                }
                                                $sql_data .= $schema_insert . implode(', ', $values) . ");\n";
                                                if ($store == true) {
                                                    $write($fp, $sql_data);
                                                }
                                                if ($download == true) {
                                                    if (!empty($oper)) {
                                                        echo $oper($sql_data);
                                                    } else {
                                                        echo $sql_data;
                                                    }
                                                }
                                                $sql_data = '';
                                                $values = array();
                                            }
                                            mysqli_free_result($result);
                                        }
                                        break;
                                    case 'mysql4':
                                    case 'mysql':
                                        $sql = "SELECT * FROM {$table_name}";
                                        $result = mysql_unbuffered_query($sql, $db->db_connect_id);
                                        if ($result != false) {
                                            $fields_cnt = mysql_num_fields($result);
                                            // Get field information
                                            $field = array();
                                            for ($i = 0; $i < $fields_cnt; $i++) {
                                                $field[$i] = mysql_fetch_field($result, $i);
                                            }
                                            $field_set = array();
                                            for ($j = 0; $j < $fields_cnt; $j++) {
                                                $field_set[$j] = $field[$j]->name;
                                            }
                                            $search = array('\\', "'", "", "\n", "\r", "");
                                            $replace = array('\\\\\\\\', "''", '\\0', '\\n', '\\r', '\\Z');
                                            $fields = implode(', ', $field_set);
                                            $schema_insert = 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES (';
                                            while ($row = mysql_fetch_row($result)) {
                                                $values = array();
                                                for ($j = 0; $j < $fields_cnt; $j++) {
                                                    if (!isset($row[$j]) || is_null($row[$j])) {
                                                        $values[$j] = 'NULL';
                                                    } else {
                                                        if ($field[$j]->numeric && $field[$j]->type !== 'timestamp') {
                                                            $values[$j] = $row[$j];
                                                        } else {
                                                            $values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
                                                        }
                                                    }
                                                }
                                                $sql_data .= $schema_insert . implode(', ', $values) . ");\n";
                                                if ($store == true) {
                                                    $write($fp, $sql_data);
                                                }
                                                if ($download == true) {
                                                    if (!empty($oper)) {
                                                        echo $oper($sql_data);
                                                    } else {
                                                        echo $sql_data;
                                                    }
                                                }
                                                $sql_data = '';
                                            }
                                            mysql_free_result($result);
                                        }
                                        break;
                                    case 'sqlite':
                                        $col_types = sqlite_fetch_column_types($table_name, $db->db_connect_id);
                                        $sql = "SELECT * FROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $names = $data = array();
                                            foreach ($row as $row_name => $row_data) {
                                                $names[] = $row_name;
                                                // Figure out what this data is, escape it properly
                                                if (is_null($row_data)) {
                                                    $row_data = 'NULL';
                                                } else {
                                                    if ($row_data == '') {
                                                        $row_data = "''";
                                                    } else {
                                                        if (strpos($col_types[$row_name], 'text') !== false || strpos($col_types[$row_name], 'char') !== false) {
                                                            $row_data = "'" . $row_data . "'";
                                                        }
                                                    }
                                                }
                                                $data[] = $row_data;
                                            }
                                            $sql_data .= 'INSERT INTO ' . $table_name . ' (' . implode(', ', $names) . ') VALUES (' . implode(', ', $data) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        break;
                                    case 'postgres':
                                        $ary_type = $ary_name = array();
                                        // Grab all of the data from current table.
                                        $sql = "SELECT *\n\t\t\t\t\t\t\t\t\t\t\tFROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        $i_num_fields = pg_num_fields($result);
                                        $seq = '';
                                        for ($i = 0; $i < $i_num_fields; $i++) {
                                            $ary_type[$i] = pg_field_type($result, $i);
                                            $ary_name[$i] = pg_field_name($result, $i);
                                            $sql = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault\n\t\t\t\t\t\t\t\t\t\t\t\tFROM pg_attrdef d, pg_class c\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE (c.relname = '{$table_name}')\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND (c.oid = d.adrelid)\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.adnum = " . strval($i + 1);
                                            $result2 = $db->sql_query($sql);
                                            if ($row = $db->sql_fetchrow($result2)) {
                                                // Determine if we must reset the sequences
                                                if (strpos($row['rowdefault'], 'nextval(\'') === 0) {
                                                    $seq .= "SELECT SETVAL('{$table_name}_seq',(select case when max({$ary_name[$i]})>0 then max({$ary_name[$i]})+1 else 1 end from {$table_name}));\n";
                                                }
                                            }
                                        }
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $schema_vals = $schema_fields = array();
                                            // Build the SQL statement to recreate the data.
                                            for ($i = 0; $i < $i_num_fields; $i++) {
                                                $str_val = $row[$ary_name[$i]];
                                                if (preg_match('#char|text|bool#i', $ary_type[$i])) {
                                                    $str_quote = "'";
                                                    $str_empty = '';
                                                    $str_val = addslashes($str_val);
                                                } else {
                                                    if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                                                        if (empty($str_val)) {
                                                            $str_quote = '';
                                                        } else {
                                                            $str_quote = "'";
                                                        }
                                                    } else {
                                                        $str_quote = '';
                                                        $str_empty = 'NULL';
                                                    }
                                                }
                                                if (empty($str_val) && $str_val !== '0') {
                                                    $str_val = $str_empty;
                                                }
                                                $schema_vals[$i] = $str_quote . $str_val . $str_quote;
                                                $schema_fields[$i] = $ary_name[$i];
                                            }
                                            // Take the ordered fields and their associated data and build it
                                            // into a valid sql statement to recreate that field in the data.
                                            $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES(' . implode(', ', $schema_vals) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        // Write out the sequence statements
                                        if ($store == true) {
                                            $write($fp, $seq);
                                        }
                                        if ($download == true) {
                                            if (!empty($oper)) {
                                                echo $oper($seq);
                                            } else {
                                                echo $seq;
                                            }
                                        }
                                        $seq = '';
                                        break;
                                    case 'mssql_odbc':
                                        $ary_type = $ary_name = array();
                                        $ident_set = false;
                                        // Grab all of the data from current table.
                                        $sql = "SELECT *\n\t\t\t\t\t\t\t\t\t\t\tFROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        $retrieved_data = odbc_num_rows($result);
                                        if ($retrieved_data) {
                                            $sql = "SELECT 1 as has_identity\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM INFORMATION_SCHEMA.COLUMNS\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE COLUMNPROPERTY(object_id('{$table_name}'), COLUMN_NAME, 'IsIdentity') = 1";
                                            $result2 = $db->sql_query($sql);
                                            $row2 = $db->sql_fetchrow($result2);
                                            if (!empty($row2['has_identity'])) {
                                                $sql_data .= "\nSET IDENTITY_INSERT {$table_name} ON\nGO\n";
                                                $ident_set = true;
                                            }
                                            $db->sql_freeresult($result2);
                                        }
                                        $i_num_fields = odbc_num_fields($result);
                                        for ($i = 0; $i < $i_num_fields; $i++) {
                                            $ary_type[$i] = odbc_field_type($result, $i);
                                            $ary_name[$i] = odbc_field_name($result, $i);
                                        }
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $schema_vals = $schema_fields = array();
                                            // Build the SQL statement to recreate the data.
                                            for ($i = 0; $i < $i_num_fields; $i++) {
                                                $str_val = $row[$ary_name[$i]];
                                                if (preg_match('#char|text|bool#i', $ary_type[$i])) {
                                                    $str_quote = "'";
                                                    $str_empty = '';
                                                    $str_val = addslashes($str_val);
                                                } else {
                                                    if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                                                        if (empty($str_val)) {
                                                            $str_quote = '';
                                                        } else {
                                                            $str_quote = "'";
                                                        }
                                                    } else {
                                                        $str_quote = '';
                                                        $str_empty = 'NULL';
                                                    }
                                                }
                                                if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val))) {
                                                    $str_val = $str_empty;
                                                }
                                                $schema_vals[$i] = $str_quote . $str_val . $str_quote;
                                                $schema_fields[$i] = $ary_name[$i];
                                            }
                                            // Take the ordered fields and their associated data and build it
                                            // into a valid sql statement to recreate that field in the data.
                                            $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES(' . implode(', ', $schema_vals) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        if ($retrieved_data) {
                                            $sql_data = "\nGO\n";
                                            if ($ident_set) {
                                                $sql_data .= "\nSET IDENTITY_INSERT {$table_name} OFF\nGO\n";
                                            }
                                        }
                                        break;
                                    case 'mssql':
                                        $ary_type = $ary_name = array();
                                        $ident_set = false;
                                        // Grab all of the data from current table.
                                        $sql = "SELECT *\n\t\t\t\t\t\t\t\t\t\t\tFROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        $retrieved_data = mssql_num_rows($result);
                                        $i_num_fields = mssql_num_fields($result);
                                        for ($i = 0; $i < $i_num_fields; $i++) {
                                            $ary_type[$i] = mssql_field_type($result, $i);
                                            $ary_name[$i] = mssql_field_name($result, $i);
                                        }
                                        if ($retrieved_data) {
                                            $sql = "SELECT 1 as has_identity\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM INFORMATION_SCHEMA.COLUMNS\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE COLUMNPROPERTY(object_id('{$table_name}'), COLUMN_NAME, 'IsIdentity') = 1";
                                            $result2 = $db->sql_query($sql);
                                            $row2 = $db->sql_fetchrow($result2);
                                            if (!empty($row2['has_identity'])) {
                                                $sql_data .= "\nSET IDENTITY_INSERT {$table_name} ON\nGO\n";
                                                $ident_set = true;
                                            }
                                            $db->sql_freeresult($result2);
                                        }
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $schema_vals = $schema_fields = array();
                                            // Build the SQL statement to recreate the data.
                                            for ($i = 0; $i < $i_num_fields; $i++) {
                                                $str_val = $row[$ary_name[$i]];
                                                if (preg_match('#char|text|bool#i', $ary_type[$i])) {
                                                    $str_quote = "'";
                                                    $str_empty = '';
                                                    $str_val = addslashes($str_val);
                                                } else {
                                                    if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                                                        if (empty($str_val)) {
                                                            $str_quote = '';
                                                        } else {
                                                            $str_quote = "'";
                                                        }
                                                    } else {
                                                        $str_quote = '';
                                                        $str_empty = 'NULL';
                                                    }
                                                }
                                                if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val))) {
                                                    $str_val = $str_empty;
                                                }
                                                $schema_vals[$i] = $str_quote . $str_val . $str_quote;
                                                $schema_fields[$i] = $ary_name[$i];
                                            }
                                            // Take the ordered fields and their associated data and build it
                                            // into a valid sql statement to recreate that field in the data.
                                            $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES(' . implode(', ', $schema_vals) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        if ($retrieved_data) {
                                            $sql_data = "\nGO\n";
                                            if ($ident_set) {
                                                $sql_data .= "\nSET IDENTITY_INSERT {$table_name} OFF\nGO\n";
                                            }
                                        }
                                        break;
                                    case 'firebird':
                                        $ary_type = $ary_name = array();
                                        // Grab all of the data from current table.
                                        $sql = "SELECT *\n\t\t\t\t\t\t\t\t\t\t\tFROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        $i_num_fields = ibase_num_fields($result);
                                        for ($i = 0; $i < $i_num_fields; $i++) {
                                            $info = ibase_field_info($result, $i);
                                            $ary_type[$i] = $info['type'];
                                            $ary_name[$i] = $info['name'];
                                        }
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $schema_vals = $schema_fields = array();
                                            // Build the SQL statement to recreate the data.
                                            for ($i = 0; $i < $i_num_fields; $i++) {
                                                $str_val = $row[strtolower($ary_name[$i])];
                                                if (preg_match('#char|text|bool#i', $ary_type[$i])) {
                                                    $str_quote = "'";
                                                    $str_empty = '';
                                                    $str_val = addslashes($str_val);
                                                } else {
                                                    if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                                                        if (empty($str_val)) {
                                                            $str_quote = '';
                                                        } else {
                                                            $str_quote = "'";
                                                        }
                                                    } else {
                                                        $str_quote = '';
                                                        $str_empty = 'NULL';
                                                    }
                                                }
                                                if (empty($str_val) && $str_val !== '0') {
                                                    $str_val = $str_empty;
                                                }
                                                $schema_vals[$i] = $str_quote . $str_val . $str_quote;
                                                $schema_fields[$i] = "'" . $ary_name[$i] . "'";
                                            }
                                            // Take the ordered fields and their associated data and build it
                                            // into a valid sql statement to recreate that field in the data.
                                            $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES(' . implode(', ', $schema_vals) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        break;
                                    case 'oracle':
                                        $ary_type = $ary_name = array();
                                        // Grab all of the data from current table.
                                        $sql = "SELECT *\n\t\t\t\t\t\t\t\t\t\t\tFROM {$table_name}";
                                        $result = $db->sql_query($sql);
                                        $i_num_fields = ocinumcols($result);
                                        for ($i = 0; $i < $i_num_fields; $i++) {
                                            $ary_type[$i] = ocicolumntype($result, $i);
                                            $ary_name[$i] = ocicolumnname($result, $i);
                                        }
                                        while ($row = $db->sql_fetchrow($result)) {
                                            $schema_vals = $schema_fields = array();
                                            // Build the SQL statement to recreate the data.
                                            for ($i = 0; $i < $i_num_fields; $i++) {
                                                $str_val = $row[$ary_name[$i]];
                                                if (preg_match('#char|text|bool#i', $ary_type[$i])) {
                                                    $str_quote = "'";
                                                    $str_empty = '';
                                                    $str_val = addslashes($str_val);
                                                } else {
                                                    if (preg_match('#date|timestamp#i', $ary_type[$i])) {
                                                        if (empty($str_val)) {
                                                            $str_quote = '';
                                                        } else {
                                                            $str_quote = "'";
                                                        }
                                                    } else {
                                                        $str_quote = '';
                                                        $str_empty = 'NULL';
                                                    }
                                                }
                                                if (empty($str_val) && $str_val !== '0') {
                                                    $str_val = $str_empty;
                                                }
                                                $schema_vals[$i] = $str_quote . $str_val . $str_quote;
                                                $schema_fields[$i] = '"' . $ary_name[$i] . "'";
                                            }
                                            // Take the ordered fields and their associated data and build it
                                            // into a valid sql statement to recreate that field in the data.
                                            $sql_data .= "INSERT INTO {$table_name} (" . implode(', ', $schema_fields) . ') VALUES(' . implode(', ', $schema_vals) . ");\n";
                                            if ($store == true) {
                                                $write($fp, $sql_data);
                                            }
                                            if ($download == true) {
                                                if (!empty($oper)) {
                                                    echo $oper($sql_data);
                                                } else {
                                                    echo $sql_data;
                                                }
                                            }
                                            $sql_data = '';
                                        }
                                        $db->sql_freeresult($result);
                                        break;
                                }
                            }
                        }
                        switch (SQL_LAYER) {
                            case 'sqlite':
                            case 'postgres':
                                $sql_data .= "COMMIT;";
                                break;
                            case 'mssql':
                            case 'mssql_odbc':
                                $sql_data .= "COMMIT\nGO";
                                break;
                        }
                        if ($store == true) {
                            $write($fp, $sql_data);
                            $close($fp);
                        }
                        if ($download == true) {
                            if (!empty($oper)) {
                                echo $oper($sql_data);
                            } else {
                                echo $sql_data;
                            }
                            exit;
                        }
                        unset($sql_data);
                        add_log('admin', 'LOG_DB_BACKUP');
                        trigger_error($user->lang['BACKUP_SUCCESS']);
                        break;
                    default:
                        $tables = array();
                        switch (SQL_LAYER) {
                            case 'sqlite':
                                $sql = "SELECT name\n\t\t\t\t\t\t\t\t\tFROM sqlite_master\n\t\t\t\t\t\t\t\t\tWHERE type='table'\n\t\t\t\t\t\t\t\t\tORDER BY name";
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (strpos($row['name'], $table_prefix) === 0) {
                                        $tables[] = $row['name'];
                                    }
                                }
                                $db->sql_freeresult($result);
                                break;
                            case 'mysqli':
                            case 'mysql4':
                            case 'mysql':
                                $sql = "SHOW TABLES\n\t\t\t\t\t\t\t\t\tLIKE '{$table_prefix}%'";
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    $tables[] = current($row);
                                }
                                $db->sql_freeresult($result);
                                break;
                            case 'postgres':
                                $sql = "SELECT relname\n\t\t\t\t\t\t\t\t\tFROM pg_stat_user_tables\n\t\t\t\t\t\t\t\t\tORDER BY relname;";
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (strpos($row['relname'], $table_prefix) === 0) {
                                        $tables[] = $row['relname'];
                                    }
                                }
                                $db->sql_freeresult($result);
                                break;
                            case 'mssql':
                            case 'mssql_odbc':
                                $sql = "SELECT TABLE_NAME\n\t\t\t\t\t\t\t\t\tFROM INFORMATION_SCHEMA.TABLES\n\t\t\t\t\t\t\t\t\tWHERE TABLE_TYPE = 'BASE TABLE'\n\t\t\t\t\t\t\t\t\tORDER BY TABLE_NAME";
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (strpos($row['TABLE_NAME'], $table_prefix) === 0) {
                                        $tables[] = $row['TABLE_NAME'];
                                    }
                                }
                                $db->sql_freeresult($result);
                                break;
                            case 'firebird':
                                $sql = 'SELECT RDB$RELATION_NAME as TABLE_NAME
									FROM RDB$RELATIONS
									WHERE RDB$SYSTEM_FLAG=0
										AND RDB$VIEW_BLR IS NULL';
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (stripos($row['table_name'], $table_prefix) === 0) {
                                        $tables[] = $row['table_name'];
                                    }
                                }
                                $db->sql_freeresult($result);
                                break;
                            case 'oracle':
                                $sql = 'SELECT TNAME as table_name
									FROM TAB';
                                $result = $db->sql_query($sql);
                                while ($row = $db->sql_fetchrow($result)) {
                                    if (stripos($row['table_name'], $table_prefix) === 0) {
                                        $tables[] = $row['table_name'];
                                    }
                                }
                                $db->sql_freeresult($result);
                                break;
                        }
                        foreach ($tables as $table) {
                            $template->assign_block_vars('tables', array('TABLE' => $table));
                        }
                        $template->assign_vars(array('U_ACTION' => $this->u_action . '&amp;action=download'));
                        $available_methods = array('gzip' => 'zlib', 'bzip2' => 'bz2');
                        foreach ($available_methods as $type => $module) {
                            if (!@extension_loaded($module)) {
                                continue;
                            }
                            $template->assign_block_vars('methods', array('TYPE' => $type));
                        }
                        $template->assign_block_vars('methods', array('TYPE' => 'text'));
                        break;
                }
                break;
            case 'restore':
                switch ($action) {
                    case 'submit':
                        $delete = request_var('delete', '');
                        $file = request_var('file', '');
                        preg_match('#^(\\d{10})\\.(sql(?:\\.(?:gz|bz2))?)$#', $file, $matches);
                        $file_name = $phpbb_root_path . 'store/' . $matches[0];
                        if (!(file_exists($file_name) && is_readable($file_name))) {
                            trigger_error($user->lang['BACKUP_INVALID']);
                        }
                        if ($delete) {
                            unlink($file_name);
                            trigger_error($user->lang['BACKUP_DELETE']);
                        }
                        $data = file_get_contents($file_name);
                        switch ($matches[2]) {
                            case 'sql.bz2':
                                $data = bzdecompress($data);
                                break;
                            case 'sql.gz':
                                $data = gzinflate(substr($data, 10));
                                break;
                        }
                        $download = request_var('download', '');
                        if ($download) {
                            $name = $matches[0];
                            switch ($matches[2]) {
                                case 'sql':
                                    $mimetype = 'text/x-sql';
                                    break;
                                case 'sql.bz2':
                                    $mimetype = 'application/x-bzip2';
                                    break;
                                case 'sql.gz':
                                    $mimetype = 'application/x-gzip';
                                    break;
                            }
                            header('Pragma: no-cache');
                            header("Content-Type: {$mimetype}; name=\"{$name}\"");
                            header("Content-disposition: attachment; filename={$name}");
                            echo $data;
                            die;
                        }
                        if (!empty($data)) {
                            // Strip out sql comments...
                            remove_remarks($data);
                            switch (SQL_LAYER) {
                                case 'firebird':
                                    $delim = ';;';
                                    break;
                                case 'mysql':
                                case 'mysql4':
                                case 'mysqli':
                                case 'sqlite':
                                case 'postgres':
                                    $delim = ';';
                                    break;
                                case 'oracle':
                                    $delim = '/';
                                    break;
                                case 'mssql':
                                case 'mssql-odbc':
                                    $delim = 'GO';
                                    break;
                            }
                            $pieces = split_sql_file($data, $delim);
                            $sql_count = count($pieces);
                            for ($i = 0; $i < $sql_count; $i++) {
                                $sql = trim($pieces[$i]);
                                if (!empty($sql) && $sql[0] != '#') {
                                    $db->sql_query($sql);
                                }
                            }
                        }
                        add_log('admin', 'LOG_DB_RESTORE');
                        trigger_error($user->lang['RESTORE_SUCCESS']);
                        break;
                    default:
                        $selected = false;
                        $methods = array('sql');
                        $available_methods = array('sql.gz' => 'zlib', 'sql.bz2' => 'bz2');
                        foreach ($available_methods as $type => $module) {
                            if (!@extension_loaded($module)) {
                                continue;
                            }
                            $methods[] = $type;
                        }
                        $dir = $phpbb_root_path . 'store/';
                        $dh = opendir($dir);
                        while (($file = readdir($dh)) !== false) {
                            if (preg_match('#^(\\d{10})\\.(sql(?:\\.(?:gz|bz2))?)$#', $file, $matches)) {
                                $supported = in_array($matches[2], $methods);
                                if ($supported == 'true') {
                                    $template->assign_block_vars('files', array('FILE' => $file, 'NAME' => gmdate("d-m-Y H:i:s", $matches[1]), 'SUPPORTED' => $supported));
                                    $selected = true;
                                }
                            }
                        }
                        closedir($dh);
                        if ($selected === true) {
                            $template->assign_var('EXISTS', true);
                        }
                        $template->assign_vars(array('U_ACTION' => $this->u_action . '&amp;action=submit'));
                        break;
                }
                break;
        }
    }
Exemplo n.º 18
0
 function query($query)
 {
     $query = trim($query);
     $query = str_replace('`', "'", $query);
     $query = str_replace('\\012', "\n", $query);
     $query = str_replace('\\015', "\r", $query);
     //$query = str_replace("\n",'',$query);
     //$query = str_replace("\r",'',$query);
     //$query = $this->escape($query);
     //$query = str_replace('"','\"',$query);
     //$query = str_replace("'","\'",$query);
     if (substr($query, 0, 7) == 'SELECT ') {
         dbug($query, 'SELECT : ORIGINAL QUERY ::::::: ', 'orange');
         $query_arr = explode('LIMIT', $query);
         if ($query_arr[0] and $query_arr[1]) {
             $query_one = str_replace('SELECT ', '', $query_arr[0]);
             $top_arr = explode(' ', $query_arr[1]);
             if ($top_arr[1] && $top_arr[2]) {
                 $query = 'SELECT TOP ' . $top_arr[2] . ' ' . $query_one;
             } else {
                 $query = 'SELECT TOP ' . $top_arr[1] . ' ' . $query_one;
             }
             /*
             // TO BE DEVELOP 
             //LIMIT 1, 3
             
             					SELECT * FROM (
             						SELECT TOP 3 * FROM
             							(SELECT TOP (1+3) * FROM wp_posts WHERE 1=1 AND post_type = 'post' AND (post_status = 'publish' OR post_status = 'private') ORDER BY post_date DESC)
             						AS table1 ORDER BY post_date ASC
             					) AS table2  ORDER BY post_date DESC					
             */
             //pre($query_arr);
             //exit();
         }
         if (substr($query, 0, 23) == "SELECT TOP 1 comment_ID") {
             $query = str_replace(' = ', ' = ', $query);
         }
         /* DUMP DIRTY SWEPT TEST */
         $query = str_replace('wp_posts.', '', $query);
         /*
         hacks for query;
         - SELECT * FROM wp_posts WHERE (post_type = 'page' AND post_status = 'publish') ORDER BY menu_order, post_title ASC
         - SELECT * FROM wp_posts WHERE 1=1 AND post_type = 'page' AND (post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'pending' OR post_status = 'private') ORDER BY menu_order,post_title asc
         notes;
         somehow Wordpress developer create this 'post_title' date-type as 'text' in database. the post_title should be varchar since the amount of character in title is generally less then 255 char.
         and in ms-sql, text cannot be sorted. so this is a big mistake. haihhh...
         */
         $pattern = '/post_title asc/is';
         $replacement = 'cast(post_title as varchar(500)) ASC';
         $query = preg_replace($pattern, $replacement, $query);
         /*
         hacks for query;
         - SELECT DISTINCT  YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM wp_posts WHERE post_type = 'post' ORDER BY post_date DESC
         notes;
         this is one another hacks for SELECT DISTINCT call. 
         The above query tries to sort by the column post_date. Because the keyword DISTINCT is also specified, column post_date must appear in the SELECT list
         expected return;
          - SELECT DISTINCT  post_date, YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM wp_posts WHERE post_type = 'post' ORDER BY post_date DESC
         */
         if (substr($query, 0, 15) == "SELECT DISTINCT") {
             $string = $query;
             $pattern = '/SELECT DISTINCT (.*)? ORDER BY (.*)? (asc|desc)/i';
             $replacement = 'cast(post_title as varchar(500)) ASC';
             preg_match_all($pattern, $string, $result);
             $order_by_col = $result[2][0];
             $col_calls = $result[1][0];
             $order_by_prop = $result[3][0];
             $query = 'SELECT DISTINCT ' . $order_by_col . ', ' . $col_calls . ' ORDER BY ' . $order_by_col . ' ' . $order_by_prop;
         }
         /*
         hacks for query;
         - SELECT user_id FROM wp_usermeta WHERE meta_key = 'wp_user_level' AND meta_value != '0'
         notes;
         replace != into NOT <col_name> LIKE
         expected return;
         - SELECT user_id FROM wp_usermeta WHERE meta_key = 'wp_user_level' AND NOT meta_value LIKE '0'
         */
         $pattern = "/ (?:[a-z][a-z0-9_]*)? \\!\\= /is";
         preg_match_all($pattern, $query, $result);
         $result_arr = $result[0];
         $query = str_replace('!=', '', $query);
         foreach ($result_arr as $result_item) {
             $result_item = str_replace('!=', '', $result_item);
             $result_item = trim($result_item);
             $query = str_replace($result_item, ' NOT ' . $result_item . ' LIKE ', $query);
         }
         /*
         hacks for;
         - SQL have 'GROUP BY'
         - SELECT DISTINCT post_date, YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish
         GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC
         */
         if (preg_match("/GROUP BY/i", $query)) {
             $pattern = '/SELECT (.*) GROUP BY (.*)? ORDER BY (.*)/i';
             preg_match($pattern, $string, $output);
             $query0 = 'SELECT ' . $output[1] . ' ORDER BY ' . $output[3];
         }
         $query = str_replace('SQL_CALC_FOUND_ROWS', ' ', $query);
         if (preg_match("/SELECT FOUND_ROWS()/i", $query)) {
             $last_query = $this->last_query;
             $last_query_one_arr = explode('TOP', $last_query);
             $last_query_two = trim($last_query_one_arr[1]);
             $last_query_three_arr = explode(' ', $last_query_two);
             $last_query_four = str_replace($last_query_three_arr[0], '', $last_query_two);
             $query = 'SELECT ' . $last_query_four;
         }
         dbug($query, 'SELECT : MODDED QUERY :::::::: ', 'orange');
     } elseif (substr($query, 0, 7) == 'INSERT ') {
         dbug($query, 'INSERT : ORIGINAL QUERY ::::::::: ', 'purple');
         $pattern = '/INSERT INTO (.*)?\\((.*)\\).*?VALUES.*?\\((.*)\\)/is';
         preg_match_all($pattern, $query, $output);
         $insert_table = trim($output[1][0]);
         $insert_cols = trim($output[2][0]);
         $insert_values = trim($output[3][0]);
         /* STRIP QUOTE FROM COLS NAME */
         $insert_cols = str_replace("'", '', $insert_cols);
         $query = $this->prepare($query);
         /* PROCESS THE $insert_values. NEED TO REPLACE THE INNER QUOTES */
         preg_match_all("/([0-9]+|\\'(.*?)\\'[ ]*?),/is", $insert_values . ',', $output);
         $insert_values_arr = array();
         //PREPARE THE NEW FRESH VALUES
         foreach ($output[0] as $insert_values_item) {
             if (substr(trim($insert_values_item), 0, 1) == "'") {
                 $insert_values_item = substr($insert_values_item, 1);
                 // TAKE OUT THE FIRST 1 CHAR, WHICH IS QUOTE
             }
             $insert_values_item = trim($insert_values_item);
             // TRIM THE WHITESPACE
             if (substr(trim($insert_values_item), -1) == ",") {
                 $insert_values_item = substr($insert_values_item, 0, -1);
                 // TAKE OUT THE LAST 1 CHAR, WHICH IS COMMA
             }
             if (substr(trim($insert_values_item), -1) == "'") {
                 $insert_values_item = substr($insert_values_item, 0, -1);
                 // TAKE OUT THE LAST 1 CHAR, WHICH IS QUOTE
             }
             $insert_values_item = str_replace("'", "''", $insert_values_item);
             // NOW WE PUT THE EXTRA QUOTE ON IT
             $insert_values_item = trim($insert_values_item);
             // TRIM THE WHITESPACE
             $insert_values_item = "'" . $insert_values_item . "'";
             // WRAP THE VALUES WITH OUR SINGLE-QUOTE
             $insert_values_arr[] = $insert_values_item;
         }
         $insert_values = implode(',', $insert_values_arr);
         /* CONSTRUCT NEW INSERT CALL */
         $query = 'INSERT INTO ' . $insert_table . ' (' . $insert_cols . ') VALUES (' . $insert_values . ');';
         dbug($query, 'INSERT : MODDED QUERY :::::::::: ', 'purple');
     } elseif (substr($query, 0, 7) == 'UPDATE ') {
         dbug($query, 'UPDATE : ORIGINAL QUERY ::::::::: ', 'blue');
         $pattern = '/UPDATE ([A-Za-z0-9_-]+) SET (.*)? WHERE (.*)?/is';
         preg_match_all($pattern, $query, $output);
         $update_table = trim($output[1][0]);
         $update_values = trim($output[2][0]);
         $update_where = trim($output[3][0]);
         preg_match_all("/(.*?)[ *]?=[ *]?(\\'(.*?)\\'|[0-9]+),/is", $update_values . ',', $output_vals);
         $update_vals_colname = $output_vals[1];
         $update_vals_values = $output_vals[2];
         $update_vals_colname_mod = array();
         foreach ($update_vals_colname as $update_vals_colname_item) {
             $update_vals_colname_item = str_replace("'", '', $update_vals_colname_item);
             // GREEDY REPLACE ALL QUOTES. NO QUOTES ALLOWED IN COL NAME
             $update_vals_colname_item = trim($update_vals_colname_item);
             // TRIM THE WHITESPACE
             $update_vals_colname_mod[] = $update_vals_colname_item;
         }
         $update_vals_values_mod = array();
         foreach ($update_vals_values as $update_vals_values_item) {
             if (substr(trim($update_vals_values_item), 0, 1) == "'") {
                 $update_vals_values_item = substr($update_vals_values_item, 1);
                 // TAKE OUT THE FIRST 1 CHAR, WHICH IS QUOTE
             }
             if (substr(trim($update_vals_values_item), -1) == "'") {
                 $update_vals_values_item = substr($update_vals_values_item, 0, -1);
                 // TAKE OUT THE LAST 1 CHAR, WHICH IS QUOTE
             }
             $update_vals_values_item = trim($update_vals_values_item);
             // TRIM THE WHITESPACE
             $update_vals_values_item = str_replace("'", "''", $update_vals_values_item);
             // ADD ADDITIONAL QUOTE TO  ESCAPE IT IN MSSQL
             $update_vals_values_mod[] = $update_vals_values_item;
         }
         $update_values_modded = array_combine($update_vals_colname_mod, $update_vals_values_mod);
         $update_values = '';
         $update_values_prepare_arr = '';
         $update_values_item = '';
         foreach ($update_values_modded as $update_values_item_colname => $update_values_item_value) {
             $update_values_prepare_arr[] = $update_values_item_colname . " = '" . $update_values_item_value . "'";
         }
         $update_values = implode(',', $update_values_prepare_arr);
         /* CONSTRUCT NEW UPDATE CALL */
         $query = 'UPDATE ' . $update_table . ' SET ' . $update_values . ' WHERE ' . $update_where . ';';
         dbug($query, 'UPDATE : MODDED QUERY :::::::::: ', 'blue');
     } elseif (substr($query, 0, 7) == 'DELETE ') {
         dbug($query, 'DELETE', 'orange');
     } elseif (substr($query, 0, 7) == 'CREATE ') {
         $query_two = str_replace('auto_increment', 'IDENTITY(1,1)', $query);
         $query_two = str_replace('tinytext', 'text', $query_two);
         $query_two = str_replace('longtext', 'text', $query_two);
         $query_two = str_replace('mediumtext', 'text', $query_two);
         $query_two = str_replace('unsigned ', '', $query_two);
         $query_three = preg_replace('/bigint\\(\\d+\\)/i', 'int', $query_two);
         $query_three = preg_replace('/int\\(\\d+\\)/i', 'int', $query_three);
         $query_four_arr = explode('PRIMARY KEY', $query_three);
         $query_five = $query_four_arr[0] . ' ';
         $query_six = $query_four_arr[1];
         $query_seven_arr = explode('),', $query_six);
         $query_eight_arr = explode('(', $query);
         $query_nine = trim($query_eight_arr[0]);
         $query_ten = str_replace($query_nine, '', $query_five);
         $table_name = trim(str_replace('CREATE TABLE', '', $query_nine));
         $create_table_header = "\t\t\t\t\nIF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[tretinoin_wpuser].[" . $table_name . "]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)\n    DROP TABLE [tretinoin_wpuser].[" . $table_name . "]\nGO\nCREATE TABLE [tretinoin_wpuser].[" . $table_name . "]";
         $create_table_header_simple = "CREATE TABLE [tretinoin_wpuser].[" . $table_name . "]\t\t\t\n\t\t\t\t\n\t\t\t\t";
         $query = $create_table_header_simple . $query_ten . ' PRIMARY KEY ' . $query_seven_arr[0] . '))';
         dbug($query, 'CREATE', 'purple');
     } elseif (substr($query, 0, 5) == 'SHOW ') {
         $query = str_replace('SHOW TABLES;', '', $query);
         dbug($query, 'SHOW', 'yellow');
     } else {
         dbug($query);
     }
     // For reg expressions
     $query = trim($query);
     // Flush cached values..
     $this->flush();
     // Log how the function was called
     $this->func_call = "\$db->query(\"{$query}\")";
     // Keep track of the last query for debug..
     $this->last_query = $query;
     // Perform the query via std mssql_query function..
     if (substr($query, 0, 7) == 'SELECT ') {
         $this->result_check = @mssql_query($query, $this->dbh);
     } elseif (substr($query, 0, 7) == 'INSERT ') {
     } elseif (substr($query, 0, 7) == 'UPDATE ') {
         $this->result_check = @mssql_query($query, $this->dbh);
     } elseif (substr($query, 0, 7) == 'DELETE ') {
     } elseif (substr($query, 0, 7) == 'CREATE ') {
     } elseif (substr($query, 0, 5) == 'SHOW ') {
     }
     // Unfortunately, PHP fuctions for MS SQL currently don't offer a decent way
     // to retrieve errors from MS SQL
     // Make sure not to run a query between the actual query and this one !
     $get_errorcode = "SELECT @@ERROR as errorcode";
     $error_res = @mssql_query($get_errorcode, $this->dbh);
     $errorcode = @mssql_result($error_res, 0, "errorcode");
     // ERROR LIST
     // 402 : The data types text and varchar are incompatible in the equal to operator.
     // 306 : The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
     if ($errorcode == '402') {
         $query_two = str_replace(' = ', ' LIKE ', $query);
         /* NEED MORE IMPROVEMENT HERE */
     } else {
         $query_two = $query;
     }
     dbug($query, $errorcode, 'green');
     $this->result = @mssql_query($query_two, $this->dbh);
     $this->num_queries++;
     // If there was an insert, delete or update see how many rows were affected
     // (Also, If there there was an insert take note of the last OID
     $query_type = array("insert", "delete", "update", "replace");
     // loop through the above array
     foreach ($query_type as $word) {
         // This is true if the query starts with insert, delete or update
         if (preg_match("/^{$word}\\s+/i", $query)) {
             $this->rows_affected = @mssql_rows_affected($this->dbh);
             // This gets the insert ID
             if ($word == "insert" || $word == "replace") {
                 $get_last_ident = "SELECT @@IDENTITY as id";
                 $last_res = @mssql_query($get_last_ident, $this->dbh);
                 $this->insert_id = @mssql_result($last_res, 0, "id");
                 // If insert id then return it - true evaluation
                 return $this->insert_id;
             }
             // Set to false if there was no insert id
             $this->result = false;
         }
     }
     if ($errorcode != 0) {
         // there is an error
         $this->print_error();
     } else {
         // =======================================================
         // Take note of column info
         $i = 0;
         while ($i < @mssql_num_fields($this->result)) {
             $this->col_info[$i]->name = @mssql_field_name($this->result, $i);
             $this->col_info[$i]->type = @mssql_field_type($this->result, $i);
             $this->col_info[$i]->size = @mssql_field_length($this->result, $i);
             $i++;
         }
         // =======================================================
         // Store Query Results
         $i = 0;
         while ($row_arr = @mssql_fetch_array($this->result)) {
             $row = array_to_object($row_arr);
             $this->last_result[$i] = $row;
             // Store relults as an objects within main array
             $i++;
         }
         if ($i == 0) {
             $this->last_result = array();
         }
         //pre($this->last_result);
         // Log number of rows the query returned
         $this->num_rows = $i;
         //}
         @mssql_free_result($this->result);
         // If this was a select..
         if (preg_match("/^(select|show|desc)\\s+/i", $query)) {
             // If debug ALL queries
             $this->debug_all ? $this->debug() : null;
             // If there were results then return true for $db->query
             if ($i) {
                 return true;
             } else {
                 return false;
             }
         } else {
             // If debug ALL queries
             $this->debug_all ? $this->debug() : null;
             // Update insert etc. was good..
             return true;
         }
     }
 }
Exemplo n.º 19
0
 function sql_fieldtype($offset, $query_id = 0)
 {
     if (!$query_id) {
         $query_id = $this->result;
     }
     return $query_id ? @mssql_field_type($query_id, $offset) : false;
 }
Exemplo n.º 20
0
 function sql_fieldtype($offset, $query_id = 0)
 {
     $mtime = microtime();
     $mtime = explode(" ", $mtime);
     $mtime = $mtime[1] + $mtime[0];
     $starttime = $mtime;
     if (!$query_id) {
         $query_id = $this->result;
     }
     $mtime = microtime();
     $mtime = explode(" ", $mtime);
     $mtime = $mtime[1] + $mtime[0];
     $endtime = $mtime;
     $this->sql_time += $endtime - $starttime;
     return $query_id ? @mssql_field_type($query_id, $offset) : false;
 }
Exemplo n.º 21
0
 public function table_info($table)
 {
     if ($table) {
         $this->result = mssql_query("select * from {$table}");
         $this->query = "select * from {$table}";
         $fields = mssql_num_fields($this->result);
         $rows = mssql_num_rows($this->result);
         $table = mssql_field_table($this->result, 0);
         print "\tThe '<strong>" . $table . "</strong>' table has <strong>" . $fields . "</strong> fields and <strong>" . $rows . "</strong>\n\t\t\t\t\t\trecord(s) with following fields.\n<br /><ul>";
         for ($i = 0; $i < $fields; $i++) {
             $type = mssql_field_type($this->result, $i);
             $name = mssql_field_name($this->result, $i);
             $len = mssql_field_len($this->result, $i);
             $flags = mssql_field_flags($this->result, $i);
             print "<strong><li>" . $type . " " . $name . " " . $len . " " . $flags . "</strong></li>\n";
         }
         print "</ul>";
     } else {
         print "The table not specified !!";
     }
 }
Exemplo n.º 22
0
 function query($query)
 {
     //去掉查询语句的前后空格
     $query = trim($query);
     //初始化返回值为0
     $return_val = 0;
     //清空缓存..
     $this->flush();
     //记录此函数如何被调用,用于调试...
     $this->func_call = "\$db->query(\"{$query}\")";
     //跟踪最后查询语句,用于调试..
     $this->last_query = $query;
     //通过mysql_query函数执行查询操作..
     $this->result = @mssql_query($query, $this->dbh);
     $this->num_queries++;
     //php现在还不支持从sqlserver服务器获取错误信息
     #这里以后要进行讨论,改进。
     $get_errorcode = "SELECT @@ERROR as errorcode";
     $error_res = @mssql_query($get_errorcode, $this->dbh);
     $errorcode = @mssql_result($error_res, 0, "errorcode");
     //执行insert, delete, update, replace操作
     if (preg_match("/^(insert|delete|update|replace)\\s+/i", $query)) {
         $this->rows_affected = @mssql_rows_affected($this->dbh);
         $return_val = $this->rows_affected;
         //获取操作所影响的记录行数
         if (preg_match("/^(insert|replace)\\s+/i", $query)) {
             $get_last_ident = "SELECT @@IDENTITY as id";
             $last_res = @mssql_query($get_last_ident, $this->dbh);
             $this->insert_id = @mssql_result($last_res, 0, "id");
             //$return_val = $this->insert_id;
         }
     }
     if ($errorcode != 0) {
         //如果有错误
         $this->print_error();
     } else {
         //获取字段信息
         $i = 0;
         while ($i < @mssql_num_fields($this->result)) {
             $this->col_info[$i]->name = @mssql_field_name($this->result, $i);
             $this->col_info[$i]->type = @mssql_field_type($this->result, $i);
             $this->col_info[$i]->size = @mssql_field_length($this->result, $i);
             $i++;
         }
         //获取查询结果
         $i = 0;
         while ($row = @mssql_fetch_object($this->result)) {
             //取得包含数组的结果对象
             $this->last_result[$i] = $row;
             $i++;
         }
         //获取查询结果行数
         $this->num_rows = $i;
         @mssql_free_result($this->result);
         //返回选中的结果行数
         $return_val = $this->num_rows;
     }
     //是否显示所有的查询信息
     $this->debug_all ? $this->debug() : null;
     return $return_val;
 }
Exemplo n.º 23
0
 /**
  * Returns information about a table or a result set
  *
  * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  * is a table name.
  *
  * @param object|string  $result  MDB2_result object from a query or a
  *                                 string containing the name of a table.
  *                                 While this also accepts a query result
  *                                 resource identifier, this behavior is
  *                                 deprecated.
  * @param int            $mode    a valid tableInfo mode
  *
  * @return array  an associative array with the information requested.
  *                 A MDB2_Error object on failure.
  *
  * @see MDB2_Driver_Common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     if (is_string($result)) {
         return parent::tableInfo($result, $mode);
     }
     $db =& $this->getDBInstance();
     if (PEAR::isError($db)) {
         return $db;
     }
     $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
     if (!is_resource($resource)) {
         return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'Could not generate result resource', __FUNCTION__);
     }
     if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
         if ($db->options['field_case'] == CASE_LOWER) {
             $case_func = 'strtolower';
         } else {
             $case_func = 'strtoupper';
         }
     } else {
         $case_func = 'strval';
     }
     $count = @mssql_num_fields($resource);
     $res = array();
     if ($mode) {
         $res['num_fields'] = $count;
     }
     $db->loadModule('Datatype', null, true);
     for ($i = 0; $i < $count; $i++) {
         $res[$i] = array('table' => '', 'name' => $case_func(@mssql_field_name($resource, $i)), 'type' => @mssql_field_type($resource, $i), 'length' => @mssql_field_length($resource, $i), 'flags' => '');
         $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
         if (PEAR::isError($mdb2type_info)) {
             return $mdb2type_info;
         }
         $res[$i]['mdb2type'] = $mdb2type_info[0][0];
         if ($mode & MDB2_TABLEINFO_ORDER) {
             $res['order'][$res[$i]['name']] = $i;
         }
         if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
             $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
         }
     }
     return $res;
 }
Exemplo n.º 24
0
 function FieldType($rsMain, $i)
 {
     return mssql_field_type($rsMain, $i);
 }
Exemplo n.º 25
0
 /**
  * Returns information about a table or a result set
  *
  * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  * is a table name.
  *
  * @param object|string  $result  DB_result object from a query or a
  *                                 string containing the name of a table.
  *                                 While this also accepts a query result
  *                                 resource identifier, this behavior is
  *                                 deprecated.
  * @param int            $mode    a valid tableInfo mode
  *
  * @return array  an associative array with the information requested.
  *                 A DB_Error object on failure.
  *
  * @see DB_common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     if (is_string($result)) {
         /*
          * Probably received a table name.
          * Create a result resource identifier.
          */
         if (!@mssql_select_db($this->_db, $this->connection)) {
             return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
         }
         $id = @mssql_query("SELECT * FROM {$result} WHERE 1=0", $this->connection);
         $got_string = true;
     } elseif (isset($result->result)) {
         /*
          * Probably received a result object.
          * Extract the result resource identifier.
          */
         $id = $result->result;
         $got_string = false;
     } else {
         /*
          * Probably received a result resource identifier.
          * Copy it.
          * Deprecated.  Here for compatibility only.
          */
         $id = $result;
         $got_string = false;
     }
     if (!is_resource($id)) {
         return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA);
     }
     if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
         $case_func = 'strtolower';
     } else {
         $case_func = 'strval';
     }
     $count = @mssql_num_fields($id);
     $res = array();
     if ($mode) {
         $res['num_fields'] = $count;
     }
     for ($i = 0; $i < $count; $i++) {
         if ($got_string) {
             $flags = $this->_mssql_field_flags($result, @mssql_field_name($id, $i));
             if (DB::isError($flags)) {
                 return $flags;
             }
         } else {
             $flags = '';
         }
         $res[$i] = array('table' => $got_string ? $case_func($result) : '', 'name' => $case_func(@mssql_field_name($id, $i)), 'type' => @mssql_field_type($id, $i), 'len' => @mssql_field_length($id, $i), 'flags' => $flags);
         if ($mode & DB_TABLEINFO_ORDER) {
             $res['order'][$res[$i]['name']] = $i;
         }
         if ($mode & DB_TABLEINFO_ORDERTABLE) {
             $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
         }
     }
     // free the result only if we were called on a table
     if ($got_string) {
         @mssql_free_result($id);
     }
     return $res;
 }
Exemplo n.º 26
0
 public function _Execute()
 {
     switch (strtoupper($this->dbdriver)) {
         case "POSTGRES":
             for ($i = 0; $i < $this->pNumRows; $i++) {
                 $this->pRow = pg_fetch_array($this->RecordSet);
                 for ($j = 0; $j < $this->pNumFields; $j++) {
                     $this->aRecords[$i][$j] = $this->pRow[$j];
                     if ($i == 0) {
                         $this->aFieldsName[$j] = pg_field_name($this->RecordSet, $j);
                         $this->aFieldsType[$j] = pg_field_type($this->RecordSet, $j);
                     }
                 }
             }
             break;
         case "MSSQL":
             if (trim($this->pFieldsSelect) != "" and trim($this->pFieldsSelect) != "*" and $this->pNameStoreProcedure) {
                 $sw = 1;
             }
             if ($this->pRowsPage != "ALL") {
                 $this->setTotalPages($this->pRowsPage);
                 $k = 0;
                 for ($i = 0; $i < $this->pNumRows; $i++) {
                     if ($k < $this->pRowsPage) {
                         break;
                     }
                     $this->pRow = mssql_fetch_array($this->RecordSet);
                     if ($i >= $this->pOffset and $k < $this->pRowsPage) {
                         if ($sw == 1) {
                             $m = 0;
                         }
                         for ($j = 0; $j < $this->pNumFields; $j++) {
                             if ($sw == 1) {
                                 $posicion = strpos($this->pFieldsSelect, mssql_field_name($this->RecordSet, $j));
                                 if ($posicion) {
                                     $this->aRecords[$k][$m] = $this->pRow[$j];
                                     if ($k == 0) {
                                         $this->aFieldsName[$m] = mssql_field_name($this->RecordSet, $j);
                                         $this->aFieldsType[$m] = mssql_field_type($this->RecordSet, $j);
                                         $m++;
                                     }
                                 }
                             } else {
                                 $this->aRecords[$k][$j] = $this->pRow[$j];
                                 if ($k == 0) {
                                     $this->aFieldsName[$j] = mssql_field_name($this->RecordSet, $j);
                                     $this->aFieldsType[$j] = mssql_field_type($this->RecordSet, $j);
                                 }
                                 $m = $j + 1;
                             }
                         }
                     }
                     $k++;
                 }
                 $this->pNumRows = $k;
                 $this->pNumFields = $m;
             } else {
                 $cont = 0;
                 for ($i = 0; $i < $this->pNumRows; $i++) {
                     $this->pRow = mssql_fetch_array($this->RecordSet);
                     $almacena_reg = 0;
                     if (count($this->pParamFilterField) > 0) {
                         switch ($this->pParamFilterType[0]) {
                             case '=':
                                 if (trim($this->pRow[$this->pParamFilterField[0]]) == trim($this->pParamFilterValue1[0])) {
                                     $almacena_reg = 1;
                                 }
                                 break;
                             case '!=':
                             case '<>':
                                 if (trim($this->pRow[$this->pParamFilterField[0]]) != trim($this->pParamFilterValue1[0])) {
                                     $almacena_reg = 1;
                                 }
                                 break;
                         }
                     } else {
                         $almacena_reg = 1;
                     }
                     if ($almacena_reg == 1) {
                         $sw = 1;
                         if ($sw == 1) {
                             $m = 0;
                         }
                         for ($j = 0; $j < $this->pNumFields; $j++) {
                             if ($sw == 1) {
                                 $posicion = strpos($this->pFieldsSelect, mssql_field_name($this->RecordSet, $j));
                                 if ($posicion) {
                                     $this->aRecords[$cont][$m] = $this->pRow[$j];
                                     if ($cont == 0) {
                                         $this->aFieldsName[$m] = mssql_field_name($this->RecordSet, $j);
                                         $this->aFieldsType[$m] = mssql_field_type($this->RecordSet, $j);
                                         $m++;
                                     }
                                 }
                             } else {
                                 $this->aRecords[$cont][$j] = $this->pRow[$j];
                                 if ($cont == 0) {
                                     $this->aFieldsName[$j] = mssql_field_name($this->RecordSet, $j);
                                     $this->aFieldsType[$j] = mssql_field_type($this->RecordSet, $j);
                                 }
                                 $m = $j + 1;
                             }
                         }
                         $cont++;
                     }
                 }
                 $m = 1;
                 //añadido por mi
                 $this->pNumRows = $cont;
                 $this->pNumFields = $m;
             }
             break;
     }
     $this->MoveFirst();
     return $this->RecordSet;
 }