<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  Christopher Graham
 * @package    core_database_drivers
 */

/*EXTRA FUNCTIONS: odbc\_.+*/

// See tut_sqlserver tutorial for documentation on using SQL Server.

require_code('database/shared/sqlserver');

/**
 * Standard code module initialisation function.
 *
 * @ignore
 */
function init__database__sqlserver_odbc()
{
    cms_ini_set('odbc.defaultlrl', '20M');
}

/**
 * Database driver class.
 *
 * @package core_database_drivers
 */
class Database_Static_sqlserver_odbc extends Database_super_sqlserver
{
    protected $cache_db = [];

    /**
     * Get a database connection. This function shouldn't be used by you, as a connection to the database is established automatically.
     *
     * @param  boolean $persistent Whether to create a persistent connection
     * @param  string $db_name The database name
     * @param  string $db_host The database host (the server)
     * @param  string $db_user The database connection username
     * @param  string $db_password The database connection password
     * @param  boolean $fail_ok Whether to on error echo an error and return with a null, rather than giving a critical error
     * @return ?mixed A database connection (null: failed)
     */
    public function get_connection(bool $persistent, string $db_name, string $db_host, string $db_user, string $db_password, bool $fail_ok = false)
    {
        // Potential caching
        if (isset($this->cache_db[$db_name][$db_host])) {
            return $this->cache_db[$db_name][$db_host];
        }

        $dsn = $db_name;

        if (!function_exists('odbc_connect')) {
            $error = 'The ODBC PHP extension not installed (anymore?). You need to contact the system administrator of this server.';
            if ($fail_ok) {
                echo ((running_script('install')) && (get_param_string('type', '') == 'ajax_db_details')) ? strip_html($error) : $error;
                return null;
            }
            critical_error('PASSON', $error);
        }

        $connection = $persistent ? @odbc_pconnect($dsn, $db_user, $db_password) : @odbc_connect($dsn, $db_user, $db_password);
        if ($connection === false) {
            $error = 'Could not connect to database-server (' . odbc_errormsg() . ', ' . cms_error_get_last() . ')';
            if ($fail_ok) {
                echo ((running_script('install')) && (get_param_string('type', '') == 'ajax_db_details')) ? strip_html($error) : $error;
                return null;
            }
            critical_error('PASSON', $error);
        }

        odbc_exec($connection, 'SET TEXTSIZE 20000000');

        $this->cache_db[$db_name][$db_host] = $connection;
        return $connection;
    }

