1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
|
<?php
// vim: set et ts=4 sw=4 fdm=marker:
// +----------------------------------------------------------------------+
// | PHP versions 4 and 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
// | Stig. S. Bakken, Lukas Smith |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Author: Lukas Smith <smith@pooteeweet.org> |
// +----------------------------------------------------------------------+
//
// $Id: MDB2.php,v 1.335 2008/11/29 14:57:01 afz Exp $
//
/**
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
require_once('PEAR.php');
// {{{ Error constants
/**
* The method mapErrorCode in each MDB2_dbtype implementation maps
* native error codes to one of these.
*
* If you add an error code here, make sure you also add a textual
* version of it in MDB2::errorMessage().
*/
define('MDB2_OK', true);
define('MDB2_ERROR', -1);
define('MDB2_ERROR_SYNTAX', -2);
define('MDB2_ERROR_CONSTRAINT', -3);
define('MDB2_ERROR_NOT_FOUND', -4);
define('MDB2_ERROR_ALREADY_EXISTS', -5);
define('MDB2_ERROR_UNSUPPORTED', -6);
define('MDB2_ERROR_MISMATCH', -7);
define('MDB2_ERROR_INVALID', -8);
define('MDB2_ERROR_NOT_CAPABLE', -9);
define('MDB2_ERROR_TRUNCATED', -10);
define('MDB2_ERROR_INVALID_NUMBER', -11);
define('MDB2_ERROR_INVALID_DATE', -12);
define('MDB2_ERROR_DIVZERO', -13);
define('MDB2_ERROR_NODBSELECTED', -14);
define('MDB2_ERROR_CANNOT_CREATE', -15);
define('MDB2_ERROR_CANNOT_DELETE', -16);
define('MDB2_ERROR_CANNOT_DROP', -17);
define('MDB2_ERROR_NOSUCHTABLE', -18);
define('MDB2_ERROR_NOSUCHFIELD', -19);
define('MDB2_ERROR_NEED_MORE_DATA', -20);
define('MDB2_ERROR_NOT_LOCKED', -21);
define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
define('MDB2_ERROR_INVALID_DSN', -23);
define('MDB2_ERROR_CONNECT_FAILED', -24);
define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
define('MDB2_ERROR_NOSUCHDB', -26);
define('MDB2_ERROR_ACCESS_VIOLATION', -27);
define('MDB2_ERROR_CANNOT_REPLACE', -28);
define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
define('MDB2_ERROR_DEADLOCK', -30);
define('MDB2_ERROR_CANNOT_ALTER', -31);
define('MDB2_ERROR_MANAGER', -32);
define('MDB2_ERROR_MANAGER_PARSE', -33);
define('MDB2_ERROR_LOADMODULE', -34);
define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
define('MDB2_ERROR_NO_PERMISSION', -36);
define('MDB2_ERROR_DISCONNECT_FAILED', -37);
// }}}
// {{{ Verbose constants
/**
* These are just helper constants to more verbosely express parameters to prepare()
*/
define('MDB2_PREPARE_MANIP', false);
define('MDB2_PREPARE_RESULT', null);
// }}}
// {{{ Fetchmode constants
/**
* This is a special constant that tells MDB2 the user hasn't specified
* any particular get mode, so the default should be used.
*/
define('MDB2_FETCHMODE_DEFAULT', 0);
/**
* Column data indexed by numbers, ordered from 0 and up
*/
define('MDB2_FETCHMODE_ORDERED', 1);
/**
* Column data indexed by column names
*/
define('MDB2_FETCHMODE_ASSOC', 2);
/**
* Column data as object properties
*/
define('MDB2_FETCHMODE_OBJECT', 3);
/**
* For multi-dimensional results: normally the first level of arrays
* is the row number, and the second level indexed by column number or name.
* MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
* is the column name, and the second level the row number.
*/
define('MDB2_FETCHMODE_FLIPPED', 4);
// }}}
// {{{ Portability mode constants
/**
* Portability: turn off all portability features.
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_NONE', 0);
/**
* Portability: convert names of tables and fields to case defined in the
* "field_case" option when using the query*(), fetch*() and tableInfo() methods.
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_FIX_CASE', 1);
/**
* Portability: right trim the data output by query*() and fetch*().
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_RTRIM', 2);
/**
* Portability: force reporting the number of rows deleted.
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_DELETE_COUNT', 4);
/**
* Portability: not needed in MDB2 (just left here for compatibility to DB)
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_NUMROWS', 8);
/**
* Portability: makes certain error messages in certain drivers compatible
* with those from other DBMS's.
*
* + mysql, mysqli: change unique/primary key constraints
* MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
*
* + odbc(access): MS's ODBC driver reports 'no such field' as code
* 07001, which means 'too few parameters.' When this option is on
* that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
*
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_ERRORS', 16);
/**
* Portability: convert empty values to null strings in data output by
* query*() and fetch*().
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
/**
* Portability: removes database/table qualifiers from associative indexes
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
/**
* Portability: turn on all portability features.
* @see MDB2_Driver_Common::setOption()
*/
define('MDB2_PORTABILITY_ALL', 127);
// }}}
// {{{ Globals for class instance tracking
/**
* These are global variables that are used to track the various class instances
*/
$GLOBALS['_MDB2_databases'] = array();
$GLOBALS['_MDB2_dsninfo_default'] = array(
'phptype' => false,
'dbsyntax' => false,
'username' => false,
'password' => false,
'protocol' => false,
'hostspec' => false,
'port' => false,
'socket' => false,
'database' => false,
'mode' => false,
);
// }}}
// {{{ class MDB2
/**
* The main 'MDB2' class is simply a container class with some static
* methods for creating DB objects as well as some utility functions
* common to all parts of DB.
*
* The object model of MDB2 is as follows (indentation means inheritance):
*
* MDB2 The main MDB2 class. This is simply a utility class
* with some 'static' methods for creating MDB2 objects as
* well as common utility functions for other MDB2 classes.
*
* MDB2_Driver_Common The base for each MDB2 implementation. Provides default
* | implementations (in OO lingo virtual methods) for
* | the actual DB implementations as well as a bunch of
* | query utility functions.
* |
* +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
* When calling MDB2::factory or MDB2::connect for MySQL
* connections, the object returned is an instance of this
* class.
* +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
* When calling MDB2::factory or MDB2::connect for PostGreSQL
* connections, the object returned is an instance of this
* class.
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2
{
// {{{ function setOptions(&$db, $options)
/**
* set option array in an exiting database object
*
* @param MDB2_Driver_Common MDB2 object
* @param array An associative array of option names and their values.
*
* @return mixed MDB2_OK or a PEAR Error object
*
* @access public
*/
static function setOptions(&$db, $options)
{
if (is_array($options)) {
foreach ($options as $option => $value) {
$test = $db->setOption($option, $value);
if (PEAR::isError($test)) {
return $test;
}
}
}
return MDB2_OK;
}
// }}}
// {{{ function classExists($classname)
/**
* Checks if a class exists without triggering __autoload
*
* @param string classname
*
* @return bool true success and false on error
* @static
* @access public
*/
static function classExists($classname)
{
if (version_compare(phpversion(), "5.0", ">=")) {
return class_exists($classname, false);
}
return class_exists($classname);
}
// }}}
// {{{ function loadClass($class_name, $debug)
/**
* Loads a PEAR class.
*
* @param string classname to load
* @param bool if errors should be suppressed
*
* @return mixed true success or PEAR_Error on failure
*
* @access public
*/
static function loadClass($class_name, $debug)
{
if (!MDB2::classExists($class_name)) {
$file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
if ($debug) {
$include = include_once($file_name);
} else {
$include = include_once($file_name);
}
if (!$include) {
if (!MDB2::fileExists($file_name)) {
$msg = "unable to find package '$class_name' file '$file_name'";
} else {
$msg = "unable to load class '$class_name' from file '$file_name'";
}
$err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND, null, null, $msg);
return $err;
}
}
return MDB2_OK;
}
// }}}
// {{{ function &factory($dsn, $options = false)
/**
* Create a new MDB2 object for the specified database type
*
* IMPORTANT: In order for MDB2 to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
*
* For example:
* $db =& MDB2::factory($dsn);
* ^^
* And not:
* $db = MDB2::factory($dsn);
*
* @param mixed 'data source name', see the MDB2::parseDSN
* method for a description of the dsn format.
* Can also be specified as an array of the
* format returned by MDB2::parseDSN.
* @param array An associative array of option names and
* their values.
*
* @return mixed a newly created MDB2 object, or false on error
*
* @access public
*/
static function factory($dsn, $options = false)
{
$dsninfo = MDB2::parseDSN($dsn);
if (empty($dsninfo['phptype'])) {
$err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND,
null, null, 'no RDBMS driver specified');
return $err;
}
$class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
$debug = (!empty($options['debug']));
$err = MDB2::loadClass($class_name, $debug);
if (PEAR::isError($err)) {
return $err;
}
$db =new $class_name();
$db->setDSN($dsninfo);
$err = MDB2::setOptions($db, $options);
if (PEAR::isError($err)) {
return $err;
}
return $db;
}
// }}}
// {{{ function &connect($dsn, $options = false)
/**
* Create a new MDB2_Driver_* connection object and connect to the specified
* database
*
* IMPORTANT: In order for MDB2 to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
*
* For example:
* $db =& MDB2::connect($dsn);
* ^^
* And not:
* $db = MDB2::connect($dsn);
* ^^
*
* @param mixed $dsn 'data source name', see the MDB2::parseDSN
* method for a description of the dsn format.
* Can also be specified as an array of the
* format returned by MDB2::parseDSN.
* @param array $options An associative array of option names and
* their values.
*
* @return mixed a newly created MDB2 connection object, or a MDB2
* error object on error
*
* @access public
* @see MDB2::parseDSN
*/
function &connect($dsn, $options = false)
{
$db =MDB2::factory($dsn, $options);
if (PEAR::isError($db)) {
return $db;
}
$err = $db->connect();
if (PEAR::isError($err)) {
$dsn = $db->getDSN('string', 'xxx');
$db->disconnect();
$err->addUserInfo($dsn);
return $err;
}
return $db;
}
// }}}
// {{{ function &singleton($dsn = null, $options = false)
/**
* Returns a MDB2 connection with the requested DSN.
* A new MDB2 connection object is only created if no object with the
* requested DSN exists yet.
*
* IMPORTANT: In order for MDB2 to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
*
* For example:
* $db =& MDB2::singleton($dsn);
* ^^
* And not:
* $db = MDB2::singleton($dsn);
* ^^
*
* @param mixed 'data source name', see the MDB2::parseDSN
* method for a description of the dsn format.
* Can also be specified as an array of the
* format returned by MDB2::parseDSN.
* @param array An associative array of option names and
* their values.
*
* @return mixed a newly created MDB2 connection object, or a MDB2
* error object on error
*
* @access public
* @see MDB2::parseDSN
*/
function &singleton($dsn = null, $options = false)
{
if ($dsn) {
$dsninfo = MDB2::parseDSN($dsn);
$dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
$keys = array_keys($GLOBALS['_MDB2_databases']);
for ($i=0, $j=count($keys); $i<$j; ++$i) {
if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
$tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
return $GLOBALS['_MDB2_databases'][$keys[$i]];
}
}
}
} elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
$db =$GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
return $db;
}
$db =MDB2::factory($dsn, $options);
return $db;
}
// }}}
// {{{ function areEquals()
/**
* It looks like there's a memory leak in array_diff() in PHP 5.1.x,
* so use this method instead.
* @see http://pear.php.net/bugs/bug.php?id=11790
*
* @param array $arr1
* @param array $arr2
* @return boolean
*/
static function areEquals($arr1, $arr2)
{
if (count($arr1) != count($arr2)) {
return false;
}
foreach (array_keys($arr1) as $k) {
if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
return false;
}
}
return true;
}
// }}}
// {{{ function loadFile($file)
/**
* load a file (like 'Date')
*
* @param string name of the file in the MDB2 directory (without '.php')
*
* @return string name of the file that was included
*
* @access public
*/
function loadFile($file)
{
$file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
if (!MDB2::fileExists($file_name)) {
return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'unable to find: '.$file_name);
}
if (!include_once($file_name)) {
return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'unable to load driver class: '.$file_name);
}
return $file_name;
}
// }}}
// {{{ function apiVersion()
/**
* Return the MDB2 API version
*
* @return string the MDB2 API version number
*
* @access public
*/
function apiVersion()
{
return '2.5.0b2';
}
// }}}
// {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
/**
* This method is used to communicate an error and invoke error
* callbacks etc. Basically a wrapper for PEAR::raiseError
* without the message string.
*
* @param mixed int error code
*
* @param int error mode, see PEAR_Error docs
*
* @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
* error level (E_USER_NOTICE etc). If error mode is
* PEAR_ERROR_CALLBACK, this is the callback function,
* either as a function name, or as an array of an
* object and method name. For other error modes this
* parameter is ignored.
*
* @param string Extra debug information. Defaults to the last
* query and native error code.
*
* @return PEAR_Error instance of a PEAR Error object
*
* @access private
* @see PEAR_Error
*/
function raiseError($code = null,
$mode = null,
$options = null,
$userinfo = null,
$dummy1 = null,
$dummy2 = null,
$dummy3 = false)
{
$err =PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
return $err;
}
static function raiseErrorStatic($code = null,
$mode = null,
$options = null,
$userinfo = null,
$dummy1 = null,
$dummy2 = null,
$dummy3 = false)
{
$pear=new PEAR();
$err =$pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
return $err;
}
// }}}
// {{{ function isError($data, $code = null)
/**
* Tell whether a value is a MDB2 error.
*
* @param mixed the value to test
* @param int if is an error object, return true
* only if $code is a string and
* $db->getMessage() == $code or
* $code is an integer and $db->getCode() == $code
*
* @return bool true if parameter is an error
*
* @access public
*/
static function isError($data, $code = null)
{
if ($data instanceof MDB2_Error) {
if (is_null($code)) {
return true;
} elseif (is_string($code)) {
return $data->getMessage() === $code;
} else {
$code = (array)$code;
return in_array($data->getCode(), $code);
}
}
return false;
}
// }}}
// {{{ function isConnection($value)
/**
* Tell whether a value is a MDB2 connection
*
* @param mixed value to test
*
* @return bool whether $value is a MDB2 connection
*
* @access public
*/
static function isConnection($value)
{
return ($value instanceof MDB2_Driver_Common);
}
// }}}
// {{{ function isResult($value)
/**
* Tell whether a value is a MDB2 result
*
* @param mixed value to test
*
* @return bool whether $value is a MDB2 result
*
* @access public
*/
static function isResult($value)
{
return $value instanceof MDB2_Result;
}
// }}}
// {{{ function isResultCommon($value)
/**
* Tell whether a value is a MDB2 result implementing the common interface
*
* @param mixed value to test
*
* @return bool whether $value is a MDB2 result implementing the common interface
*
* @access public
*/
static function isResultCommon($value)
{
return ($value instanceof MDB2_Result_Common);
}
// }}}
// {{{ function isStatement($value)
/**
* Tell whether a value is a MDB2 statement interface
*
* @param mixed value to test
*
* @return bool whether $value is a MDB2 statement interface
*
* @access public
*/
static function isStatement($value)
{
return $value instanceof MDB2_Statement_Common;
}
// }}}
// {{{ function errorMessage($value = null)
/**
* Return a textual error message for a MDB2 error code
*
* @param int|array integer error code,
null to get the current error code-message map,
or an array with a new error code-message map
*
* @return string error message, or false if the error code was
* not recognized
*
* @access public
*/
static function errorMessage($value = null)
{
static $errorMessages;
if (is_array($value)) {
$errorMessages = $value;
return MDB2_OK;
}
if (!isset($errorMessages)) {
$errorMessages = array(
MDB2_OK => 'no error',
MDB2_ERROR => 'unknown error',
MDB2_ERROR_ALREADY_EXISTS => 'already exists',
MDB2_ERROR_CANNOT_CREATE => 'can not create',
MDB2_ERROR_CANNOT_ALTER => 'can not alter',
MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
MDB2_ERROR_CANNOT_DELETE => 'can not delete',
MDB2_ERROR_CANNOT_DROP => 'can not drop',
MDB2_ERROR_CONSTRAINT => 'constraint violation',
MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
MDB2_ERROR_DIVZERO => 'division by zero',
MDB2_ERROR_INVALID => 'invalid',
MDB2_ERROR_INVALID_DATE => 'invalid date or time',
MDB2_ERROR_INVALID_NUMBER => 'invalid number',
MDB2_ERROR_MISMATCH => 'mismatch',
MDB2_ERROR_NODBSELECTED => 'no database selected',
MDB2_ERROR_NOSUCHFIELD => 'no such field',
MDB2_ERROR_NOSUCHTABLE => 'no such table',
MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
MDB2_ERROR_NOT_FOUND => 'not found',
MDB2_ERROR_NOT_LOCKED => 'not locked',
MDB2_ERROR_SYNTAX => 'syntax error',
MDB2_ERROR_UNSUPPORTED => 'not supported',
MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
MDB2_ERROR_INVALID_DSN => 'invalid DSN',
MDB2_ERROR_CONNECT_FAILED => 'connect failed',
MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
MDB2_ERROR_NOSUCHDB => 'no such database',
MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
MDB2_ERROR_LOADMODULE => 'error while including on demand module',
MDB2_ERROR_TRUNCATED => 'truncated',
MDB2_ERROR_DEADLOCK => 'deadlock detected',
MDB2_ERROR_NO_PERMISSION => 'no permission',
MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed',
);
}
if (is_null($value)) {
return $errorMessages;
}
if (PEAR::isError($value)) {
$value = $value->getCode();
}
return isset($errorMessages[$value]) ?
$errorMessages[$value] : $errorMessages[MDB2_ERROR];
}
// }}}
// {{{ function parseDSN($dsn)
/**
* Parse a data source name.
*
* Additional keys can be added by appending a URI query string to the
* end of the DSN.
*
* The format of the supplied DSN is in its fullest form:
* <code>
* phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
* </code>
*
* Most variations are allowed:
* <code>
* phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
* </code>
*
* @param string Data Source Name to be parsed
*
* @return array an associative array with the following keys:
* + phptype: Database backend used in PHP (mysql, odbc etc.)
* + dbsyntax: Database used with regards to SQL syntax etc.
* + protocol: Communication protocol to use (tcp, unix etc.)
* + hostspec: Host specification (hostname[:port])
* + database: Database to use on the DBMS server
* + username: User name for login
* + password: Password for login
*
* @access public
* @author Tomas V.V.Cox <cox@idecnet.com>
*/
static function parseDSN($dsn)
{
$parsed = $GLOBALS['_MDB2_dsninfo_default'];
if (is_array($dsn)) {
$dsn = array_merge($parsed, $dsn);
if (!$dsn['dbsyntax']) {
$dsn['dbsyntax'] = $dsn['phptype'];
}
return $dsn;
}
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 3);
} else {
$str = $dsn;
$dsn = null;
}
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1];
$parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
} else {
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
}
if (!count($dsn)) {
return $parsed;
}
// Get (if found): username and password
// $dsn => username:password@protocol+hostspec/database
if (($at = strrpos($dsn,'@')) !== false) {
$str = substr($dsn, 0, $at);
$dsn = substr($dsn, $at + 1);
if (($pos = strpos($str, ':')) !== false) {
$parsed['username'] = rawurldecode(substr($str, 0, $pos));
$parsed['password'] = rawurldecode(substr($str, $pos + 1));
} else {
$parsed['username'] = rawurldecode($str);
}
}
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database
if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
$proto = $match[1];
$proto_opts = $match[2] ? $match[2] : false;
$dsn = $match[3];
// $dsn => protocol+hostspec/database (old format)
} else {
if (strpos($dsn, '+') !== false) {
list($proto, $dsn) = explode('+', $dsn, 2);
}
if ( strpos($dsn, '//') === 0
&& strpos($dsn, '/', 2) !== false
&& $parsed['phptype'] == 'oci8'
) {
//oracle's "Easy Connect" syntax:
//"username/password@[//]host[:port][/service_name]"
//e.g. "scott/tiger@//mymachine:1521/oracle"
$proto_opts = $dsn;
$dsn = substr($proto_opts, strrpos($proto_opts, '/') + 1);
} elseif (strpos($dsn, '/') !== false) {
list($proto_opts, $dsn) = explode('/', $dsn, 2);
} else {
$proto_opts = $dsn;
$dsn = null;
}
}
// process the different protocol options
$parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
$proto_opts = rawurldecode($proto_opts);
if (strpos($proto_opts, ':') !== false) {
list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
}
if ($parsed['protocol'] == 'tcp') {
$parsed['hostspec'] = $proto_opts;
} elseif ($parsed['protocol'] == 'unix') {
$parsed['socket'] = $proto_opts;
}
// Get dabase if any
// $dsn => database
if ($dsn) {
// /database
if (($pos = strpos($dsn, '?')) === false) {
$parsed['database'] = $dsn;
// /database?param1=value1¶m2=value2
} else {
$parsed['database'] = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 1);
if (strpos($dsn, '&') !== false) {
$opts = explode('&', $dsn);
} else { // database?param1=value1
$opts = array($dsn);
}
foreach ($opts as $opt) {
list($key, $value) = explode('=', $opt);
if (!isset($parsed[$key])) {
// don't allow params overwrite
$parsed[$key] = rawurldecode($value);
}
}
}
}
return $parsed;
}
// }}}
// {{{ function fileExists($file)
/**
* Checks if a file exists in the include path
*
* @param string filename
*
* @return bool true success and false on error
*
* @access public
*/
static function fileExists($file)
{
// safe_mode does notwork with is_readable()
if (!@ini_get('safe_mode')) {
$dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
array_unshift($dirs,OC::$SERVERROOT);
array_unshift($dirs,OC::$SERVERROOT. DIRECTORY_SEPARATOR .'inc');
// print_r($dirs);die();
foreach ($dirs as $dir) {
if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
return true;
}
}
} else {
$fp = @fopen($file, 'r', true);
if (is_resource($fp)) {
@fclose($fp);
return true;
}
}
return false;
}
// }}}
}
// }}}
// {{{ class MDB2_Error extends PEAR_Error
/**
* MDB2_Error implements a class for reporting portable database error
* messages.
*
* @package MDB2
* @category Database
* @author Stig Bakken <ssb@fast.no>
*/
class MDB2_Error extends PEAR_Error
{
// {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
/**
* MDB2_Error constructor.
*
* @param mixed MDB2 error code, or string with error message.
* @param int what 'error mode' to operate in
* @param int what error level to use for $mode raPEAR_ERROR_TRIGGER
* @param mixed additional debug info, such as the last query
*/
function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
$level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
{
if (is_null($code)) {
$code = MDB2_ERROR;
}
$this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
$mode, $level, $debuginfo);
}
// }}}
}
// }}}
// {{{ class MDB2_Driver_Common extends PEAR
/**
* MDB2_Driver_Common: Base class that is extended by each MDB2 driver
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Driver_Common extends PEAR
{
// {{{ Variables (Properties)
/**
* index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
* @var int
* @access public
*/
var $db_index = 0;
/**
* DSN used for the next query
* @var array
* @access protected
*/
var $dsn = array();
/**
* DSN that was used to create the current connection
* @var array
* @access protected
*/
var $connected_dsn = array();
/**
* connection resource
* @var mixed
* @access protected
*/
var $connection = 0;
/**
* if the current opened connection is a persistent connection
* @var bool
* @access protected
*/
var $opened_persistent;
/**
* the name of the database for the next query
* @var string
* @access protected
*/
var $database_name = '';
/**
* the name of the database currently selected
* @var string
* @access protected
*/
var $connected_database_name = '';
/**
* server version information
* @var string
* @access protected
*/
var $connected_server_info = '';
/**
* list of all supported features of the given driver
* @var array
* @access public
*/
var $supported = array(
'sequences' => false,
'indexes' => false,
'affected_rows' => false,
'summary_functions' => false,
'order_by_text' => false,
'transactions' => false,
'savepoints' => false,
'current_id' => false,
'limit_queries' => false,
'LOBs' => false,
'replace' => false,
'sub_selects' => false,
'triggers' => false,
'auto_increment' => false,
'primary_key' => false,
'result_introspection' => false,
'prepared_statements' => false,
'identifier_quoting' => false,
'pattern_escaping' => false,
'new_link' => false,
);
/**
* Array of supported options that can be passed to the MDB2 instance.
*
* The options can be set during object creation, using
* MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
* also be set after the object is created, using MDB2::setOptions() or
* MDB2_Driver_Common::setOption().
* The list of available option includes:
* <ul>
* <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
* <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
* <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
* <li>$options['result_class'] -> string: class used for result sets</li>
* <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
* <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
* <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
* <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
* <li>$options['persistent'] -> boolean: persistent connection?</li>
* <li>$options['debug'] -> integer: numeric debug level</li>
* <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
* <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
* <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
* <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
* <li>$options['log_line_break'] -> string: line-break format</li>
* <li>$options['idxname_format'] -> string: pattern for index name</li>
* <li>$options['seqname_format'] -> string: pattern for sequence name</li>
* <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
* <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
* <li>$options['seqcol_name'] -> string: sequence column name</li>
* <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
* <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
* <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
* <li>$options['portability'] -> integer: portability constant</li>
* <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
* <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
* <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
* <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
* <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
* <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
* <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
* <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
* <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
* </ul>
*
* @var array
* @access public
* @see MDB2::connect()
* @see MDB2::factory()
* @see MDB2::singleton()
* @see MDB2_Driver_Common::setOption()
*/
var $options = array(
'ssl' => false,
'field_case' => CASE_LOWER,
'disable_query' => false,
'result_class' => 'MDB2_Result_%s',
'buffered_result_class' => 'MDB2_BufferedResult_%s',
'result_wrap_class' => false,
'result_buffering' => true,
'fetch_class' => 'stdClass',
'persistent' => false,
'debug' => 0,
'debug_handler' => 'MDB2_defaultDebugOutput',
'debug_expanded_output' => false,
'default_text_field_length' => 4096,
'lob_buffer_length' => 8192,
'log_line_break' => "\n",
'idxname_format' => '%s_idx',
'seqname_format' => '%s_seq',
'savepoint_format' => 'MDB2_SAVEPOINT_%s',
'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
'seqcol_name' => 'sequence',
'quote_identifier' => false,
'use_transactions' => true,
'decimal_places' => 2,
'portability' => MDB2_PORTABILITY_ALL,
'modules' => array(
'ex' => 'Extended',
'dt' => 'Datatype',
'mg' => 'Manager',
'rv' => 'Reverse',
'na' => 'Native',
'fc' => 'Function',
),
'emulate_prepared' => false,
'datatype_map' => array(),
'datatype_map_callback' => array(),
'nativetype_map_callback' => array(),
'lob_allow_url_include' => false,
'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
'max_identifiers_length' => 30,
'default_fk_action_onupdate' => 'RESTRICT',
'default_fk_action_ondelete' => 'RESTRICT',
);
/**
* string array
* @var string
* @access protected
*/
var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
/**
* identifier quoting
* @var array
* @access protected
*/
var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
/**
* sql comments
* @var array
* @access protected
*/
var $sql_comments = array(
array('start' => '--', 'end' => "\n", 'escape' => false),
array('start' => '/*', 'end' => '*/', 'escape' => false),
);
/**
* comparision wildcards
* @var array
* @access protected
*/
var $wildcards = array('%', '_');
/**
* column alias keyword
* @var string
* @access protected
*/
var $as_keyword = ' AS ';
/**
* warnings
* @var array
* @access protected
*/
var $warnings = array();
/**
* string with the debugging information
* @var string
* @access public
*/
var $debug_output = '';
/**
* determine if there is an open transaction
* @var bool
* @access protected
*/
var $in_transaction = false;
/**
* the smart transaction nesting depth
* @var int
* @access protected
*/
var $nested_transaction_counter = null;
/**
* the first error that occured inside a nested transaction
* @var MDB2_Error|bool
* @access protected
*/
var $has_transaction_error = false;
/**
* result offset used in the next query
* @var int
* @access protected
*/
var $offset = 0;
/**
* result limit used in the next query
* @var int
* @access protected
*/
var $limit = 0;
/**
* Database backend used in PHP (mysql, odbc etc.)
* @var string
* @access public
*/
var $phptype;
/**
* Database used with regards to SQL syntax etc.
* @var string
* @access public
*/
var $dbsyntax;
/**
* the last query sent to the driver
* @var string
* @access public
*/
var $last_query;
/**
* the default fetchmode used
* @var int
* @access protected
*/
var $fetchmode = MDB2_FETCHMODE_ORDERED;
/**
* array of module instances
* @var array
* @access protected
*/
var $modules = array();
/**
* determines of the PHP4 destructor emulation has been enabled yet
* @var array
* @access protected
*/
var $destructor_registered = true;
// }}}
// {{{ constructor: function __construct()
/**
* Constructor
*/
function __construct()
{
end($GLOBALS['_MDB2_databases']);
$db_index = key($GLOBALS['_MDB2_databases']) + 1;
$GLOBALS['_MDB2_databases'][$db_index] = &$this;
$this->db_index = $db_index;
}
// }}}
// {{{ destructor: function __destruct()
/**
* Destructor
*/
function __destruct()
{
$this->disconnect(false);
}
// }}}
// {{{ function free()
/**
* Free the internal references so that the instance can be destroyed
*
* @return bool true on success, false if result is invalid
*
* @access public
*/
function free()
{
unset($GLOBALS['_MDB2_databases'][$this->db_index]);
unset($this->db_index);
return MDB2_OK;
}
// }}}
// {{{ function __toString()
/**
* String conversation
*
* @return string representation of the object
*
* @access public
*/
function __toString()
{
$info = get_class($this);
$info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
if ($this->connection) {
$info.= ' [connected]';
}
return $info;
}
// }}}
// {{{ function errorInfo($error = null)
/**
* This method is used to collect information about an error
*
* @param mixed error code or resource
*
* @return array with MDB2 errorcode, native error code, native message
*
* @access public
*/
function errorInfo($error = null)
{
return array($error, null, null);
}
// }}}
// {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
/**
* This method is used to communicate an error and invoke error
* callbacks etc. Basically a wrapper for PEAR::raiseError
* without the message string.
*
* @param mixed $code integer error code, or a PEAR error object (all
* other parameters are ignored if this parameter is
* an object
* @param int $mode error mode, see PEAR_Error docs
* @param mixed $options If error mode is PEAR_ERROR_TRIGGER, this is the
* error level (E_USER_NOTICE etc). If error mode is
* PEAR_ERROR_CALLBACK, this is the callback function,
* either as a function name, or as an array of an
* object and method name. For other error modes this
* parameter is ignored.
* @param string $userinfo Extra debug information. Defaults to the last
* query and native error code.
* @param string $method name of the method that triggered the error
* @param string $dummy1 not used
* @param bool $dummy2 not used
*
* @return PEAR_Error instance of a PEAR Error object
* @access public
* @see PEAR_Error
*/
function raiseError($code = null,
$mode = null,
$options = null,
$userinfo = null,
$method = null,
$dummy1 = null,
$dummy2 = false
) {
$userinfo = "[Error message: $userinfo]\n";
// The error is yet a MDB2 error object
if (PEAR::isError($code)) {
// because we use the static PEAR::raiseError, our global
// handler should be used if it is set
if (is_null($mode) && !empty($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
}
if (is_null($userinfo)) {
$userinfo = $code->getUserinfo();
}
$code = $code->getCode();
} elseif ($code == MDB2_ERROR_NOT_FOUND) {
// extension not loaded: don't call $this->errorInfo() or the script
// will die
} elseif (isset($this->connection)) {
if (!empty($this->last_query)) {
$userinfo.= "[Last executed query: {$this->last_query}]\n";
}
$native_errno = $native_msg = null;
list($code, $native_errno, $native_msg) = $this->errorInfo($code);
if (!is_null($native_errno) && $native_errno !== '') {
$userinfo.= "[Native code: $native_errno]\n";
}
if (!is_null($native_msg) && $native_msg !== '') {
$userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
}
echo $userinfo;
if (!is_null($method)) {
$userinfo = $method.': '.$userinfo;
}
}
$err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
if ($err->getMode() !== PEAR_ERROR_RETURN
&& isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
$this->has_transaction_error =$err;
}
return $err;
}
// }}}
// {{{ function resetWarnings()
/**
* reset the warning array
*
* @return void
*
* @access public
*/
function resetWarnings()
{
$this->warnings = array();
}
// }}}
// {{{ function getWarnings()
/**
* Get all warnings in reverse order.
* This means that the last warning is the first element in the array
*
* @return array with warnings
*
* @access public
* @see resetWarnings()
*/
function getWarnings()
{
return array_reverse($this->warnings);
}
// }}}
// {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
/**
* Sets which fetch mode should be used by default on queries
* on this connection
*
* @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
* or MDB2_FETCHMODE_OBJECT
* @param string the class name of the object to be returned
* by the fetch methods when the
* MDB2_FETCHMODE_OBJECT mode is selected.
* If no class is specified by default a cast
* to object from the assoc array row will be
* done. There is also the possibility to use
* and extend the 'MDB2_row' class.
*
* @return mixed MDB2_OK or MDB2 Error Object
*
* @access public
* @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
*/
function setFetchMode($fetchmode, $object_class = 'stdClass')
{
switch ($fetchmode) {
case MDB2_FETCHMODE_OBJECT:
$this->options['fetch_class'] = $object_class;
case MDB2_FETCHMODE_ORDERED:
case MDB2_FETCHMODE_ASSOC:
$this->fetchmode = $fetchmode;
break;
default:
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'invalid fetchmode mode', __FUNCTION__);
}
return MDB2_OK;
}
// }}}
// {{{ function setOption($option, $value)
/**
* set the option for the db class
*
* @param string option name
* @param mixed value for the option
*
* @return mixed MDB2_OK or MDB2 Error Object
*
* @access public
*/
function setOption($option, $value)
{
if (array_key_exists($option, $this->options)) {
$this->options[$option] = $value;
return MDB2_OK;
}
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
"unknown option $option", __FUNCTION__);
}
// }}}
// {{{ function getOption($option)
/**
* Returns the value of an option
*
* @param string option name
*
* @return mixed the option value or error object
*
* @access public
*/
function getOption($option)
{
if (array_key_exists($option, $this->options)) {
return $this->options[$option];
}
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
"unknown option $option", __FUNCTION__);
}
// }}}
// {{{ function debug($message, $scope = '', $is_manip = null)
/**
* set a debug message
*
* @param string message that should be appended to the debug variable
* @param string usually the method name that triggered the debug call:
* for example 'query', 'prepare', 'execute', 'parameters',
* 'beginTransaction', 'commit', 'rollback'
* @param array contains context information about the debug() call
* common keys are: is_manip, time, result etc.
*
* @return void
*
* @access public
*/
function debug($message, $scope = '', $context = array())
{
if ($this->options['debug'] && $this->options['debug_handler']) {
if (!$this->options['debug_expanded_output']) {
if (!empty($context['when']) && $context['when'] !== 'pre') {
return null;
}
$context = empty($context['is_manip']) ? false : $context['is_manip'];
}
return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
}
return null;
}
// }}}
// {{{ function getDebugOutput()
/**
* output debug info
*
* @return string content of the debug_output class variable
*
* @access public
*/
function getDebugOutput()
{
return $this->debug_output;
}
// }}}
// {{{ function escape($text)
/**
* Quotes a string so it can be safely used in a query. It will quote
* the text so it can safely be used within a query.
*
* @param string the input string to quote
* @param bool escape wildcards
*
* @return string quoted string
*
* @access public
*/
function escape($text, $escape_wildcards = false)
{
if ($escape_wildcards) {
$text = $this->escapePattern($text);
}
$text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
return $text;
}
// }}}
// {{{ function escapePattern($text)
/**
* Quotes pattern (% and _) characters in a string)
*
* @param string the input string to quote
*
* @return string quoted string
*
* @access public
*/
function escapePattern($text)
{
if ($this->string_quoting['escape_pattern']) {
$text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
foreach ($this->wildcards as $wildcard) {
$text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
}
}
return $text;
}
// }}}
// {{{ function quoteIdentifier($str, $check_option = false)
/**
* Quote a string so it can be safely used as a table or column name
*
* Delimiting style depends on which database driver is being used.
*
* NOTE: just because you CAN use delimited identifiers doesn't mean
* you SHOULD use them. In general, they end up causing way more
* problems than they solve.
*
* NOTE: if you have table names containing periods, don't use this method
* (@see bug #11906)
*
* Portability is broken by using the following characters inside
* delimited identifiers:
* + backtick (<kbd>`</kbd>) -- due to MySQL
* + double quote (<kbd>"</kbd>) -- due to Oracle
* + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
*
* Delimited identifiers are known to generally work correctly under
* the following drivers:
* + mssql
* + mysql
* + mysqli
* + oci8
* + pgsql
* + sqlite
*
* InterBase doesn't seem to be able to use delimited identifiers
* via PHP 4. They work fine under PHP 5.
*
* @param string identifier name to be quoted
* @param bool check the 'quote_identifier' option
*
* @return string quoted identifier string
*
* @access public
*/
function quoteIdentifier($str, $check_option = false)
{
if ($check_option && !$this->options['quote_identifier']) {
return $str;
}
$str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
$parts = explode('.', $str);
foreach (array_keys($parts) as $k) {
$parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
}
return implode('.', $parts);
}
// }}}
// {{{ function getAsKeyword()
/**
* Gets the string to alias column
*
* @return string to use when aliasing a column
*/
function getAsKeyword()
{
return $this->as_keyword;
}
// }}}
// {{{ function getConnection()
/**
* Returns a native connection
*
* @return mixed a valid MDB2 connection object,
* or a MDB2 error object on error
*
* @access public
*/
function getConnection()
{
$result = $this->connect();
if (PEAR::isError($result)) {
return $result;
}
return $this->connection;
}
// }}}
// {{{ function _fixResultArrayValues(&$row, $mode)
/**
* Do all necessary conversions on result arrays to fix DBMS quirks
*
* @param array the array to be fixed (passed by reference)
* @param array bit-wise addition of the required portability modes
*
* @return void
*
* @access protected
*/
function _fixResultArrayValues(&$row, $mode)
{
switch ($mode) {
case MDB2_PORTABILITY_EMPTY_TO_NULL:
foreach ($row as $key => $value) {
if ($value === '') {
$row[$key] = null;
}
}
break;
case MDB2_PORTABILITY_RTRIM:
foreach ($row as $key => $value) {
if (is_string($value)) {
$row[$key] = rtrim($value);
}
}
break;
case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
$tmp_row = array();
foreach ($row as $key => $value) {
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
}
$row = $tmp_row;
break;
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
foreach ($row as $key => $value) {
if ($value === '') {
$row[$key] = null;
} elseif (is_string($value)) {
$row[$key] = rtrim($value);
}
}
break;
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
$tmp_row = array();
foreach ($row as $key => $value) {
if (is_string($value)) {
$value = rtrim($value);
}
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
}
$row = $tmp_row;
break;
case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
$tmp_row = array();
foreach ($row as $key => $value) {
if ($value === '') {
$value = null;
}
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
}
$row = $tmp_row;
break;
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
$tmp_row = array();
foreach ($row as $key => $value) {
if ($value === '') {
$value = null;
} elseif (is_string($value)) {
$value = rtrim($value);
}
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
}
$row = $tmp_row;
break;
}
}
// }}}
// {{{ function &loadModule($module, $property = null, $phptype_specific = null)
/**
* loads a module
*
* @param string name of the module that should be loaded
* (only used for error messages)
* @param string name of the property into which the class will be loaded
* @param bool if the class to load for the module is specific to the
* phptype
*
* @return object on success a reference to the given module is returned
* and on failure a PEAR error
*
* @access public
*/
function &loadModule($module, $property = null, $phptype_specific = null)
{
if (!$property) {
$property = strtolower($module);
}
if (!isset($this->{$property})) {
$version = $phptype_specific;
if ($phptype_specific !== false) {
$version = true;
$class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
$file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
}
if ($phptype_specific === false
|| (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
) {
$version = false;
$class_name = 'MDB2_'.$module;
$file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
}
$err = MDB2::loadClass($class_name, $this->getOption('debug'));
if (PEAR::isError($err)) {
return $err;
}
// load module in a specific version
if ($version) {
if (method_exists($class_name, 'getClassName')) {
$class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
if ($class_name != $class_name_new) {
$class_name = $class_name_new;
$err = MDB2::loadClass($class_name, $this->getOption('debug'));
if (PEAR::isError($err)) {
return $err;
}
}
}
}
if (!MDB2::classExists($class_name)) {
$err =$this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
"unable to load module '$module' into property '$property'", __FUNCTION__);
return $err;
}
$this->{$property} = new $class_name($this->db_index);
$this->modules[$module] =$this->{$property};
if ($version) {
// this will be used in the connect method to determine if the module
// needs to be loaded with a different version if the server
// version changed in between connects
$this->loaded_version_modules[] = $property;
}
}
return $this->{$property};
}
// }}}
// {{{ function __call($method, $params)
/**
* Calls a module method using the __call magic method
*
* @param string Method name.
* @param array Arguments.
*
* @return mixed Returned value.
*/
function __call($method, $params)
{
$module = null;
if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
&& isset($this->options['modules'][$match[1]])
) {
$module = $this->options['modules'][$match[1]];
$method = strtolower($match[2]).$match[3];
if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
$result =& $this->loadModule($module);
if (PEAR::isError($result)) {
return $result;
}
}
} else {
foreach ($this->modules as $key => $foo) {
if (is_object($this->modules[$key])
&& method_exists($this->modules[$key], $method)
) {
$module = $key;
break;
}
}
}
if (!is_null($module)) {
return call_user_func_array(array(&$this->modules[$module], $method), $params);
}
trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
}
// }}}
// {{{ function beginTransaction($savepoint = null)
/**
* Start a transaction or set a savepoint.
*
* @param string name of a savepoint to set
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function beginTransaction($savepoint = null)
{
$this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'transactions are not supported', __FUNCTION__);
}
// }}}
// {{{ function commit($savepoint = null)
/**
* Commit the database changes done during a transaction that is in
* progress or release a savepoint. This function may only be called when
* auto-committing is disabled, otherwise it will fail. Therefore, a new
* transaction is implicitly started after committing the pending changes.
*
* @param string name of a savepoint to release
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function commit($savepoint = null)
{
$this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'commiting transactions is not supported', __FUNCTION__);
}
// }}}
// {{{ function rollback($savepoint = null)
/**
* Cancel any database changes done during a transaction or since a specific
* savepoint that is in progress. This function may only be called when
* auto-committing is disabled, otherwise it will fail. Therefore, a new
* transaction is implicitly started after canceling the pending changes.
*
* @param string name of a savepoint to rollback to
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function rollback($savepoint = null)
{
$this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'rolling back transactions is not supported', __FUNCTION__);
}
// }}}
// {{{ function inTransaction($ignore_nested = false)
/**
* If a transaction is currently open.
*
* @param bool if the nested transaction count should be ignored
* @return int|bool - an integer with the nesting depth is returned if a
* nested transaction is open
* - true is returned for a normal open transaction
* - false is returned if no transaction is open
*
* @access public
*/
function inTransaction($ignore_nested = false)
{
if (!$ignore_nested && isset($this->nested_transaction_counter)) {
return $this->nested_transaction_counter;
}
return $this->in_transaction;
}
// }}}
// {{{ function setTransactionIsolation($isolation)
/**
* Set the transacton isolation level.
*
* @param string standard isolation level
* READ UNCOMMITTED (allows dirty reads)
* READ COMMITTED (prevents dirty reads)
* REPEATABLE READ (prevents nonrepeatable reads)
* SERIALIZABLE (prevents phantom reads)
* @param array some transaction options:
* 'wait' => 'WAIT' | 'NO WAIT'
* 'rw' => 'READ WRITE' | 'READ ONLY'
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
* @since 2.1.1
*/
static function setTransactionIsolation($isolation, $options = array())
{
$this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'isolation level setting is not supported', __FUNCTION__);
}
// }}}
// {{{ function beginNestedTransaction($savepoint = false)
/**
* Start a nested transaction.
*
* @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
*
* @access public
* @since 2.1.1
*/
function beginNestedTransaction()
{
if ($this->in_transaction) {
++$this->nested_transaction_counter;
$savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
if ($this->supports('savepoints') && $savepoint) {
return $this->beginTransaction($savepoint);
}
return MDB2_OK;
}
$this->has_transaction_error = false;
$result = $this->beginTransaction();
$this->nested_transaction_counter = 1;
return $result;
}
// }}}
// {{{ function completeNestedTransaction($force_rollback = false, $release = false)
/**
* Finish a nested transaction by rolling back if an error occured or
* committing otherwise.
*
* @param bool if the transaction should be rolled back regardless
* even if no error was set within the nested transaction
* @return mixed MDB_OK on commit/counter decrementing, false on rollback
* and a MDB2 error on failure
*
* @access public
* @since 2.1.1
*/
function completeNestedTransaction($force_rollback = false)
{
if ($this->nested_transaction_counter > 1) {
$savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
if ($this->supports('savepoints') && $savepoint) {
if ($force_rollback || $this->has_transaction_error) {
$result = $this->rollback($savepoint);
if (!PEAR::isError($result)) {
$result = false;
$this->has_transaction_error = false;
}
} else {
$result = $this->commit($savepoint);
}
} else {
$result = MDB2_OK;
}
--$this->nested_transaction_counter;
return $result;
}
$this->nested_transaction_counter = null;
$result = MDB2_OK;
// transaction has not yet been rolled back
if ($this->in_transaction) {
if ($force_rollback || $this->has_transaction_error) {
$result = $this->rollback();
if (!PEAR::isError($result)) {
$result = false;
}
} else {
$result = $this->commit();
}
}
$this->has_transaction_error = false;
return $result;
}
// }}}
// {{{ function failNestedTransaction($error = null, $immediately = false)
/**
* Force setting nested transaction to failed.
*
* @param mixed value to return in getNestededTransactionError()
* @param bool if the transaction should be rolled back immediately
* @return bool MDB2_OK
*
* @access public
* @since 2.1.1
*/
function failNestedTransaction($error = null, $immediately = false)
{
if (is_null($error)) {
$error = $this->has_transaction_error ? $this->has_transaction_error : true;
} elseif (!$error) {
$error = true;
}
$this->has_transaction_error = $error;
if (!$immediately) {
return MDB2_OK;
}
return $this->rollback();
}
// }}}
// {{{ function getNestedTransactionError()
/**
* The first error that occured since the transaction start.
*
* @return MDB2_Error|bool MDB2 error object if an error occured or false.
*
* @access public
* @since 2.1.1
*/
function getNestedTransactionError()
{
return $this->has_transaction_error;
}
// }}}
// {{{ connect()
/**
* Connect to the database
*
* @return true on success, MDB2 Error Object on failure
*/
function connect()
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ databaseExists()
/**
* check if given database name is exists?
*
* @param string $name name of the database that should be checked
*
* @return mixed true/false on success, a MDB2 error on failure
* @access public
*/
function databaseExists($name)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ setCharset($charset, $connection = null)
/**
* Set the charset on the current connection
*
* @param string charset
* @param resource connection handle
*
* @return true on success, MDB2 Error Object on failure
*/
function setCharset($charset, $connection = null)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function disconnect($force = true)
/**
* Log out and disconnect from the database.
*
* @param boolean $force whether the disconnect should be forced even if the
* connection is opened persistently
*
* @return mixed true on success, false if not connected and error object on error
*
* @access public
*/
function disconnect($force = true)
{
$this->connection = 0;
$this->connected_dsn = array();
$this->connected_database_name = '';
$this->opened_persistent = null;
$this->connected_server_info = '';
$this->in_transaction = null;
$this->nested_transaction_counter = null;
return MDB2_OK;
}
// }}}
// {{{ function setDatabase($name)
/**
* Select a different database
*
* @param string name of the database that should be selected
*
* @return string name of the database previously connected to
*
* @access public
*/
function setDatabase($name)
{
$previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
$this->database_name = $name;
if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
$this->disconnect(false);
}
return $previous_database_name;
}
// }}}
// {{{ function getDatabase()
/**
* Get the current database
*
* @return string name of the database
*
* @access public
*/
function getDatabase()
{
return $this->database_name;
}
// }}}
// {{{ function setDSN($dsn)
/**
* set the DSN
*
* @param mixed DSN string or array
*
* @return MDB2_OK
*
* @access public
*/
function setDSN($dsn)
{
$dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
$dsn = MDB2::parseDSN($dsn);
if (array_key_exists('database', $dsn)) {
$this->database_name = $dsn['database'];
unset($dsn['database']);
}
$this->dsn = array_merge($dsn_default, $dsn);
return $this->disconnect(false);
}
// }}}
// {{{ function getDSN($type = 'string', $hidepw = false)
/**
* return the DSN as a string
*
* @param string format to return ("array", "string")
* @param string string to hide the password with
*
* @return mixed DSN in the chosen type
*
* @access public
*/
function getDSN($type = 'string', $hidepw = false)
{
$dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
$dsn['phptype'] = $this->phptype;
$dsn['database'] = $this->database_name;
if ($hidepw) {
$dsn['password'] = $hidepw;
}
switch ($type) {
// expand to include all possible options
case 'string':
$dsn = $dsn['phptype'].
($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
'://'.$dsn['username'].':'.
$dsn['password'].'@'.$dsn['hostspec'].
($dsn['port'] ? (':'.$dsn['port']) : '').
'/'.$dsn['database'];
break;
case 'array':
default:
break;
}
return $dsn;
}
// }}}
// {{{ _isNewLinkSet()
/**
* Check if the 'new_link' option is set
*
* @return boolean
*
* @access protected
*/
function _isNewLinkSet()
{
return (isset($this->dsn['new_link'])
&& ($this->dsn['new_link'] === true
|| (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
|| (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
)
);
}
// }}}
// {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
/**
* execute a query as database administrator
*
* @param string the SQL query
* @param mixed array that contains the types of the columns in
* the result set
* @param bool if the query is a manipulation query
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function &standaloneQuery($query, $types = null, $is_manip = false)
{
$offset = $this->offset;
$limit = $this->limit;
$this->offset = $this->limit = 0;
$query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
$connection = $this->getConnection();
if (PEAR::isError($connection)) {
return $connection;
}
$result =$this->_doQuery($query, $is_manip, $connection, false);
if (PEAR::isError($result)) {
return $result;
}
if ($is_manip) {
$affected_rows = $this->_affectedRows($connection, $result);
return $affected_rows;
}
$result =$this->_wrapResult($result, $types, true, false, $limit, $offset);
return $result;
}
// }}}
// {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
/**
* Changes a query string for various DBMS specific reasons
*
* @param string query to modify
* @param bool if it is a DML query
* @param int limit the number of rows
* @param int start reading from given offset
*
* @return string modified query
*
* @access protected
*/
function _modifyQuery($query, $is_manip, $limit, $offset)
{
return $query;
}
// }}}
// {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
/**
* Execute a query
* @param string query
* @param bool if the query is a manipulation query
* @param resource connection handle
* @param string database name
*
* @return result or error object
*
* @access protected
*/
function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
{
$this->last_query = $query;
$result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
if ($result) {
if (PEAR::isError($result)) {
return $result;
}
$query = $result;
}
$err =$this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
return $err;
}
// }}}
// {{{ function _affectedRows($connection, $result = null)
/**
* Returns the number of rows affected
*
* @param resource result handle
* @param resource connection handle
*
* @return mixed MDB2 Error Object or the number of rows affected
*
* @access private
*/
function _affectedRows($connection, $result = null)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function &exec($query)
/**
* Execute a manipulation query to the database and return the number of affected rows
*
* @param string the SQL query
*
* @return mixed number of affected rows on success, a MDB2 error on failure
*
* @access public
*/
function &exec($query)
{
$offset = $this->offset;
$limit = $this->limit;
$this->offset = $this->limit = 0;
$query = $this->_modifyQuery($query, true, $limit, $offset);
$connection = $this->getConnection();
if (PEAR::isError($connection)) {
return $connection;
}
$result =$this->_doQuery($query, true, $connection, $this->database_name);
if (PEAR::isError($result)) {
return $result;
}
$affectedRows = $this->_affectedRows($connection, $result);
return $affectedRows;
}
// }}}
// {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
/**
* Send a query to the database and return any results
*
* @param string the SQL query
* @param mixed array that contains the types of the columns in
* the result set
* @param mixed string which specifies which result class to use
* @param mixed string which specifies which class to wrap results in
*
* @return mixed an MDB2_Result handle on success, a MDB2 error on failure
*
* @access public
*/
function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
{
$offset = $this->offset;
$limit = $this->limit;
$this->offset = $this->limit = 0;
$query = $this->_modifyQuery($query, false, $limit, $offset);
$connection = $this->getConnection();
if (PEAR::isError($connection)) {
return $connection;
}
$result =$this->_doQuery($query, false, $connection, $this->database_name);
if (PEAR::isError($result)) {
return $result;
}
$result =$this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
return $result;
}
// }}}
// {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
/**
* wrap a result set into the correct class
*
* @param resource result handle
* @param mixed array that contains the types of the columns in
* the result set
* @param mixed string which specifies which result class to use
* @param mixed string which specifies which class to wrap results in
* @param string number of rows to select
* @param string first row to select
*
* @return mixed an MDB2_Result, a MDB2 error on failure
*
* @access protected
*/
function &_wrapResult($result, $types = array(), $result_class = true,
$result_wrap_class = false, $limit = null, $offset = null)
{
if ($types === true) {
if ($this->supports('result_introspection')) {
$this->loadModule('Reverse', null, true);
$tableInfo = $this->reverse->tableInfo($result);
if (PEAR::isError($tableInfo)) {
return $tableInfo;
}
$types = array();
foreach ($tableInfo as $field) {
$types[] = $field['mdb2type'];
}
} else {
$types = null;
}
}
if ($result_class === true) {
$result_class = $this->options['result_buffering']
? $this->options['buffered_result_class'] : $this->options['result_class'];
}
if ($result_class) {
$class_name = sprintf($result_class, $this->phptype);
if (!MDB2::classExists($class_name)) {
$err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'result class does not exist '.$class_name, __FUNCTION__);
return $err;
}
$result =new $class_name($this, $result, $limit, $offset);
if (!MDB2::isResultCommon($result)) {
$err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'result class is not extended from MDB2_Result_Common', __FUNCTION__);
return $err;
}
if (!empty($types)) {
$err = $result->setResultTypes($types);
if (PEAR::isError($err)) {
$result->free();
return $err;
}
}
}
if ($result_wrap_class === true) {
$result_wrap_class = $this->options['result_wrap_class'];
}
if ($result_wrap_class) {
if (!MDB2::classExists($result_wrap_class)) {
$err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
return $err;
}
$result = new $result_wrap_class($result, $this->fetchmode);
}
return $result;
}
// }}}
// {{{ function getServerVersion($native = false)
/**
* return version information about the server
*
* @param bool determines if the raw version string should be returned
*
* @return mixed array with version information or row string
*
* @access public
*/
function getServerVersion($native = false)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function setLimit($limit, $offset = null)
/**
* set the range of the next query
*
* @param string number of rows to select
* @param string first row to select
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function setLimit($limit, $offset = null)
{
if (!$this->supports('limit_queries')) {
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'limit is not supported by this driver', __FUNCTION__);
}
$limit = (int)$limit;
if ($limit < 0) {
return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
'it was not specified a valid selected range row limit', __FUNCTION__);
}
$this->limit = $limit;
if (!is_null($offset)) {
$offset = (int)$offset;
if ($offset < 0) {
return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
'it was not specified a valid first selected range row', __FUNCTION__);
}
$this->offset = $offset;
}
return MDB2_OK;
}
// }}}
// {{{ function subSelect($query, $type = false)
/**
* simple subselect emulation: leaves the query untouched for all RDBMS
* that support subselects
*
* @param string the SQL query for the subselect that may only
* return a column
* @param string determines type of the field
*
* @return string the query
*
* @access public
*/
function subSelect($query, $type = false)
{
if ($this->supports('sub_selects') === true) {
return $query;
}
if (!$this->supports('sub_selects')) {
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
$col = $this->queryCol($query, $type);
if (PEAR::isError($col)) {
return $col;
}
if (!is_array($col) || count($col) == 0) {
return 'NULL';
}
if ($type) {
$this->loadModule('Datatype', null, true);
return $this->datatype->implodeArray($col, $type);
}
return implode(', ', $col);
}
// }}}
// {{{ function replace($table, $fields)
/**
* Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
* query, except that if there is already a row in the table with the same
* key field values, the old row is deleted before the new row is inserted.
*
* The REPLACE type of query does not make part of the SQL standards. Since
* practically only MySQL and SQLite implement it natively, this type of
* query isemulated through this method for other DBMS using standard types
* of queries inside a transaction to assure the atomicity of the operation.
*
* @param string name of the table on which the REPLACE query will
* be executed.
* @param array associative array that describes the fields and the
* values that will be inserted or updated in the specified table. The
* indexes of the array are the names of all the fields of the table.
* The values of the array are also associative arrays that describe
* the values and other properties of the table fields.
*
* Here follows a list of field properties that need to be specified:
*
* value
* Value to be assigned to the specified field. This value may be
* of specified in database independent type format as this
* function can perform the necessary datatype conversions.
*
* Default: this property is required unless the Null property is
* set to 1.
*
* type
* Name of the type of the field. Currently, all types MDB2
* are supported except for clob and blob.
*
* Default: no type conversion
*
* null
* bool property that indicates that the value for this field
* should be set to null.
*
* The default value for fields missing in INSERT queries may be
* specified the definition of a table. Often, the default value
* is already null, but since the REPLACE may be emulated using
* an UPDATE query, make sure that all fields of the table are
* listed in this function argument array.
*
* Default: 0
*
* key
* bool property that indicates that this field should be
* handled as a primary key or at least as part of the compound
* unique index of the table that will determine the row that will
* updated if it exists or inserted a new row otherwise.
*
* This function will fail if no key field is specified or if the
* value of a key field is set to null because fields that are
* part of unique index they may not be null.
*
* Default: 0
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function replace($table, $fields)
{
if (!$this->supports('replace')) {
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'replace query is not supported', __FUNCTION__);
}
$count = count($fields);
$condition = $values = array();
for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
$name = key($fields);
if (isset($fields[$name]['null']) && $fields[$name]['null']) {
$value = 'NULL';
} else {
$type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
$value = $this->quote($fields[$name]['value'], $type);
}
$values[$name] = $value;
if (isset($fields[$name]['key']) && $fields[$name]['key']) {
if ($value === 'NULL') {
return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
'key value '.$name.' may not be NULL', __FUNCTION__);
}
$condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
}
}
if (empty($condition)) {
return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
'not specified which fields are keys', __FUNCTION__);
}
$result = null;
$in_transaction = $this->in_transaction;
if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
return $result;
}
$connection = $this->getConnection();
if (PEAR::isError($connection)) {
return $connection;
}
$condition = ' WHERE '.implode(' AND ', $condition);
$query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
$result =$this->_doQuery($query, true, $connection);
if (!PEAR::isError($result)) {
$affected_rows = $this->_affectedRows($connection, $result);
$insert = '';
foreach ($values as $key => $value) {
$insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
}
$values = implode(', ', $values);
$query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
$result =$this->_doQuery($query, true, $connection);
if (!PEAR::isError($result)) {
$affected_rows += $this->_affectedRows($connection, $result);;
}
}
if (!$in_transaction) {
if (PEAR::isError($result)) {
$this->rollback();
} else {
$result = $this->commit();
}
}
if (PEAR::isError($result)) {
return $result;
}
return $affected_rows;
}
// }}}
// {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
/**
* Prepares a query for multiple execution with execute().
* With some database backends, this is emulated.
* prepare() requires a generic query as string like
* 'INSERT INTO numbers VALUES(?,?)' or
* 'INSERT INTO numbers VALUES(:foo,:bar)'.
* The ? and :name and are placeholders which can be set using
* bindParam() and the query can be sent off using the execute() method.
* The allowed format for :name can be set with the 'bindname_format' option.
*
* @param string the query to prepare
* @param mixed array that contains the types of the placeholders
* @param mixed array that contains the types of the columns in
* the result set or MDB2_PREPARE_RESULT, if set to
* MDB2_PREPARE_MANIP the query is handled as a manipulation query
* @param mixed key (field) value (parameter) pair for all lob placeholders
*
* @return mixed resource handle for the prepared query on success,
* a MDB2 error on failure
*
* @access public
* @see bindParam, execute
*/
function &prepare($query, $types = null, $result_types = null, $lobs = array())
{
$is_manip = ($result_types === MDB2_PREPARE_MANIP);
$offset = $this->offset;
$limit = $this->limit;
$this->offset = $this->limit = 0;
$result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
if ($result) {
if (PEAR::isError($result)) {
return $result;
}
$query = $result;
}
$placeholder_type_guess = $placeholder_type = null;
$question = '?';
$colon = ':';
$positions = array();
$position = 0;
while ($position < strlen($query)) {
$q_position = strpos($query, $question, $position);
$c_position = strpos($query, $colon, $position);
if ($q_position && $c_position) {
$p_position = min($q_position, $c_position);
} elseif ($q_position) {
$p_position = $q_position;
} elseif ($c_position) {
$p_position = $c_position;
} else {
break;
}
if (is_null($placeholder_type)) {
$placeholder_type_guess = $query[$p_position];
}
$new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
if (PEAR::isError($new_pos)) {
return $new_pos;
}
if ($new_pos != $position) {
$position = $new_pos;
continue; //evaluate again starting from the new position
}
if ($query[$position] == $placeholder_type_guess) {
if (is_null($placeholder_type)) {
$placeholder_type = $query[$p_position];
$question = $colon = $placeholder_type;
if (!empty($types) && is_array($types)) {
if ($placeholder_type == ':') {
if (is_int(key($types))) {
$types_tmp = $types;
$types = array();
$count = -1;
}
} else {
$types = array_values($types);
}
}
}
if ($placeholder_type == ':') {
$regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
$parameter = preg_replace($regexp, '\\1', $query);
if ($parameter === '') {
$err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null,
'named parameter name must match "bindname_format" option', __FUNCTION__);
return $err;
}
$positions[$p_position] = $parameter;
$query = substr_replace($query, '?', $position, strlen($parameter)+1);
// use parameter name in type array
if (isset($count) && isset($types_tmp[++$count])) {
$types[$parameter] = $types_tmp[$count];
}
} else {
$positions[$p_position] = count($positions);
}
$position = $p_position + 1;
} else {
$position = $p_position;
}
}
$class_name = 'MDB2_Statement_'.$this->phptype;
$statement = null;
$obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
$this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
return $obj;
}
// }}}
// {{{ function _skipDelimitedStrings($query, $position, $p_position)
/**
* Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
* Check if the placeholder is contained within a delimited string.
* If so, skip it and advance the position, otherwise return the current position,
* which is valid
*
* @param string $query
* @param integer $position current string cursor position
* @param integer $p_position placeholder position
*
* @return mixed integer $new_position on success
* MDB2_Error on failure
*
* @access protected
*/
function _skipDelimitedStrings($query, $position, $p_position)
{
$ignores = $this->string_quoting;
$ignores[] = $this->identifier_quoting;
$ignores = array_merge($ignores, $this->sql_comments);
foreach ($ignores as $ignore) {
if (!empty($ignore['start'])) {
if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
$end_quote = $start_quote;
do {
if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
if ($ignore['end'] === "\n") {
$end_quote = strlen($query) - 1;
} else {
$err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null,
'query with an unterminated text string specified', __FUNCTION__);
return $err;
}
}
} while ($ignore['escape']
&& $end_quote-1 != $start_quote
&& $query[($end_quote - 1)] == $ignore['escape']
&& ( $ignore['escape_pattern'] !== $ignore['escape']
|| $query[($end_quote - 2)] != $ignore['escape'])
);
$position = $end_quote + 1;
return $position;
}
}
}
return $position;
}
// }}}
// {{{ function quote($value, $type = null, $quote = true)
/**
* Convert a text value into a DBMS specific format that is suitable to
* compose query statements.
*
* @param string text string value that is intended to be converted.
* @param string type to which the value should be converted to
* @param bool quote
* @param bool escape wildcards
*
* @return string text string that represents the given argument value in
* a DBMS specific format.
*
* @access public
*/
function quote($value, $type = null, $quote = true, $escape_wildcards = false)
{
$result = $this->loadModule('Datatype', null, true);
if (PEAR::isError($result)) {
return $result;
}
return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
}
// }}}
// {{{ function getDeclaration($type, $name, $field)
/**
* Obtain DBMS specific SQL code portion needed to declare
* of the given type
*
* @param string type to which the value should be converted to
* @param string name the field to be declared.
* @param string definition of the field
*
* @return string DBMS specific SQL code portion that should be used to
* declare the specified field.
*
* @access public
*/
function getDeclaration($type, $name, $field)
{
$result = $this->loadModule('Datatype', null, true);
if (PEAR::isError($result)) {
return $result;
}
return $this->datatype->getDeclaration($type, $name, $field);
}
// }}}
// {{{ function compareDefinition($current, $previous)
/**
* Obtain an array of changes that may need to applied
*
* @param array new definition
* @param array old definition
*
* @return array containing all changes that will need to be applied
*
* @access public
*/
function compareDefinition($current, $previous)
{
$result = $this->loadModule('Datatype', null, true);
if (PEAR::isError($result)) {
return $result;
}
return $this->datatype->compareDefinition($current, $previous);
}
// }}}
// {{{ function supports($feature)
/**
* Tell whether a DB implementation or its backend extension
* supports a given feature.
*
* @param string name of the feature (see the MDB2 class doc)
*
* @return bool|string if this DB implementation supports a given feature
* false means no, true means native,
* 'emulated' means emulated
*
* @access public
*/
function supports($feature)
{
if (array_key_exists($feature, $this->supported)) {
return $this->supported[$feature];
}
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
"unknown support feature $feature", __FUNCTION__);
}
// }}}
// {{{ function getSequenceName($sqn)
/**
* adds sequence name formatting to a sequence name
*
* @param string name of the sequence
*
* @return string formatted sequence name
*
* @access public
*/
function getSequenceName($sqn)
{
return sprintf($this->options['seqname_format'],
preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
}
// }}}
// {{{ function getIndexName($idx)
/**
* adds index name formatting to a index name
*
* @param string name of the index
*
* @return string formatted index name
*
* @access public
*/
function getIndexName($idx)
{
return sprintf($this->options['idxname_format'],
preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
}
// }}}
// {{{ function nextID($seq_name, $ondemand = true)
/**
* Returns the next free id of a sequence
*
* @param string name of the sequence
* @param bool when true missing sequences are automatic created
*
* @return mixed MDB2 Error Object or id
*
* @access public
*/
function nextID($seq_name, $ondemand = true)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function lastInsertID($table = null, $field = null)
/**
* Returns the autoincrement ID if supported or $id or fetches the current
* ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
*
* @param string name of the table into which a new row was inserted
* @param string name of the field into which a new row was inserted
*
* @return mixed MDB2 Error Object or id
*
* @access public
*/
function lastInsertID($table = null, $field = null)
{
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function currID($seq_name)
/**
* Returns the current id of a sequence
*
* @param string name of the sequence
*
* @return mixed MDB2 Error Object or id
*
* @access public
*/
function currID($seq_name)
{
$this->warnings[] = 'database does not support getting current
sequence value, the sequence value was incremented';
return $this->nextID($seq_name);
}
// }}}
// {{{ function queryOne($query, $type = null, $colnum = 0)
/**
* Execute the specified query, fetch the value from the first column of
* the first row of the result set and then frees
* the result set.
*
* @param string $query the SELECT query statement to be executed.
* @param string $type optional argument that specifies the expected
* datatype of the result set field, so that an eventual
* conversion may be performed. The default datatype is
* text, meaning that no conversion is performed
* @param mixed $colnum the column number (or name) to fetch
*
* @return mixed MDB2_OK or field value on success, a MDB2 error on failure
*
* @access public
*/
function queryOne($query, $type = null, $colnum = 0)
{
$result = $this->query($query, $type);
if (!MDB2::isResultCommon($result)) {
return $result;
}
$one = $result->fetchOne($colnum);
$result->free();
return $one;
}
// }}}
// {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
/**
* Execute the specified query, fetch the values from the first
* row of the result set into an array and then frees
* the result set.
*
* @param string the SELECT query statement to be executed.
* @param array optional array argument that specifies a list of
* expected datatypes of the result set columns, so that the eventual
* conversions may be performed. The default list of datatypes is
* empty, meaning that no conversion is performed.
* @param int how the array data should be indexed
*
* @return mixed MDB2_OK or data array on success, a MDB2 error on failure
*
* @access public
*/
function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
{
$result = $this->query($query, $types);
if (!MDB2::isResultCommon($result)) {
return $result;
}
$row = $result->fetchRow($fetchmode);
$result->free();
return $row;
}
// }}}
// {{{ function queryCol($query, $type = null, $colnum = 0)
/**
* Execute the specified query, fetch the value from the first column of
* each row of the result set into an array and then frees the result set.
*
* @param string $query the SELECT query statement to be executed.
* @param string $type optional argument that specifies the expected
* datatype of the result set field, so that an eventual
* conversion may be performed. The default datatype is text,
* meaning that no conversion is performed
* @param mixed $colnum the column number (or name) to fetch
*
* @return mixed MDB2_OK or data array on success, a MDB2 error on failure
* @access public
*/
function queryCol($query, $type = null, $colnum = 0)
{
$result = $this->query($query, $type);
if (!MDB2::isResultCommon($result)) {
return $result;
}
$col = $result->fetchCol($colnum);
$result->free();
return $col;
}
// }}}
// {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
/**
* Execute the specified query, fetch all the rows of the result set into
* a two dimensional array and then frees the result set.
*
* @param string the SELECT query statement to be executed.
* @param array optional array argument that specifies a list of
* expected datatypes of the result set columns, so that the eventual
* conversions may be performed. The default list of datatypes is
* empty, meaning that no conversion is performed.
* @param int how the array data should be indexed
* @param bool if set to true, the $all will have the first
* column as its first dimension
* @param bool used only when the query returns exactly
* two columns. If true, the values of the returned array will be
* one-element arrays instead of scalars.
* @param bool if true, the values of the returned array is
* wrapped in another array. If the same key value (in the first
* column) repeats itself, the values will be appended to this array
* instead of overwriting the existing values.
*
* @return mixed MDB2_OK or data array on success, a MDB2 error on failure
*
* @access public
*/
function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
$rekey = false, $force_array = false, $group = false)
{
$result = $this->query($query, $types);
if (!MDB2::isResultCommon($result)) {
return $result;
}
$all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
$result->free();
return $all;
}
// }}}
}
// }}}
// {{{ class MDB2_Result
/**
* The dummy class that all user space result classes should extend from
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Result
{
}
// }}}
// {{{ class MDB2_Result_Common extends MDB2_Result
/**
* The common result class for MDB2 result objects
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Result_Common extends MDB2_Result
{
// {{{ Variables (Properties)
var $db;
var $result;
var $rownum = -1;
var $types = array();
var $values = array();
var $offset;
var $offset_count = 0;
var $limit;
var $column_names;
// }}}
// {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0)
/**
* Constructor
*/
function __construct(&$db, &$result, $limit = 0, $offset = 0)
{
$this->db =$db;
$this->result =$result;
$this->offset = $offset;
$this->limit = max(0, $limit - 1);
}
// }}}
// {{{ function setResultTypes($types)
/**
* Define the list of types to be associated with the columns of a given
* result set.
*
* This function may be called before invoking fetchRow(), fetchOne(),
* fetchCol() and fetchAll() so that the necessary data type
* conversions are performed on the data to be retrieved by them. If this
* function is not called, the type of all result set columns is assumed
* to be text, thus leading to not perform any conversions.
*
* @param array variable that lists the
* data types to be expected in the result set columns. If this array
* contains less types than the number of columns that are returned
* in the result set, the remaining columns are assumed to be of the
* type text. Currently, the types clob and blob are not fully
* supported.
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function setResultTypes($types)
{
$load = $this->db->loadModule('Datatype', null, true);
if (PEAR::isError($load)) {
return $load;
}
$types = $this->db->datatype->checkResultTypes($types);
if (PEAR::isError($types)) {
return $types;
}
$this->types = $types;
return MDB2_OK;
}
// }}}
// {{{ function seek($rownum = 0)
/**
* Seek to a specific row in a result set
*
* @param int number of the row where the data can be found
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function seek($rownum = 0)
{
$target_rownum = $rownum - 1;
if ($this->rownum > $target_rownum) {
return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'seeking to previous rows not implemented', __FUNCTION__);
}
while ($this->rownum < $target_rownum) {
$this->fetchRow();
}
return MDB2_OK;
}
// }}}
// {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
/**
* Fetch and return a row of data
*
* @param int how the array data should be indexed
* @param int number of the row where the data can be found
*
* @return int data array on success, a MDB2 error on failure
*
* @access public
*/
function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
{
$err =$this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
return $err;
}
// }}}
// {{{ function fetchOne($colnum = 0)
/**
* fetch single column from the next row from a result set
*
* @param int|string the column number (or name) to fetch
* @param int number of the row where the data can be found
*
* @return string data on success, a MDB2 error on failure
* @access public
*/
function fetchOne($colnum = 0, $rownum = null)
{
$fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
$row = $this->fetchRow($fetchmode, $rownum);
if (!is_array($row) || PEAR::isError($row)) {
return $row;
}
if (!array_key_exists($colnum, $row)) {
return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
'column is not defined in the result set: '.$colnum, __FUNCTION__);
}
return $row[$colnum];
}
// }}}
// {{{ function fetchCol($colnum = 0)
/**
* Fetch and return a column from the current row pointer position
*
* @param int|string the column number (or name) to fetch
*
* @return mixed data array on success, a MDB2 error on failure
* @access public
*/
function fetchCol($colnum = 0)
{
$column = array();
$fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
$row = $this->fetchRow($fetchmode);
if (is_array($row)) {
if (!array_key_exists($colnum, $row)) {
return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
'column is not defined in the result set: '.$colnum, __FUNCTION__);
}
do {
$column[] = $row[$colnum];
} while (is_array($row = $this->fetchRow($fetchmode)));
}
if (PEAR::isError($row)) {
return $row;
}
return $column;
}
// }}}
// {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
/**
* Fetch and return all rows from the current row pointer position
*
* @param int $fetchmode the fetch mode to use:
* + MDB2_FETCHMODE_ORDERED
* + MDB2_FETCHMODE_ASSOC
* + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
* + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
* @param bool if set to true, the $all will have the first
* column as its first dimension
* @param bool used only when the query returns exactly
* two columns. If true, the values of the returned array will be
* one-element arrays instead of scalars.
* @param bool if true, the values of the returned array is
* wrapped in another array. If the same key value (in the first
* column) repeats itself, the values will be appended to this array
* instead of overwriting the existing values.
*
* @return mixed data array on success, a MDB2 error on failure
*
* @access public
* @see getAssoc()
*/
function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
$force_array = false, $group = false)
{
$all = array();
$row = $this->fetchRow($fetchmode);
if (PEAR::isError($row)) {
return $row;
} elseif (!$row) {
return $all;
}
$shift_array = $rekey ? false : null;
if (!is_null($shift_array)) {
if (is_object($row)) {
$colnum = count(get_object_vars($row));
} else {
$colnum = count($row);
}
if ($colnum < 2) {
return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
'rekey feature requires atleast 2 column', __FUNCTION__);
}
$shift_array = (!$force_array && $colnum == 2);
}
if ($rekey) {
do {
if (is_object($row)) {
$arr = get_object_vars($row);
$key = reset($arr);
unset($row->{$key});
} else {
if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
$key = reset($row);
unset($row[key($row)]);
} else {
$key = array_shift($row);
}
if ($shift_array) {
$row = array_shift($row);
}
}
if ($group) {
$all[$key][] = $row;
} else {
$all[$key] = $row;
}
} while (($row = $this->fetchRow($fetchmode)));
} elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
do {
foreach ($row as $key => $val) {
$all[$key][] = $val;
}
} while (($row = $this->fetchRow($fetchmode)));
} else {
do {
$all[] = $row;
} while (($row = $this->fetchRow($fetchmode)));
}
return $all;
}
// }}}
// {{{ function rowCount()
/**
* Returns the actual row number that was last fetched (count from 0)
* @return int
*
* @access public
*/
function rowCount()
{
return $this->rownum + 1;
}
// }}}
// {{{ function numRows()
/**
* Returns the number of rows in a result object
*
* @return mixed MDB2 Error Object or the number of rows
*
* @access public
*/
function numRows()
{
return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function nextResult()
/**
* Move the internal result pointer to the next available result
*
* @return true on success, false if there is no more result set or an error object on failure
*
* @access public
*/
function nextResult()
{
return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function getColumnNames()
/**
* Retrieve the names of columns returned by the DBMS in a query result or
* from the cache.
*
* @param bool If set to true the values are the column names,
* otherwise the names of the columns are the keys.
* @return mixed Array variable that holds the names of columns or an
* MDB2 error on failure.
* Some DBMS may not return any columns when the result set
* does not contain any rows.
*
* @access public
*/
function getColumnNames($flip = false)
{
if (!isset($this->column_names)) {
$result = $this->_getColumnNames();
if (PEAR::isError($result)) {
return $result;
}
$this->column_names = $result;
}
if ($flip) {
return array_flip($this->column_names);
}
return $this->column_names;
}
// }}}
// {{{ function _getColumnNames()
/**
* Retrieve the names of columns returned by the DBMS in a query result.
*
* @return mixed Array variable that holds the names of columns as keys
* or an MDB2 error on failure.
* Some DBMS may not return any columns when the result set
* does not contain any rows.
*
* @access private
*/
function _getColumnNames()
{
return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function numCols()
/**
* Count the number of columns returned by the DBMS in a query result.
*
* @return mixed integer value with the number of columns, a MDB2 error
* on failure
*
* @access public
*/
function numCols()
{
return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
'method not implemented', __FUNCTION__);
}
// }}}
// {{{ function getResource()
/**
* return the resource associated with the result object
*
* @return resource
*
* @access public
*/
function getResource()
{
return $this->result;
}
// }}}
// {{{ function bindColumn($column, &$value, $type = null)
/**
* Set bind variable to a column.
*
* @param int column number or name
* @param mixed variable reference
* @param string specifies the type of the field
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function bindColumn($column, &$value, $type = null)
{
if (!is_numeric($column)) {
$column_names = $this->getColumnNames();
if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
if ($this->db->options['field_case'] == CASE_LOWER) {
$column = strtolower($column);
} else {
$column = strtoupper($column);
}
}
$column = $column_names[$column];
}
$this->values[$column] =$value;
if (!is_null($type)) {
$this->types[$column] = $type;
}
return MDB2_OK;
}
// }}}
// {{{ function _assignBindColumns($row)
/**
* Bind a variable to a value in the result row.
*
* @param array row data
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access private
*/
function _assignBindColumns($row)
{
$row = array_values($row);
foreach ($row as $column => $value) {
if (array_key_exists($column, $this->values)) {
$this->values[$column] = $value;
}
}
return MDB2_OK;
}
// }}}
// {{{ function free()
/**
* Free the internal resources associated with result.
*
* @return bool true on success, false if result is invalid
*
* @access public
*/
function free()
{
$this->result = false;
return MDB2_OK;
}
// }}}
}
// }}}
// {{{ class MDB2_Row
/**
* The simple class that accepts row data as an array
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Row
{
// {{{ constructor: function __construct(&$row)
/**
* constructor
*
* @param resource row data as array
*/
function __construct(&$row)
{
foreach ($row as $key => $value) {
$this->$key = &$row[$key];
}
}
}
// }}}
// {{{ class MDB2_Statement_Common
/**
* The common statement class for MDB2 statement objects
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Statement_Common
{
// {{{ Variables (Properties)
var $db;
var $statement;
var $query;
var $result_types;
var $types;
var $values = array();
var $limit;
var $offset;
var $is_manip;
// }}}
// {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
/**
* Constructor
*/
function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
{
$this->db =$db;
$this->statement =$statement;
$this->positions = $positions;
$this->query = $query;
$this->types = (array)$types;
$this->result_types = (array)$result_types;
$this->limit = $limit;
$this->is_manip = $is_manip;
$this->offset = $offset;
}
// }}}
// {{{ function bindValue($parameter, &$value, $type = null)
/**
* Set the value of a parameter of a prepared query.
*
* @param int the order number of the parameter in the query
* statement. The order number of the first parameter is 1.
* @param mixed value that is meant to be assigned to specified
* parameter. The type of the value depends on the $type argument.
* @param string specifies the type of the field
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function bindValue($parameter, $value, $type = null)
{
if (!is_numeric($parameter)) {
$parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
}
if (!in_array($parameter, $this->positions)) {
return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
}
$this->values[$parameter] = $value;
if (!is_null($type)) {
$this->types[$parameter] = $type;
}
return MDB2_OK;
}
// }}}
// {{{ function bindValueArray($values, $types = null)
/**
* Set the values of multiple a parameter of a prepared query in bulk.
*
* @param array specifies all necessary information
* for bindValue() the array elements must use keys corresponding to
* the number of the position of the parameter.
* @param array specifies the types of the fields
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
* @see bindParam()
*/
function bindValueArray($values, $types = null)
{
$types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
$parameters = array_keys($values);
foreach ($parameters as $key => $parameter) {
$this->db->pushErrorHandling(PEAR_ERROR_RETURN);
$this->db->expectError(MDB2_ERROR_NOT_FOUND);
$err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
$this->db->popExpect();
$this->db->popErrorHandling();
if (PEAR::isError($err)) {
if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
//ignore (extra value for missing placeholder)
continue;
}
return $err;
}
}
return MDB2_OK;
}
// }}}
// {{{ function bindParam($parameter, &$value, $type = null)
/**
* Bind a variable to a parameter of a prepared query.
*
* @param int the order number of the parameter in the query
* statement. The order number of the first parameter is 1.
* @param mixed variable that is meant to be bound to specified
* parameter. The type of the value depends on the $type argument.
* @param string specifies the type of the field
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function bindParam($parameter, &$value, $type = null)
{
if (!is_numeric($parameter)) {
$parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
}
if (!in_array($parameter, $this->positions)) {
return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
}
$this->values[$parameter] =$value;
if (!is_null($type)) {
$this->types[$parameter] = $type;
}
return MDB2_OK;
}
// }}}
// {{{ function bindParamArray(&$values, $types = null)
/**
* Bind the variables of multiple a parameter of a prepared query in bulk.
*
* @param array specifies all necessary information
* for bindParam() the array elements must use keys corresponding to
* the number of the position of the parameter.
* @param array specifies the types of the fields
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
* @see bindParam()
*/
function bindParamArray(&$values, $types = null)
{
$types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
$parameters = array_keys($values);
foreach ($parameters as $key => $parameter) {
$err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
if (PEAR::isError($err)) {
return $err;
}
}
return MDB2_OK;
}
// }}}
// {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
/**
* Execute a prepared query statement.
*
* @param array specifies all necessary information
* for bindParam() the array elements must use keys corresponding
* to the number of the position of the parameter.
* @param mixed specifies which result class to use
* @param mixed specifies which class to wrap results in
*
* @return mixed MDB2_Result or integer (affected rows) on success,
* a MDB2 error on failure
* @access public
*/
function &execute($values = null, $result_class = true, $result_wrap_class = false)
{
if (is_null($this->positions)) {
return $this->db->raiseError(MDB2_ERROR, null, null,
'Prepared statement has already been freed', __FUNCTION__);
}
$values = (array)$values;
if (!empty($values)) {
$err = $this->bindValueArray($values);
if (PEAR::isError($err)) {
return $this->db->raiseError(MDB2_ERROR, null, null,
'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
}
}
$result =$this->_execute($result_class, $result_wrap_class);
return $result;
}
// }}}
// {{{ function &_execute($result_class = true, $result_wrap_class = false)
/**
* Execute a prepared query statement helper method.
*
* @param mixed specifies which result class to use
* @param mixed specifies which class to wrap results in
*
* @return mixed MDB2_Result or integer (affected rows) on success,
* a MDB2 error on failure
* @access private
*/
function &_execute($result_class = true, $result_wrap_class = false)
{
$this->last_query = $this->query;
$query = '';
$last_position = 0;
foreach ($this->positions as $current_position => $parameter) {
if (!array_key_exists($parameter, $this->values)) {
return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
}
$value = $this->values[$parameter];
$query.= substr($this->query, $last_position, $current_position - $last_position);
if (!isset($value)) {
$value_quoted = 'NULL';
} else {
$type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
$value_quoted = $this->db->quote($value, $type);
if (PEAR::isError($value_quoted)) {
return $value_quoted;
}
}
$query.= $value_quoted;
$last_position = $current_position + 1;
}
$query.= substr($this->query, $last_position);
$this->db->offset = $this->offset;
$this->db->limit = $this->limit;
if ($this->is_manip) {
$result = $this->db->exec($query);
} else {
$result =$this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
}
return $result;
}
// }}}
// {{{ function free()
/**
* Release resources allocated for the specified prepared query.
*
* @return mixed MDB2_OK on success, a MDB2 error on failure
*
* @access public
*/
function free()
{
if (is_null($this->positions)) {
return $this->db->raiseError(MDB2_ERROR, null, null,
'Prepared statement has already been freed', __FUNCTION__);
}
$this->statement = null;
$this->positions = null;
$this->query = null;
$this->types = null;
$this->result_types = null;
$this->limit = null;
$this->is_manip = null;
$this->offset = null;
$this->values = null;
return MDB2_OK;
}
// }}}
}
// }}}
// {{{ class MDB2_Module_Common
/**
* The common modules class for MDB2 module objects
*
* @package MDB2
* @category Database
* @author Lukas Smith <smith@pooteeweet.org>
*/
class MDB2_Module_Common
{
// {{{ Variables (Properties)
/**
* contains the key to the global MDB2 instance array of the associated
* MDB2 instance
*
* @var int
* @access protected
*/
var $db_index;
// }}}
// {{{ constructor: function __construct($db_index)
/**
* Constructor
*/
function __construct($db_index)
{
$this->db_index = $db_index;
}
// }}}
// {{{ function &getDBInstance()
/**
* Get the instance of MDB2 associated with the module instance
*
* @return object MDB2 instance or a MDB2 error on failure
*
* @access public
*/
function getDBInstance()
{
if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
$result =$GLOBALS['_MDB2_databases'][$this->db_index];
} else {
$result =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
'could not find MDB2 instance');
}
return $result;
}
// }}}
}
// }}}
// {{{ function MDB2_closeOpenTransactions()
/**
* Close any open transactions form persistent connections
*
* @return void
*
* @access public
*/
function MDB2_closeOpenTransactions()
{
reset($GLOBALS['_MDB2_databases']);
while (next($GLOBALS['_MDB2_databases'])) {
$key = key($GLOBALS['_MDB2_databases']);
if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
&& $GLOBALS['_MDB2_databases'][$key]->in_transaction
) {
$GLOBALS['_MDB2_databases'][$key]->rollback();
}
}
}
// }}}
// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
/**
* default debug output handler
*
* @param object reference to an MDB2 database object
* @param string usually the method name that triggered the debug call:
* for example 'query', 'prepare', 'execute', 'parameters',
* 'beginTransaction', 'commit', 'rollback'
* @param string message that should be appended to the debug variable
* @param array contains context information about the debug() call
* common keys are: is_manip, time, result etc.
*
* @return void|string optionally return a modified message, this allows
* rewriting a query before being issued or prepared
*
* @access public
*/
function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
{
$db->debug_output.= $scope.'('.$db->db_index.'): ';
$db->debug_output.= $message.$db->getOption('log_line_break');
return $message;
}
// }}}
?>
|