<?php
/*
	From the project : SYIBIB - Système d'Information Bibtex
	Now for the project : Memento Plus
	Developped at TAEMA, Air Liquide Santé
	Creation date : January 2004
	@author david.han-sze-chuen
	School : ISTY
	
	filename : func_db.inc.php
	Description : html output functions
*/
// //////////////////////////////////////////////////////////////////////////////
/**
 * * function which build an array of results from a db_result object
 */
function fetchAll($res, $format = 0) {
    if (!preg_match("/db_result/i",get_class($res)) && (!is_subclass_of($res, "db_result")||!is_subclass_of($res, "DB_result"))) {
        death("ERR_ArgumentTypeMismatch", "\$res must be an object of db_result or a child. type=" . gettype($res) . " class=" . get_class($res));
    } 

    if ($format > 0)
        $print_null_value = true;
    else
        $print_null_value = false;

    $tab = array();

    if ($print_null_value == true) {
        $res_types = $res->tableInfo();
    } 

    for ($i = 0; $i < $res->numRows(); $i++) {
        $j = 0;
        foreach($res->fetchRow(DB_FETCHMODE_ASSOC, $i) as $t => $v) {
            // DEBUG
            // println("$i : [$t] = '$v'");
            if ($print_null_value == true) {
                if (($v == '') && ($res_types[$j]["type"] == "string")) {
                    $v = "''";
                } elseif ($v == null) {
                    $v = 'null';
                } 
            } 
            // $tab[$i][$t] = $v . " type=" . pg_field_type($res, $j);
            $tab[$i][$t] = $v;
            $j++;
        } 
        // echo "<BR>";
    } 
    return $tab;
} // fin de printres($res)
// //////////////////////////////////////////////////////////////////////////////
/**
 * Function which prepare the select part of a sql query
 * Ex: [$prefix] $fields [as $alt_col_names] [$suffix]
 * Note : $prefix = '' by default, set $prefix = 'SELECT' to create a Select query for example
 * 
 * @param mixed $fields The fields to get
 * @param string $prefix prefix of the select
 * @param string $suffix suffix of the select
 * @param mixed $alt_col_names Put the value of $alt_col_names to rename column in the result. Same as using "as '<name>'"
 * @return string the Select par of a sql query.
 */
