1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Stig S�ther Bakken <ssb@php.net>                            |
16   |          Andreas Karajannis <Andreas.Karajannis@gmd.de>              |
17   |          Frank M. Kromann <frank@kromann.info>  Support for DB/2 CLI |
18   |          Kevin N. Shallow <kshallow@tampabay.rr.com> Birdstep Support|
19   |          Daniel R. Kalowsky <kalowsky@php.net>                       |
20   +----------------------------------------------------------------------+
21*/
22
23/* $Id$ */
24
25#ifdef HAVE_CONFIG_H
26#include "config.h"
27#endif
28
29#include "php.h"
30#include "php_globals.h"
31
32#include "ext/standard/info.h"
33#include "ext/standard/php_string.h"
34#include "ext/standard/php_standard.h"
35
36#include "php_odbc.h"
37#include "php_odbc_includes.h"
38#include "php_globals.h"
39
40#if HAVE_UODBC
41
42#include <fcntl.h>
43#include "ext/standard/head.h"
44#include "php_ini.h"
45
46#ifdef PHP_WIN32
47#include <winsock2.h>
48
49#define ODBC_TYPE "Win32"
50#define PHP_ODBC_TYPE ODBC_TYPE
51
52#endif
53
54/*
55 * not defined elsewhere
56 */
57
58#ifndef TRUE
59#define TRUE 1
60#define FALSE 0
61#endif
62
63void odbc_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent);
64
65static int le_result, le_conn, le_pconn;
66
67#define SAFE_SQL_NTS(n) ((SQLSMALLINT) ((n)?(SQL_NTS):0))
68
69/* {{{ arginfo */
70ZEND_BEGIN_ARG_INFO(arginfo_odbc_close_all, 0)
71ZEND_END_ARG_INFO()
72
73ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_binmode, 0, 0, 2)
74    ZEND_ARG_INFO(0, result_id)
75    ZEND_ARG_INFO(0, mode)
76ZEND_END_ARG_INFO()
77
78ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_longreadlen, 0, 0, 2)
79    ZEND_ARG_INFO(0, result_id)
80    ZEND_ARG_INFO(0, length)
81ZEND_END_ARG_INFO()
82
83ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_prepare, 0, 0, 2)
84    ZEND_ARG_INFO(0, connection_id)
85    ZEND_ARG_INFO(0, query)
86ZEND_END_ARG_INFO()
87
88ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_execute, 0, 0, 1)
89    ZEND_ARG_INFO(0, result_id)
90    ZEND_ARG_INFO(0, parameters_array)
91ZEND_END_ARG_INFO()
92
93ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_cursor, 0, 0, 1)
94    ZEND_ARG_INFO(0, result_id)
95ZEND_END_ARG_INFO()
96
97#ifdef HAVE_SQLDATASOURCES
98ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_data_source, 0, 0, 2)
99    ZEND_ARG_INFO(0, connection_id)
100    ZEND_ARG_INFO(0, fetch_type)
101ZEND_END_ARG_INFO()
102#endif
103
104ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_exec, 0, 0, 2)
105    ZEND_ARG_INFO(0, connection_id)
106    ZEND_ARG_INFO(0, query)
107    ZEND_ARG_INFO(0, flags)
108ZEND_END_ARG_INFO()
109
110#ifdef PHP_ODBC_HAVE_FETCH_HASH
111ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_object, 0, 0, 1)
112    ZEND_ARG_INFO(0, result)
113    ZEND_ARG_INFO(0, rownumber)
114ZEND_END_ARG_INFO()
115
116ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_array, 0, 0, 1)
117    ZEND_ARG_INFO(0, result)
118    ZEND_ARG_INFO(0, rownumber)
119ZEND_END_ARG_INFO()
120#endif
121
122ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_into, 0, 0, 2)
123    ZEND_ARG_INFO(0, result_id)
124    ZEND_ARG_INFO(1, result_array)
125    ZEND_ARG_INFO(0, rownumber)
126ZEND_END_ARG_INFO()
127
128ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_row, 0, 0, 1)
129    ZEND_ARG_INFO(0, result_id)
130    ZEND_ARG_INFO(0, row_number)
131ZEND_END_ARG_INFO()
132
133ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_result, 0, 0, 2)
134    ZEND_ARG_INFO(0, result_id)
135    ZEND_ARG_INFO(0, field)
136ZEND_END_ARG_INFO()
137
138ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_result_all, 0, 0, 1)
139    ZEND_ARG_INFO(0, result_id)
140    ZEND_ARG_INFO(0, format)
141ZEND_END_ARG_INFO()
142
143ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_free_result, 0, 0, 1)
144    ZEND_ARG_INFO(0, result_id)
145ZEND_END_ARG_INFO()
146
147ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_connect, 0, 0, 3)
148    ZEND_ARG_INFO(0, dsn)
149    ZEND_ARG_INFO(0, user)
150    ZEND_ARG_INFO(0, password)
151    ZEND_ARG_INFO(0, cursor_option)
152ZEND_END_ARG_INFO()
153
154ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_pconnect, 0, 0, 3)
155    ZEND_ARG_INFO(0, dsn)
156    ZEND_ARG_INFO(0, user)
157    ZEND_ARG_INFO(0, password)
158    ZEND_ARG_INFO(0, cursor_option)
159ZEND_END_ARG_INFO()
160
161ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_close, 0, 0, 1)
162    ZEND_ARG_INFO(0, connection_id)
163ZEND_END_ARG_INFO()
164
165ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_num_rows, 0, 0, 1)
166    ZEND_ARG_INFO(0, result_id)
167ZEND_END_ARG_INFO()
168
169#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
170ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_next_result, 0, 0, 1)
171    ZEND_ARG_INFO(0, result_id)
172ZEND_END_ARG_INFO()
173#endif
174
175ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_num_fields, 0, 0, 1)
176    ZEND_ARG_INFO(0, result_id)
177ZEND_END_ARG_INFO()
178
179ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_name, 0, 0, 2)
180    ZEND_ARG_INFO(0, result_id)
181    ZEND_ARG_INFO(0, field_number)
182ZEND_END_ARG_INFO()
183
184ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_type, 0, 0, 2)
185    ZEND_ARG_INFO(0, result_id)
186    ZEND_ARG_INFO(0, field_number)
187ZEND_END_ARG_INFO()
188
189ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_len, 0, 0, 2)
190    ZEND_ARG_INFO(0, result_id)
191    ZEND_ARG_INFO(0, field_number)
192ZEND_END_ARG_INFO()
193
194ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_scale, 0, 0, 2)
195    ZEND_ARG_INFO(0, result_id)
196    ZEND_ARG_INFO(0, field_number)
197ZEND_END_ARG_INFO()
198
199ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_num, 0, 0, 2)
200    ZEND_ARG_INFO(0, result_id)
201    ZEND_ARG_INFO(0, field_name)
202ZEND_END_ARG_INFO()
203
204ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_autocommit, 0, 0, 1)
205    ZEND_ARG_INFO(0, connection_id)
206    ZEND_ARG_INFO(0, onoff)
207ZEND_END_ARG_INFO()
208
209ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_commit, 0, 0, 1)
210    ZEND_ARG_INFO(0, connection_id)
211ZEND_END_ARG_INFO()
212
213ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_rollback, 0, 0, 1)
214    ZEND_ARG_INFO(0, connection_id)
215ZEND_END_ARG_INFO()
216
217ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_error, 0, 0, 0)
218    ZEND_ARG_INFO(0, connection_id)
219ZEND_END_ARG_INFO()
220
221ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_errormsg, 0, 0, 0)
222    ZEND_ARG_INFO(0, connection_id)
223ZEND_END_ARG_INFO()
224
225ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_setoption, 0, 0, 4)
226    ZEND_ARG_INFO(0, conn_id)
227    ZEND_ARG_INFO(0, which)
228    ZEND_ARG_INFO(0, option)
229    ZEND_ARG_INFO(0, value)
230ZEND_END_ARG_INFO()
231
232ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_tables, 0, 0, 1)
233    ZEND_ARG_INFO(0, connection_id)
234    ZEND_ARG_INFO(0, qualifier)
235    ZEND_ARG_INFO(0, owner)
236    ZEND_ARG_INFO(0, name)
237    ZEND_ARG_INFO(0, table_types)
238ZEND_END_ARG_INFO()
239
240ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_columns, 0, 0, 1)
241    ZEND_ARG_INFO(0, connection_id)
242    ZEND_ARG_INFO(0, qualifier)
243    ZEND_ARG_INFO(0, owner)
244    ZEND_ARG_INFO(0, table_name)
245    ZEND_ARG_INFO(0, column_name)
246ZEND_END_ARG_INFO()
247
248ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_gettypeinfo, 0, 0, 1)
249    ZEND_ARG_INFO(0, connection_id)
250    ZEND_ARG_INFO(0, data_type)
251ZEND_END_ARG_INFO()
252
253ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_primarykeys, 0, 0, 4)
254    ZEND_ARG_INFO(0, connection_id)
255    ZEND_ARG_INFO(0, qualifier)
256    ZEND_ARG_INFO(0, owner)
257    ZEND_ARG_INFO(0, table)
258ZEND_END_ARG_INFO()
259
260#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
261#if !defined(HAVE_BIRDSTEP)
262ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_procedurecolumns, 0, 0, 1)
263    ZEND_ARG_INFO(0, connection_id)
264    ZEND_ARG_INFO(0, qualifier)
265    ZEND_ARG_INFO(0, owner)
266    ZEND_ARG_INFO(0, proc)
267    ZEND_ARG_INFO(0, column)
268ZEND_END_ARG_INFO()
269#endif
270
271ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_procedures, 0, 0, 1)
272    ZEND_ARG_INFO(0, connection_id)
273    ZEND_ARG_INFO(0, qualifier)
274    ZEND_ARG_INFO(0, owner)
275    ZEND_ARG_INFO(0, name)
276ZEND_END_ARG_INFO()
277
278ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_foreignkeys, 0, 0, 7)
279    ZEND_ARG_INFO(0, connection_id)
280    ZEND_ARG_INFO(0, pk_qualifier)
281    ZEND_ARG_INFO(0, pk_owner)
282    ZEND_ARG_INFO(0, pk_table)
283    ZEND_ARG_INFO(0, fk_qualifier)
284    ZEND_ARG_INFO(0, fk_owner)
285    ZEND_ARG_INFO(0, fk_table)
286ZEND_END_ARG_INFO()
287#endif
288
289ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_specialcolumns, 0, 0, 7)
290    ZEND_ARG_INFO(0, connection_id)
291    ZEND_ARG_INFO(0, type)
292    ZEND_ARG_INFO(0, qualifier)
293    ZEND_ARG_INFO(0, owner)
294    ZEND_ARG_INFO(0, table)
295    ZEND_ARG_INFO(0, scope)
296    ZEND_ARG_INFO(0, nullable)
297ZEND_END_ARG_INFO()
298
299ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_statistics, 0, 0, 6)
300    ZEND_ARG_INFO(0, connection_id)
301    ZEND_ARG_INFO(0, qualifier)
302    ZEND_ARG_INFO(0, owner)
303    ZEND_ARG_INFO(0, name)
304    ZEND_ARG_INFO(0, unique)
305    ZEND_ARG_INFO(0, accuracy)
306ZEND_END_ARG_INFO()
307
308#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) &&!defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
309ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_tableprivileges, 0, 0, 4)
310    ZEND_ARG_INFO(0, connection_id)
311    ZEND_ARG_INFO(0, qualifier)
312    ZEND_ARG_INFO(0, owner)
313    ZEND_ARG_INFO(0, name)
314ZEND_END_ARG_INFO()
315
316ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_columnprivileges, 0, 0, 5)
317    ZEND_ARG_INFO(0, connection_id)
318    ZEND_ARG_INFO(0, catalog)
319    ZEND_ARG_INFO(0, schema)
320    ZEND_ARG_INFO(0, table)
321    ZEND_ARG_INFO(0, column)
322ZEND_END_ARG_INFO()
323#endif
324/* }}} */
325
326/* {{{ odbc_functions[]
327 */
328const zend_function_entry odbc_functions[] = {
329    PHP_FE(odbc_autocommit, arginfo_odbc_autocommit)
330    PHP_FE(odbc_binmode, arginfo_odbc_binmode)
331    PHP_FE(odbc_close, arginfo_odbc_close)
332    PHP_FE(odbc_close_all, arginfo_odbc_close_all)
333    PHP_FE(odbc_columns, arginfo_odbc_columns)
334    PHP_FE(odbc_commit, arginfo_odbc_commit)
335    PHP_FE(odbc_connect, arginfo_odbc_connect)
336    PHP_FE(odbc_cursor, arginfo_odbc_cursor)
337#ifdef HAVE_SQLDATASOURCES
338    PHP_FE(odbc_data_source, arginfo_odbc_data_source)
339#endif
340    PHP_FE(odbc_execute, arginfo_odbc_execute)
341    PHP_FE(odbc_error, arginfo_odbc_error)
342    PHP_FE(odbc_errormsg, arginfo_odbc_errormsg)
343    PHP_FE(odbc_exec, arginfo_odbc_exec)
344#ifdef PHP_ODBC_HAVE_FETCH_HASH
345    PHP_FE(odbc_fetch_array, arginfo_odbc_fetch_array)
346    PHP_FE(odbc_fetch_object, arginfo_odbc_fetch_object)
347#endif
348    PHP_FE(odbc_fetch_row, arginfo_odbc_fetch_row)
349    PHP_FE(odbc_fetch_into, arginfo_odbc_fetch_into)
350    PHP_FE(odbc_field_len, arginfo_odbc_field_len)
351    PHP_FE(odbc_field_scale, arginfo_odbc_field_scale)
352    PHP_FE(odbc_field_name, arginfo_odbc_field_name)
353    PHP_FE(odbc_field_type, arginfo_odbc_field_type)
354    PHP_FE(odbc_field_num, arginfo_odbc_field_num)
355    PHP_FE(odbc_free_result, arginfo_odbc_free_result)
356    PHP_FE(odbc_gettypeinfo, arginfo_odbc_gettypeinfo)
357    PHP_FE(odbc_longreadlen, arginfo_odbc_longreadlen)
358#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
359    PHP_FE(odbc_next_result, arginfo_odbc_next_result)
360#endif
361    PHP_FE(odbc_num_fields, arginfo_odbc_num_fields)
362    PHP_FE(odbc_num_rows, arginfo_odbc_num_rows)
363    PHP_FE(odbc_pconnect, arginfo_odbc_pconnect)
364    PHP_FE(odbc_prepare, arginfo_odbc_prepare)
365    PHP_FE(odbc_result, arginfo_odbc_result)
366    PHP_FE(odbc_result_all, arginfo_odbc_result_all)
367    PHP_FE(odbc_rollback, arginfo_odbc_rollback)
368    PHP_FE(odbc_setoption, arginfo_odbc_setoption)
369    PHP_FE(odbc_specialcolumns, arginfo_odbc_specialcolumns)
370    PHP_FE(odbc_statistics, arginfo_odbc_statistics)
371    PHP_FE(odbc_tables, arginfo_odbc_tables)
372    PHP_FE(odbc_primarykeys, arginfo_odbc_primarykeys)
373#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) &&!defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)    /* not supported now */
374    PHP_FE(odbc_columnprivileges, arginfo_odbc_columnprivileges)
375    PHP_FE(odbc_tableprivileges, arginfo_odbc_tableprivileges)
376#endif
377#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) /* not supported */
378    PHP_FE(odbc_foreignkeys, arginfo_odbc_foreignkeys)
379    PHP_FE(odbc_procedures, arginfo_odbc_procedures)
380#if !defined(HAVE_BIRDSTEP)
381    PHP_FE(odbc_procedurecolumns, arginfo_odbc_procedurecolumns)
382#endif
383#endif
384    PHP_FALIAS(odbc_do, odbc_exec, arginfo_odbc_exec)
385    PHP_FALIAS(odbc_field_precision, odbc_field_len, arginfo_odbc_field_len)
386    PHP_FE_END
387};
388/* }}} */
389
390ZEND_DECLARE_MODULE_GLOBALS(odbc)
391static PHP_GINIT_FUNCTION(odbc);
392
393/* {{{ odbc_module_entry
394 */
395zend_module_entry odbc_module_entry = {
396    STANDARD_MODULE_HEADER,
397    "odbc",
398    odbc_functions,
399    PHP_MINIT(odbc),
400    PHP_MSHUTDOWN(odbc),
401    PHP_RINIT(odbc),
402    PHP_RSHUTDOWN(odbc),
403    PHP_MINFO(odbc),
404    "1.0",
405    PHP_MODULE_GLOBALS(odbc),
406    PHP_GINIT(odbc),
407    NULL,
408    NULL,
409    STANDARD_MODULE_PROPERTIES_EX
410};
411/* }}} */
412
413#ifdef COMPILE_DL_ODBC
414ZEND_GET_MODULE(odbc)
415#endif
416
417/* {{{ _free_odbc_result
418 */
419static void _free_odbc_result(zend_resource *rsrc)
420{
421    odbc_result *res = (odbc_result *)rsrc->ptr;
422    int i;
423    RETCODE rc;
424
425    if (res) {
426        if (res->values) {
427            for(i = 0; i < res->numcols; i++) {
428                if (res->values[i].value)
429                    efree(res->values[i].value);
430            }
431            efree(res->values);
432            res->values = NULL;
433        }
434        if (res->stmt) {
435#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30) || defined(HAVE_SOLID_35)
436            SQLTransact(res->conn_ptr->henv, res->conn_ptr->hdbc,
437                        (SQLUSMALLINT) SQL_COMMIT);
438#endif
439            rc = SQLFreeStmt(res->stmt,SQL_DROP);
440            /* We don't want the connection to be closed after the last statement has been closed
441             * Connections will be closed on shutdown
442             * zend_list_delete(res->conn_ptr->id);
443             */
444        }
445        efree(res);
446    }
447}
448/* }}} */
449
450/* {{{ safe_odbc_disconnect
451 * disconnect, and if it fails, then issue a rollback for any pending transaction (lurcher)
452 */
453static void safe_odbc_disconnect( void *handle )
454{
455    int ret;
456
457    ret = SQLDisconnect( handle );
458    if ( ret == SQL_ERROR )
459    {
460        SQLTransact( NULL, handle, SQL_ROLLBACK );
461        SQLDisconnect( handle );
462    }
463}
464/* }}} */
465
466/* {{{ _close_odbc_conn
467 */
468static void _close_odbc_conn(zend_resource *rsrc)
469{
470    zend_resource *p;
471    odbc_result *res;
472
473    odbc_connection *conn = (odbc_connection *)rsrc->ptr;
474
475    ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
476        if (p->ptr && (p->type == le_result)) {
477            res = (odbc_result *)p->ptr;
478            if (res->conn_ptr == conn) {
479                zend_list_close(p);
480            }
481        }
482    } ZEND_HASH_FOREACH_END();
483
484    safe_odbc_disconnect(conn->hdbc);
485    SQLFreeConnect(conn->hdbc);
486    SQLFreeEnv(conn->henv);
487    efree(conn);
488    ODBCG(num_links)--;
489}
490/* }}} */
491
492/* {{{ void _close_odbc_pconn
493 */
494static void _close_odbc_pconn(zend_resource *rsrc)
495{
496    zend_resource *p;
497    odbc_result *res;
498    odbc_connection *conn = (odbc_connection *)rsrc->ptr;
499
500    ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
501        if (p->ptr && (p->type == le_result)) {
502            res = (odbc_result *)p->ptr;
503            if (res->conn_ptr == conn) {
504                zend_list_close(p);
505            }
506        }
507    } ZEND_HASH_FOREACH_END();
508
509    safe_odbc_disconnect(conn->hdbc);
510    SQLFreeConnect(conn->hdbc);
511    SQLFreeEnv(conn->henv);
512    free(conn);
513
514    ODBCG(num_links)--;
515    ODBCG(num_persistent)--;
516}
517/* }}} */
518
519/* {{{ PHP_INI_DISP(display_link_nums)
520 */
521static PHP_INI_DISP(display_link_nums)
522{
523    char *value;
524
525    if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
526        value = ini_entry->orig_value->val;
527    } else if (ini_entry->value) {
528        value = ini_entry->value->val;
529    } else {
530        value = NULL;
531    }
532
533    if (value) {
534        if (atoi(value) == -1) {
535            PUTS("Unlimited");
536        } else {
537            php_printf("%s", value);
538        }
539    }
540}
541/* }}} */
542
543/* {{{ PHP_INI_DISP(display_defPW)
544 */
545static PHP_INI_DISP(display_defPW)
546{
547    char *value;
548
549    if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
550        value = ini_entry->orig_value->val;
551    } else if (ini_entry->value) {
552        value = ini_entry->value->val;
553    } else {
554        value = NULL;
555    }
556
557    if (value) {
558#if PHP_DEBUG
559        php_printf("%s", value);
560#else
561        PUTS("********");
562#endif
563    } else {
564        if (PG(html_errors)) {
565            PUTS("<i>no value</i>");
566        } else {
567            PUTS("no value");
568        }
569    }
570}
571/* }}} */
572
573/* {{{ PHP_INI_DISP(display_binmode)
574 */
575static PHP_INI_DISP(display_binmode)
576{
577    char *value;
578
579    if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
580        value = ini_entry->orig_value->val;
581    } else if (ini_entry->value) {
582        value = ini_entry->value->val;
583    } else {
584        value = NULL;
585    }
586
587    if (value) {
588        switch(atoi(value)) {
589            case 0:
590                PUTS("passthru");
591                break;
592            case 1:
593                PUTS("return as is");
594                break;
595            case 2:
596                PUTS("return as char");
597                break;
598        }
599    }
600}
601/* }}} */
602
603/* {{{ PHP_INI_DISP(display_lrl)
604 */
605static PHP_INI_DISP(display_lrl)
606{
607    char *value;
608
609    if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
610        value = ini_entry->orig_value->val;
611    } else if (ini_entry->value) {
612        value = ini_entry->value->val;
613    } else {
614        value = NULL;
615    }
616
617    if (value) {
618        if (atoi(value) <= 0) {
619            PUTS("Passthru");
620        } else {
621            php_printf("return up to %s bytes", value);
622        }
623    }
624}
625/* }}} */
626
627
628/* {{{ PHP_INI_DISP(display_cursortype)
629 */
630static PHP_INI_DISP(display_cursortype)
631{
632    char *value;
633
634    if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
635        value = ini_entry->orig_value->val;
636    } else if (ini_entry->value) {
637        value = ini_entry->value->val;
638    } else {
639        value = NULL;
640    }
641
642    if (value) {
643        switch (atoi (value))
644          {
645            case SQL_CURSOR_FORWARD_ONLY:
646                PUTS ("Forward Only cursor");
647                break;
648
649            case SQL_CURSOR_STATIC:
650                PUTS ("Static cursor");
651                break;
652
653            case SQL_CURSOR_KEYSET_DRIVEN:
654                PUTS ("Keyset driven cursor");
655                break;
656
657            case SQL_CURSOR_DYNAMIC:
658                PUTS ("Dynamic cursor");
659                break;
660
661            default:
662                php_printf("Unknown cursor model %s", value);
663                break;
664          }
665    }
666}
667
668/* }}} */
669
670/* {{{ PHP_INI_BEGIN
671 */
672PHP_INI_BEGIN()
673    STD_PHP_INI_BOOLEAN("odbc.allow_persistent", "1", PHP_INI_SYSTEM, OnUpdateLong,
674            allow_persistent, zend_odbc_globals, odbc_globals)
675    STD_PHP_INI_ENTRY_EX("odbc.max_persistent",  "-1", PHP_INI_SYSTEM, OnUpdateLong,
676            max_persistent, zend_odbc_globals, odbc_globals, display_link_nums)
677    STD_PHP_INI_ENTRY_EX("odbc.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong,
678            max_links, zend_odbc_globals, odbc_globals, display_link_nums)
679    STD_PHP_INI_ENTRY("odbc.default_db", NULL, PHP_INI_ALL, OnUpdateString,
680            defDB, zend_odbc_globals, odbc_globals)
681    STD_PHP_INI_ENTRY("odbc.default_user", NULL, PHP_INI_ALL, OnUpdateString,
682            defUser, zend_odbc_globals, odbc_globals)
683    STD_PHP_INI_ENTRY_EX("odbc.default_pw", NULL, PHP_INI_ALL, OnUpdateString,
684            defPW, zend_odbc_globals, odbc_globals, display_defPW)
685    STD_PHP_INI_ENTRY_EX("odbc.defaultlrl", "4096", PHP_INI_ALL, OnUpdateLong,
686            defaultlrl, zend_odbc_globals, odbc_globals, display_lrl)
687    STD_PHP_INI_ENTRY_EX("odbc.defaultbinmode", "1", PHP_INI_ALL, OnUpdateLong,
688            defaultbinmode, zend_odbc_globals, odbc_globals, display_binmode)
689    STD_PHP_INI_BOOLEAN("odbc.check_persistent", "1", PHP_INI_SYSTEM, OnUpdateLong,
690            check_persistent, zend_odbc_globals, odbc_globals)
691    STD_PHP_INI_ENTRY_EX("odbc.default_cursortype", "3", PHP_INI_ALL, OnUpdateLong,
692            default_cursortype, zend_odbc_globals, odbc_globals, display_cursortype)
693PHP_INI_END()
694/* }}} */
695
696static PHP_GINIT_FUNCTION(odbc)
697{
698    odbc_globals->num_persistent = 0;
699}
700
701/* {{{ PHP_MINIT_FUNCTION */
702PHP_MINIT_FUNCTION(odbc)
703{
704#ifdef SQLANY_BUG
705    ODBC_SQL_CONN_T foobar;
706    RETCODE rc;
707#endif
708
709    REGISTER_INI_ENTRIES();
710    le_result = zend_register_list_destructors_ex(_free_odbc_result, NULL, "odbc result", module_number);
711    le_conn = zend_register_list_destructors_ex(_close_odbc_conn, NULL, "odbc link", module_number);
712    le_pconn = zend_register_list_destructors_ex(NULL, _close_odbc_pconn, "odbc link persistent", module_number);
713    odbc_module_entry.type = type;
714
715    REGISTER_STRING_CONSTANT("ODBC_TYPE", PHP_ODBC_TYPE, CONST_CS | CONST_PERSISTENT);
716    REGISTER_LONG_CONSTANT("ODBC_BINMODE_PASSTHRU", 0, CONST_CS | CONST_PERSISTENT);
717    REGISTER_LONG_CONSTANT("ODBC_BINMODE_RETURN", 1, CONST_CS | CONST_PERSISTENT);
718    REGISTER_LONG_CONSTANT("ODBC_BINMODE_CONVERT", 2, CONST_CS | CONST_PERSISTENT);
719    /* Define Constants for options
720       these Constants are defined in <sqlext.h>
721    */
722    REGISTER_LONG_CONSTANT("SQL_ODBC_CURSORS", SQL_ODBC_CURSORS, CONST_PERSISTENT | CONST_CS);
723    REGISTER_LONG_CONSTANT("SQL_CUR_USE_DRIVER", SQL_CUR_USE_DRIVER, CONST_PERSISTENT | CONST_CS);
724    REGISTER_LONG_CONSTANT("SQL_CUR_USE_IF_NEEDED", SQL_CUR_USE_IF_NEEDED, CONST_PERSISTENT | CONST_CS);
725    REGISTER_LONG_CONSTANT("SQL_CUR_USE_ODBC", SQL_CUR_USE_ODBC, CONST_PERSISTENT | CONST_CS);
726
727
728    REGISTER_LONG_CONSTANT("SQL_CONCURRENCY", SQL_CONCURRENCY, CONST_PERSISTENT | CONST_CS);
729    REGISTER_LONG_CONSTANT("SQL_CONCUR_READ_ONLY", SQL_CONCUR_READ_ONLY, CONST_PERSISTENT | CONST_CS);
730    REGISTER_LONG_CONSTANT("SQL_CONCUR_LOCK", SQL_CONCUR_LOCK, CONST_PERSISTENT | CONST_CS);
731    REGISTER_LONG_CONSTANT("SQL_CONCUR_ROWVER", SQL_CONCUR_ROWVER, CONST_PERSISTENT | CONST_CS);
732    REGISTER_LONG_CONSTANT("SQL_CONCUR_VALUES", SQL_CONCUR_VALUES, CONST_PERSISTENT | CONST_CS);
733
734    REGISTER_LONG_CONSTANT("SQL_CURSOR_TYPE", SQL_CURSOR_TYPE, CONST_PERSISTENT | CONST_CS);
735    REGISTER_LONG_CONSTANT("SQL_CURSOR_FORWARD_ONLY", SQL_CURSOR_FORWARD_ONLY, CONST_PERSISTENT | CONST_CS);
736    REGISTER_LONG_CONSTANT("SQL_CURSOR_KEYSET_DRIVEN", SQL_CURSOR_KEYSET_DRIVEN, CONST_PERSISTENT | CONST_CS);
737    REGISTER_LONG_CONSTANT("SQL_CURSOR_DYNAMIC", SQL_CURSOR_DYNAMIC, CONST_PERSISTENT | CONST_CS);
738    REGISTER_LONG_CONSTANT("SQL_CURSOR_STATIC", SQL_CURSOR_STATIC, CONST_PERSISTENT | CONST_CS);
739
740    REGISTER_LONG_CONSTANT("SQL_KEYSET_SIZE", SQL_KEYSET_SIZE, CONST_PERSISTENT | CONST_CS);
741
742    /* these are for the Data Source type */
743    REGISTER_LONG_CONSTANT("SQL_FETCH_FIRST", SQL_FETCH_FIRST, CONST_PERSISTENT | CONST_CS);
744    REGISTER_LONG_CONSTANT("SQL_FETCH_NEXT", SQL_FETCH_NEXT, CONST_PERSISTENT | CONST_CS);
745
746    /*
747     * register the standard data types
748     */
749    REGISTER_LONG_CONSTANT("SQL_CHAR", SQL_CHAR, CONST_PERSISTENT | CONST_CS);
750    REGISTER_LONG_CONSTANT("SQL_VARCHAR", SQL_VARCHAR, CONST_PERSISTENT | CONST_CS);
751    REGISTER_LONG_CONSTANT("SQL_LONGVARCHAR", SQL_LONGVARCHAR, CONST_PERSISTENT | CONST_CS);
752    REGISTER_LONG_CONSTANT("SQL_DECIMAL", SQL_DECIMAL, CONST_PERSISTENT | CONST_CS);
753    REGISTER_LONG_CONSTANT("SQL_NUMERIC", SQL_NUMERIC, CONST_PERSISTENT | CONST_CS);
754    REGISTER_LONG_CONSTANT("SQL_BIT", SQL_BIT, CONST_PERSISTENT | CONST_CS);
755    REGISTER_LONG_CONSTANT("SQL_TINYINT", SQL_TINYINT, CONST_PERSISTENT | CONST_CS);
756    REGISTER_LONG_CONSTANT("SQL_SMALLINT", SQL_SMALLINT, CONST_PERSISTENT | CONST_CS);
757    REGISTER_LONG_CONSTANT("SQL_INTEGER", SQL_INTEGER, CONST_PERSISTENT | CONST_CS);
758    REGISTER_LONG_CONSTANT("SQL_BIGINT", SQL_BIGINT, CONST_PERSISTENT | CONST_CS);
759    REGISTER_LONG_CONSTANT("SQL_REAL", SQL_REAL, CONST_PERSISTENT | CONST_CS);
760    REGISTER_LONG_CONSTANT("SQL_FLOAT", SQL_FLOAT, CONST_PERSISTENT | CONST_CS);
761    REGISTER_LONG_CONSTANT("SQL_DOUBLE", SQL_DOUBLE, CONST_PERSISTENT | CONST_CS);
762    REGISTER_LONG_CONSTANT("SQL_BINARY", SQL_BINARY, CONST_PERSISTENT | CONST_CS);
763    REGISTER_LONG_CONSTANT("SQL_VARBINARY", SQL_VARBINARY, CONST_PERSISTENT | CONST_CS);
764    REGISTER_LONG_CONSTANT("SQL_LONGVARBINARY", SQL_LONGVARBINARY, CONST_PERSISTENT | CONST_CS);
765    REGISTER_LONG_CONSTANT("SQL_DATE", SQL_DATE, CONST_PERSISTENT | CONST_CS);
766    REGISTER_LONG_CONSTANT("SQL_TIME", SQL_TIME, CONST_PERSISTENT | CONST_CS);
767    REGISTER_LONG_CONSTANT("SQL_TIMESTAMP", SQL_TIMESTAMP, CONST_PERSISTENT | CONST_CS);
768#if defined(ODBCVER) && (ODBCVER >= 0x0300)
769    REGISTER_LONG_CONSTANT("SQL_TYPE_DATE", SQL_TYPE_DATE, CONST_PERSISTENT | CONST_CS);
770    REGISTER_LONG_CONSTANT("SQL_TYPE_TIME", SQL_TYPE_TIME, CONST_PERSISTENT | CONST_CS);
771    REGISTER_LONG_CONSTANT("SQL_TYPE_TIMESTAMP", SQL_TYPE_TIMESTAMP, CONST_PERSISTENT | CONST_CS);
772    REGISTER_LONG_CONSTANT("SQL_WCHAR", SQL_WCHAR, CONST_PERSISTENT | CONST_CS);
773    REGISTER_LONG_CONSTANT("SQL_WVARCHAR", SQL_WVARCHAR, CONST_PERSISTENT | CONST_CS);
774    REGISTER_LONG_CONSTANT("SQL_WLONGVARCHAR", SQL_WLONGVARCHAR, CONST_PERSISTENT | CONST_CS);
775
776    /*
777     * SQLSpecialColumns values
778     */
779    REGISTER_LONG_CONSTANT("SQL_BEST_ROWID", SQL_BEST_ROWID, CONST_PERSISTENT | CONST_CS);
780    REGISTER_LONG_CONSTANT("SQL_ROWVER", SQL_ROWVER, CONST_PERSISTENT | CONST_CS);
781    REGISTER_LONG_CONSTANT("SQL_SCOPE_CURROW", SQL_SCOPE_CURROW, CONST_PERSISTENT | CONST_CS);
782    REGISTER_LONG_CONSTANT("SQL_SCOPE_TRANSACTION", SQL_SCOPE_TRANSACTION, CONST_PERSISTENT | CONST_CS);
783    REGISTER_LONG_CONSTANT("SQL_SCOPE_SESSION", SQL_SCOPE_SESSION, CONST_PERSISTENT | CONST_CS);
784    REGISTER_LONG_CONSTANT("SQL_NO_NULLS", SQL_NO_NULLS, CONST_PERSISTENT | CONST_CS);
785    REGISTER_LONG_CONSTANT("SQL_NULLABLE", SQL_NULLABLE, CONST_PERSISTENT | CONST_CS);
786
787    /*
788     * SQLStatistics values
789     */
790    REGISTER_LONG_CONSTANT("SQL_INDEX_UNIQUE", SQL_INDEX_UNIQUE, CONST_PERSISTENT | CONST_CS);
791    REGISTER_LONG_CONSTANT("SQL_INDEX_ALL", SQL_INDEX_ALL, CONST_PERSISTENT | CONST_CS);
792    REGISTER_LONG_CONSTANT("SQL_ENSURE", SQL_ENSURE, CONST_PERSISTENT | CONST_CS);
793    REGISTER_LONG_CONSTANT("SQL_QUICK", SQL_QUICK, CONST_PERSISTENT | CONST_CS);
794#endif
795
796#if defined(HAVE_IBMDB2) && defined(_AIX)
797    /* atexit() handler in the DB2/AIX library segfaults in PHP CLI */
798    /* DB2NOEXITLIST env variable prevents DB2 from invoking atexit() */
799    putenv("DB2NOEXITLIST=TRUE");
800#endif
801
802    return SUCCESS;
803}
804/* }}} */
805
806/* {{{ PHP_RINIT_FUNCTION */
807PHP_RINIT_FUNCTION(odbc)
808{
809    ODBCG(defConn) = -1;
810    ODBCG(num_links) = ODBCG(num_persistent);
811    memset(ODBCG(laststate), '\0', 6);
812    memset(ODBCG(lasterrormsg), '\0', SQL_MAX_MESSAGE_LENGTH);
813    return SUCCESS;
814}
815/* }}} */
816
817/* {{{ PHP_RSHUTDOWN_FUNCTION */
818PHP_RSHUTDOWN_FUNCTION(odbc)
819{
820    return SUCCESS;
821}
822/* }}} */
823
824/* {{{ PHP_MSHUTDOWN_FUNCTION */
825PHP_MSHUTDOWN_FUNCTION(odbc)
826{
827    UNREGISTER_INI_ENTRIES();
828    return SUCCESS;
829}
830/* }}} */
831
832/* {{{ PHP_MINFO_FUNCTION */
833PHP_MINFO_FUNCTION(odbc)
834{
835    char buf[32];
836
837    php_info_print_table_start();
838    php_info_print_table_header(2, "ODBC Support", "enabled");
839    snprintf(buf, sizeof(buf), ZEND_LONG_FMT, ODBCG(num_persistent));
840    php_info_print_table_row(2, "Active Persistent Links", buf);
841    snprintf(buf, sizeof(buf), ZEND_LONG_FMT, ODBCG(num_links));
842    php_info_print_table_row(2, "Active Links", buf);
843    php_info_print_table_row(2, "ODBC library", PHP_ODBC_TYPE);
844#ifdef ODBCVER
845    snprintf(buf, sizeof(buf), "0x%0.4x", ODBCVER);
846    php_info_print_table_row(2, "ODBCVER", buf);
847#endif
848#ifndef PHP_WIN32
849    php_info_print_table_row(2, "ODBC_INCLUDE", PHP_ODBC_INCLUDE);
850    php_info_print_table_row(2, "ODBC_LFLAGS", PHP_ODBC_LFLAGS);
851    php_info_print_table_row(2, "ODBC_LIBS", PHP_ODBC_LIBS);
852#endif
853    php_info_print_table_end();
854
855    DISPLAY_INI_ENTRIES();
856
857}
858/* }}} */
859
860/* {{{ odbc_sql_error */
861void odbc_sql_error(ODBC_SQL_ERROR_PARAMS)
862{
863    char        state[6];
864    SQLINTEGER  error;        /* Not used */
865    char        errormsg[SQL_MAX_MESSAGE_LENGTH];
866    SQLSMALLINT errormsgsize; /* Not used */
867    RETCODE rc;
868    ODBC_SQL_ENV_T henv;
869    ODBC_SQL_CONN_T conn;
870
871    if (conn_resource) {
872        henv = conn_resource->henv;
873        conn = conn_resource->hdbc;
874    } else {
875        henv = SQL_NULL_HENV;
876        conn = SQL_NULL_HDBC;
877    }
878
879    /* This leads to an endless loop in many drivers!
880     *
881       while(henv != SQL_NULL_HENV){
882        do {
883     */
884    rc = SQLError(henv, conn, stmt, state, &error, errormsg, sizeof(errormsg)-1, &errormsgsize);
885    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
886        snprintf(state, sizeof(state), "HY000");
887        snprintf(errormsg, sizeof(errormsg), "Failed to fetch error message");
888    }
889    if (conn_resource) {
890        memcpy(conn_resource->laststate, state, sizeof(state));
891        memcpy(conn_resource->lasterrormsg, errormsg, sizeof(errormsg));
892    }
893    memcpy(ODBCG(laststate), state, sizeof(state));
894    memcpy(ODBCG(lasterrormsg), errormsg, sizeof(errormsg));
895    if (func) {
896        php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s in %s", errormsg, state, func);
897    } else {
898        php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s", errormsg, state);
899    }
900    /*
901        } while (SQL_SUCCEEDED(rc));
902    }
903    */
904}
905/* }}} */
906
907/* {{{ php_odbc_fetch_attribs */
908void php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAMETERS, int mode)
909{
910    odbc_result *result;
911    zval *pv_res;
912    zend_long flag;
913
914    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &flag) == FAILURE) {
915        return;
916    }
917
918    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
919        RETURN_FALSE;
920    }
921
922    if (mode) {
923        result->longreadlen = flag;
924    } else {
925        result->binmode = flag;
926    }
927
928    RETURN_TRUE;
929}
930/* }}} */
931
932/* {{{ odbc_bindcols */
933int odbc_bindcols(odbc_result *result)
934{
935    RETCODE rc;
936    int i;
937    SQLSMALLINT     colnamelen; /* Not used */
938    SQLLEN          displaysize;
939    SQLUSMALLINT    colfieldid;
940    int     charextraalloc;
941
942    result->values = (odbc_result_value *) safe_emalloc(sizeof(odbc_result_value), result->numcols, 0);
943
944    result->longreadlen = ODBCG(defaultlrl);
945    result->binmode = ODBCG(defaultbinmode);
946
947    for(i = 0; i < result->numcols; i++) {
948        charextraalloc = 0;
949        colfieldid = SQL_COLUMN_DISPLAY_SIZE;
950
951        rc = SQLColAttributes(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_NAME,
952                result->values[i].name, sizeof(result->values[i].name), &colnamelen, 0);
953        rc = SQLColAttributes(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_TYPE,
954                NULL, 0, NULL, &result->values[i].coltype);
955
956        /* Don't bind LONG / BINARY columns, so that fetch behaviour can
957         * be controlled by odbc_binmode() / odbc_longreadlen()
958         */
959
960        switch(result->values[i].coltype) {
961            case SQL_BINARY:
962            case SQL_VARBINARY:
963            case SQL_LONGVARBINARY:
964            case SQL_LONGVARCHAR:
965#if defined(ODBCVER) && (ODBCVER >= 0x0300)
966            case SQL_WLONGVARCHAR:
967#endif
968                result->values[i].value = NULL;
969                break;
970
971#ifdef HAVE_ADABAS
972            case SQL_TIMESTAMP:
973                result->values[i].value = (char *)emalloc(27);
974                SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value,
975                            27, &result->values[i].vallen);
976                break;
977#endif /* HAVE_ADABAS */
978            case SQL_CHAR:
979            case SQL_VARCHAR:
980#if defined(ODBCVER) && (ODBCVER >= 0x0300)
981            case SQL_WCHAR:
982            case SQL_WVARCHAR:
983                colfieldid = SQL_DESC_OCTET_LENGTH;
984#else
985                charextraalloc = 1;
986#endif
987            default:
988                rc = SQLColAttributes(result->stmt, (SQLUSMALLINT)(i+1), colfieldid,
989                                NULL, 0, NULL, &displaysize);
990                /* Workaround for Oracle ODBC Driver bug (#50162) when fetching TIMESTAMP column */
991                if (result->values[i].coltype == SQL_TIMESTAMP) {
992                    displaysize += 3;
993                }
994
995                if (charextraalloc) {
996                    /* Since we don't know the exact # of bytes, allocate extra */
997                    displaysize *= 4;
998                }
999                result->values[i].value = (char *)emalloc(displaysize + 1);
1000                rc = SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value,
1001                            displaysize + 1, &result->values[i].vallen);
1002                break;
1003        }
1004    }
1005    return 1;
1006}
1007/* }}} */
1008
1009/* {{{ odbc_transact */
1010void odbc_transact(INTERNAL_FUNCTION_PARAMETERS, int type)
1011{
1012    odbc_connection *conn;
1013    RETCODE rc;
1014    zval *pv_conn;
1015
1016    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_conn) == FAILURE) {
1017        return;
1018    }
1019
1020    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1021        RETURN_FALSE;
1022    }
1023
1024    rc = SQLTransact(conn->henv, conn->hdbc, (SQLUSMALLINT)((type)?SQL_COMMIT:SQL_ROLLBACK));
1025    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1026        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTransact");
1027        RETURN_FALSE;
1028    }
1029
1030    RETURN_TRUE;
1031}
1032/* }}} */
1033
1034/* {{{ _close_pconn_with_res */
1035static int _close_pconn_with_res(zend_resource *le, zend_resource *res)
1036{
1037    if (le->type == le_pconn && (((odbc_connection *)(le->ptr))->res == res)){
1038        return 1;
1039    }else{
1040        return 0;
1041    }
1042}
1043/* }}} */
1044
1045/* {{{ odbc_column_lengths */
1046void odbc_column_lengths(INTERNAL_FUNCTION_PARAMETERS, int type)
1047{
1048    odbc_result *result;
1049#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30)
1050    /* this seems to be necessary for Solid2.3 ( tested by
1051     * tammy@synchronis.com) and Solid 3.0 (tested by eric@terra.telemediair.nl)
1052     * Solid does not seem to declare a SQLINTEGER, but it does declare a
1053     * SQL_INTEGER which does not work (despite being the same type as a SDWORD.
1054     * Solid 3.5 does not have this issue.
1055     */
1056    SDWORD len;
1057#else
1058    SQLLEN len;
1059#endif
1060    zval *pv_res;
1061    zend_long pv_num;
1062
1063    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
1064        return;
1065    }
1066
1067    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1068        RETURN_FALSE;
1069    }
1070
1071    if (result->numcols == 0) {
1072        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1073        RETURN_FALSE;
1074    }
1075
1076    if (pv_num > result->numcols) {
1077        php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
1078        RETURN_FALSE;
1079    }
1080
1081    if (pv_num < 1) {
1082        php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
1083        RETURN_FALSE;
1084    }
1085
1086    SQLColAttributes(result->stmt, (SQLUSMALLINT)pv_num, (SQLUSMALLINT) (type?SQL_COLUMN_SCALE:SQL_COLUMN_PRECISION), NULL, 0, NULL, &len);
1087
1088    RETURN_LONG(len);
1089}
1090/* }}} */
1091
1092/* Main User Functions */
1093
1094/* {{{ proto void odbc_close_all(void)
1095   Close all ODBC connections */
1096PHP_FUNCTION(odbc_close_all)
1097{
1098    zend_resource *p;
1099
1100    if (zend_parse_parameters_none() == FAILURE) {
1101        return;
1102    }
1103
1104    /* Loop through list and close all statements */
1105    ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
1106        if (p->ptr && (p->type == le_result)) {
1107            zend_list_close(p);
1108        }
1109    } ZEND_HASH_FOREACH_END();
1110
1111    /* Second loop through list, now close all connections */
1112    ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
1113        if (p->ptr) {
1114            if (p->type == le_conn){
1115                zend_list_close(p);
1116            } else if (p->type == le_pconn){
1117                zend_list_close(p);
1118                /* Delete the persistent connection */
1119                zend_hash_apply_with_argument(&EG(persistent_list),
1120                    (apply_func_arg_t) _close_pconn_with_res, (void *)p);
1121            }
1122        }
1123    } ZEND_HASH_FOREACH_END();
1124}
1125/* }}} */
1126
1127/* {{{ proto bool odbc_binmode(int result_id, int mode)
1128   Handle binary column data */
1129PHP_FUNCTION(odbc_binmode)
1130{
1131    php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1132}
1133/* }}} */
1134
1135/* {{{ proto bool odbc_longreadlen(int result_id, int length)
1136   Handle LONG columns */
1137PHP_FUNCTION(odbc_longreadlen)
1138{
1139    php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1140}
1141/* }}} */
1142
1143/* {{{ proto resource odbc_prepare(resource connection_id, string query)
1144   Prepares a statement for execution */
1145PHP_FUNCTION(odbc_prepare)
1146{
1147    zval *pv_conn;
1148    char *query;
1149    size_t query_len;
1150    odbc_result *result = NULL;
1151    odbc_connection *conn;
1152    RETCODE rc;
1153#ifdef HAVE_SQL_EXTENDED_FETCH
1154    SQLUINTEGER      scrollopts;
1155#endif
1156
1157    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pv_conn, &query, &query_len) == FAILURE) {
1158        return;
1159    }
1160
1161    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1162        RETURN_FALSE;
1163    }
1164
1165    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
1166
1167    result->numparams = 0;
1168
1169    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
1170    if (rc == SQL_INVALID_HANDLE) {
1171        efree(result);
1172        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
1173        RETURN_FALSE;
1174    }
1175
1176    if (rc == SQL_ERROR) {
1177        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
1178        efree(result);
1179        RETURN_FALSE;
1180    }
1181
1182#ifdef HAVE_SQL_EXTENDED_FETCH
1183    /* Solid doesn't have ExtendedFetch, if DriverManager is used, get Info,
1184       whether Driver supports ExtendedFetch */
1185    rc = SQLGetInfo(conn->hdbc, SQL_FETCH_DIRECTION, (void *) &scrollopts, sizeof(scrollopts), NULL);
1186    if (rc == SQL_SUCCESS) {
1187        if ((result->fetch_abs = (scrollopts & SQL_FD_FETCH_ABSOLUTE))) {
1188            /* Try to set CURSOR_TYPE to dynamic. Driver will replace this with other
1189               type if not possible.
1190            */
1191            SQLSetStmtOption(result->stmt, SQL_CURSOR_TYPE, ODBCG(default_cursortype));
1192        }
1193    } else {
1194        result->fetch_abs = 0;
1195    }
1196#endif
1197
1198    rc = SQLPrepare(result->stmt, query, SQL_NTS);
1199    switch (rc) {
1200        case SQL_SUCCESS:
1201            break;
1202        case SQL_SUCCESS_WITH_INFO:
1203            odbc_sql_error(conn, result->stmt, "SQLPrepare");
1204            break;
1205        default:
1206            odbc_sql_error(conn, result->stmt, "SQLPrepare");
1207            RETURN_FALSE;
1208    }
1209
1210    SQLNumParams(result->stmt, &(result->numparams));
1211    SQLNumResultCols(result->stmt, &(result->numcols));
1212
1213    if (result->numcols > 0) {
1214        if (!odbc_bindcols(result)) {
1215            efree(result);
1216            RETURN_FALSE;
1217        }
1218    } else {
1219        result->values = NULL;
1220    }
1221    Z_ADDREF_P(pv_conn);
1222    result->conn_ptr = conn;
1223    result->fetched = 0;
1224    RETURN_RES(zend_register_resource(result, le_result));
1225}
1226/* }}} */
1227
1228/*
1229 * Execute prepared SQL statement. Supports only input parameters.
1230 */
1231
1232/* {{{ proto bool odbc_execute(resource result_id [, array parameters_array])
1233   Execute a prepared statement */
1234PHP_FUNCTION(odbc_execute)
1235{
1236    zval *pv_res, *pv_param_arr, *tmp;
1237    typedef struct params_t {
1238        SQLLEN vallen;
1239        int fp;
1240    } params_t;
1241    params_t *params = NULL;
1242    char *filename;
1243    unsigned char otype;
1244    SQLSMALLINT sqltype, ctype, scale;
1245    SQLSMALLINT nullable;
1246    SQLULEN precision;
1247    odbc_result *result;
1248    int numArgs, i, ne;
1249    RETCODE rc;
1250
1251    numArgs = ZEND_NUM_ARGS();
1252
1253    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|a", &pv_res, &pv_param_arr) == FAILURE) {
1254        return;
1255    }
1256
1257    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1258        RETURN_FALSE;
1259    }
1260
1261    /* XXX check for already bound parameters*/
1262    if (result->numparams > 0 && numArgs == 1) {
1263        php_error_docref(NULL, E_WARNING, "No parameters to SQL statement given");
1264        RETURN_FALSE;
1265    }
1266
1267    if (result->numparams > 0) {
1268        if ((ne = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr))) < result->numparams) {
1269            php_error_docref(NULL, E_WARNING,"Not enough parameters (%d should be %d) given", ne, result->numparams);
1270            RETURN_FALSE;
1271        }
1272
1273        zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
1274        params = (params_t *)safe_emalloc(sizeof(params_t), result->numparams, 0);
1275        for(i = 0; i < result->numparams; i++) {
1276            params[i].fp = -1;
1277        }
1278
1279        for(i = 1; i <= result->numparams; i++) {
1280            if ((tmp = zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr))) == NULL) {
1281                php_error_docref(NULL, E_WARNING,"Error getting parameter");
1282                SQLFreeStmt(result->stmt,SQL_RESET_PARAMS);
1283                for (i = 0; i < result->numparams; i++) {
1284                    if (params[i].fp != -1) {
1285                        close(params[i].fp);
1286                    }
1287                }
1288                efree(params);
1289                RETURN_FALSE;
1290            }
1291
1292            otype = Z_TYPE_P(tmp);
1293            convert_to_string_ex(tmp);
1294            if (Z_TYPE_P(tmp) != IS_STRING) {
1295                php_error_docref(NULL, E_WARNING,"Error converting parameter");
1296                SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1297                for (i = 0; i < result->numparams; i++) {
1298                    if (params[i].fp != -1) {
1299                        close(params[i].fp);
1300                    }
1301                }
1302                efree(params);
1303                RETURN_FALSE;
1304            }
1305
1306            rc = SQLDescribeParam(result->stmt, (SQLUSMALLINT)i, &sqltype, &precision, &scale, &nullable);
1307            params[i-1].vallen = Z_STRLEN_P(tmp);
1308            params[i-1].fp = -1;
1309            if (rc == SQL_ERROR) {
1310                odbc_sql_error(result->conn_ptr, result->stmt, "SQLDescribeParameter");
1311                SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1312                for (i = 0; i < result->numparams; i++) {
1313                    if (params[i].fp != -1) {
1314                        close(params[i].fp);
1315                    }
1316                }
1317                efree(params);
1318                RETURN_FALSE;
1319            }
1320
1321            if (IS_SQL_BINARY(sqltype)) {
1322                ctype = SQL_C_BINARY;
1323            } else {
1324                ctype = SQL_C_CHAR;
1325            }
1326
1327            if (Z_STRLEN_P(tmp) > 2 &&
1328                Z_STRVAL_P(tmp)[0] == '\'' &&
1329                Z_STRVAL_P(tmp)[Z_STRLEN_P(tmp) - 1] == '\'') {
1330
1331                if (CHECK_ZVAL_NULL_PATH(tmp)) {
1332                    RETURN_FALSE;
1333                }
1334                filename = estrndup(&Z_STRVAL_P(tmp)[1], Z_STRLEN_P(tmp) - 2);
1335                filename[strlen(filename)] = '\0';
1336
1337                /* Check the basedir */
1338                if (php_check_open_basedir(filename)) {
1339                    efree(filename);
1340                    SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1341                    for (i = 0; i < result->numparams; i++) {
1342                        if (params[i].fp != -1) {
1343                            close(params[i].fp);
1344                        }
1345                    }
1346                    efree(params);
1347                    RETURN_FALSE;
1348                }
1349
1350                if ((params[i-1].fp = open(filename,O_RDONLY)) == -1) {
1351                    php_error_docref(NULL, E_WARNING,"Can't open file %s", filename);
1352                    SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1353                    for (i = 0; i < result->numparams; i++) {
1354                        if (params[i].fp != -1) {
1355                            close(params[i].fp);
1356                        }
1357                    }
1358                    efree(params);
1359                    efree(filename);
1360                    RETURN_FALSE;
1361                }
1362
1363                efree(filename);
1364
1365                params[i-1].vallen = SQL_LEN_DATA_AT_EXEC(0);
1366
1367                rc = SQLBindParameter(result->stmt, (SQLUSMALLINT)i, SQL_PARAM_INPUT,
1368                                      ctype, sqltype, precision, scale,
1369                                      (void *)(intptr_t)params[i-1].fp, 0,
1370                                      &params[i-1].vallen);
1371            } else {
1372#ifdef HAVE_DBMAKER
1373                precision = params[i-1].vallen;
1374#endif
1375                if (otype == IS_NULL) {
1376                    params[i-1].vallen = SQL_NULL_DATA;
1377                }
1378
1379                rc = SQLBindParameter(result->stmt, (SQLUSMALLINT)i, SQL_PARAM_INPUT,
1380                                      ctype, sqltype, precision, scale,
1381                                      Z_STRVAL_P(tmp), 0,
1382                                      &params[i-1].vallen);
1383            }
1384            if (rc == SQL_ERROR) {
1385                odbc_sql_error(result->conn_ptr, result->stmt, "SQLBindParameter");
1386                SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1387                for (i = 0; i < result->numparams; i++) {
1388                    if (params[i].fp != -1) {
1389                        close(params[i].fp);
1390                    }
1391                }
1392                efree(params);
1393                RETURN_FALSE;
1394            }
1395            zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
1396        }
1397    }
1398    /* Close cursor, needed for doing multiple selects */
1399    rc = SQLFreeStmt(result->stmt, SQL_CLOSE);
1400
1401    if (rc == SQL_ERROR) {
1402        odbc_sql_error(result->conn_ptr, result->stmt, "SQLFreeStmt");
1403    }
1404
1405    rc = SQLExecute(result->stmt);
1406
1407    result->fetched = 0;
1408    if (rc == SQL_NEED_DATA) {
1409        char buf[4096];
1410        int fp, nbytes;
1411        while (rc == SQL_NEED_DATA) {
1412            rc = SQLParamData(result->stmt, (void*)&fp);
1413            if (rc == SQL_NEED_DATA) {
1414                while ((nbytes = read(fp, &buf, 4096)) > 0) {
1415                    SQLPutData(result->stmt, (void*)&buf, nbytes);
1416                }
1417            }
1418        }
1419    } else {
1420        switch (rc) {
1421            case SQL_SUCCESS:
1422                break;
1423            case SQL_NO_DATA_FOUND:
1424            case SQL_SUCCESS_WITH_INFO:
1425                odbc_sql_error(result->conn_ptr, result->stmt, "SQLExecute");
1426                break;
1427            default:
1428                odbc_sql_error(result->conn_ptr, result->stmt, "SQLExecute");
1429                RETVAL_FALSE;
1430        }
1431    }
1432
1433    if (result->numparams > 0) {
1434        SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1435        for(i = 0; i < result->numparams; i++) {
1436            if (params[i].fp != -1) {
1437                close(params[i].fp);
1438            }
1439        }
1440        efree(params);
1441    }
1442
1443    if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO || rc == SQL_NO_DATA_FOUND) {
1444        RETVAL_TRUE;
1445    }
1446
1447    if (result->numcols == 0) {
1448        SQLNumResultCols(result->stmt, &(result->numcols));
1449
1450        if (result->numcols > 0) {
1451            if (!odbc_bindcols(result)) {
1452                efree(result);
1453                RETVAL_FALSE;
1454            }
1455        } else {
1456            result->values = NULL;
1457        }
1458    }
1459}
1460/* }}} */
1461
1462/* {{{ proto string odbc_cursor(resource result_id)
1463   Get cursor name */
1464PHP_FUNCTION(odbc_cursor)
1465{
1466    zval *pv_res;
1467    SQLUSMALLINT max_len;
1468    SQLSMALLINT len;
1469    char *cursorname;
1470    odbc_result *result;
1471    RETCODE rc;
1472
1473    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1474        return;
1475    }
1476
1477    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1478        RETURN_FALSE;
1479    }
1480
1481    rc = SQLGetInfo(result->conn_ptr->hdbc,SQL_MAX_CURSOR_NAME_LEN, (void *)&max_len,sizeof(max_len),&len);
1482    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1483        RETURN_FALSE;
1484    }
1485
1486    if (max_len > 0) {
1487        cursorname = emalloc(max_len + 1);
1488        rc = SQLGetCursorName(result->stmt,cursorname,(SQLSMALLINT)max_len,&len);
1489        if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1490            char        state[6];     /* Not used */
1491            SQLINTEGER  error;        /* Not used */
1492            char        errormsg[SQL_MAX_MESSAGE_LENGTH];
1493            SQLSMALLINT errormsgsize; /* Not used */
1494
1495            SQLError( result->conn_ptr->henv, result->conn_ptr->hdbc,
1496                        result->stmt, state, &error, errormsg,
1497                        sizeof(errormsg)-1, &errormsgsize);
1498            if (!strncmp(state,"S1015",5)) {
1499                snprintf(cursorname, max_len+1, "php_curs_%d", (int)result->stmt);
1500                if (SQLSetCursorName(result->stmt,cursorname,SQL_NTS) != SQL_SUCCESS) {
1501                    odbc_sql_error(result->conn_ptr, result->stmt, "SQLSetCursorName");
1502                    RETVAL_FALSE;
1503                } else {
1504                    RETVAL_STRING(cursorname);
1505                }
1506            } else {
1507                php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s", errormsg, state);
1508                RETVAL_FALSE;
1509            }
1510        } else {
1511            RETVAL_STRING(cursorname);
1512        }
1513        efree(cursorname);
1514    } else {
1515        RETVAL_FALSE;
1516    }
1517}
1518/* }}} */
1519
1520#ifdef HAVE_SQLDATASOURCES
1521/* {{{ proto array odbc_data_source(resource connection_id, int fetch_type)
1522   Return information about the currently connected data source */
1523PHP_FUNCTION(odbc_data_source)
1524{
1525    zval *zv_conn;
1526    zend_long zv_fetch_type;
1527    RETCODE rc = 0; /* assume all is good */
1528    odbc_connection *conn;
1529    UCHAR server_name[100], desc[200];
1530    SQLSMALLINT len1=0, len2=0, fetch_type;
1531
1532    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zv_conn, &zv_fetch_type) == FAILURE) {
1533        return;
1534    }
1535
1536    fetch_type = (SQLSMALLINT) zv_fetch_type;
1537
1538    if (!(fetch_type == SQL_FETCH_FIRST || fetch_type == SQL_FETCH_NEXT)) {
1539        php_error_docref(NULL, E_WARNING, "Invalid fetch type (%d)", fetch_type);
1540        RETURN_FALSE;
1541    }
1542
1543    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(zv_conn), "ODBC-Link", le_conn, le_pconn))) {
1544        RETURN_FALSE;
1545    }
1546
1547    /* now we have the "connection" lets call the DataSource object */
1548    rc = SQLDataSources(conn->henv,
1549            fetch_type,
1550            server_name,
1551            (SQLSMALLINT)sizeof(server_name),
1552            &len1,
1553            desc,
1554            (SQLSMALLINT)sizeof(desc),
1555            &len2);
1556
1557    if (rc != SQL_SUCCESS) {
1558        /* ummm.... he did it */
1559        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLDataSources");
1560        RETURN_FALSE;
1561    }
1562
1563    if (len1 == 0 || len2 == 0) {
1564        /* we have a non-valid entry... so stop the looping */
1565        RETURN_FALSE;
1566    }
1567
1568    array_init(return_value);
1569
1570    add_assoc_string_ex(return_value, "server", sizeof("server")-1, server_name);
1571    add_assoc_string_ex(return_value, "description", sizeof("description")-1, desc);
1572
1573}
1574/* }}} */
1575#endif /* HAVE_SQLDATASOURCES */
1576
1577/* {{{ proto resource odbc_exec(resource connection_id, string query [, int flags])
1578   Prepare and execute an SQL statement */
1579/* XXX Use flags */
1580PHP_FUNCTION(odbc_exec)
1581{
1582    zval *pv_conn;
1583    zend_long pv_flags;
1584    int numArgs;
1585    char *query;
1586    size_t query_len;
1587    odbc_result *result = NULL;
1588    odbc_connection *conn;
1589    RETCODE rc;
1590#ifdef HAVE_SQL_EXTENDED_FETCH
1591    SQLUINTEGER      scrollopts;
1592#endif
1593
1594    numArgs = ZEND_NUM_ARGS();
1595
1596    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|l", &pv_conn, &query, &query_len, &pv_flags) == FAILURE) {
1597        return;
1598    }
1599
1600    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1601        RETURN_FALSE;
1602    }
1603
1604    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
1605
1606    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
1607    if (rc == SQL_INVALID_HANDLE) {
1608        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
1609        efree(result);
1610        RETURN_FALSE;
1611    }
1612
1613    if (rc == SQL_ERROR) {
1614        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
1615        efree(result);
1616        RETURN_FALSE;
1617    }
1618
1619#ifdef HAVE_SQL_EXTENDED_FETCH
1620    /* Solid doesn't have ExtendedFetch, if DriverManager is used, get Info,
1621       whether Driver supports ExtendedFetch */
1622    rc = SQLGetInfo(conn->hdbc, SQL_FETCH_DIRECTION, (void *) &scrollopts, sizeof(scrollopts), NULL);
1623    if (rc == SQL_SUCCESS) {
1624        if ((result->fetch_abs = (scrollopts & SQL_FD_FETCH_ABSOLUTE))) {
1625            /* Try to set CURSOR_TYPE to dynamic. Driver will replace this with other
1626               type if not possible.
1627             */
1628            SQLSetStmtOption(result->stmt, SQL_CURSOR_TYPE, ODBCG(default_cursortype));
1629        }
1630    } else {
1631        result->fetch_abs = 0;
1632    }
1633#endif
1634
1635    rc = SQLExecDirect(result->stmt, query, SQL_NTS);
1636    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && rc != SQL_NO_DATA_FOUND) {
1637        /* XXX FIXME we should really check out SQLSTATE with SQLError
1638         * in case rc is SQL_SUCCESS_WITH_INFO here.
1639         */
1640        odbc_sql_error(conn, result->stmt, "SQLExecDirect");
1641        SQLFreeStmt(result->stmt, SQL_DROP);
1642        efree(result);
1643        RETURN_FALSE;
1644    }
1645
1646    SQLNumResultCols(result->stmt, &(result->numcols));
1647
1648    /* For insert, update etc. cols == 0 */
1649    if (result->numcols > 0) {
1650        if (!odbc_bindcols(result)) {
1651            efree(result);
1652            RETURN_FALSE;
1653        }
1654    } else {
1655        result->values = NULL;
1656    }
1657    Z_ADDREF_P(pv_conn);
1658    result->conn_ptr = conn;
1659    result->fetched = 0;
1660    RETURN_RES(zend_register_resource(result, le_result));
1661}
1662/* }}} */
1663
1664#ifdef PHP_ODBC_HAVE_FETCH_HASH
1665#define ODBC_NUM  1
1666#define ODBC_OBJECT  2
1667
1668/* {{{ php_odbc_fetch_hash */
1669static void php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, int result_type)
1670{
1671    int i;
1672    odbc_result *result;
1673    RETCODE rc;
1674    SQLSMALLINT sql_c_type;
1675    char *buf = NULL;
1676#ifdef HAVE_SQL_EXTENDED_FETCH
1677    SQLULEN crow;
1678    SQLUSMALLINT RowStatus[1];
1679    SQLLEN rownum;
1680    zval *pv_res, tmp;
1681    zend_long pv_row = -1;
1682
1683    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_res, &pv_row) == FAILURE) {
1684        return;
1685    }
1686
1687    rownum = pv_row;
1688#else
1689    zval *pv_res, tmp;
1690
1691    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1692        return;
1693    }
1694#endif
1695
1696    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1697        RETURN_FALSE;
1698    }
1699
1700    if (result->numcols == 0) {
1701        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1702        RETURN_FALSE;
1703    }
1704
1705#ifdef HAVE_SQL_EXTENDED_FETCH
1706    if (result->fetch_abs) {
1707        if (rownum > 0) {
1708            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
1709        } else {
1710            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
1711        }
1712    } else
1713#endif
1714    rc = SQLFetch(result->stmt);
1715
1716    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1717        RETURN_FALSE;
1718    }
1719
1720    array_init(return_value);
1721
1722#ifdef HAVE_SQL_EXTENDED_FETCH
1723    if (rownum > 0 && result->fetch_abs)
1724        result->fetched = rownum;
1725    else
1726#endif
1727        result->fetched++;
1728
1729    for(i = 0; i < result->numcols; i++) {
1730        sql_c_type = SQL_C_CHAR;
1731
1732        switch(result->values[i].coltype) {
1733            case SQL_BINARY:
1734            case SQL_VARBINARY:
1735            case SQL_LONGVARBINARY:
1736                if (result->binmode <= 0) {
1737                    ZVAL_EMPTY_STRING(&tmp);
1738                    break;
1739                }
1740                if (result->binmode == 1) {
1741                    sql_c_type = SQL_C_BINARY;
1742                }
1743            case SQL_LONGVARCHAR:
1744#if defined(ODBCVER) && (ODBCVER >= 0x0300)
1745            case SQL_WLONGVARCHAR:
1746#endif
1747                if (IS_SQL_LONG(result->values[i].coltype) && result->longreadlen <= 0) {
1748                    ZVAL_EMPTY_STRING(&tmp);
1749                    break;
1750                }
1751                if (buf == NULL) {
1752                    buf = emalloc(result->longreadlen + 1);
1753                }
1754
1755                rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1), sql_c_type, buf, result->longreadlen + 1, &result->values[i].vallen);
1756
1757                if (rc == SQL_ERROR) {
1758                    odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
1759                    efree(buf);
1760                    RETURN_FALSE;
1761                }
1762
1763                if (rc == SQL_SUCCESS_WITH_INFO) {
1764                    ZVAL_STRINGL(&tmp, buf, result->longreadlen);
1765                } else if (result->values[i].vallen == SQL_NULL_DATA) {
1766                    ZVAL_NULL(&tmp);
1767                    break;
1768                } else {
1769                    ZVAL_STRINGL(&tmp, buf, result->values[i].vallen);
1770                }
1771                break;
1772
1773            default:
1774                if (result->values[i].vallen == SQL_NULL_DATA) {
1775                    ZVAL_NULL(&tmp);
1776                    break;
1777                }
1778                ZVAL_STRINGL(&tmp, result->values[i].value, result->values[i].vallen);
1779                break;
1780        }
1781
1782        if (result_type & ODBC_NUM) {
1783            zend_hash_index_update(Z_ARRVAL_P(return_value), i, &tmp);
1784        } else {
1785            if (!*(result->values[i].name) && Z_TYPE(tmp) == IS_STRING) {
1786                zend_hash_update(Z_ARRVAL_P(return_value), Z_STR(tmp), &tmp);
1787            } else {
1788                zend_hash_str_update(Z_ARRVAL_P(return_value), result->values[i].name, strlen(result->values[i].name), &tmp);
1789            }
1790        }
1791    }
1792    if (buf) {
1793        efree(buf);
1794    }
1795}
1796/* }}} */
1797
1798
1799/* {{{ proto object odbc_fetch_object(int result [, int rownumber])
1800   Fetch a result row as an object */
1801PHP_FUNCTION(odbc_fetch_object)
1802{
1803    php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, ODBC_OBJECT);
1804    if (Z_TYPE_P(return_value) == IS_ARRAY) {
1805        object_and_properties_init(return_value, ZEND_STANDARD_CLASS_DEF_PTR, Z_ARRVAL_P(return_value));
1806    }
1807}
1808/* }}} */
1809
1810/* {{{ proto array odbc_fetch_array(int result [, int rownumber])
1811   Fetch a result row as an associative array */
1812PHP_FUNCTION(odbc_fetch_array)
1813{
1814    php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, ODBC_OBJECT);
1815}
1816/* }}} */
1817#endif
1818
1819/* {{{ proto int odbc_fetch_into(resource result_id, array &result_array, [, int rownumber])
1820   Fetch one result row into an array */
1821PHP_FUNCTION(odbc_fetch_into)
1822{
1823    int i;
1824    odbc_result *result;
1825    RETCODE rc;
1826    SQLSMALLINT sql_c_type;
1827    char *buf = NULL;
1828    zval *pv_res, *pv_res_arr, tmp;
1829#ifdef HAVE_SQL_EXTENDED_FETCH
1830    zend_long pv_row = 0;
1831    SQLULEN crow;
1832    SQLUSMALLINT RowStatus[1];
1833    SQLLEN rownum = -1;
1834#endif /* HAVE_SQL_EXTENDED_FETCH */
1835
1836#ifdef HAVE_SQL_EXTENDED_FETCH
1837    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz/|l", &pv_res, &pv_res_arr, &pv_row) == FAILURE) {
1838        return;
1839    }
1840
1841    rownum = pv_row;
1842#else
1843    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz/", &pv_res, &pv_res_arr) == FAILURE) {
1844        return;
1845    }
1846#endif /* HAVE_SQL_EXTENDED_FETCH */
1847
1848    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1849        RETURN_FALSE;
1850    }
1851
1852    if (result->numcols == 0) {
1853        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1854        RETURN_FALSE;
1855    }
1856
1857    if (Z_TYPE_P(pv_res_arr) != IS_ARRAY) {
1858        array_init(pv_res_arr);
1859    }
1860
1861#ifdef HAVE_SQL_EXTENDED_FETCH
1862    if (result->fetch_abs) {
1863        if (rownum > 0) {
1864            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
1865        } else {
1866            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
1867        }
1868    } else
1869#endif
1870        rc = SQLFetch(result->stmt);
1871
1872    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1873        RETURN_FALSE;
1874    }
1875
1876#ifdef HAVE_SQL_EXTENDED_FETCH
1877    if (rownum > 0 && result->fetch_abs)
1878        result->fetched = rownum;
1879    else
1880#endif
1881        result->fetched++;
1882
1883    for(i = 0; i < result->numcols; i++) {
1884        sql_c_type = SQL_C_CHAR;
1885
1886        switch(result->values[i].coltype) {
1887            case SQL_BINARY:
1888            case SQL_VARBINARY:
1889            case SQL_LONGVARBINARY:
1890                if (result->binmode <= 0) {
1891                    ZVAL_EMPTY_STRING(&tmp);
1892                    break;
1893                }
1894                if (result->binmode == 1) sql_c_type = SQL_C_BINARY;
1895
1896            case SQL_LONGVARCHAR:
1897#if defined(ODBCVER) && (ODBCVER >= 0x0300)
1898            case SQL_WLONGVARCHAR:
1899#endif
1900                if (IS_SQL_LONG(result->values[i].coltype) && result->longreadlen <= 0) {
1901                    ZVAL_EMPTY_STRING(&tmp);
1902                    break;
1903                }
1904
1905                if (buf == NULL) {
1906                    buf = emalloc(result->longreadlen + 1);
1907                }
1908                rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1),sql_c_type, buf, result->longreadlen + 1, &result->values[i].vallen);
1909
1910                if (rc == SQL_ERROR) {
1911                    odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
1912                    efree(buf);
1913                    RETURN_FALSE;
1914                }
1915                if (rc == SQL_SUCCESS_WITH_INFO) {
1916                    ZVAL_STRINGL(&tmp, buf, result->longreadlen);
1917                } else if (result->values[i].vallen == SQL_NULL_DATA) {
1918                    ZVAL_NULL(&tmp);
1919                    break;
1920                } else {
1921                    ZVAL_STRINGL(&tmp, buf, result->values[i].vallen);
1922                }
1923                break;
1924
1925            default:
1926                if (result->values[i].vallen == SQL_NULL_DATA) {
1927                    ZVAL_NULL(&tmp);
1928                    break;
1929                }
1930                ZVAL_STRINGL(&tmp, result->values[i].value, result->values[i].vallen);
1931                break;
1932        }
1933        zend_hash_index_update(Z_ARRVAL_P(pv_res_arr), i, &tmp);
1934    }
1935    if (buf) efree(buf);
1936    RETURN_LONG(result->numcols);
1937}
1938/* }}} */
1939
1940/* {{{ proto bool solid_fetch_prev(resource result_id)
1941   */
1942#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30) || defined(HAVE_SOLID_35)
1943PHP_FUNCTION(solid_fetch_prev)
1944{
1945    odbc_result *result;
1946    RETCODE rc;
1947    zval *pv_res;
1948
1949    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1950        return;
1951    }
1952
1953    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1954        RETURN_FALSE;
1955    }
1956    if (result->numcols == 0) {
1957        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1958        RETURN_FALSE;
1959    }
1960    rc = SQLFetchPrev(result->stmt);
1961
1962    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1963        RETURN_FALSE;
1964    }
1965
1966    if (result->fetched > 1) {
1967        result->fetched--;
1968    }
1969
1970    RETURN_TRUE;
1971}
1972#endif
1973/* }}} */
1974
1975/* {{{ proto bool odbc_fetch_row(resource result_id [, int row_number])
1976   Fetch a row */
1977PHP_FUNCTION(odbc_fetch_row)
1978{
1979    SQLLEN rownum;
1980    odbc_result *result;
1981    RETCODE rc;
1982    zval *pv_res;
1983    zend_long pv_row = 1;
1984#ifdef HAVE_SQL_EXTENDED_FETCH
1985    SQLULEN crow;
1986    SQLUSMALLINT RowStatus[1];
1987#endif
1988
1989    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_res, &pv_row) == FAILURE) {
1990        return;
1991    }
1992
1993    rownum = pv_row;
1994
1995    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1996        RETURN_FALSE;
1997    }
1998
1999    if (result->numcols == 0) {
2000        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2001        RETURN_FALSE;
2002    }
2003
2004#ifdef HAVE_SQL_EXTENDED_FETCH
2005    if (result->fetch_abs) {
2006        if (ZEND_NUM_ARGS() > 1) {
2007            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
2008        } else {
2009            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2010        }
2011    } else
2012#endif
2013        rc = SQLFetch(result->stmt);
2014
2015    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2016        RETURN_FALSE;
2017    }
2018
2019    if (ZEND_NUM_ARGS() > 1) {
2020        result->fetched = rownum;
2021    } else {
2022        result->fetched++;
2023    }
2024
2025    RETURN_TRUE;
2026}
2027/* }}} */
2028
2029/* {{{ proto mixed odbc_result(resource result_id, mixed field)
2030   Get result data */
2031PHP_FUNCTION(odbc_result)
2032{
2033    char *field;
2034    int field_ind;
2035    SQLSMALLINT sql_c_type = SQL_C_CHAR;
2036    odbc_result *result;
2037    int i = 0;
2038    RETCODE rc;
2039    SQLLEN  fieldsize;
2040    zval *pv_res, *pv_field;
2041#ifdef HAVE_SQL_EXTENDED_FETCH
2042    SQLULEN crow;
2043    SQLUSMALLINT RowStatus[1];
2044#endif
2045
2046    field_ind = -1;
2047    field = NULL;
2048
2049    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz", &pv_res, &pv_field) == FAILURE) {
2050        return;
2051    }
2052
2053    if (Z_TYPE_P(pv_field) == IS_STRING) {
2054        field = Z_STRVAL_P(pv_field);
2055    } else {
2056        convert_to_long_ex(pv_field);
2057        field_ind = Z_LVAL_P(pv_field) - 1;
2058    }
2059
2060    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2061        RETURN_FALSE;
2062    }
2063
2064    if ((result->numcols == 0)) {
2065        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2066        RETURN_FALSE;
2067    }
2068
2069    /* get field index if the field parameter was a string */
2070    if (field != NULL) {
2071        if (result->values == NULL) {
2072            php_error_docref(NULL, E_WARNING, "Result set contains no data");
2073            RETURN_FALSE;
2074        }
2075
2076        for(i = 0; i < result->numcols; i++) {
2077            if (!strcasecmp(result->values[i].name, field)) {
2078                field_ind = i;
2079                break;
2080            }
2081        }
2082
2083        if (field_ind < 0) {
2084            php_error_docref(NULL, E_WARNING, "Field %s not found", field);
2085            RETURN_FALSE;
2086        }
2087    } else {
2088        /* check for limits of field_ind if the field parameter was an int */
2089        if (field_ind >= result->numcols || field_ind < 0) {
2090            php_error_docref(NULL, E_WARNING, "Field index is larger than the number of fields");
2091            RETURN_FALSE;
2092        }
2093    }
2094
2095    if (result->fetched == 0) {
2096        /* User forgot to call odbc_fetch_row(), or wants to reload the results, do it now */
2097#ifdef HAVE_SQL_EXTENDED_FETCH
2098        if (result->fetch_abs)
2099            rc = SQLExtendedFetch(result->stmt, SQL_FETCH_NEXT, 1, &crow,RowStatus);
2100        else
2101#endif
2102            rc = SQLFetch(result->stmt);
2103
2104        if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2105            RETURN_FALSE;
2106        }
2107
2108        result->fetched++;
2109    }
2110
2111    switch(result->values[field_ind].coltype) {
2112        case SQL_BINARY:
2113        case SQL_VARBINARY:
2114        case SQL_LONGVARBINARY:
2115            if (result->binmode <= 1) {
2116                sql_c_type = SQL_C_BINARY;
2117            }
2118            if (result->binmode <= 0) {
2119                break;
2120            }
2121        case SQL_LONGVARCHAR:
2122#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2123        case SQL_WLONGVARCHAR:
2124#endif
2125            if (IS_SQL_LONG(result->values[field_ind].coltype)) {
2126                if (result->longreadlen <= 0) {
2127                   break;
2128                } else {
2129                   fieldsize = result->longreadlen;
2130                }
2131            } else {
2132               SQLColAttributes(result->stmt, (SQLUSMALLINT)(field_ind + 1),
2133                                (SQLUSMALLINT)((sql_c_type == SQL_C_BINARY) ? SQL_COLUMN_LENGTH :
2134                                SQL_COLUMN_DISPLAY_SIZE),
2135                                NULL, 0, NULL, &fieldsize);
2136            }
2137            /* For char data, the length of the returned string will be longreadlen - 1 */
2138            fieldsize = (result->longreadlen <= 0) ? 4096 : result->longreadlen;
2139            field = emalloc(fieldsize);
2140
2141        /* SQLGetData will truncate CHAR data to fieldsize - 1 bytes and append \0.
2142         * For binary data it is truncated to fieldsize bytes.
2143         */
2144            rc = SQLGetData(result->stmt, (SQLUSMALLINT)(field_ind + 1), sql_c_type,
2145                            field, fieldsize, &result->values[field_ind].vallen);
2146
2147            if (rc == SQL_ERROR) {
2148                odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2149                efree(field);
2150                RETURN_FALSE;
2151            }
2152
2153            if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2154                efree(field);
2155                RETURN_NULL();
2156            } else if (rc == SQL_NO_DATA_FOUND) {
2157                efree(field);
2158                RETURN_FALSE;
2159            }
2160            /* Reduce fieldlen by 1 if we have char data. One day we might
2161               have binary strings... */
2162            if ((result->values[field_ind].coltype == SQL_LONGVARCHAR)
2163#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2164                || (result->values[field_ind].coltype == SQL_WLONGVARCHAR)
2165#endif
2166            ) {
2167                fieldsize -= 1;
2168            }
2169            /* Don't duplicate result, saves one emalloc.
2170               For SQL_SUCCESS, the length is in vallen.
2171             */
2172            RETVAL_STRINGL(field, (rc == SQL_SUCCESS_WITH_INFO) ? fieldsize : result->values[field_ind].vallen);
2173            // TODO: avoid dpouble reallocation ???
2174            efree(field);
2175            return;
2176            break;
2177
2178        default:
2179            if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2180                RETURN_NULL();
2181            } else {
2182                RETURN_STRINGL(result->values[field_ind].value, result->values[field_ind].vallen);
2183            }
2184            break;
2185    }
2186
2187/* If we come here, output unbound LONG and/or BINARY column data to the client */
2188
2189    /* We emalloc 1 byte more for SQL_C_CHAR (trailing \0) */
2190    fieldsize = (sql_c_type == SQL_C_CHAR) ? 4096 : 4095;
2191    field = emalloc(fieldsize);
2192
2193    /* Call SQLGetData() until SQL_SUCCESS is returned */
2194    while(1) {
2195        rc = SQLGetData(result->stmt, (SQLUSMALLINT)(field_ind + 1),sql_c_type, field, fieldsize, &result->values[field_ind].vallen);
2196
2197        if (rc == SQL_ERROR) {
2198            odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2199            efree(field);
2200            RETURN_FALSE;
2201        }
2202
2203        if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2204            efree(field);
2205            RETURN_NULL();
2206        }
2207        /* chop the trailing \0 by outputing only 4095 bytes */
2208        PHPWRITE(field,(rc == SQL_SUCCESS_WITH_INFO) ? 4095 : result->values[field_ind].vallen);
2209
2210        if (rc == SQL_SUCCESS) { /* no more data avail */
2211            efree(field);
2212            RETURN_TRUE;
2213        }
2214    }
2215    RETURN_TRUE;
2216}
2217/* }}} */
2218
2219/* {{{ proto int odbc_result_all(resource result_id [, string format])
2220   Print result as HTML table */
2221PHP_FUNCTION(odbc_result_all)
2222{
2223    char *buf = NULL;
2224    odbc_result *result;
2225    RETCODE rc;
2226    zval *pv_res;
2227    char *pv_format = NULL;
2228    size_t i, pv_format_len = 0;
2229    SQLSMALLINT sql_c_type;
2230#ifdef HAVE_SQL_EXTENDED_FETCH
2231    SQLULEN crow;
2232    SQLUSMALLINT RowStatus[1];
2233#endif
2234
2235    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s", &pv_res, &pv_format, &pv_format_len) == FAILURE) {
2236        return;
2237    }
2238
2239    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2240        RETURN_FALSE;
2241    }
2242
2243    if (result->numcols == 0) {
2244        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2245        RETURN_FALSE;
2246    }
2247#ifdef HAVE_SQL_EXTENDED_FETCH
2248    if (result->fetch_abs)
2249        rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2250    else
2251#endif
2252        rc = SQLFetch(result->stmt);
2253
2254    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2255        php_printf("<h2>No rows found</h2>\n");
2256        RETURN_LONG(0);
2257    }
2258
2259    /* Start table tag */
2260    if (ZEND_NUM_ARGS() == 1) {
2261        php_printf("<table><tr>");
2262    } else {
2263        php_printf("<table %s ><tr>", pv_format);
2264    }
2265
2266    for (i = 0; i < result->numcols; i++) {
2267        php_printf("<th>%s</th>", result->values[i].name);
2268    }
2269
2270    php_printf("</tr>\n");
2271
2272    while(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
2273        result->fetched++;
2274        php_printf("<tr>");
2275        for(i = 0; i < result->numcols; i++) {
2276            sql_c_type = SQL_C_CHAR;
2277            switch(result->values[i].coltype) {
2278                case SQL_BINARY:
2279                case SQL_VARBINARY:
2280                case SQL_LONGVARBINARY:
2281                    if (result->binmode <= 0) {
2282                        php_printf("<td>Not printable</td>");
2283                        break;
2284                    }
2285                    if (result->binmode <= 1) sql_c_type = SQL_C_BINARY;
2286                case SQL_LONGVARCHAR:
2287#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2288                case SQL_WLONGVARCHAR:
2289#endif
2290                    if (IS_SQL_LONG(result->values[i].coltype) &&
2291                        result->longreadlen <= 0) {
2292                        php_printf("<td>Not printable</td>");
2293                        break;
2294                    }
2295
2296                    if (buf == NULL) {
2297                        buf = emalloc(result->longreadlen);
2298                    }
2299
2300                    rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1),sql_c_type, buf, result->longreadlen, &result->values[i].vallen);
2301
2302                    php_printf("<td>");
2303
2304                    if (rc == SQL_ERROR) {
2305                        odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2306                        php_printf("</td></tr></table>");
2307                        efree(buf);
2308                        RETURN_FALSE;
2309                    }
2310                    if (rc == SQL_SUCCESS_WITH_INFO) {
2311                        PHPWRITE(buf, result->longreadlen);
2312                    } else if (result->values[i].vallen == SQL_NULL_DATA) {
2313                        php_printf("<td>NULL</td>");
2314                        break;
2315                    } else {
2316                        PHPWRITE(buf, result->values[i].vallen);
2317                    }
2318                    php_printf("</td>");
2319                    break;
2320                default:
2321                    if (result->values[i].vallen == SQL_NULL_DATA) {
2322                        php_printf("<td>NULL</td>");
2323                    } else {
2324                        php_printf("<td>%s</td>", result->values[i].value);
2325                    }
2326                    break;
2327            }
2328        }
2329        php_printf("</tr>\n");
2330
2331#ifdef HAVE_SQL_EXTENDED_FETCH
2332        if (result->fetch_abs)
2333            rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2334        else
2335#endif
2336            rc = SQLFetch(result->stmt);
2337    }
2338    php_printf("</table>\n");
2339    if (buf) efree(buf);
2340    RETURN_LONG(result->fetched);
2341}
2342/* }}} */
2343
2344/* {{{ proto bool odbc_free_result(resource result_id)
2345   Free resources associated with a result */
2346PHP_FUNCTION(odbc_free_result)
2347{
2348    zval *pv_res;
2349    odbc_result *result;
2350    int i;
2351
2352    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2353        return;
2354    }
2355
2356    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2357        RETURN_FALSE;
2358    }
2359
2360    if (result->values) {
2361        for (i = 0; i < result->numcols; i++) {
2362            if (result->values[i].value) {
2363                efree(result->values[i].value);
2364            }
2365        }
2366        efree(result->values);
2367        result->values = NULL;
2368    }
2369
2370    zend_list_close(Z_RES_P(pv_res));
2371
2372    RETURN_TRUE;
2373}
2374/* }}} */
2375
2376/* {{{ proto resource odbc_connect(string DSN, string user, string password [, int cursor_option])
2377   Connect to a datasource */
2378PHP_FUNCTION(odbc_connect)
2379{
2380    odbc_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2381}
2382/* }}} */
2383
2384/* {{{ proto resource odbc_pconnect(string DSN, string user, string password [, int cursor_option])
2385   Establish a persistent connection to a datasource */
2386PHP_FUNCTION(odbc_pconnect)
2387{
2388    odbc_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2389}
2390/* }}} */
2391
2392/* {{{ odbc_sqlconnect */
2393int odbc_sqlconnect(odbc_connection **conn, char *db, char *uid, char *pwd, int cur_opt, int persistent)
2394{
2395    RETCODE rc;
2396
2397    *conn = (odbc_connection *)pemalloc(sizeof(odbc_connection), persistent);
2398    (*conn)->persistent = persistent;
2399    SQLAllocEnv(&((*conn)->henv));
2400    SQLAllocConnect((*conn)->henv, &((*conn)->hdbc));
2401
2402#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30)
2403    SQLSetConnectOption((*conn)->hdbc, SQL_TRANSLATE_OPTION,
2404            SQL_SOLID_XLATOPT_NOCNV);
2405#endif
2406#ifdef HAVE_ODBC_ROUTER
2407    {
2408#define CONNSTRSIZE 2048
2409     char *lpszConnStr = emalloc(CONNSTRSIZE);
2410     if (lpszConnStr && db) {
2411         short cbszConnStr;
2412         if (strstr(db, ";")) {
2413             /* the caller has apparently passed a connection-string */
2414             if (strstr(db, "uid") || strstr(db, "UID")) {
2415                 uid = NULL;
2416             }
2417             if (strstr(db, "pwd") || strstr(db, "PWD")) {
2418                 pwd = NULL;
2419             }
2420             strlcpy( lpszConnStr, db, CONNSTRSIZE);
2421         }
2422         else {
2423             strcpy(lpszConnStr, "DSN=");
2424             strlcat(lpszConnStr, db, CONNSTRSIZE);
2425         }
2426         if (uid) {
2427             if (uid[0]) {
2428                 strlcat(lpszConnStr, ";UID=", CONNSTRSIZE);
2429                 strlcat(lpszConnStr, uid, CONNSTRSIZE);
2430                 strlcat(lpszConnStr, ";", CONNSTRSIZE);
2431             }
2432             if (pwd) {
2433                 if (pwd[0]) {
2434                     strlcat(lpszConnStr, "PWD=", CONNSTRSIZE);
2435                     strlcat(lpszConnStr, pwd, CONNSTRSIZE);
2436                     strlcat(lpszConnStr, ";", CONNSTRSIZE);
2437                 }
2438             }
2439         }
2440         rc = SQLDriverConnect((*conn)->hdbc, NULL, lpszConnStr, SQL_NTS, lpszConnStr, CONNSTRSIZE, &cbszConnStr, SQL_DRIVER_NOPROMPT);
2441         efree(lpszConnStr);
2442     }
2443    }
2444#else
2445#ifdef HAVE_OPENLINK
2446    {
2447        char dsnbuf[1024];
2448        short dsnbuflen;
2449
2450        rc = SQLDriverConnect((*conn)->hdbc, NULL, db, SQL_NTS, dsnbuf, sizeof(dsnbuf) - 1, &dsnbuflen, SQL_DRIVER_NOPROMPT);
2451    }
2452#else
2453    if (cur_opt != SQL_CUR_DEFAULT) {
2454        rc = SQLSetConnectOption((*conn)->hdbc, SQL_ODBC_CURSORS, cur_opt);
2455        if (rc != SQL_SUCCESS) {  /* && rc != SQL_SUCCESS_WITH_INFO ? */
2456            odbc_sql_error(*conn, SQL_NULL_HSTMT, "SQLSetConnectOption");
2457            SQLFreeConnect((*conn)->hdbc);
2458            pefree(*conn, persistent);
2459            return FALSE;
2460        }
2461    }
2462/*  Possible fix for bug #10250
2463 *  Needs testing on UnixODBC < 2.0.5 though. */
2464#if defined(HAVE_EMPRESS) || defined(HAVE_UNIXODBC) || defined(PHP_WIN32) || defined (HAVE_IODBC)
2465/* *  Uncomment the line above, and comment line below to fully test
2466 * #ifdef HAVE_EMPRESS */
2467    {
2468        int     direct = 0;
2469        char    dsnbuf[1024];
2470        short   dsnbuflen;
2471        char    *ldb = 0;
2472        int     ldb_len = 0;
2473
2474        if (strstr((char*)db, ";")) {
2475            direct = 1;
2476            if (uid && !strstr ((char*)db, "uid") && !strstr((char*)db, "UID")) {
2477                spprintf(&ldb, 0, "%s;UID=%s;PWD=%s", db, uid, pwd);
2478            } else {
2479                ldb_len = strlen(db)+1;
2480                ldb = (char*) emalloc(ldb_len);
2481                memcpy(ldb, db, ldb_len);
2482            }
2483        }
2484
2485        if (direct) {
2486            rc = SQLDriverConnect((*conn)->hdbc, NULL, ldb, strlen(ldb), dsnbuf, sizeof(dsnbuf) - 1, &dsnbuflen, SQL_DRIVER_NOPROMPT);
2487        } else {
2488            rc = SQLConnect((*conn)->hdbc, db, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
2489        }
2490
2491        if (ldb) {
2492            efree(ldb);
2493        }
2494    }
2495#else
2496    rc = SQLConnect((*conn)->hdbc, db, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
2497#endif
2498#endif
2499#endif
2500    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2501        odbc_sql_error(*conn, SQL_NULL_HSTMT, "SQLConnect");
2502        SQLFreeConnect((*conn)->hdbc);
2503        pefree((*conn), persistent);
2504        return FALSE;
2505    }
2506/*  (*conn)->open = 1;*/
2507    return TRUE;
2508}
2509/* }}} */
2510
2511/* Persistent connections: two list-types le_pconn, le_conn and a plist
2512 * where hashed connection info is stored together with index pointer to
2513 * the actual link of type le_pconn in the list. Only persistent
2514 * connections get hashed up. Normal connections use existing pconnections.
2515 * Maybe this has to change with regard to transactions on pconnections?
2516 * Possibly set autocommit to on on request shutdown.
2517 *
2518 * We do have to hash non-persistent connections, and reuse connections.
2519 * In the case where two connects were being made, without closing the first
2520 * connect, access violations were occurring.  This is because some of the
2521 * "globals" in this module should actually be per-connection variables.  I
2522 * simply fixed things to get them working for now.  Shane
2523 */
2524/* {{{ odbc_do_connect */
2525void odbc_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
2526{
2527    char *db, *uid, *pwd;
2528    size_t db_len, uid_len, pwd_len;
2529    zend_long pv_opt = SQL_CUR_DEFAULT;
2530    odbc_connection *db_conn;
2531    char *hashed_details;
2532    int hashed_len, cur_opt;
2533
2534    /*  Now an optional 4th parameter specifying the cursor type
2535     *  defaulting to the cursors default
2536     */
2537    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|l", &db, &db_len, &uid, &uid_len, &pwd, &pwd_len, &pv_opt) == FAILURE) {
2538        return;
2539    }
2540
2541    cur_opt = pv_opt;
2542
2543    if (ZEND_NUM_ARGS() > 3) {
2544        /* Confirm the cur_opt range */
2545        if (! (cur_opt == SQL_CUR_USE_IF_NEEDED ||
2546            cur_opt == SQL_CUR_USE_ODBC ||
2547            cur_opt == SQL_CUR_USE_DRIVER ||
2548            cur_opt == SQL_CUR_DEFAULT) ) {
2549            php_error_docref(NULL, E_WARNING, "Invalid Cursor type (%d)", cur_opt);
2550            RETURN_FALSE;
2551        }
2552    }
2553
2554    if (ODBCG(allow_persistent) <= 0) {
2555        persistent = 0;
2556    }
2557
2558    hashed_len = spprintf(&hashed_details, 0, "%s_%s_%s_%s_%d", ODBC_TYPE, db, uid, pwd, cur_opt);
2559
2560    /* FIXME the idea of checking to see if our connection is already persistent
2561        is good, but it adds a lot of overhead to non-persistent connections.  We
2562        should look and see if we can fix that somehow */
2563    /* try to find if we already have this link in our persistent list,
2564     * no matter if it is to be persistent or not
2565     */
2566
2567try_and_get_another_connection:
2568
2569    if (persistent) {
2570        zend_resource *le;
2571
2572        /* the link is not in the persistent list */
2573        if ((le = zend_hash_str_find_ptr(&EG(persistent_list), hashed_details, hashed_len)) == NULL) {
2574            zend_resource new_le;
2575
2576            if (ODBCG(max_links) != -1 && ODBCG(num_links) >= ODBCG(max_links)) {
2577                php_error_docref(NULL, E_WARNING, "Too many open links (%ld)", ODBCG(num_links));
2578                efree(hashed_details);
2579                RETURN_FALSE;
2580            }
2581            if (ODBCG(max_persistent) != -1 && ODBCG(num_persistent) >= ODBCG(max_persistent)) {
2582                php_error_docref(NULL, E_WARNING,"Too many open persistent links (%ld)", ODBCG(num_persistent));
2583                efree(hashed_details);
2584                RETURN_FALSE;
2585            }
2586
2587            if (!odbc_sqlconnect(&db_conn, db, uid, pwd, cur_opt, 1)) {
2588                efree(hashed_details);
2589                RETURN_FALSE;
2590            }
2591
2592            new_le.type = le_pconn;
2593            new_le.ptr = db_conn;
2594            new_le.handle = -1;
2595            if (zend_hash_str_update_mem(&EG(persistent_list), hashed_details, hashed_len, &new_le,
2596                        sizeof(zend_resource)) == NULL) {
2597                free(db_conn);
2598                efree(hashed_details);
2599                RETURN_FALSE;
2600            }
2601            ODBCG(num_persistent)++;
2602            ODBCG(num_links)++;
2603            db_conn->res = zend_register_resource(db_conn, le_pconn);
2604            RETVAL_RES(db_conn->res);
2605        } else { /* found connection */
2606            if (le->type != le_pconn) {
2607                RETURN_FALSE;
2608            }
2609            /*
2610             * check to see if the connection is still valid
2611             */
2612            db_conn = (odbc_connection *)le->ptr;
2613
2614            /*
2615             * check to see if the connection is still in place (lurcher)
2616             */
2617            if(ODBCG(check_persistent)){
2618                RETCODE ret;
2619                UCHAR d_name[32];
2620                SQLSMALLINT len;
2621
2622                ret = SQLGetInfo(db_conn->hdbc,
2623                    SQL_DATA_SOURCE_READ_ONLY,
2624                    d_name, sizeof(d_name), &len);
2625
2626                if(ret != SQL_SUCCESS || len == 0) {
2627                    zend_hash_str_del(&EG(persistent_list), hashed_details, hashed_len);
2628                    /* Commented out to fix a possible double closure error
2629                     * when working with persistent connections as submitted by
2630                     * bug #15758
2631                     *
2632                     * safe_odbc_disconnect(db_conn->hdbc);
2633                     * SQLFreeConnect(db_conn->hdbc);
2634                     */
2635                    goto try_and_get_another_connection;
2636                }
2637            }
2638        }
2639        db_conn->res = zend_register_resource(db_conn, le_pconn);
2640        RETVAL_RES(db_conn->res);
2641    } else { /* non persistent */
2642        zend_resource *index_ptr, new_index_ptr;
2643
2644        if ((index_ptr = zend_hash_str_find_ptr(&EG(regular_list), hashed_details, hashed_len)) != NULL) {
2645            zend_ulong conn_id;
2646            zend_resource *p;
2647
2648            if (index_ptr->type != le_index_ptr) {
2649                RETURN_FALSE;
2650            }
2651            conn_id = (zend_ulong)index_ptr->ptr;
2652            p = zend_hash_index_find_ptr(&EG(regular_list), conn_id);   /* check if the connection is still there */
2653
2654            if (p && p->ptr && (p->type == le_conn || p->type == le_pconn)) {
2655                GC_REFCOUNT(p)++;
2656                RETVAL_RES(p);
2657                efree(hashed_details);
2658                return;
2659            } else {
2660                zend_hash_str_del(&EG(regular_list), hashed_details, hashed_len);
2661            }
2662        }
2663        if (ODBCG(max_links) != -1 && ODBCG(num_links) >= ODBCG(max_links)) {
2664            php_error_docref(NULL, E_WARNING,"Too many open connections (%ld)",ODBCG(num_links));
2665            efree(hashed_details);
2666            RETURN_FALSE;
2667        }
2668
2669        if (!odbc_sqlconnect(&db_conn, db, uid, pwd, cur_opt, 0)) {
2670            efree(hashed_details);
2671            RETURN_FALSE;
2672        }
2673        db_conn->res = zend_register_resource(db_conn, le_conn);
2674        RETVAL_RES(db_conn->res);
2675        new_index_ptr.ptr = (void *)(zend_uintptr_t)Z_RES_HANDLE_P(return_value);
2676        new_index_ptr.type = le_index_ptr;
2677
2678        if (zend_hash_str_update_mem(&EG(regular_list), hashed_details, hashed_len, (void *) &new_index_ptr,
2679                   sizeof(zend_resource)) == NULL) {
2680            efree(hashed_details);
2681            RETURN_FALSE;
2682            /* XXX Free Connection */
2683        }
2684        ODBCG(num_links)++;
2685    }
2686    efree(hashed_details);
2687}
2688/* }}} */
2689
2690/* {{{ proto void odbc_close(resource connection_id)
2691   Close an ODBC connection */
2692PHP_FUNCTION(odbc_close)
2693{
2694    zval *pv_conn;
2695    zend_resource *p;
2696    odbc_connection *conn;
2697    odbc_result *res;
2698    int is_pconn = 0;
2699
2700    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_conn) == FAILURE) {
2701        return;
2702    }
2703
2704    conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn);
2705    if (Z_RES_P(pv_conn)->type == le_pconn) {
2706        is_pconn = 1;
2707    }
2708
2709    ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
2710        if (p->ptr && (p->type == le_result)) {
2711            res = (odbc_result *)p->ptr;
2712            if (res->conn_ptr == conn) {
2713                zend_list_close(p);
2714            }
2715        }
2716    } ZEND_HASH_FOREACH_END();
2717
2718    zend_list_close(Z_RES_P(pv_conn));
2719
2720    if(is_pconn){
2721        zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _close_pconn_with_res, (void *) Z_RES_P(pv_conn));
2722    }
2723}
2724/* }}} */
2725
2726/* {{{ proto int odbc_num_rows(resource result_id)
2727   Get number of rows in a result */
2728PHP_FUNCTION(odbc_num_rows)
2729{
2730    odbc_result *result;
2731    SQLLEN rows;
2732    zval *pv_res;
2733
2734    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2735        return;
2736    }
2737
2738    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2739        RETURN_FALSE;
2740    }
2741
2742    SQLRowCount(result->stmt, &rows);
2743    RETURN_LONG(rows);
2744}
2745/* }}} */
2746
2747#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
2748/* {{{ proto bool odbc_next_result(resource result_id)
2749   Checks if multiple results are available */
2750PHP_FUNCTION(odbc_next_result)
2751{
2752    odbc_result *result;
2753    zval *pv_res;
2754    int rc, i;
2755
2756    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2757        return;
2758    }
2759
2760    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2761        RETURN_FALSE;
2762    }
2763
2764    if (result->values) {
2765        for(i = 0; i < result->numcols; i++) {
2766            if (result->values[i].value) {
2767                efree(result->values[i].value);
2768            }
2769        }
2770        efree(result->values);
2771        result->values = NULL;
2772    }
2773
2774    result->fetched = 0;
2775    rc = SQLMoreResults(result->stmt);
2776    if (rc == SQL_SUCCESS_WITH_INFO || rc == SQL_SUCCESS) {
2777        rc = SQLFreeStmt(result->stmt, SQL_UNBIND);
2778        SQLNumParams(result->stmt, &(result->numparams));
2779        SQLNumResultCols(result->stmt, &(result->numcols));
2780
2781        if (result->numcols > 0) {
2782            if (!odbc_bindcols(result)) {
2783                efree(result);
2784                RETVAL_FALSE;
2785            }
2786        } else {
2787            result->values = NULL;
2788        }
2789        RETURN_TRUE;
2790    } else if (rc == SQL_NO_DATA_FOUND) {
2791        RETURN_FALSE;
2792    } else {
2793        odbc_sql_error(result->conn_ptr, result->stmt, "SQLMoreResults");
2794        RETURN_FALSE;
2795    }
2796}
2797/* }}} */
2798#endif
2799
2800/* {{{ proto int odbc_num_fields(resource result_id)
2801   Get number of columns in a result */
2802PHP_FUNCTION(odbc_num_fields)
2803{
2804    odbc_result *result;
2805    zval *pv_res;
2806
2807    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2808        return;
2809    }
2810
2811    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2812        RETURN_FALSE;
2813    }
2814
2815    RETURN_LONG(result->numcols);
2816}
2817/* }}} */
2818
2819/* {{{ proto string odbc_field_name(resource result_id, int field_number)
2820   Get a column name */
2821PHP_FUNCTION(odbc_field_name)
2822{
2823    odbc_result *result;
2824    zval *pv_res;
2825    zend_long pv_num;
2826
2827    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
2828        return;
2829    }
2830
2831    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2832        RETURN_FALSE;
2833    }
2834
2835    if (result->numcols == 0) {
2836        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2837        RETURN_FALSE;
2838    }
2839
2840    if (pv_num > result->numcols) {
2841        php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
2842        RETURN_FALSE;
2843    }
2844
2845    if (pv_num < 1) {
2846        php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
2847        RETURN_FALSE;
2848    }
2849
2850    RETURN_STRING(result->values[pv_num - 1].name);
2851}
2852/* }}} */
2853
2854/* {{{ proto string odbc_field_type(resource result_id, int field_number)
2855   Get the datatype of a column */
2856PHP_FUNCTION(odbc_field_type)
2857{
2858    odbc_result *result;
2859    char        tmp[32];
2860    SQLSMALLINT tmplen;
2861    zval        *pv_res;
2862    zend_long       pv_num;
2863
2864    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
2865        return;
2866    }
2867
2868    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2869        RETURN_FALSE;
2870    }
2871
2872    if (result->numcols == 0) {
2873        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2874        RETURN_FALSE;
2875    }
2876
2877    if (pv_num > result->numcols) {
2878        php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
2879        RETURN_FALSE;
2880    }
2881
2882    if (pv_num < 1) {
2883        php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
2884        RETURN_FALSE;
2885    }
2886
2887    SQLColAttributes(result->stmt, (SQLUSMALLINT)pv_num, SQL_COLUMN_TYPE_NAME, tmp, 31, &tmplen, NULL);
2888    RETURN_STRING(tmp)
2889}
2890/* }}} */
2891
2892/* {{{ proto int odbc_field_len(resource result_id, int field_number)
2893   Get the length (precision) of a column */
2894PHP_FUNCTION(odbc_field_len)
2895{
2896    odbc_column_lengths(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2897}
2898/* }}} */
2899
2900/* {{{ proto int odbc_field_scale(resource result_id, int field_number)
2901   Get the scale of a column */
2902PHP_FUNCTION(odbc_field_scale)
2903{
2904    odbc_column_lengths(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2905}
2906/* }}} */
2907
2908/* {{{ proto int odbc_field_num(resource result_id, string field_name)
2909   Return column number */
2910PHP_FUNCTION(odbc_field_num)
2911{
2912    char *fname;
2913    size_t i, field_ind, fname_len;
2914    odbc_result *result;
2915    zval *pv_res;
2916
2917    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pv_res, &fname, &fname_len) == FAILURE) {
2918        return;
2919    }
2920
2921    if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2922        RETURN_FALSE;
2923    }
2924
2925    if (result->numcols == 0) {
2926        php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2927        RETURN_FALSE;
2928    }
2929
2930    field_ind = -1;
2931    for(i = 0; i < result->numcols; i++) {
2932        if (strcasecmp(result->values[i].name, fname) == 0) {
2933            field_ind = i + 1;
2934        }
2935    }
2936
2937    if (field_ind == -1) {
2938        RETURN_FALSE;
2939    }
2940    RETURN_LONG(field_ind);
2941}
2942/* }}} */
2943
2944/* {{{ proto mixed odbc_autocommit(resource connection_id [, int OnOff])
2945   Toggle autocommit mode or get status */
2946/* There can be problems with pconnections!*/
2947PHP_FUNCTION(odbc_autocommit)
2948{
2949    odbc_connection *conn;
2950    RETCODE rc;
2951    zval *pv_conn;
2952    zend_long pv_onoff = 0;
2953
2954    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_conn, &pv_onoff) == FAILURE) {
2955        return;
2956    }
2957
2958    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
2959        RETURN_FALSE;
2960    }
2961
2962    if (ZEND_NUM_ARGS() > 1) {
2963        rc = SQLSetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, (pv_onoff) ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF);
2964        if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2965            odbc_sql_error(conn, SQL_NULL_HSTMT, "Set autocommit");
2966            RETURN_FALSE;
2967        }
2968        RETVAL_TRUE;
2969    } else {
2970        SQLINTEGER status;
2971
2972        rc = SQLGetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, (PTR)&status);
2973        if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2974            odbc_sql_error(conn, SQL_NULL_HSTMT, "Get commit status");
2975            RETURN_FALSE;
2976        }
2977        RETVAL_LONG((zend_long)status);
2978    }
2979}
2980/* }}} */
2981
2982/* {{{ proto bool odbc_commit(resource connection_id)
2983   Commit an ODBC transaction */
2984PHP_FUNCTION(odbc_commit)
2985{
2986    odbc_transact(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2987}
2988/* }}} */
2989
2990/* {{{ proto bool odbc_rollback(resource connection_id)
2991   Rollback a transaction */
2992PHP_FUNCTION(odbc_rollback)
2993{
2994    odbc_transact(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2995}
2996/* }}} */
2997
2998/* {{{ php_odbc_lasterror */
2999static void php_odbc_lasterror(INTERNAL_FUNCTION_PARAMETERS, int mode)
3000{
3001    odbc_connection *conn;
3002    zval *pv_handle;
3003    zend_string *ptr;
3004    int len;
3005
3006    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|r", &pv_handle) == FAILURE) {
3007        return;
3008    }
3009
3010    if (mode == 0) {  /* last state */
3011        len = 6;
3012    } else { /* last error message */
3013        len = SQL_MAX_MESSAGE_LENGTH;
3014    }
3015
3016    if (ZEND_NUM_ARGS() == 1) {
3017        if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_handle), "ODBC-Link", le_conn, le_pconn))) {
3018            RETURN_FALSE;
3019        }
3020        ptr = zend_string_alloc(len + 1, 0);
3021        if (mode == 0) {
3022            strlcpy(ptr->val, conn->laststate, len+1);
3023        } else {
3024            strlcpy(ptr->val, conn->lasterrormsg, len+1);
3025        }
3026    } else {
3027        ptr = zend_string_alloc(len, 0);
3028        if (mode == 0) {
3029            strlcpy(ptr->val, ODBCG(laststate), len+1);
3030        } else {
3031            strlcpy(ptr->val, ODBCG(lasterrormsg), len+1);
3032        }
3033    }
3034    RETVAL_STR(ptr);
3035}
3036/* }}} */
3037
3038/* {{{ proto string odbc_error([resource connection_id])
3039   Get the last error code */
3040PHP_FUNCTION(odbc_error)
3041{
3042    php_odbc_lasterror(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3043}
3044/* }}} */
3045
3046/* {{{ proto string odbc_errormsg([resource connection_id])
3047   Get the last error message */
3048PHP_FUNCTION(odbc_errormsg)
3049{
3050    php_odbc_lasterror(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3051}
3052/* }}} */
3053
3054/* {{{ proto bool odbc_setoption(resource conn_id|result_id, int which, int option, int value)
3055   Sets connection or statement options */
3056/* This one has to be used carefully. We can't allow to set connection options for
3057   persistent connections. I think that SetStmtOption is of little use, since most
3058   of those can only be specified before preparing/executing statements.
3059   On the other hand, they can be made connection wide default through SetConnectOption
3060   - but will be overidden by calls to SetStmtOption() in odbc_prepare/odbc_do
3061*/
3062PHP_FUNCTION(odbc_setoption)
3063{
3064    odbc_connection *conn;
3065    odbc_result *result;
3066    RETCODE rc;
3067    zval *pv_handle;
3068    zend_long pv_which, pv_opt, pv_val;
3069
3070    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlll", &pv_handle, &pv_which, &pv_opt, &pv_val) == FAILURE) {
3071        return;
3072    }
3073
3074    switch (pv_which) {
3075        case 1:     /* SQLSetConnectOption */
3076            if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_handle), "ODBC-Link", le_conn, le_pconn))) {
3077                RETURN_FALSE;
3078            }
3079
3080            if (conn->persistent) {
3081                php_error_docref(NULL, E_WARNING, "Unable to set option for persistent connection");
3082                RETURN_FALSE;
3083            }
3084            rc = SQLSetConnectOption(conn->hdbc, (unsigned short) pv_opt, pv_val);
3085            if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3086                odbc_sql_error(conn, SQL_NULL_HSTMT, "SetConnectOption");
3087                RETURN_FALSE;
3088            }
3089            break;
3090        case 2:     /* SQLSetStmtOption */
3091            if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_handle), "ODBC-Link", le_conn, le_pconn))) {
3092                RETURN_FALSE;
3093            }
3094
3095            rc = SQLSetStmtOption(result->stmt, (unsigned short) pv_opt, pv_val);
3096
3097            if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3098                odbc_sql_error(result->conn_ptr, result->stmt, "SetStmtOption");
3099                RETURN_FALSE;
3100            }
3101            break;
3102        default:
3103            php_error_docref(NULL, E_WARNING, "Unknown option type");
3104            RETURN_FALSE;
3105            break;
3106    }
3107
3108    RETURN_TRUE;
3109}
3110/* }}} */
3111
3112/*
3113 * metadata functions
3114 */
3115
3116/* {{{ proto resource odbc_tables(resource connection_id [, string qualifier [, string owner [, string name [, string table_types]]]])
3117   Call the SQLTables function */
3118PHP_FUNCTION(odbc_tables)
3119{
3120    zval *pv_conn;
3121    odbc_result   *result = NULL;
3122    odbc_connection *conn;
3123    char *cat = NULL, *schema = NULL, *table = NULL, *type = NULL;
3124    size_t cat_len = 0, schema_len = 0, table_len = 0, type_len = 0;
3125    RETCODE rc;
3126
3127    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3128        &table, &table_len, &type, &type_len) == FAILURE) {
3129        return;
3130    }
3131
3132    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3133        RETURN_FALSE;
3134    }
3135
3136    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3137
3138    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3139    if (rc == SQL_INVALID_HANDLE) {
3140        efree(result);
3141        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3142        RETURN_FALSE;
3143    }
3144
3145    if (rc == SQL_ERROR) {
3146        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3147        efree(result);
3148        RETURN_FALSE;
3149    }
3150
3151    /* This hack is needed to access table information in Access databases (fmk) */
3152    if (table && table_len && schema && schema_len == 0) {
3153        schema = NULL;
3154    }
3155
3156    rc = SQLTables(result->stmt,
3157            cat, SAFE_SQL_NTS(cat),
3158            schema, SAFE_SQL_NTS(schema),
3159            table, SAFE_SQL_NTS(table),
3160            type, SAFE_SQL_NTS(type));
3161
3162    if (rc == SQL_ERROR) {
3163        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTables");
3164        efree(result);
3165        RETURN_FALSE;
3166    }
3167
3168    result->numparams = 0;
3169    SQLNumResultCols(result->stmt, &(result->numcols));
3170
3171    if (result->numcols > 0) {
3172        if (!odbc_bindcols(result)) {
3173            efree(result);
3174            RETURN_FALSE;
3175        }
3176    } else {
3177        result->values = NULL;
3178    }
3179    result->conn_ptr = conn;
3180    result->fetched = 0;
3181    RETURN_RES(zend_register_resource(result, le_result));
3182}
3183/* }}} */
3184
3185/* {{{ proto resource odbc_columns(resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])
3186   Returns a result identifier that can be used to fetch a list of column names in specified tables */
3187PHP_FUNCTION(odbc_columns)
3188{
3189    zval *pv_conn;
3190    odbc_result *result = NULL;
3191    odbc_connection *conn;
3192    char *cat = NULL, *schema = NULL, *table = NULL, *column = NULL;
3193    size_t cat_len = 0, schema_len = 0, table_len = 0, column_len = 0;
3194    RETCODE rc;
3195
3196    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3197        &table, &table_len, &column, &column_len) == FAILURE) {
3198        return;
3199    }
3200
3201    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3202        RETURN_FALSE;
3203    }
3204
3205    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3206
3207    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3208    if (rc == SQL_INVALID_HANDLE) {
3209        efree(result);
3210        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3211        RETURN_FALSE;
3212    }
3213
3214    if (rc == SQL_ERROR) {
3215        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3216        efree(result);
3217        RETURN_FALSE;
3218    }
3219
3220    /*
3221     * Needed to make MS Access happy
3222     */
3223    if (table && table_len && schema && schema_len == 0) {
3224        schema = NULL;
3225    }
3226
3227    rc = SQLColumns(result->stmt,
3228            cat, (SQLSMALLINT) cat_len,
3229            schema, (SQLSMALLINT) schema_len,
3230            table, (SQLSMALLINT) table_len,
3231            column, (SQLSMALLINT) column_len);
3232
3233    if (rc == SQL_ERROR) {
3234        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLColumns");
3235        efree(result);
3236        RETURN_FALSE;
3237    }
3238
3239    result->numparams = 0;
3240    SQLNumResultCols(result->stmt, &(result->numcols));
3241
3242    if (result->numcols > 0) {
3243        if (!odbc_bindcols(result)) {
3244            efree(result);
3245            RETURN_FALSE;
3246        }
3247    } else {
3248        result->values = NULL;
3249    }
3250    result->conn_ptr = conn;
3251    result->fetched = 0;
3252    RETURN_RES(zend_register_resource(result, le_result));
3253}
3254/* }}} */
3255
3256#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3257/* {{{ proto resource odbc_columnprivileges(resource connection_id, string catalog, string schema, string table, string column)
3258   Returns a result identifier that can be used to fetch a list of columns and associated privileges for the specified table */
3259PHP_FUNCTION(odbc_columnprivileges)
3260{
3261    zval *pv_conn;
3262    odbc_result *result = NULL;
3263    odbc_connection *conn;
3264    char *cat = NULL, *schema, *table, *column;
3265    size_t cat_len = 0, schema_len, table_len, column_len;
3266    RETCODE rc;
3267
3268    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3269        &table, &table_len, &column, &column_len) == FAILURE) {
3270        return;
3271    }
3272
3273    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3274        RETURN_FALSE;
3275    }
3276
3277    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3278
3279    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3280    if (rc == SQL_INVALID_HANDLE) {
3281        efree(result);
3282        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3283        RETURN_FALSE;
3284    }
3285
3286    if (rc == SQL_ERROR) {
3287        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3288        efree(result);
3289        RETURN_FALSE;
3290    }
3291
3292    rc = SQLColumnPrivileges(result->stmt,
3293            cat, SAFE_SQL_NTS(cat),
3294            schema, SAFE_SQL_NTS(schema),
3295            table, SAFE_SQL_NTS(table),
3296            column, SAFE_SQL_NTS(column));
3297
3298    if (rc == SQL_ERROR) {
3299        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLColumnPrivileges");
3300        efree(result);
3301        RETURN_FALSE;
3302    }
3303
3304    result->numparams = 0;
3305    SQLNumResultCols(result->stmt, &(result->numcols));
3306
3307    if (result->numcols > 0) {
3308        if (!odbc_bindcols(result)) {
3309            efree(result);
3310            RETURN_FALSE;
3311        }
3312    } else {
3313        result->values = NULL;
3314    }
3315    result->conn_ptr = conn;
3316    result->fetched = 0;
3317    RETURN_RES(zend_register_resource(result, le_result));
3318}
3319/* }}} */
3320#endif /* HAVE_DBMAKER || HAVE_SOLID*/
3321
3322#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
3323/* {{{ proto resource odbc_foreignkeys(resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)
3324   Returns a result identifier to either a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table */
3325PHP_FUNCTION(odbc_foreignkeys)
3326{
3327    zval *pv_conn;
3328    odbc_result *result = NULL;
3329    odbc_connection *conn;
3330    char *pcat = NULL, *pschema, *ptable, *fcat, *fschema, *ftable;
3331    size_t pcat_len = 0, pschema_len, ptable_len, fcat_len, fschema_len, ftable_len;
3332    RETCODE rc;
3333
3334    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!sssss", &pv_conn, &pcat, &pcat_len, &pschema, &pschema_len,
3335        &ptable, &ptable_len, &fcat, &fcat_len, &fschema, &fschema_len, &ftable, &ftable_len) == FAILURE) {
3336        return;
3337    }
3338
3339#if defined(HAVE_DBMAKER) || defined(HAVE_IBMDB2)
3340#define EMPTY_TO_NULL(xstr) \
3341    if ((int)strlen((xstr)) == 0) (xstr) = NULL
3342
3343        EMPTY_TO_NULL(pcat);
3344        EMPTY_TO_NULL(pschema);
3345        EMPTY_TO_NULL(ptable);
3346        EMPTY_TO_NULL(fcat);
3347        EMPTY_TO_NULL(fschema);
3348        EMPTY_TO_NULL(ftable);
3349#endif
3350
3351    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3352        RETURN_FALSE;
3353    }
3354
3355    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3356
3357    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3358    if (rc == SQL_INVALID_HANDLE) {
3359        efree(result);
3360        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3361        RETURN_FALSE;
3362    }
3363
3364    if (rc == SQL_ERROR) {
3365        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3366        efree(result);
3367        RETURN_FALSE;
3368    }
3369
3370    rc = SQLForeignKeys(result->stmt,
3371            pcat, SAFE_SQL_NTS(pcat),
3372            pschema, SAFE_SQL_NTS(pschema),
3373            ptable, SAFE_SQL_NTS(ptable),
3374            fcat, SAFE_SQL_NTS(fcat),
3375            fschema, SAFE_SQL_NTS(fschema),
3376            ftable, SAFE_SQL_NTS(ftable) );
3377
3378    if (rc == SQL_ERROR) {
3379        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLForeignKeys");
3380        efree(result);
3381        RETURN_FALSE;
3382    }
3383
3384    result->numparams = 0;
3385    SQLNumResultCols(result->stmt, &(result->numcols));
3386
3387    if (result->numcols > 0) {
3388        if (!odbc_bindcols(result)) {
3389            efree(result);
3390            RETURN_FALSE;
3391        }
3392    } else {
3393        result->values = NULL;
3394    }
3395    result->conn_ptr = conn;
3396    result->fetched = 0;
3397    RETURN_RES(zend_register_resource(result, le_result));
3398}
3399/* }}} */
3400#endif /* HAVE_SOLID */
3401
3402/* {{{ proto resource odbc_gettypeinfo(resource connection_id [, int data_type])
3403   Returns a result identifier containing information about data types supported by the data source */
3404PHP_FUNCTION(odbc_gettypeinfo)
3405{
3406    zval *pv_conn;
3407    zend_long pv_data_type = SQL_ALL_TYPES;
3408    odbc_result *result = NULL;
3409    odbc_connection *conn;
3410    RETCODE rc;
3411    SQLSMALLINT data_type;
3412
3413    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_conn, &pv_data_type) == FAILURE) {
3414        return;
3415    }
3416
3417    data_type = (SQLSMALLINT) pv_data_type;
3418
3419    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3420        RETURN_FALSE;
3421    }
3422
3423    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3424
3425    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3426    if (rc == SQL_INVALID_HANDLE) {
3427        efree(result);
3428        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3429        RETURN_FALSE;
3430    }
3431
3432    if (rc == SQL_ERROR) {
3433        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3434        efree(result);
3435        RETURN_FALSE;
3436    }
3437
3438    rc = SQLGetTypeInfo(result->stmt, data_type );
3439
3440    if (rc == SQL_ERROR) {
3441        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLGetTypeInfo");
3442        efree(result);
3443        RETURN_FALSE;
3444    }
3445
3446    result->numparams = 0;
3447    SQLNumResultCols(result->stmt, &(result->numcols));
3448
3449    if (result->numcols > 0) {
3450        if (!odbc_bindcols(result)) {
3451            efree(result);
3452            RETURN_FALSE;
3453        }
3454    } else {
3455        result->values = NULL;
3456    }
3457    result->conn_ptr = conn;
3458    result->fetched = 0;
3459    RETURN_RES(zend_register_resource(result, le_result));
3460}
3461/* }}} */
3462
3463/* {{{ proto resource odbc_primarykeys(resource connection_id, string qualifier, string owner, string table)
3464   Returns a result identifier listing the column names that comprise the primary key for a table */
3465PHP_FUNCTION(odbc_primarykeys)
3466{
3467    zval *pv_conn;
3468    odbc_result   *result = NULL;
3469    odbc_connection *conn;
3470    char *cat = NULL, *schema = NULL, *table = NULL;
3471    size_t cat_len = 0, schema_len, table_len;
3472    RETCODE rc;
3473
3474    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &table, &table_len) == FAILURE) {
3475        return;
3476    }
3477
3478    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3479        RETURN_FALSE;
3480    }
3481
3482    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3483
3484    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3485    if (rc == SQL_INVALID_HANDLE) {
3486        efree(result);
3487        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3488        RETURN_FALSE;
3489    }
3490
3491    if (rc == SQL_ERROR) {
3492        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3493        efree(result);
3494        RETURN_FALSE;
3495    }
3496
3497    rc = SQLPrimaryKeys(result->stmt,
3498            cat, SAFE_SQL_NTS(cat),
3499            schema, SAFE_SQL_NTS(schema),
3500            table, SAFE_SQL_NTS(table) );
3501
3502    if (rc == SQL_ERROR) {
3503        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLPrimaryKeys");
3504        efree(result);
3505        RETURN_FALSE;
3506    }
3507
3508    result->numparams = 0;
3509    SQLNumResultCols(result->stmt, &(result->numcols));
3510
3511    if (result->numcols > 0) {
3512        if (!odbc_bindcols(result)) {
3513            efree(result);
3514            RETURN_FALSE;
3515        }
3516    } else {
3517        result->values = NULL;
3518    }
3519    result->conn_ptr = conn;
3520    result->fetched = 0;
3521    RETURN_RES(zend_register_resource(result, le_result));
3522}
3523/* }}} */
3524
3525#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3526/* {{{ proto resource odbc_procedurecolumns(resource connection_id [, string qualifier, string owner, string proc, string column])
3527   Returns a result identifier containing the list of input and output parameters, as well as the columns that make up the result set for the specified procedures */
3528PHP_FUNCTION(odbc_procedurecolumns)
3529{
3530    zval *pv_conn;
3531    odbc_result *result = NULL;
3532    odbc_connection *conn;
3533    char *cat = NULL, *schema = NULL, *proc = NULL, *col = NULL;
3534    size_t cat_len = 0, schema_len = 0, proc_len = 0, col_len = 0;
3535    RETCODE rc;
3536
3537    if (ZEND_NUM_ARGS() != 1 && ZEND_NUM_ARGS() != 5) {
3538        WRONG_PARAM_COUNT;
3539    }
3540
3541    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3542        &proc, &proc_len, &col, &col_len) == FAILURE) {
3543        return;
3544    }
3545
3546    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3547        RETURN_FALSE;
3548    }
3549
3550    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3551
3552    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3553    if (rc == SQL_INVALID_HANDLE) {
3554        efree(result);
3555        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3556        RETURN_FALSE;
3557    }
3558
3559    if (rc == SQL_ERROR) {
3560        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3561        efree(result);
3562        RETURN_FALSE;
3563    }
3564
3565    rc = SQLProcedureColumns(result->stmt,
3566            cat, SAFE_SQL_NTS(cat),
3567            schema, SAFE_SQL_NTS(schema),
3568            proc, SAFE_SQL_NTS(proc),
3569            col, SAFE_SQL_NTS(col) );
3570
3571    if (rc == SQL_ERROR) {
3572        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLProcedureColumns");
3573        efree(result);
3574        RETURN_FALSE;
3575    }
3576
3577    result->numparams = 0;
3578    SQLNumResultCols(result->stmt, &(result->numcols));
3579
3580    if (result->numcols > 0) {
3581        if (!odbc_bindcols(result)) {
3582            efree(result);
3583            RETURN_FALSE;
3584        }
3585    } else {
3586        result->values = NULL;
3587    }
3588    result->conn_ptr = conn;
3589    result->fetched = 0;
3590    RETURN_RES(zend_register_resource(result, le_result));
3591}
3592/* }}} */
3593#endif /* HAVE_SOLID */
3594
3595#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
3596/* {{{ proto resource odbc_procedures(resource connection_id [, string qualifier, string owner, string name])
3597   Returns a result identifier containg the list of procedure names in a datasource */
3598PHP_FUNCTION(odbc_procedures)
3599{
3600    zval *pv_conn;
3601    odbc_result   *result = NULL;
3602    odbc_connection *conn;
3603    char *cat = NULL, *schema = NULL, *proc = NULL;
3604    size_t cat_len = 0, schema_len = 0, proc_len = 0;
3605    RETCODE rc;
3606
3607    if (ZEND_NUM_ARGS() != 1 && ZEND_NUM_ARGS() != 4) {
3608        WRONG_PARAM_COUNT;
3609    }
3610
3611    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &proc, &proc_len) == FAILURE) {
3612        return;
3613    }
3614
3615    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3616        RETURN_FALSE;
3617    }
3618
3619    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3620
3621    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3622    if (rc == SQL_INVALID_HANDLE) {
3623        efree(result);
3624        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3625        RETURN_FALSE;
3626    }
3627
3628    if (rc == SQL_ERROR) {
3629        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3630        efree(result);
3631        RETURN_FALSE;
3632    }
3633
3634    rc = SQLProcedures(result->stmt,
3635            cat, SAFE_SQL_NTS(cat),
3636            schema, SAFE_SQL_NTS(schema),
3637            proc, SAFE_SQL_NTS(proc) );
3638
3639    if (rc == SQL_ERROR) {
3640        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLProcedures");
3641        efree(result);
3642        RETURN_FALSE;
3643    }
3644
3645    result->numparams = 0;
3646    SQLNumResultCols(result->stmt, &(result->numcols));
3647
3648    if (result->numcols > 0) {
3649        if (!odbc_bindcols(result)) {
3650            efree(result);
3651            RETURN_FALSE;
3652        }
3653    } else {
3654        result->values = NULL;
3655    }
3656    result->conn_ptr = conn;
3657    result->fetched = 0;
3658    RETURN_RES(zend_register_resource(result, le_result));
3659}
3660/* }}} */
3661#endif /* HAVE_SOLID */
3662
3663/* {{{ proto resource odbc_specialcolumns(resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)
3664   Returns a result identifier containing either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction */
3665PHP_FUNCTION(odbc_specialcolumns)
3666{
3667    zval *pv_conn;
3668    zend_long vtype, vscope, vnullable;
3669    odbc_result *result = NULL;
3670    odbc_connection *conn;
3671    char *cat = NULL, *schema = NULL, *name = NULL;
3672    size_t cat_len = 0, schema_len, name_len;
3673    SQLUSMALLINT type, scope, nullable;
3674    RETCODE rc;
3675
3676    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rls!ssl", &pv_conn, &vtype, &cat, &cat_len, &schema, &schema_len,
3677        &name, &name_len, &vscope, &vnullable) == FAILURE) {
3678        return;
3679    }
3680
3681    type = (SQLUSMALLINT) vtype;
3682    scope = (SQLUSMALLINT) vscope;
3683    nullable = (SQLUSMALLINT) vnullable;
3684
3685    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3686        RETURN_FALSE;
3687    }
3688
3689    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3690
3691    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3692    if (rc == SQL_INVALID_HANDLE) {
3693        efree(result);
3694        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3695        RETURN_FALSE;
3696    }
3697
3698    if (rc == SQL_ERROR) {
3699        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3700        efree(result);
3701        RETURN_FALSE;
3702    }
3703
3704    rc = SQLSpecialColumns(result->stmt,
3705            type,
3706            cat, SAFE_SQL_NTS(cat),
3707            schema, SAFE_SQL_NTS(schema),
3708            name, SAFE_SQL_NTS(name),
3709            scope,
3710            nullable);
3711
3712    if (rc == SQL_ERROR) {
3713        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLSpecialColumns");
3714        efree(result);
3715        RETURN_FALSE;
3716    }
3717
3718    result->numparams = 0;
3719    SQLNumResultCols(result->stmt, &(result->numcols));
3720
3721    if (result->numcols > 0) {
3722        if (!odbc_bindcols(result)) {
3723            efree(result);
3724            RETURN_FALSE;
3725        }
3726    } else {
3727        result->values = NULL;
3728    }
3729    result->conn_ptr = conn;
3730    result->fetched = 0;
3731    RETURN_RES(zend_register_resource(result, le_result));
3732}
3733/* }}} */
3734
3735/* {{{ proto resource odbc_statistics(resource connection_id, string qualifier, string owner, string name, int unique, int accuracy)
3736   Returns a result identifier that contains statistics about a single table and the indexes associated with the table */
3737PHP_FUNCTION(odbc_statistics)
3738{
3739    zval *pv_conn;
3740    zend_long vunique, vreserved;
3741    odbc_result *result = NULL;
3742    odbc_connection *conn;
3743    char *cat = NULL, *schema, *name;
3744    size_t cat_len = 0, schema_len, name_len;
3745    SQLUSMALLINT unique, reserved;
3746    RETCODE rc;
3747
3748    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ssll", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3749        &name, &name_len, &vunique, &vreserved) == FAILURE) {
3750        return;
3751    }
3752
3753    unique = (SQLUSMALLINT) vunique;
3754    reserved = (SQLUSMALLINT) vreserved;
3755
3756    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3757        RETURN_FALSE;
3758    }
3759
3760    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3761
3762    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3763    if (rc == SQL_INVALID_HANDLE) {
3764        efree(result);
3765        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3766        RETURN_FALSE;
3767    }
3768
3769    if (rc == SQL_ERROR) {
3770        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3771        efree(result);
3772        RETURN_FALSE;
3773    }
3774
3775    rc = SQLStatistics(result->stmt,
3776            cat, SAFE_SQL_NTS(cat),
3777            schema, SAFE_SQL_NTS(schema),
3778            name, SAFE_SQL_NTS(name),
3779            unique,
3780            reserved);
3781
3782    if (rc == SQL_ERROR) {
3783        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLStatistics");
3784        efree(result);
3785        RETURN_FALSE;
3786    }
3787
3788    result->numparams = 0;
3789    SQLNumResultCols(result->stmt, &(result->numcols));
3790
3791    if (result->numcols > 0) {
3792        if (!odbc_bindcols(result)) {
3793            efree(result);
3794            RETURN_FALSE;
3795        }
3796    } else {
3797        result->values = NULL;
3798    }
3799    result->conn_ptr = conn;
3800    result->fetched = 0;
3801    RETURN_RES(zend_register_resource(result, le_result));
3802}
3803/* }}} */
3804
3805#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3806/* {{{ proto resource odbc_tableprivileges(resource connection_id, string qualifier, string owner, string name)
3807   Returns a result identifier containing a list of tables and the privileges associated with each table */
3808PHP_FUNCTION(odbc_tableprivileges)
3809{
3810    zval *pv_conn;
3811    odbc_result   *result = NULL;
3812    odbc_connection *conn;
3813    char *cat = NULL, *schema = NULL, *table = NULL;
3814    size_t cat_len = 0, schema_len, table_len;
3815    RETCODE rc;
3816
3817    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &table, &table_len) == FAILURE) {
3818        return;
3819    }
3820
3821    if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3822        RETURN_FALSE;
3823    }
3824
3825    result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3826
3827    rc = SQLAllocStmt(conn->hdbc, &(result->stmt));
3828    if (rc == SQL_INVALID_HANDLE) {
3829        efree(result);
3830        php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3831        RETURN_FALSE;
3832    }
3833
3834    if (rc == SQL_ERROR) {
3835        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3836        efree(result);
3837        RETURN_FALSE;
3838    }
3839
3840    rc = SQLTablePrivileges(result->stmt,
3841            cat, SAFE_SQL_NTS(cat),
3842            schema, SAFE_SQL_NTS(schema),
3843            table, SAFE_SQL_NTS(table));
3844
3845    if (rc == SQL_ERROR) {
3846        odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTablePrivileges");
3847        efree(result);
3848        RETURN_FALSE;
3849    }
3850
3851    result->numparams = 0;
3852    SQLNumResultCols(result->stmt, &(result->numcols));
3853
3854    if (result->numcols > 0) {
3855        if (!odbc_bindcols(result)) {
3856            efree(result);
3857            RETURN_FALSE;
3858        }
3859    } else {
3860        result->values = NULL;
3861    }
3862    result->conn_ptr = conn;
3863    result->fetched = 0;
3864    RETURN_RES(zend_register_resource(result, le_result));
3865}
3866/* }}} */
3867#endif /* HAVE_DBMAKER */
3868
3869#endif /* HAVE_UODBC */
3870
3871/*
3872 * Local variables:
3873 * tab-width: 4
3874 * c-basic-offset: 4
3875 * End:
3876 * vim600: sw=4 ts=4 fdm=marker
3877 * vim<600: sw=4 ts=4
3878 */
3879