<?php
/**************************************************************************
* This file is part of the WebIssues Server program
* Copyright (C) 2006 Michał Męciński
* Copyright (C) 2007-2009 WebIssues Team
*
* This file is based on code written by Alex Bekhtin.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
**************************************************************************/

function wi_db_connect( $host, $database, $user, $password )
{
    global $db_link;

    if ( !( $db_link = ibase_connect( $host . ':' . $database, $user, $password, 'UTF-8' ) ) )
        return false;

    return true;
}

function wi_db_escape_arg( $arg, $type, &$params )
{
    switch( $type ) {
        case 'd':
            return (int)$arg;
        case 's':
        case 'b':
            $params[] = $arg;
            return '?';
    }
}

function wi_db_query( $query, $params )
{
    global $db_link;

    $log = wi_log_open( 'sql' );
    if ( $log )
        fwrite( $log, "> $query\n" );

    if ( empty( $params ) ) {
        $rs = ibase_query( $db_link, $query );
    } else {
        $args = array_merge( array( $db_link, $query ), $params );
        $rs = call_user_func_array( 'ibase_query', $args );
    }

    if ( !$rs ) {
        $error = ibase_errcode() . ": " . ibase_errmsg();
        trigger_error( 'ibase_query(): ' . $error, E_USER_WARNING );
        if ( $log )
            fwrite( $log, "ERROR: $error\n" );
        return false;
    }

    return $rs;
}

function wi_db_fetch_assoc( $rs )
{
    $row_original = ibase_fetch_assoc( $rs, IBASE_TEXT );

    if ( !$row_original )
        return false;

    foreach ( $row_original as $key => $value )
        $row[ strtolower( $key ) ] = $value;

    return $row;
}

function wi_db_unescape_blob( $data )
{
    return $data;
}

function wi_db_insert_id( $table, $column )
{
    global $db_link;

    $query = "SELECT RDB\$GET_CONTEXT('USER_SESSION', UPPER('${table}.${column}')) as VAL FROM RDB\$DATABASE";
    $rs = ibase_query( $db_link, $query );
    $row = ibase_fetch_assoc( $rs );
    return $row[ 'VAL' ];
}

function wi_db_table_exists( $table )
{
    global $db_link;

    $query = "SELECT COUNT(*) AS VAL FROM RDB\$RELATIONS WHERE RDB\$RELATION_NAME = UPPER('$table') AND RDB\$SYSTEM_FLAG = 0;";
    $rs = ibase_query( $db_link, $query );
    $row = ibase_fetch_assoc( $rs );
    return $row[ 'VAL' ] > 0;
}