function buildSelect($fields = null, $alt_col_names = null, $prefix = '', $suffix = null) {
    global $db, $QUERY; 
    // analyse param
    // escape $alt_col_names
    if (!empty($alt_col_names)) {
        switch (gettype($alt_col_names)) {
            case 'string' : 
                // we should filter this string
                $alt_col_names = str_replace("'", "\\'", $alt_col_names); 
                // $alt_col_names = $db->escapeSimple($alt_col_names);	// not yet implemented in our Pear:DB release
                break;
            case 'array' :
                foreach($alt_col_names as $k => $v) {
                    $alt_col_names[$k] = str_replace("'", "\\'", $v); 
                    // $alt_col_names[$k] = $db->escapeSimple($v);
                } 
                break;
            default:
                death("ERR_InvalidParameter", "Bad parameter type, 01 buildSelect(). \$alt_col_names type must be string or array.");
        } 
    } 

    if (empty($fields)) {
        $f = "*";
        if (!empty($alt_col_names)) {; 
            // echo ("WARNING : 02 buildSelect(). This function ignores \$alt_col_names if \$fields is null or equal to '*'.");
        } 
    } elseif (is_array($fields)) {
        // add the 'as'
        if (!empty($alt_col_names)) {
            switch (gettype($alt_col_names)) {
                case 'string' : 
                    // echo ("WARNING : 03 buildSelect(). This function ignores \$alt_col_names if \$fields is an array and \$alt_col_names is a string.");
                    break;
                case 'array' :
                    reset($alt_col_names);
                    foreach($fields as $k => $v) {
                        $fields[$k] = "$v as '" . current($alt_col_names) . "'";
                        next($alt_col_names);
                    } 
                    break;
            } 
        } 
        $f = implode(", ", $fields);
    } elseif (is_string($fields)) {
        $f = $fields; 
        // add the 'as'
        if (!empty($alt_col_names)) {
            switch (gettype($alt_col_names)) {
                case 'string' :
                    $f .= " as '$alt_col_names'";
                    break;
                case 'array' :
                    list($temp) = $alt_col_names;
                    $f .= " as '" . $temp . "'";
                    break;
            } 
        } 

        if (trim($fields) == '*') { // if the user put a '*', we'd rather return an array for convenience
            $fields = null; 
            // echo ("WARNING : 04 buildSelect(). This function ignores \$alt_col_names if \$fields is null or equal to '*'.");
        } 
    } else {
        death("ERR_InvalidParameter", "Bad parameter type, 05 buildSelect(\$fields : " . gettype($fields) . ") accepts only array, string or null.");
    } 
    // DEBUG
    // echo "<br>returns : '$prefix $f $suffix' <br>";
    return " $prefix $f $suffix ";
} // end of buildSelect($fields = null, $alt_col_names = null, $prefix = '', $suffix = null)
// //////////////////////////////////////////////////////////////////////////////
/*
* Function which prepare the FROM part of a sql query
* Ex: [$prefix] $table_names [$table_nicknames] [$suffix]
* Note : $prefix = '' by default, set $prefix = 'FROM' if needed
*  
* @param mixed $table_names The tables to import
* @param string $prefix prefix of the select
* @param string $suffix suffix of the select
* @param mixed $alt_col_names Put the value of $table_nicknames to rename a table when executing the query.
* 
* @return string the FROM par of a sql query.
*/
function buildFrom($table_names = null, $alt_col_names = null, $prefix = '', $suffix = null) {
    global $db, $QUERY; 
    // analyse param
    // check that $alt_col_names is a string or an arrat
    if (!empty($alt_col_names)) {
        switch (gettype($alt_col_names)) {
            case 'string' :
            case 'array' :
                break;
            default:
                death("ERR_InvalidParameter", "Bad parameter type, 01 buildFrom(). \$alt_col_names type must be string or array.");
        } 
    } 

    if (empty($table_names)) {
        death("ERR_InvalidParameter", "Bad parameter type, 02 buildFrom(). \$alt_col_names must not be null.");
    } elseif (is_array($table_names)) {
        // add the 'nicknames'
        if (!empty($alt_col_names)) {
            switch (gettype($alt_col_names)) {
                case 'string' : 
                    // if $alt_col_names is a string, it's just ignored
                    break;
                case 'array' :
                    reset($alt_col_names);
                    foreach($table_names as $k => $v) {
                        $table_names[$k] = "$v " . current($alt_col_names);
                        next($alt_col_names);
                    } 
                    break;
            } 
        } 
        $f = implode(", ", $table_names);
    } elseif (is_string($table_names)) {
        $f = $table_names; 
        // add the 'as'
        if (!empty($alt_col_names)) {
            switch (gettype($alt_col_names)) {
                case 'string' :
                    $f .= " $alt_col_names";
                    break;
                case 'array' :
                    list($temp) = $alt_col_names;
                    $f .= " $temp";
                    break;
            } 
        } 
    } else {
        death("ERR_InvalidParameter", "Bad parameter type, 03 buildFrom(\$table_names : " . gettype($table_names) . ") accepts only array or string.");
    } 
    // DEBUG
    // echo "<br>returns : '$prefix $f $suffix' <br>";
    return " $prefix $f $suffix ";
} // end of buildFrom($table_names = null, $alt_col_names = null, $prefix = '', $suffix = null)
// //////////////////////////////////////////////////////////////////////////////
/**
 * autoprepare()
 * build a query for DB like : INSERT INTO(f1, f2, ..) VALUES(?, ?, ..);
 * $type = "insert", "update" only
 * 
 * @param DB $db a DB object
 * @param string $tbl_name table name
 * @param string $type 'insert' or 'update' for the wanted query
 * @param string $query_tail a part of sql query to add at the end 
 * @param array $field_names 
 * @return string
 */
function autoprepare(&$db, $tbl_name, $field_names, $type = "insert", $query_tail = '', $verbose = false) {
    if (!is_array($field_names) || (count($field_names) == 0)) {
        death("ERR_InvalidParameter", "01 autoprepare() : field_names must be a non empty array.");
    } 
    $sql = '';
	$temp = array();
    switch ($type = strtolower($type)) {
        case 'insert':
            foreach($field_names as $k => $v) {
                $temp[] = '?';
            } 
            $sql = "INSERT INTO $tbl_name (" . implode(', ', $field_names) . ") VALUES(" . implode(', ', $temp) . ")";
            break;
		case 'update' :
			foreach($field_names as $k => $v) {
                $temp[] = "$v = ?";
            } 
            $sql = "UPDATE $tbl_name SET " . implode(', ', $temp) . " {$query_tail}";
            break;
        default :
            death("ERR_InvalidParameter", "Bad parameter type, 02 autoprepare() : type unknown.");
    } 

    if ($verbose)
        println("autoprepare() : '$sql'");
    
	return $db->prepare($sql);
} // end of autoprepare($type = "insert", $field_names)
// //////////////////////////////////////////////////////////////////////////////
?>