    /**
     * This function is a very basic query executor. It shouldn't usually be used by you, as there are abstracted versions available.
     *
     * @param  string $query The complete SQL query
     * @param  mixed $connection The DB connection
     * @param  ?integer $max The maximum number of rows to affect (null: no limit)
     * @param  integer $start The start row to affect
     * @param  boolean $fail_ok Whether to output an error on failure
     * @param  boolean $get_insert_id Whether to get the autoincrement ID created for an insert query
     * @param  boolean $save_as_volatile Whether we are saving as a 'volatile' file extension
     * @return ?mixed The results (null: no results), or the insert ID
     */
    public function query(string $query, $connection, ?int $max = null, int $start = 0, bool $fail_ok = false, bool $get_insert_id = false, bool $save_as_volatile = false)
    {
        if ($max === 0) {
            return [];
        }
        $this->apply_sql_limit_clause($query, $max, $start);

        $this->rewrite_to_unicode_syntax($query);

        $results = @odbc_exec($connection, $query);
        if (($results === false) && (cms_strtoupper_ascii(substr($query, 0, 12)) == 'INSERT INTO ') && ((strpos($query, '(id, ') !== false) || (strpos($query, '(_id, ') !== false))) {
            // FUDGE: Horrible, but we need to switch the active identity column somehow
            $pos = strpos($query, '(');
            $table_name = substr($query, 12, $pos - 13);
            if ((!multi_lang_content()) || (substr($table_name, -strlen('translate')) != 'translate')) {
                $results = @odbc_exec($connection, 'SET IDENTITY_INSERT ' . $table_name . ' ON; ' . $query);
            }
        }
        if ((($results === false) || (((cms_strtoupper_ascii(substr(ltrim($query), 0, 7)) == 'SELECT ') || (cms_strtoupper_ascii(substr(ltrim($query), 0, 8)) == '(SELECT ')) && ($results === true))) && (!$fail_ok)) {
            $err = odbc_errormsg($connection);
            if (function_exists('ocp_mark_as_escaped')) {
                ocp_mark_as_escaped($err);
            }
            if ((!running_script('upgrader')) && ((!get_mass_import_mode()) || (current_fatalistic() > 0))) {
                if (!function_exists('do_lang') || (do_lang('QUERY_FAILED', null, null, null, null, false) === null)) {
                    fatal_exit(htmlentities('Query failed: ' . $query . ' : ' . $err));
                }

                fatal_exit(do_lang_tempcode('QUERY_FAILED', escape_html($query), ($err)));
            } else {
                echo htmlentities('Database query failed: ' . $query . ' [') . ($err) . htmlentities(']') . "<br />\n";
                return null;
            }
        }

        $sub = substr(ltrim($query), 0, 4);
        if (((cms_strtoupper_ascii(substr(ltrim($query), 0, 7)) == 'SELECT ') || (cms_strtoupper_ascii(substr(ltrim($query), 0, 8)) == '(SELECT ')) && ($results !== false) && ($results !== true)) {
            return $this->get_query_rows($results, $query, $start);
        }

        if ($get_insert_id) {
            if (cms_strtoupper_ascii(substr($query, 0, 7)) == 'UPDATE ') {
                return null;
            }

            $pos = strpos($query, '(');
            $table_name = substr($query, 12, $pos - 13);

            $res2 = odbc_exec($connection, 'SELECT MAX(IDENTITYCOL) FROM ' . $table_name);
            odbc_fetch_row($res2);
            return intval(odbc_result($res2, 1));
        }

        return null;
    }

    /**
     * Get the rows returned from a SELECT query.
     *
     * @param  resource $results The query result pointer
     * @param  string $query The complete SQL query (useful for debugging)
     * @param  integer $start Where to start reading from
     * @return array A list of row maps
     */
    protected function get_query_rows($results, string $query, int $start) : array
    {
        $out = [];
        if ($start === null) {
            $start = 0;
        }
        $i = 0;

        $num_fields = odbc_num_fields($results);
        $types = [];
        $names = [];
        for ($x = 1; $x <= $num_fields; $x++) {
            $types[$x] = cms_strtoupper_ascii(odbc_field_type($results, $x));
            $names[$x] = cms_strtolower_ascii(odbc_field_name($results, $x));
        }

        while (odbc_fetch_row($results, $start + $i + 1)) {
            $newrow = [];

            for ($j = 1; $j <= $num_fields; $j++) {
                $v = odbc_result($results, $j);

                $type = $types[$j];
                $name = $names[$j];

                if (($type == 'SMALLINT') || ($type == 'BIGINT') || ($type == 'INT') || ($type == 'INTEGER') || ($type == 'UINTEGER') || ($type == 'BYTE') || ($type == 'COUNTER')) {
                    if ($v !== null) {
                        $newrow[$name] = intval($v);
                    } else {
                        $newrow[$name] = null;
                    }
                } elseif (substr($type, 0, 5) == 'FLOAT') {
                    $newrow[$name] = floatval($v);
                } else {
                    $newrow[$name] = $v;
                }
            }

            $out[] = $newrow;

            $i++;
        }

        odbc_free_result($results);
        return $out;
    }

    /**
     * Close the database connections. We don't really need to close them (will close at exit), just disassociate so we can refresh them.
     */
    public function close_connections()
    {
        $this->cache_db = [];
    }
}
