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