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