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