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
|
<?php
/**
*
* @package install
* @copyright (c) 2006 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
$updates_to_version = '3.1.0-dev';
// Enter any version to update from to test updates. The version within the db will not be updated.
$debug_from_version = false;
// Which oldest version does this updater support?
$oldest_from_version = '3.0.0';
// Return if we "just include it" to find out for which version the database update is responsible for
if (defined('IN_PHPBB') && defined('IN_INSTALL'))
{
return;
}
/**
*/
define('IN_PHPBB', true);
define('IN_INSTALL', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
// Report all errors, except notices and deprecation messages
if (!defined('E_DEPRECATED'))
{
define('E_DEPRECATED', 8192);
}
//error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
error_reporting(E_ALL);
@set_time_limit(0);
// Include essential scripts
include($phpbb_root_path . 'config.' . $phpEx);
if (!defined('PHPBB_INSTALLED') || empty($dbms) || empty($acm_type))
{
die("Please read: <a href='../docs/INSTALL.html'>INSTALL.html</a> before attempting to update.");
}
// Load Extensions
if (!empty($load_extensions) && function_exists('dl'))
{
$load_extensions = explode(',', $load_extensions);
foreach ($load_extensions as $extension)
{
@dl(trim($extension));
}
}
// Include files
require($phpbb_root_path . 'includes/class_loader.' . $phpEx);
require($phpbb_root_path . 'includes/template.' . $phpEx);
require($phpbb_root_path . 'includes/session.' . $phpEx);
require($phpbb_root_path . 'includes/auth.' . $phpEx);
require($phpbb_root_path . 'includes/functions.' . $phpEx);
if (file_exists($phpbb_root_path . 'includes/functions_content.' . $phpEx))
{
require($phpbb_root_path . 'includes/functions_content.' . $phpEx);
}
require($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
require($phpbb_root_path . 'includes/constants.' . $phpEx);
require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
require($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);
// If we are on PHP >= 6.0.0 we do not need some code
if (version_compare(PHP_VERSION, '6.0.0-dev', '>='))
{
/**
* @ignore
*/
define('STRIP', false);
}
else
{
@set_magic_quotes_runtime(0);
define('STRIP', (get_magic_quotes_gpc()) ? true : false);
}
$class_loader = new phpbb_class_loader($phpbb_root_path, '.' . $phpEx);
$class_loader->register();
// set up caching
$cache_factory = new phpbb_cache_factory($acm_type);
$cache = $cache_factory->get_service();
$class_loader->set_cache($cache->get_driver());
$request = new phpbb_request();
$user = new user();
$db = new $sql_db();
// make sure request_var uses this request instance
request_var('', 0, false, false, $request); // "dependency injection" for a function
// Add own hook handler, if present. :o
if (file_exists($phpbb_root_path . 'includes/hooks/index.' . $phpEx))
{
require($phpbb_root_path . 'includes/hooks/index.' . $phpEx);
$phpbb_hook = new phpbb_hook(array('exit_handler', 'phpbb_user_session_handler', 'append_sid', array('template', 'display')));
foreach ($cache->obtain_hooks() as $hook)
{
@include($phpbb_root_path . 'includes/hooks/' . $hook . '.' . $phpEx);
}
}
else
{
$phpbb_hook = false;
}
// Connect to DB
$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false);
// We do not need this any longer, unset for safety purposes
unset($dbpasswd);
$user->ip = '';
if (!empty($_SERVER['REMOTE_ADDR']))
{
$user->ip = (function_exists('phpbb_ip_normalise')) ? phpbb_ip_normalise($_SERVER['REMOTE_ADDR']) : htmlspecialchars($_SERVER['REMOTE_ADDR']);
}
$sql = "SELECT config_value
FROM " . CONFIG_TABLE . "
WHERE config_name = 'default_lang'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$language = basename(request_var('language', ''));
if (!$language)
{
$language = $row['config_value'];
}
if (!file_exists($phpbb_root_path . 'language/' . $language))
{
die('No language found!');
}
// And finally, load the relevant language files
include($phpbb_root_path . 'language/' . $language . '/common.' . $phpEx);
include($phpbb_root_path . 'language/' . $language . '/acp/common.' . $phpEx);
include($phpbb_root_path . 'language/' . $language . '/install.' . $phpEx);
// Set PHP error handler to ours
//set_error_handler('msg_handler');
// Define some variables for the database update
$inline_update = (request_var('type', 0)) ? true : false;
// To let set_config() calls succeed, we need to make the config array available globally
$config = new phpbb_config_db($db, $cache->get_driver(), CONFIG_TABLE);
set_config(null, null, null, $config);
set_config_count(null, null, null, $config);
// We do not include DB Tools here, because we can not be sure the file is up-to-date ;)
// Instead, this file defines a clean db_tools version (we are also not able to provide a different file, else the database update will not work standalone)
$db_tools = new updater_db_tools($db, true);
$database_update_info = database_update_info();
$error_ary = array();
$errored = false;
header('Content-type: text/html; charset=UTF-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="<?php echo $lang['DIRECTION']; ?>" lang="<?php echo $lang['USER_LANG']; ?>" xml:lang="<?php echo $lang['USER_LANG']; ?>">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="content-language" content="<?php echo $lang['USER_LANG']; ?>" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="imagetoolbar" content="no" />
<title><?php echo $lang['UPDATING_TO_LATEST_STABLE']; ?></title>
<link href="../adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrap">
<div id="page-header"> </div>
<div id="page-body">
<div id="acp">
<div class="panel">
<span class="corners-top"><span></span></span>
<div id="content">
<div id="main" class="install-body">
<h1><?php echo $lang['UPDATING_TO_LATEST_STABLE']; ?></h1>
<br />
<p><?php echo $lang['DATABASE_TYPE']; ?> :: <strong><?php echo $db->sql_layer; ?></strong><br />
<?php
if ($debug_from_version !== false)
{
$config['version'] = $debug_from_version;
}
echo $lang['PREVIOUS_VERSION'] . ' :: <strong>' . $config['version'] . '</strong><br />';
echo $lang['UPDATED_VERSION'] . ' :: <strong>' . $updates_to_version . '</strong></p>';
$current_version = str_replace('rc', 'RC', strtolower($config['version']));
$latest_version = str_replace('rc', 'RC', strtolower($updates_to_version));
$orig_version = $config['version'];
// Fill DB version
if (empty($config['dbms_version']))
{
set_config('dbms_version', $db->sql_server_info(true));
}
// Firebird update from Firebord 2.0 to 2.1+ required?
if ($db->sql_layer == 'firebird')
{
// We do not trust any PHP5 function enabled, we will simply test for a function new in 2.1
$db->sql_return_on_error(true);
$sql = 'SELECT 1 FROM RDB$DATABASE
WHERE BIN_AND(10, 1) = 0';
$result = $db->sql_query($sql);
if (!$result || $db->sql_error_triggered)
{
echo '<br /><br />';
echo '<h1>' . $lang['ERROR'] . '</h1><br />';
echo '<p>' . $lang['FIREBIRD_DBMS_UPDATE_REQUIRED'] . '</p>';
_print_footer();
exit_handler();
exit;
}
$db->sql_freeresult($result);
$db->sql_return_on_error(false);
}
// MySQL update from MySQL 3.x/4.x to > 4.1.x required?
if ($db->sql_layer == 'mysql' || $db->sql_layer == 'mysql4' || $db->sql_layer == 'mysqli')
{
// Verify by fetching column... if the column type matches the new type we update dbms_version...
$sql = "SHOW COLUMNS FROM " . CONFIG_TABLE;
$result = $db->sql_query($sql);
$column_type = '';
while ($row = $db->sql_fetchrow($result))
{
$field = strtolower($row['Field']);
if ($field == 'config_value')
{
$column_type = strtolower($row['Type']);
break;
}
}
$db->sql_freeresult($result);
// If column type is blob, but mysql version says we are on > 4.1.3, then the schema needs an update
if (strpos($column_type, 'blob') !== false && version_compare($db->sql_server_info(true), '4.1.3', '>='))
{
echo '<br /><br />';
echo '<h1>' . $lang['ERROR'] . '</h1><br />';
echo '<p>' . sprintf($lang['MYSQL_SCHEMA_UPDATE_REQUIRED'], $config['dbms_version'], $db->sql_server_info(true)) . '</p>';
_print_footer();
exit_handler();
exit;
}
}
// Now check if the user wants to update from a version we no longer support updates from
if (version_compare($current_version, $oldest_from_version, '<'))
{
echo '<br /><br /><h1>' . $lang['ERROR'] . '</h1><br />';
echo '<p>' . sprintf($lang['DB_UPDATE_NOT_SUPPORTED'], $oldest_from_version, $current_version) . '</p>';
_print_footer();
exit_handler();
exit;
}
// If the latest version and the current version are 'unequal', we will update the version_update_from, else we do not update anything.
if ($inline_update)
{
if ($current_version !== $latest_version)
{
set_config('version_update_from', $orig_version);
}
}
else
{
// If not called from the update script, we will actually remove the traces
$db->sql_query('DELETE FROM ' . CONFIG_TABLE . " WHERE config_name = 'version_update_from'");
}
// Schema updates
?>
<br /><br />
<h1><?php echo $lang['UPDATE_DATABASE_SCHEMA']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>
<?php
flush();
// We go through the schema changes from the lowest to the highest version
// We try to also include versions 'in-between'...
$no_updates = true;
$versions = array_keys($database_update_info);
for ($i = 0; $i < sizeof($versions); $i++)
{
$version = $versions[$i];
$schema_changes = $database_update_info[$version];
$next_version = (isset($versions[$i + 1])) ? $versions[$i + 1] : $updates_to_version;
// If the installed version to be updated to is < than the current version, and if the current version is >= as the version to be updated to next, we will skip the process
if (version_compare($version, $current_version, '<') && version_compare($current_version, $next_version, '>='))
{
continue;
}
if (!sizeof($schema_changes))
{
continue;
}
$no_updates = false;
// We run one index after the other... to be consistent with schema changes...
foreach ($schema_changes as $key => $changes)
{
$statements = $db_tools->perform_schema_changes(array($key => $changes));
foreach ($statements as $sql)
{
_sql($sql, $errored, $error_ary);
}
}
}
_write_result($no_updates, $errored, $error_ary);
// Data updates
$error_ary = array();
$errored = $no_updates = false;
?>
<br /><br />
<h1><?php echo $lang['UPDATING_DATA']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>
<?php
flush();
$no_updates = true;
$versions = array_keys($database_update_info);
// some code magic
for ($i = 0; $i < sizeof($versions); $i++)
{
$version = $versions[$i];
$next_version = (isset($versions[$i + 1])) ? $versions[$i + 1] : $updates_to_version;
// If the installed version to be updated to is < than the current version, and if the current version is >= as the version to be updated to next, we will skip the process
if (version_compare($version, $current_version, '<') && version_compare($current_version, $next_version, '>='))
{
continue;
}
change_database_data($no_updates, $version);
}
_write_result($no_updates, $errored, $error_ary);
$error_ary = array();
$errored = $no_updates = false;
?>
<br /><br />
<h1><?php echo $lang['UPDATE_VERSION_OPTIMIZE']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>
<?php
flush();
if ($debug_from_version === false)
{
// update the version
$sql = "UPDATE " . CONFIG_TABLE . "
SET config_value = '$updates_to_version'
WHERE config_name = 'version'";
_sql($sql, $errored, $error_ary);
}
// Reset permissions
$sql = 'UPDATE ' . USERS_TABLE . "
SET user_permissions = '',
user_perm_from = 0";
_sql($sql, $errored, $error_ary);
// Update the dbms version if everything is ok...
set_config('dbms_version', $db->sql_server_info(true));
/* Optimize/vacuum analyze the tables where appropriate
// this should be done for each version in future along with
// the version number update
switch ($db->sql_layer)
{
case 'mysql':
case 'mysqli':
case 'mysql4':
$sql = 'OPTIMIZE TABLE ' . $table_prefix . 'auth_access, ' . $table_prefix . 'banlist, ' . $table_prefix . 'categories, ' . $table_prefix . 'config, ' . $table_prefix . 'disallow, ' . $table_prefix . 'forum_prune, ' . $table_prefix . 'forums, ' . $table_prefix . 'groups, ' . $table_prefix . 'posts, ' . $table_prefix . 'posts_text, ' . $table_prefix . 'privmsgs, ' . $table_prefix . 'privmsgs_text, ' . $table_prefix . 'ranks, ' . $table_prefix . 'search_results, ' . $table_prefix . 'search_wordlist, ' . $table_prefix . 'search_wordmatch, ' . $table_prefix . 'sessions_keys' . $table_prefix . 'smilies, ' . $table_prefix . 'themes, ' . $table_prefix . 'themes_name, ' . $table_prefix . 'topics, ' . $table_prefix . 'topics_watch, ' . $table_prefix . 'user_group, ' . $table_prefix . 'users, ' . $table_prefix . 'vote_desc, ' . $table_prefix . 'vote_results, ' . $table_prefix . 'vote_voters, ' . $table_prefix . 'words';
_sql($sql, $errored, $error_ary);
break;
case 'postgresql':
_sql("VACUUM ANALYZE", $errored, $error_ary);
break;
}
*/
_write_result($no_updates, $errored, $error_ary);
?>
<br />
<h1><?php echo $lang['UPDATE_COMPLETED']; ?></h1>
<br />
<?php
if (!$inline_update)
{
?>
<p style="color:red"><?php echo $lang['UPDATE_FILES_NOTICE']; ?></p>
<p><?php echo $lang['COMPLETE_LOGIN_TO_BOARD']; ?></p>
<?php
}
else
{
?>
<p><?php echo ((isset($lang['INLINE_UPDATE_SUCCESSFUL'])) ? $lang['INLINE_UPDATE_SUCCESSFUL'] : 'The database update was successful. Now you need to continue the update process.'); ?></p>
<p><a href="<?php echo append_sid("{$phpbb_root_path}install/index.{$phpEx}", "mode=update&sub=file_check&language=$language"); ?>" class="button1"><?php echo (isset($lang['CONTINUE_UPDATE_NOW'])) ? $lang['CONTINUE_UPDATE_NOW'] : 'Continue the update process now'; ?></a></p>
<?php
}
// Add database update to log
add_log('admin', 'LOG_UPDATE_DATABASE', $orig_version, $updates_to_version);
// Now we purge the session table as well as all cache files
$cache->purge();
_print_footer();
garbage_collection();
if (function_exists('exit_handler'))
{
exit_handler();
}
/**
* Print out footer
*/
function _print_footer()
{
echo <<<EOF
</div>
</div>
<span class="corners-bottom"><span></span></span>
</div>
</div>
</div>
<div id="page-footer">
Powered by <a href="http://www.phpbb.com/">phpBB</a> © phpBB Group
</div>
</div>
</body>
</html>
EOF;
}
/**
* Function for triggering an sql statement
*/
function _sql($sql, &$errored, &$error_ary, $echo_dot = true)
{
global $db;
if (defined('DEBUG_EXTRA'))
{
echo "<br />\n{$sql}\n<br />";
}
$db->sql_return_on_error(true);
$result = $db->sql_query($sql);
if ($db->sql_error_triggered)
{
$errored = true;
$error_ary['sql'][] = $db->sql_error_sql;
$error_ary['error_code'][] = $db->sql_error_returned;
}
$db->sql_return_on_error(false);
if ($echo_dot)
{
echo ". \n";
flush();
}
return $result;
}
function _write_result($no_updates, $errored, $error_ary)
{
global $lang;
if ($no_updates)
{
echo ' ' . $lang['NO_UPDATES_REQUIRED'] . '</strong></p>';
}
else
{
echo ' <span class="success">' . $lang['DONE'] . '</span></strong><br />' . $lang['RESULT'] . ' :: ';
if ($errored)
{
echo ' <strong>' . $lang['SOME_QUERIES_FAILED'] . '</strong> <ul>';
for ($i = 0; $i < sizeof($error_ary['sql']); $i++)
{
echo '<li>' . $lang['ERROR'] . ' :: <strong>' . htmlspecialchars($error_ary['error_code'][$i]['message']) . '</strong><br />';
echo $lang['SQL'] . ' :: <strong>' . htmlspecialchars($error_ary['sql'][$i]) . '</strong><br /><br /></li>';
}
echo '</ul> <br /><br />' . $lang['SQL_FAILURE_EXPLAIN'] . '</p>';
}
else
{
echo '<strong>' . $lang['NO_ERRORS'] . '</strong></p>';
}
}
}
function _add_modules($modules_to_install)
{
global $phpbb_root_path, $phpEx, $db;
include_once($phpbb_root_path . 'includes/acp/acp_modules.' . $phpEx);
$_module = new acp_modules();
foreach ($modules_to_install as $module_mode => $module_data)
{
$_module->module_class = $module_data['class'];
// Determine parent id first
$sql = 'SELECT module_id
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($module_data['class']) . "'
AND module_langname = '" . $db->sql_escape($module_data['cat']) . "'
AND module_mode = ''
AND module_basename = ''";
$result = $db->sql_query($sql);
// There may be more than one categories with the same name
$categories = array();
while ($row = $db->sql_fetchrow($result))
{
$categories[] = (int) $row['module_id'];
}
$db->sql_freeresult($result);
if (!sizeof($categories))
{
continue;
}
// Add the module to all categories found
foreach ($categories as $parent_id)
{
// Check if the module already exists
$sql = 'SELECT *
FROM ' . MODULES_TABLE . "
WHERE module_basename = '" . $db->sql_escape($module_data['base']) . "'
AND module_class = '" . $db->sql_escape($module_data['class']) . "'
AND module_langname = '" . $db->sql_escape($module_data['title']) . "'
AND module_mode = '" . $db->sql_escape($module_mode) . "'
AND module_auth = '" . $db->sql_escape($module_data['auth']) . "'
AND parent_id = {$parent_id}";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
// If it exists, we simply continue with the next category
if ($row)
{
continue;
}
// Build the module sql row
$module_row = array(
'module_basename' => $module_data['base'],
'module_enabled' => (isset($module_data['enabled'])) ? (int) $module_data['enabled'] : 1,
'module_display' => (isset($module_data['display'])) ? (int) $module_data['display'] : 1,
'parent_id' => $parent_id,
'module_class' => $module_data['class'],
'module_langname' => $module_data['title'],
'module_mode' => $module_mode,
'module_auth' => $module_data['auth'],
);
$_module->update_module_data($module_row, true);
// Ok, do we need to re-order the module, move it up or down?
if (!isset($module_data['after']))
{
continue;
}
$after_mode = $module_data['after'][0];
$after_langname = $module_data['after'][1];
// First of all, get the module id for the module this one has to be placed after
$sql = 'SELECT left_id
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($module_data['class']) . "'
AND module_basename = '" . $db->sql_escape($module_data['base']) . "'
AND module_langname = '" . $db->sql_escape($after_langname) . "'
AND module_mode = '" . $db->sql_escape($after_mode) . "'
AND parent_id = '{$parent_id}'";
$result = $db->sql_query($sql);
$first_left_id = (int) $db->sql_fetchfield('left_id');
$db->sql_freeresult($result);
if (!$first_left_id)
{
continue;
}
// Ok, count the number of modules between $after_mode and the added module
$sql = 'SELECT COUNT(module_id) as num_modules
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($module_data['class']) . "'
AND parent_id = {$parent_id}
AND left_id BETWEEN {$first_left_id} AND {$module_row['left_id']}";
$result = $db->sql_query($sql);
$steps = (int) $db->sql_fetchfield('num_modules');
$db->sql_freeresult($result);
// We need to substract 2
$steps -= 2;
if ($steps <= 0)
{
continue;
}
// Ok, move module up $num_modules times. ;)
$_module->move_module_by($module_row, 'move_up', $steps);
}
}
$_module->remove_cache_file();
}
/****************************************************************************
* ADD YOUR DATABASE SCHEMA CHANGES HERE *
*****************************************************************************/
function database_update_info()
{
return array(
// Changes from 3.0.0 to the next version
'3.0.0' => array(
// Add the following columns
'add_columns' => array(
FORUMS_TABLE => array(
'display_subforum_list' => array('BOOL', 1),
),
SESSIONS_TABLE => array(
'session_forum_id' => array('UINT', 0),
),
),
'drop_keys' => array(
GROUPS_TABLE => array('group_legend'),
),
'add_index' => array(
SESSIONS_TABLE => array(
'session_forum_id' => array('session_forum_id'),
),
GROUPS_TABLE => array(
'group_legend_name' => array('group_legend', 'group_name'),
),
),
),
// No changes from 3.0.1-RC1 to 3.0.1
'3.0.1-RC1' => array(),
// No changes from 3.0.1 to 3.0.2-RC1
'3.0.1' => array(),
// Changes from 3.0.2-RC1 to 3.0.2-RC2
'3.0.2-RC1' => array(
'change_columns' => array(
DRAFTS_TABLE => array(
'draft_subject' => array('STEXT_UNI', ''),
),
FORUMS_TABLE => array(
'forum_last_post_subject' => array('STEXT_UNI', ''),
),
POSTS_TABLE => array(
'post_subject' => array('STEXT_UNI', '', 'true_sort'),
),
PRIVMSGS_TABLE => array(
'message_subject' => array('STEXT_UNI', ''),
),
TOPICS_TABLE => array(
'topic_title' => array('STEXT_UNI', '', 'true_sort'),
'topic_last_post_subject' => array('STEXT_UNI', ''),
),
),
'drop_keys' => array(
SESSIONS_TABLE => array('session_forum_id'),
),
'add_index' => array(
SESSIONS_TABLE => array(
'session_fid' => array('session_forum_id'),
),
),
),
// No changes from 3.0.2-RC2 to 3.0.2
'3.0.2-RC2' => array(),
// Changes from 3.0.2 to 3.0.3-RC1
'3.0.2' => array(
// Add the following columns
'add_columns' => array(
STYLES_TEMPLATE_TABLE => array(
'template_inherits_id' => array('UINT:4', 0),
'template_inherit_path' => array('VCHAR', ''),
),
GROUPS_TABLE => array(
'group_max_recipients' => array('UINT', 0),
),
),
),
// No changes from 3.0.3-RC1 to 3.0.3
'3.0.3-RC1' => array(),
// Changes from 3.0.3 to 3.0.4-RC1
'3.0.3' => array(
'add_columns' => array(
PROFILE_FIELDS_TABLE => array(
'field_show_profile' => array('BOOL', 0),
),
),
'change_columns' => array(
STYLES_TABLE => array(
'style_id' => array('UINT', NULL, 'auto_increment'),
'template_id' => array('UINT', 0),
'theme_id' => array('UINT', 0),
'imageset_id' => array('UINT', 0),
),
STYLES_IMAGESET_TABLE => array(
'imageset_id' => array('UINT', NULL, 'auto_increment'),
),
STYLES_IMAGESET_DATA_TABLE => array(
'image_id' => array('UINT', NULL, 'auto_increment'),
'imageset_id' => array('UINT', 0),
),
STYLES_THEME_TABLE => array(
'theme_id' => array('UINT', NULL, 'auto_increment'),
),
STYLES_TEMPLATE_TABLE => array(
'template_id' => array('UINT', NULL, 'auto_increment'),
),
STYLES_TEMPLATE_DATA_TABLE => array(
'template_id' => array('UINT', 0),
),
FORUMS_TABLE => array(
'forum_style' => array('UINT', 0),
),
USERS_TABLE => array(
'user_style' => array('UINT', 0),
),
),
),
// Changes from 3.0.4-RC1 to 3.0.4
'3.0.4-RC1' => array(),
// Changes from 3.0.4 to 3.0.5-RC1
'3.0.4' => array(
'change_columns' => array(
FORUMS_TABLE => array(
'forum_style' => array('UINT', 0),
),
),
),
// No changes from 3.0.5-RC1 to 3.0.5
'3.0.5-RC1' => array(),
// Changes from 3.0.5 to 3.0.6-RC1
'3.0.5' => array(
'add_columns' => array(
CONFIRM_TABLE => array(
'attempts' => array('UINT', 0),
),
USERS_TABLE => array(
'user_new' => array('BOOL', 1),
'user_reminded' => array('TINT:4', 0),
'user_reminded_time'=> array('TIMESTAMP', 0),
),
GROUPS_TABLE => array(
'group_skip_auth' => array('BOOL', 0, 'after' => 'group_founder_manage'),
),
PRIVMSGS_TABLE => array(
'message_reported' => array('BOOL', 0),
),
REPORTS_TABLE => array(
'pm_id' => array('UINT', 0),
),
PROFILE_FIELDS_TABLE => array(
'field_show_on_vt' => array('BOOL', 0),
),
FORUMS_TABLE => array(
'forum_options' => array('UINT:20', 0),
),
),
'change_columns' => array(
USERS_TABLE => array(
'user_options' => array('UINT:11', 230271),
),
),
'add_index' => array(
REPORTS_TABLE => array(
'post_id' => array('post_id'),
'pm_id' => array('pm_id'),
),
POSTS_TABLE => array(
'post_username' => array('post_username:255'),
),
),
),
// No changes from 3.0.6-RC1 to 3.0.6-RC2
'3.0.6-RC1' => array(),
// No changes from 3.0.6-RC2 to 3.0.6-RC3
'3.0.6-RC2' => array(),
// No changes from 3.0.6-RC3 to 3.0.6-RC4
'3.0.6-RC3' => array(),
// No changes from 3.0.6-RC4 to 3.0.6
'3.0.6-RC4' => array(),
// Changes from 3.0.6 to 3.0.7-RC1
'3.0.6' => array(
'drop_keys' => array(
LOG_TABLE => array('log_time'),
),
'add_index' => array(
TOPICS_TRACK_TABLE => array(
'topic_id' => array('topic_id'),
),
),
),
// No changes from 3.0.7-RC1 to 3.0.7-RC2
'3.0.7-RC1' => array(),
// No changes from 3.0.7-RC2 to 3.0.7
'3.0.7-RC2' => array(),
// No changes from 3.0.7 to 3.0.7-PL1
'3.0.7' => array(),
// No changes from 3.0.7-PL1 to 3.0.8-RC1
'3.0.7-PL1' => array(),
// No changes from 3.0.8-RC1 to 3.0.8
'3.0.8-RC1' => array(),
// No changes from 3.1.0-dev to 3.1.0-A1
'3.1.0-dev' => array(),
);
}
/****************************************************************************
* ADD YOUR DATABASE DATA CHANGES HERE *
* REMEMBER: You NEED to enter a schema array above and a data array here, *
* even if both or one of them are empty. *
*****************************************************************************/
function change_database_data(&$no_updates, $version)
{
global $db, $errored, $error_ary, $config, $phpbb_root_path, $phpEx;
switch ($version)
{
case '3.0.0':
$sql = 'UPDATE ' . TOPICS_TABLE . "
SET topic_last_view_time = topic_last_post_time
WHERE topic_last_view_time = 0";
_sql($sql, $errored, $error_ary);
// Update smiley sizes
$smileys = array('icon_e_surprised.gif', 'icon_eek.gif', 'icon_cool.gif', 'icon_lol.gif', 'icon_mad.gif', 'icon_razz.gif', 'icon_redface.gif', 'icon_cry.gif', 'icon_evil.gif', 'icon_twisted.gif', 'icon_rolleyes.gif', 'icon_exclaim.gif', 'icon_question.gif', 'icon_idea.gif', 'icon_arrow.gif', 'icon_neutral.gif', 'icon_mrgreen.gif', 'icon_e_ugeek.gif');
foreach ($smileys as $smiley)
{
if (file_exists($phpbb_root_path . 'images/smilies/' . $smiley))
{
list($width, $height) = getimagesize($phpbb_root_path . 'images/smilies/' . $smiley);
$sql = 'UPDATE ' . SMILIES_TABLE . '
SET smiley_width = ' . $width . ', smiley_height = ' . $height . "
WHERE smiley_url = '" . $db->sql_escape($smiley) . "'";
_sql($sql, $errored, $error_ary);
}
}
$no_updates = false;
break;
// No changes from 3.0.1-RC1 to 3.0.1
case '3.0.1-RC1':
break;
// changes from 3.0.1 to 3.0.2-RC1
case '3.0.1':
set_config('referer_validation', '1');
set_config('check_attachment_content', '1');
set_config('mime_triggers', 'body|head|html|img|plaintext|a href|pre|script|table|title');
$no_updates = false;
break;
// No changes from 3.0.2-RC1 to 3.0.2-RC2
case '3.0.2-RC1':
break;
// No changes from 3.0.2-RC2 to 3.0.2
case '3.0.2-RC2':
break;
// Changes from 3.0.2 to 3.0.3-RC1
case '3.0.2':
set_config('enable_queue_trigger', '0');
set_config('queue_trigger_posts', '3');
set_config('pm_max_recipients', '0');
// Set maximum number of recipients for the registered users, bots, guests group
$sql = 'UPDATE ' . GROUPS_TABLE . ' SET group_max_recipients = 5
WHERE ' . $db->sql_in_set('group_name', array('GUESTS', 'REGISTERED', 'REGISTERED_COPPA', 'BOTS'));
_sql($sql, $errored, $error_ary);
// Not prefilling yet
set_config('dbms_version', '');
// Add new permission u_masspm_group and duplicate settings from u_masspm
include_once($phpbb_root_path . 'includes/acp/auth.' . $phpEx);
$auth_admin = new auth_admin();
// Only add the new permission if it does not already exist
if (empty($auth_admin->acl_options['id']['u_masspm_group']))
{
$auth_admin->acl_add_option(array('global' => array('u_masspm_group')));
// Now the tricky part, filling the permission
$old_id = $auth_admin->acl_options['id']['u_masspm'];
$new_id = $auth_admin->acl_options['id']['u_masspm_group'];
$tables = array(ACL_GROUPS_TABLE, ACL_ROLES_DATA_TABLE, ACL_USERS_TABLE);
foreach ($tables as $table)
{
$sql = 'SELECT *
FROM ' . $table . '
WHERE auth_option_id = ' . $old_id;
$result = _sql($sql, $errored, $error_ary);
$sql_ary = array();
while ($row = $db->sql_fetchrow($result))
{
$row['auth_option_id'] = $new_id;
$sql_ary[] = $row;
}
$db->sql_freeresult($result);
if (sizeof($sql_ary))
{
$db->sql_multi_insert($table, $sql_ary);
}
}
// Remove any old permission entries
$auth_admin->acl_clear_prefetch();
}
/**
* Do not resync post counts here. An admin may do this later from the ACP
$start = 0;
$step = ($config['num_posts']) ? (max((int) ($config['num_posts'] / 5), 20000)) : 20000;
$sql = 'UPDATE ' . USERS_TABLE . ' SET user_posts = 0';
_sql($sql, $errored, $error_ary);
do
{
$sql = 'SELECT COUNT(post_id) AS num_posts, poster_id
FROM ' . POSTS_TABLE . '
WHERE post_id BETWEEN ' . ($start + 1) . ' AND ' . ($start + $step) . '
AND post_postcount = 1 AND post_approved = 1
GROUP BY poster_id';
$result = _sql($sql, $errored, $error_ary);
if ($row = $db->sql_fetchrow($result))
{
do
{
$sql = 'UPDATE ' . USERS_TABLE . " SET user_posts = user_posts + {$row['num_posts']} WHERE user_id = {$row['poster_id']}";
_sql($sql, $errored, $error_ary);
}
while ($row = $db->sql_fetchrow($result));
$start += $step;
}
else
{
$start = 0;
}
$db->sql_freeresult($result);
}
while ($start);
*/
$sql = 'UPDATE ' . MODULES_TABLE . '
SET module_auth = \'acl_a_email && cfg_email_enable\'
WHERE module_class = \'acp\'
AND module_basename = \'email\'';
_sql($sql, $errored, $error_ary);
$no_updates = false;
break;
// Changes from 3.0.3-RC1 to 3.0.3
case '3.0.3-RC1':
if ($db->sql_layer == 'oracle')
{
// log_operation is CLOB - but we can change this later
$sql = 'UPDATE ' . LOG_TABLE . "
SET log_operation = 'LOG_DELETE_TOPIC'
WHERE log_operation LIKE 'LOG_TOPIC_DELETED'";
_sql($sql, $errored, $error_ary);
}
else
{
$sql = 'UPDATE ' . LOG_TABLE . "
SET log_operation = 'LOG_DELETE_TOPIC'
WHERE log_operation = 'LOG_TOPIC_DELETED'";
_sql($sql, $errored, $error_ary);
}
$no_updates = false;
break;
// Changes from 3.0.3 to 3.0.4-RC1
case '3.0.3':
// Update the Custom Profile Fields based on previous settings to the new format
$sql = 'SELECT field_id, field_required, field_show_on_reg, field_hide
FROM ' . PROFILE_FIELDS_TABLE;
$result = _sql($sql, $errored, $error_ary);
while ($row = $db->sql_fetchrow($result))
{
$sql_ary = array(
'field_required' => 0,
'field_show_on_reg' => 0,
'field_hide' => 0,
'field_show_profile'=> 0,
);
if ($row['field_required'])
{
$sql_ary['field_required'] = $sql_ary['field_show_on_reg'] = $sql_ary['field_show_profile'] = 1;
}
else if ($row['field_show_on_reg'])
{
$sql_ary['field_show_on_reg'] = $sql_ary['field_show_profile'] = 1;
}
else if ($row['field_hide'])
{
// Only administrators and moderators can see this CPF, if the view is enabled, they can see it, otherwise just admins in the acp_users module
$sql_ary['field_hide'] = 1;
}
else
{
// equivelant to "none", which is the "Display in user control panel" option
$sql_ary['field_show_profile'] = 1;
}
_sql('UPDATE ' . PROFILE_FIELDS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . ' WHERE field_id = ' . $row['field_id'], $errored, $error_ary);
}
$no_updates = false;
break;
// Changes from 3.0.4-RC1 to 3.0.4
case '3.0.4-RC1':
break;
// Changes from 3.0.4 to 3.0.5-RC1
case '3.0.4':
// Captcha config variables
set_config('captcha_gd_wave', 0);
set_config('captcha_gd_3d_noise', 1);
set_config('captcha_gd_fonts', 1);
set_config('confirm_refresh', 1);
// Maximum number of keywords
set_config('max_num_search_keywords', 10);
// Remove static config var and put it back as dynamic variable
$sql = 'UPDATE ' . CONFIG_TABLE . "
SET is_dynamic = 1
WHERE config_name = 'search_indexing_state'";
_sql($sql, $errored, $error_ary);
// Hash old MD5 passwords
$sql = 'SELECT user_id, user_password
FROM ' . USERS_TABLE . '
WHERE user_pass_convert = 1';
$result = _sql($sql, $errored, $error_ary);
while ($row = $db->sql_fetchrow($result))
{
if (strlen($row['user_password']) == 32)
{
$sql_ary = array(
'user_password' => phpbb_hash($row['user_password']),
);
_sql('UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . ' WHERE user_id = ' . $row['user_id'], $errored, $error_ary);
}
}
$db->sql_freeresult($result);
// Adjust bot entry
$sql = 'UPDATE ' . BOTS_TABLE . "
SET bot_agent = 'ichiro/'
WHERE bot_agent = 'ichiro/2'";
_sql($sql, $errored, $error_ary);
// Before we are able to add a unique key to auth_option, we need to remove duplicate entries
// We get duplicate entries first
$sql = 'SELECT auth_option
FROM ' . ACL_OPTIONS_TABLE . '
GROUP BY auth_option
HAVING COUNT(*) >= 2';
$result = $db->sql_query($sql);
$auth_options = array();
while ($row = $db->sql_fetchrow($result))
{
$auth_options[] = $row['auth_option'];
}
$db->sql_freeresult($result);
// Remove specific auth options
if (!empty($auth_options))
{
foreach ($auth_options as $option)
{
// Select auth_option_ids... the largest id will be preserved
$sql = 'SELECT auth_option_id
FROM ' . ACL_OPTIONS_TABLE . "
WHERE auth_option = '" . $db->sql_escape($option) . "'
ORDER BY auth_option_id DESC";
// sql_query_limit not possible here, due to bug in postgresql layer
$result = $db->sql_query($sql);
// Skip first row, this is our original auth option we want to preserve
$row = $db->sql_fetchrow($result);
while ($row = $db->sql_fetchrow($result))
{
// Ok, remove this auth option...
_sql('DELETE FROM ' . ACL_OPTIONS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id'], $errored, $error_ary);
_sql('DELETE FROM ' . ACL_ROLES_DATA_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id'], $errored, $error_ary);
_sql('DELETE FROM ' . ACL_GROUPS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id'], $errored, $error_ary);
_sql('DELETE FROM ' . ACL_USERS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id'], $errored, $error_ary);
}
$db->sql_freeresult($result);
}
}
// Now make auth_option UNIQUE, by dropping the old index and adding a UNIQUE one.
$changes = array(
'drop_keys' => array(
ACL_OPTIONS_TABLE => array('auth_option'),
),
);
global $db_tools;
$statements = $db_tools->perform_schema_changes($changes);
foreach ($statements as $sql)
{
_sql($sql, $errored, $error_ary);
}
$changes = array(
'add_unique_index' => array(
ACL_OPTIONS_TABLE => array(
'auth_option' => array('auth_option'),
),
),
);
$statements = $db_tools->perform_schema_changes($changes);
foreach ($statements as $sql)
{
_sql($sql, $errored, $error_ary);
}
$no_updates = false;
break;
// No changes from 3.0.5-RC1 to 3.0.5
case '3.0.5-RC1':
break;
// Changes from 3.0.5 to 3.0.6-RC1
case '3.0.5':
// Let's see if the GD Captcha can be enabled... we simply look for what *is* enabled...
if (!empty($config['captcha_gd']) && !isset($config['captcha_plugin']))
{
set_config('captcha_plugin', 'phpbb_captcha_gd');
}
else if (!isset($config['captcha_plugin']))
{
set_config('captcha_plugin', 'phpbb_captcha_nogd');
}
// Entries for the Feed Feature
set_config('feed_enable', '0');
set_config('feed_limit', '10');
set_config('feed_overall_forums', '1');
set_config('feed_overall_forums_limit', '15');
set_config('feed_overall_topics', '0');
set_config('feed_overall_topics_limit', '15');
set_config('feed_forum', '1');
set_config('feed_topic', '1');
set_config('feed_item_statistics', '1');
// Entries for smiley pagination
set_config('smilies_per_page', '50');
// Entry for reporting PMs
set_config('allow_pm_report', '1');
// Install modules
$modules_to_install = array(
'feed' => array(
'base' => 'board',
'class' => 'acp',
'title' => 'ACP_FEED_SETTINGS',
'auth' => 'acl_a_board',
'cat' => 'ACP_BOARD_CONFIGURATION',
'after' => array('signature', 'ACP_SIGNATURE_SETTINGS')
),
'warnings' => array(
'base' => 'users',
'class' => 'acp',
'title' => 'ACP_USER_WARNINGS',
'auth' => 'acl_a_user',
'display' => 0,
'cat' => 'ACP_CAT_USERS',
'after' => array('feedback', 'ACP_USER_FEEDBACK')
),
'send_statistics' => array(
'base' => 'send_statistics',
'class' => 'acp',
'title' => 'ACP_SEND_STATISTICS',
'auth' => 'acl_a_server',
'cat' => 'ACP_SERVER_CONFIGURATION'
),
'setting_forum_copy' => array(
'base' => 'permissions',
'class' => 'acp',
'title' => 'ACP_FORUM_PERMISSIONS_COPY',
'auth' => 'acl_a_fauth && acl_a_authusers && acl_a_authgroups && acl_a_mauth',
'cat' => 'ACP_FORUM_BASED_PERMISSIONS',
'after' => array('setting_forum_local', 'ACP_FORUM_PERMISSIONS')
),
'pm_reports' => array(
'base' => 'pm_reports',
'class' => 'mcp',
'title' => 'MCP_PM_REPORTS_OPEN',
'auth' => 'aclf_m_report',
'cat' => 'MCP_REPORTS'
),
'pm_reports_closed' => array(
'base' => 'pm_reports',
'class' => 'mcp',
'title' => 'MCP_PM_REPORTS_CLOSED',
'auth' => 'aclf_m_report',
'cat' => 'MCP_REPORTS'
),
'pm_report_details' => array(
'base' => 'pm_reports',
'class' => 'mcp',
'title' => 'MCP_PM_REPORT_DETAILS',
'auth' => 'aclf_m_report',
'cat' => 'MCP_REPORTS'
),
);
_add_modules($modules_to_install);
// Add newly_registered group... but check if it already exists (we always supported running the updater on any schema)
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = 'NEWLY_REGISTERED'";
$result = $db->sql_query($sql);
$group_id = (int) $db->sql_fetchfield('group_id');
$db->sql_freeresult($result);
if (!$group_id)
{
$sql = 'INSERT INTO ' . GROUPS_TABLE . " (group_name, group_type, group_founder_manage, group_colour, group_legend, group_avatar, group_desc, group_desc_uid, group_max_recipients) VALUES ('NEWLY_REGISTERED', 3, 0, '', 0, '', '', '', 5)";
_sql($sql, $errored, $error_ary);
$group_id = $db->sql_nextid();
}
// Insert new user role... at the end of the chain
$sql = 'SELECT role_id
FROM ' . ACL_ROLES_TABLE . "
WHERE role_name = 'ROLE_USER_NEW_MEMBER'
AND role_type = 'u_'";
$result = $db->sql_query($sql);
$u_role = (int) $db->sql_fetchfield('role_id');
$db->sql_freeresult($result);
if (!$u_role)
{
$sql = 'SELECT MAX(role_order) as max_order_id
FROM ' . ACL_ROLES_TABLE . "
WHERE role_type = 'u_'";
$result = $db->sql_query($sql);
$next_order_id = (int) $db->sql_fetchfield('max_order_id');
$db->sql_freeresult($result);
$next_order_id++;
$sql = 'INSERT INTO ' . ACL_ROLES_TABLE . " (role_name, role_description, role_type, role_order) VALUES ('ROLE_USER_NEW_MEMBER', 'ROLE_DESCRIPTION_USER_NEW_MEMBER', 'u_', $next_order_id)";
_sql($sql, $errored, $error_ary);
$u_role = $db->sql_nextid();
if (!$errored)
{
// Now add the correct data to the roles...
// The standard role says that new users are not able to send a PM, Mass PM, are not able to PM groups
$sql = 'INSERT INTO ' . ACL_ROLES_DATA_TABLE . " (role_id, auth_option_id, auth_setting) SELECT $u_role, auth_option_id, 0 FROM " . ACL_OPTIONS_TABLE . " WHERE auth_option LIKE 'u_%' AND auth_option IN ('u_sendpm', 'u_masspm', 'u_masspm_group')";
_sql($sql, $errored, $error_ary);
// Add user role to group
$sql = 'INSERT INTO ' . ACL_GROUPS_TABLE . " (group_id, forum_id, auth_option_id, auth_role_id, auth_setting) VALUES ($group_id, 0, 0, $u_role, 0)";
_sql($sql, $errored, $error_ary);
}
}
// Insert new forum role
$sql = 'SELECT role_id
FROM ' . ACL_ROLES_TABLE . "
WHERE role_name = 'ROLE_FORUM_NEW_MEMBER'
AND role_type = 'f_'";
$result = $db->sql_query($sql);
$f_role = (int) $db->sql_fetchfield('role_id');
$db->sql_freeresult($result);
if (!$f_role)
{
$sql = 'SELECT MAX(role_order) as max_order_id
FROM ' . ACL_ROLES_TABLE . "
WHERE role_type = 'f_'";
$result = $db->sql_query($sql);
$next_order_id = (int) $db->sql_fetchfield('max_order_id');
$db->sql_freeresult($result);
$next_order_id++;
$sql = 'INSERT INTO ' . ACL_ROLES_TABLE . " (role_name, role_description, role_type, role_order) VALUES ('ROLE_FORUM_NEW_MEMBER', 'ROLE_DESCRIPTION_FORUM_NEW_MEMBER', 'f_', $next_order_id)";
_sql($sql, $errored, $error_ary);
$f_role = $db->sql_nextid();
if (!$errored)
{
$sql = 'INSERT INTO ' . ACL_ROLES_DATA_TABLE . " (role_id, auth_option_id, auth_setting) SELECT $f_role, auth_option_id, 0 FROM " . ACL_OPTIONS_TABLE . " WHERE auth_option LIKE 'f_%' AND auth_option IN ('f_noapprove')";
_sql($sql, $errored, $error_ary);
}
}
// Set every members user_new column to 0 (old users) only if there is no one yet (this makes sure we do not execute this more than once)
$sql = 'SELECT 1
FROM ' . USERS_TABLE . '
WHERE user_new = 0';
$result = $db->sql_query_limit($sql, 1);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
$sql = 'UPDATE ' . USERS_TABLE . ' SET user_new = 0';
_sql($sql, $errored, $error_ary);
}
// Newly registered users limit
if (!isset($config['new_member_post_limit']))
{
set_config('new_member_post_limit', (!empty($config['enable_queue_trigger'])) ? $config['queue_trigger_posts'] : 0);
}
if (!isset($config['new_member_group_default']))
{
set_config('new_member_group_default', 0);
}
// To mimick the old "feature" we will assign the forum role to every forum, regardless of the setting (this makes sure there are no "this does not work!!!! YUO!!!" posts...
// Check if the role is already assigned...
$sql = 'SELECT forum_id
FROM ' . ACL_GROUPS_TABLE . '
WHERE group_id = ' . $group_id . '
AND auth_role_id = ' . $f_role;
$result = $db->sql_query($sql);
$is_options = (int) $db->sql_fetchfield('forum_id');
$db->sql_freeresult($result);
// Not assigned at all... :/
if (!$is_options)
{
// Get postable forums
$sql = 'SELECT forum_id
FROM ' . FORUMS_TABLE . '
WHERE forum_type != ' . FORUM_LINK;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
_sql('INSERT INTO ' . ACL_GROUPS_TABLE . ' (group_id, forum_id, auth_option_id, auth_role_id, auth_setting) VALUES (' . $group_id . ', ' . (int) $row['forum_id'] . ', 0, ' . $f_role . ', 0)', $errored, $error_ary);
}
$db->sql_freeresult($result);
}
// Clear permissions...
include_once($phpbb_root_path . 'includes/acp/auth.' . $phpEx);
$auth_admin = new auth_admin();
$auth_admin->acl_clear_prefetch();
if (!isset($config['allow_avatar']))
{
if ($config['allow_avatar_upload'] || $config['allow_avatar_local'] || $config['allow_avatar_remote'])
{
set_config('allow_avatar', '1');
}
else
{
set_config('allow_avatar', '0');
}
}
if (!isset($config['allow_avatar_remote_upload']))
{
if ($config['allow_avatar_remote'] && $config['allow_avatar_upload'])
{
set_config('allow_avatar_remote_upload', '1');
}
else
{
set_config('allow_avatar_remote_upload', '0');
}
}
// Minimum number of characters
if (!isset($config['min_post_chars']))
{
set_config('min_post_chars', '1');
}
if (!isset($config['allow_quick_reply']))
{
set_config('allow_quick_reply', '1');
}
// Set every members user_options column to enable
// bbcode, smilies and URLs for signatures by default
$sql = 'SELECT user_options
FROM ' . USERS_TABLE . '
WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
$result = $db->sql_query_limit($sql, 1);
$user_option = (int) $db->sql_fetchfield('user_options');
$db->sql_freeresult($result);
// Check if we already updated the database by checking bit 15 which we used to store the sig_bbcode option
if (!($user_option & 1 << 15))
{
// 229376 is the added value to enable all three signature options
$sql = 'UPDATE ' . USERS_TABLE . ' SET user_options = user_options + 229376';
_sql($sql, $errored, $error_ary);
}
if (!isset($config['delete_time']))
{
set_config('delete_time', $config['edit_time']);
}
$no_updates = false;
break;
// No changes from 3.0.6-RC1 to 3.0.6-RC2
case '3.0.6-RC1':
break;
// Changes from 3.0.6-RC2 to 3.0.6-RC3
case '3.0.6-RC2':
// Update the Custom Profile Fields based on previous settings to the new format
$sql = 'UPDATE ' . PROFILE_FIELDS_TABLE . '
SET field_show_on_vt = 1
WHERE field_hide = 0
AND (field_required = 1 OR field_show_on_reg = 1 OR field_show_profile = 1)';
_sql($sql, $errored, $error_ary);
$no_updates = false;
break;
// No changes from 3.0.6-RC3 to 3.0.6-RC4
case '3.0.6-RC3':
break;
// No changes from 3.0.6-RC4 to 3.0.6
case '3.0.6-RC4':
break;
// Changes from 3.0.6 to 3.0.7-RC1
case '3.0.6':
// ATOM Feeds
set_config('feed_overall', '1');
set_config('feed_http_auth', '0');
set_config('feed_limit_post', (string) (isset($config['feed_limit']) ? (int) $config['feed_limit'] : 15));
set_config('feed_limit_topic', (string) (isset($config['feed_overall_topics_limit']) ? (int) $config['feed_overall_topics_limit'] : 10));
set_config('feed_topics_new', (!empty($config['feed_overall_topics']) ? '1' : '0'));
set_config('feed_topics_active', (!empty($config['feed_overall_topics']) ? '1' : '0'));
// Delete all text-templates from the template_data
$sql = 'DELETE FROM ' . STYLES_TEMPLATE_DATA_TABLE . '
WHERE template_filename ' . $db->sql_like_expression($db->any_char . '.txt');
_sql($sql, $errored, $error_ary);
$no_updates = false;
break;
// Changes from 3.0.7-RC1 to 3.0.7-RC2
case '3.0.7-RC1':
$sql = 'SELECT user_id, user_email, user_email_hash
FROM ' . USERS_TABLE . '
WHERE user_type <> ' . USER_IGNORE . "
AND user_email <> ''";
$result = $db->sql_query($sql);
$i = 0;
while ($row = $db->sql_fetchrow($result))
{
// Snapshot of the phpbb_email_hash() function
// We cannot call it directly because the auto updater updates the DB first. :/
$user_email_hash = sprintf('%u', crc32(strtolower($row['user_email']))) . strlen($row['user_email']);
if ($user_email_hash != $row['user_email_hash'])
{
$sql_ary = array(
'user_email_hash' => $user_email_hash,
);
$sql = 'UPDATE ' . USERS_TABLE . '
SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
WHERE user_id = ' . (int) $row['user_id'];
_sql($sql, $errored, $error_ary, ($i % 100 == 0));
++$i;
}
}
$db->sql_freeresult($result);
$no_updates = false;
break;
// No changes from 3.0.7-RC2 to 3.0.7
case '3.0.7-RC2':
break;
// No changes from 3.0.7 to 3.0.7-PL1
case '3.0.7':
break;
// Changes from 3.0.7-PL1 to 3.0.8-RC1
case '3.0.7-PL1':
// Update file extension group names to use language strings.
$sql = 'SELECT lang_dir
FROM ' . LANG_TABLE;
$result = $db->sql_query($sql);
$extension_groups_updated = array();
while ($lang_dir = $db->sql_fetchfield('lang_dir'))
{
$lang_dir = basename($lang_dir);
// The language strings we need are either in language/.../acp/attachments.php
// in the update package if we're updating to 3.0.8-RC1 or later,
// or they are in language/.../install.php when we're updating from 3.0.7-PL1 or earlier.
// On an already updated board, they can also already be in language/.../acp/attachments.php
// in the board root.
$lang_files = array(
"{$phpbb_root_path}install/update/new/language/$lang_dir/acp/attachments.$phpEx",
"{$phpbb_root_path}language/$lang_dir/install.$phpEx",
"{$phpbb_root_path}language/$lang_dir/acp/attachments.$phpEx",
);
foreach ($lang_files as $lang_file)
{
if (!file_exists($lang_file))
{
continue;
}
$lang = array();
include($lang_file);
foreach($lang as $lang_key => $lang_val)
{
if (isset($extension_groups_updated[$lang_key]) || strpos($lang_key, 'EXT_GROUP_') !== 0)
{
continue;
}
$sql_ary = array(
'group_name' => substr($lang_key, 10), // Strip off 'EXT_GROUP_'
);
$sql = 'UPDATE ' . EXTENSION_GROUPS_TABLE . '
SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
WHERE group_name = '" . $db->sql_escape($lang_val) . "'";
_sql($sql, $errored, $error_ary);
$extension_groups_updated[$lang_key] = true;
}
}
}
$db->sql_freeresult($result);
// Install modules
$modules_to_install = array(
'post' => array(
'base' => 'board',
'class' => 'acp',
'title' => 'ACP_POST_SETTINGS',
'auth' => 'acl_a_board',
'cat' => 'ACP_MESSAGES',
'after' => array('message', 'ACP_MESSAGE_SETTINGS')
),
);
_add_modules($modules_to_install);
// update
$sql = 'UPDATE ' . MODULES_TABLE . '
SET module_auth = \'cfg_allow_avatar && (cfg_allow_avatar_local || cfg_allow_avatar_remote || cfg_allow_avatar_upload || cfg_allow_avatar_remote_upload)\'
WHERE module_class = \'ucp\'
AND module_basename = \'profile\'
AND module_mode = \'avatar\'';
_sql($sql, $errored, $error_ary);
// add Bing Bot
$bot_name = 'Bing [Bot]';
$bot_name_clean = utf8_clean_string($bot_name);
$sql = 'SELECT user_id
FROM ' . USERS_TABLE . "
WHERE username_clean = '" . $db->sql_escape($bot_name_clean) . "'";
$result = $db->sql_query($sql);
$bing_already_added = (bool) $db->sql_fetchfield('user_id');
$db->sql_freeresult($result);
if (!$bing_already_added)
{
$bot_agent = 'bingbot/';
$bot_ip = '';
$sql = 'SELECT group_id, group_colour
FROM ' . GROUPS_TABLE . "
WHERE group_name = 'BOTS'";
$result = $db->sql_query($sql);
$group_row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$group_row)
{
// default fallback, should never get here
$group_row['group_id'] = 6;
$group_row['group_colour'] = '9E8DA7';
}
if (!function_exists('user_add'))
{
include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
}
$user_row = array(
'user_type' => USER_IGNORE,
'group_id' => $group_row['group_id'],
'username' => $bot_name,
'user_regdate' => time(),
'user_password' => '',
'user_colour' => $group_row['group_colour'],
'user_email' => '',
'user_lang' => $config['default_lang'],
'user_style' => $config['default_style'],
'user_timezone' => 0,
'user_dateformat' => $config['default_dateformat'],
'user_allow_massemail' => 0,
);
$user_id = user_add($user_row);
$sql = 'INSERT INTO ' . BOTS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
'bot_active' => 1,
'bot_name' => (string) $bot_name,
'user_id' => (int) $user_id,
'bot_agent' => (string) $bot_agent,
'bot_ip' => (string) $bot_ip,
));
_sql($sql, $errored, $error_ary);
}
// end Bing Bot addition
// Delete shadow topics pointing to not existing topics
$batch_size = 500;
// Set of affected forums we have to resync
$sync_forum_ids = array();
do
{
$sql_array = array(
'SELECT' => 't1.topic_id, t1.forum_id',
'FROM' => array(
TOPICS_TABLE => 't1',
),
'LEFT_JOIN' => array(
array(
'FROM' => array(TOPICS_TABLE => 't2'),
'ON' => 't1.topic_moved_id = t2.topic_id',
),
),
'WHERE' => 't1.topic_moved_id <> 0
AND t2.topic_id IS NULL',
);
$sql = $db->sql_build_query('SELECT', $sql_array);
$result = $db->sql_query_limit($sql, $batch_size);
$topic_ids = array();
while ($row = $db->sql_fetchrow($result))
{
$topic_ids[] = (int) $row['topic_id'];
$sync_forum_ids[(int) $row['forum_id']] = (int) $row['forum_id'];
}
$db->sql_freeresult($result);
if (!empty($topic_ids))
{
$sql = 'DELETE FROM ' . TOPICS_TABLE . '
WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
$db->sql_query($sql);
}
}
while (sizeof($topic_ids) == $batch_size);
// Sync the forums we have deleted shadow topics from.
sync('forum', 'forum_id', $sync_forum_ids, true, true);
// Unread posts search load switch
set_config('load_unreads_search', '1');
// Reduce queue interval to 60 seconds, email package size to 20
if ($config['queue_interval'] == 600)
{
set_config('queue_interval', '60');
}
if ($config['email_package_size'] == 50)
{
set_config('email_package_size', '20');
}
$no_updates = false;
break;
// No changes from 3.0.8-RC1 to 3.0.8
case '3.0.8-RC1':
break;
// Changes from 3.1.0-dev to 3.1.0-A1
case '3.1.0-dev':
set_config('use_system_cron', 0);
break;
}
}
/**
* Database Tools for handling cross-db actions such as altering columns, etc.
* Currently not supported is returning SQL for creating tables.
*
* @package dbal
*/
class updater_db_tools
{
/**
* Current sql layer
*/
var $sql_layer = '';
/**
* @var object DB object
*/
var $db = NULL;
/**
* The Column types for every database we support
* @var array
*/
var $dbms_type_map = array(
'mysql_41' => array(
'INT:' => 'int(%d)',
'BINT' => 'bigint(20)',
'UINT' => 'mediumint(8) UNSIGNED',
'UINT:' => 'int(%d) UNSIGNED',
'TINT:' => 'tinyint(%d)',
'USINT' => 'smallint(4) UNSIGNED',
'BOOL' => 'tinyint(1) UNSIGNED',
'VCHAR' => 'varchar(255)',
'VCHAR:' => 'varchar(%d)',
'CHAR:' => 'char(%d)',
'XSTEXT' => 'text',
'XSTEXT_UNI'=> 'varchar(100)',
'STEXT' => 'text',
'STEXT_UNI' => 'varchar(255)',
'TEXT' => 'text',
'TEXT_UNI' => 'text',
'MTEXT' => 'mediumtext',
'MTEXT_UNI' => 'mediumtext',
'TIMESTAMP' => 'int(11) UNSIGNED',
'DECIMAL' => 'decimal(5,2)',
'DECIMAL:' => 'decimal(%d,2)',
'PDECIMAL' => 'decimal(6,3)',
'PDECIMAL:' => 'decimal(%d,3)',
'VCHAR_UNI' => 'varchar(255)',
'VCHAR_UNI:'=> 'varchar(%d)',
'VCHAR_CI' => 'varchar(255)',
'VARBINARY' => 'varbinary(255)',
),
'mysql_40' => array(
'INT:' => 'int(%d)',
'BINT' => 'bigint(20)',
'UINT' => 'mediumint(8) UNSIGNED',
'UINT:' => 'int(%d) UNSIGNED',
'TINT:' => 'tinyint(%d)',
'USINT' => 'smallint(4) UNSIGNED',
'BOOL' => 'tinyint(1) UNSIGNED',
'VCHAR' => 'varbinary(255)',
'VCHAR:' => 'varbinary(%d)',
'CHAR:' => 'binary(%d)',
'XSTEXT' => 'blob',
'XSTEXT_UNI'=> 'blob',
'STEXT' => 'blob',
'STEXT_UNI' => 'blob',
'TEXT' => 'blob',
'TEXT_UNI' => 'blob',
'MTEXT' => 'mediumblob',
'MTEXT_UNI' => 'mediumblob',
'TIMESTAMP' => 'int(11) UNSIGNED',
'DECIMAL' => 'decimal(5,2)',
'DECIMAL:' => 'decimal(%d,2)',
'PDECIMAL' => 'decimal(6,3)',
'PDECIMAL:' => 'decimal(%d,3)',
'VCHAR_UNI' => 'blob',
'VCHAR_UNI:'=> array('varbinary(%d)', 'limit' => array('mult', 3, 255, 'blob')),
'VCHAR_CI' => 'blob',
'VARBINARY' => 'varbinary(255)',
),
'firebird' => array(
'INT:' => 'INTEGER',
'BINT' => 'DOUBLE PRECISION',
'UINT' => 'INTEGER',
'UINT:' => 'INTEGER',
'TINT:' => 'INTEGER',
'USINT' => 'INTEGER',
'BOOL' => 'INTEGER',
'VCHAR' => 'VARCHAR(255) CHARACTER SET NONE',
'VCHAR:' => 'VARCHAR(%d) CHARACTER SET NONE',
'CHAR:' => 'CHAR(%d) CHARACTER SET NONE',
'XSTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'STEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'TEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'MTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'XSTEXT_UNI'=> 'VARCHAR(100) CHARACTER SET UTF8',
'STEXT_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
'TEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
'MTEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
'TIMESTAMP' => 'INTEGER',
'DECIMAL' => 'DOUBLE PRECISION',
'DECIMAL:' => 'DOUBLE PRECISION',
'PDECIMAL' => 'DOUBLE PRECISION',
'PDECIMAL:' => 'DOUBLE PRECISION',
'VCHAR_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
'VCHAR_UNI:'=> 'VARCHAR(%d) CHARACTER SET UTF8',
'VCHAR_CI' => 'VARCHAR(255) CHARACTER SET UTF8',
'VARBINARY' => 'CHAR(255) CHARACTER SET NONE',
),
'mssql' => array(
'INT:' => '[int]',
'BINT' => '[float]',
'UINT' => '[int]',
'UINT:' => '[int]',
'TINT:' => '[int]',
'USINT' => '[int]',
'BOOL' => '[int]',
'VCHAR' => '[varchar] (255)',
'VCHAR:' => '[varchar] (%d)',
'CHAR:' => '[char] (%d)',
'XSTEXT' => '[varchar] (1000)',
'STEXT' => '[varchar] (3000)',
'TEXT' => '[varchar] (8000)',
'MTEXT' => '[text]',
'XSTEXT_UNI'=> '[varchar] (100)',
'STEXT_UNI' => '[varchar] (255)',
'TEXT_UNI' => '[varchar] (4000)',
'MTEXT_UNI' => '[text]',
'TIMESTAMP' => '[int]',
'DECIMAL' => '[float]',
'DECIMAL:' => '[float]',
'PDECIMAL' => '[float]',
'PDECIMAL:' => '[float]',
'VCHAR_UNI' => '[varchar] (255)',
'VCHAR_UNI:'=> '[varchar] (%d)',
'VCHAR_CI' => '[varchar] (255)',
'VARBINARY' => '[varchar] (255)',
),
'mssqlnative' => array(
'INT:' => '[int]',
'BINT' => '[float]',
'UINT' => '[int]',
'UINT:' => '[int]',
'TINT:' => '[int]',
'USINT' => '[int]',
'BOOL' => '[int]',
'VCHAR' => '[varchar] (255)',
'VCHAR:' => '[varchar] (%d)',
'CHAR:' => '[char] (%d)',
'XSTEXT' => '[varchar] (1000)',
'STEXT' => '[varchar] (3000)',
'TEXT' => '[varchar] (8000)',
'MTEXT' => '[text]',
'XSTEXT_UNI'=> '[varchar] (100)',
'STEXT_UNI' => '[varchar] (255)',
'TEXT_UNI' => '[varchar] (4000)',
'MTEXT_UNI' => '[text]',
'TIMESTAMP' => '[int]',
'DECIMAL' => '[float]',
'DECIMAL:' => '[float]',
'PDECIMAL' => '[float]',
'PDECIMAL:' => '[float]',
'VCHAR_UNI' => '[varchar] (255)',
'VCHAR_UNI:'=> '[varchar] (%d)',
'VCHAR_CI' => '[varchar] (255)',
'VARBINARY' => '[varchar] (255)',
),
'oracle' => array(
'INT:' => 'number(%d)',
'BINT' => 'number(20)',
'UINT' => 'number(8)',
'UINT:' => 'number(%d)',
'TINT:' => 'number(%d)',
'USINT' => 'number(4)',
'BOOL' => 'number(1)',
'VCHAR' => 'varchar2(255)',
'VCHAR:' => 'varchar2(%d)',
'CHAR:' => 'char(%d)',
'XSTEXT' => 'varchar2(1000)',
'STEXT' => 'varchar2(3000)',
'TEXT' => 'clob',
'MTEXT' => 'clob',
'XSTEXT_UNI'=> 'varchar2(300)',
'STEXT_UNI' => 'varchar2(765)',
'TEXT_UNI' => 'clob',
'MTEXT_UNI' => 'clob',
'TIMESTAMP' => 'number(11)',
'DECIMAL' => 'number(5, 2)',
'DECIMAL:' => 'number(%d, 2)',
'PDECIMAL' => 'number(6, 3)',
'PDECIMAL:' => 'number(%d, 3)',
'VCHAR_UNI' => 'varchar2(765)',
'VCHAR_UNI:'=> array('varchar2(%d)', 'limit' => array('mult', 3, 765, 'clob')),
'VCHAR_CI' => 'varchar2(255)',
'VARBINARY' => 'raw(255)',
),
'sqlite' => array(
'INT:' => 'int(%d)',
'BINT' => 'bigint(20)',
'UINT' => 'INTEGER UNSIGNED', //'mediumint(8) UNSIGNED',
'UINT:' => 'INTEGER UNSIGNED', // 'int(%d) UNSIGNED',
'TINT:' => 'tinyint(%d)',
'USINT' => 'INTEGER UNSIGNED', //'mediumint(4) UNSIGNED',
'BOOL' => 'INTEGER UNSIGNED', //'tinyint(1) UNSIGNED',
'VCHAR' => 'varchar(255)',
'VCHAR:' => 'varchar(%d)',
'CHAR:' => 'char(%d)',
'XSTEXT' => 'text(65535)',
'STEXT' => 'text(65535)',
'TEXT' => 'text(65535)',
'MTEXT' => 'mediumtext(16777215)',
'XSTEXT_UNI'=> 'text(65535)',
'STEXT_UNI' => 'text(65535)',
'TEXT_UNI' => 'text(65535)',
'MTEXT_UNI' => 'mediumtext(16777215)',
'TIMESTAMP' => 'INTEGER UNSIGNED', //'int(11) UNSIGNED',
'DECIMAL' => 'decimal(5,2)',
'DECIMAL:' => 'decimal(%d,2)',
'PDECIMAL' => 'decimal(6,3)',
'PDECIMAL:' => 'decimal(%d,3)',
'VCHAR_UNI' => 'varchar(255)',
'VCHAR_UNI:'=> 'varchar(%d)',
'VCHAR_CI' => 'varchar(255)',
'VARBINARY' => 'blob',
),
'postgres' => array(
'INT:' => 'INT4',
'BINT' => 'INT8',
'UINT' => 'INT4', // unsigned
'UINT:' => 'INT4', // unsigned
'USINT' => 'INT2', // unsigned
'BOOL' => 'INT2', // unsigned
'TINT:' => 'INT2',
'VCHAR' => 'varchar(255)',
'VCHAR:' => 'varchar(%d)',
'CHAR:' => 'char(%d)',
'XSTEXT' => 'varchar(1000)',
'STEXT' => 'varchar(3000)',
'TEXT' => 'varchar(8000)',
'MTEXT' => 'TEXT',
'XSTEXT_UNI'=> 'varchar(100)',
'STEXT_UNI' => 'varchar(255)',
'TEXT_UNI' => 'varchar(4000)',
'MTEXT_UNI' => 'TEXT',
'TIMESTAMP' => 'INT4', // unsigned
'DECIMAL' => 'decimal(5,2)',
'DECIMAL:' => 'decimal(%d,2)',
'PDECIMAL' => 'decimal(6,3)',
'PDECIMAL:' => 'decimal(%d,3)',
'VCHAR_UNI' => 'varchar(255)',
'VCHAR_UNI:'=> 'varchar(%d)',
'VCHAR_CI' => 'varchar_ci',
'VARBINARY' => 'bytea',
),
);
/**
* A list of types being unsigned for better reference in some db's
* @var array
*/
var $unsigned_types = array('UINT', 'UINT:', 'USINT', 'BOOL', 'TIMESTAMP');
/**
* A list of supported DBMS. We change this class to support more DBMS, the DBMS itself only need to follow some rules.
* @var array
*/
var $supported_dbms = array('firebird', 'mssql', 'mssqlnative', 'mysql_40', 'mysql_41', 'oracle', 'postgres', 'sqlite');
/**
* This is set to true if user only wants to return the 'to-be-executed' SQL statement(s) (as an array).
* This mode has no effect on some methods (inserting of data for example). This is expressed within the methods command.
*/
var $return_statements = false;
/**
* Constructor. Set DB Object and set {@link $return_statements return_statements}.
*
* @param phpbb_dbal $db DBAL object
* @param bool $return_statements True if only statements should be returned and no SQL being executed
*/
function updater_db_tools(&$db, $return_statements = false)
{
$this->db = $db;
$this->return_statements = $return_statements;
// Determine mapping database type
switch ($this->db->sql_layer)
{
case 'mysql':
$this->sql_layer = 'mysql_40';
break;
case 'mysql4':
if (version_compare($this->db->sql_server_info(true), '4.1.3', '>='))
{
$this->sql_layer = 'mysql_41';
}
else
{
$this->sql_layer = 'mysql_40';
}
break;
case 'mysqli':
$this->sql_layer = 'mysql_41';
break;
case 'mssql':
case 'mssql_odbc':
$this->sql_layer = 'mssql';
break;
case 'mssqlnative':
$this->sql_layer = 'mssqlnative';
break;
default:
$this->sql_layer = $this->db->sql_layer;
break;
}
}
/**
* Handle passed database update array.
* Expected structure...
* Key being one of the following
* change_columns: Column changes (only type, not name)
* add_columns: Add columns to a table
* drop_keys: Dropping keys
* drop_columns: Removing/Dropping columns
* add_primary_keys: adding primary keys
* add_unique_index: adding an unique index
* add_index: adding an index (can be column:index_size if you need to provide size)
*
* The values are in this format:
* {TABLE NAME} => array(
* {COLUMN NAME} => array({COLUMN TYPE}, {DEFAULT VALUE}, {OPTIONAL VARIABLES}),
* {KEY/INDEX NAME} => array({COLUMN NAMES}),
* )
*
* For more information have a look at /develop/create_schema_files.php (only available through SVN)
*/
function perform_schema_changes($schema_changes)
{
if (empty($schema_changes))
{
return;
}
$statements = array();
$sqlite = false;
// For SQLite we need to perform the schema changes in a much more different way
if ($this->db->sql_layer == 'sqlite' && $this->return_statements)
{
$sqlite_data = array();
$sqlite = true;
}
// Change columns?
if (!empty($schema_changes['change_columns']))
{
foreach ($schema_changes['change_columns'] as $table => $columns)
{
foreach ($columns as $column_name => $column_data)
{
// If the column exists we change it, else we add it ;)
if ($column_exists = $this->sql_column_exists($table, $column_name))
{
$result = $this->sql_column_change($table, $column_name, $column_data, true);
}
else
{
$result = $this->sql_column_add($table, $column_name, $column_data, true);
}
if ($sqlite)
{
if ($column_exists)
{
$sqlite_data[$table]['change_columns'][] = $result;
}
else
{
$sqlite_data[$table]['add_columns'][] = $result;
}
}
else if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
// Add columns?
if (!empty($schema_changes['add_columns']))
{
foreach ($schema_changes['add_columns'] as $table => $columns)
{
foreach ($columns as $column_name => $column_data)
{
// Only add the column if it does not exist yet
if ($column_exists = $this->sql_column_exists($table, $column_name))
{
continue;
// This is commented out here because it can take tremendous time on updates
// $result = $this->sql_column_change($table, $column_name, $column_data, true);
}
else
{
$result = $this->sql_column_add($table, $column_name, $column_data, true);
}
if ($sqlite)
{
if ($column_exists)
{
continue;
// $sqlite_data[$table]['change_columns'][] = $result;
}
else
{
$sqlite_data[$table]['add_columns'][] = $result;
}
}
else if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
// Remove keys?
if (!empty($schema_changes['drop_keys']))
{
foreach ($schema_changes['drop_keys'] as $table => $indexes)
{
foreach ($indexes as $index_name)
{
if (!$this->sql_index_exists($table, $index_name))
{
continue;
}
$result = $this->sql_index_drop($table, $index_name);
if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
// Drop columns?
if (!empty($schema_changes['drop_columns']))
{
foreach ($schema_changes['drop_columns'] as $table => $columns)
{
foreach ($columns as $column)
{
// Only remove the column if it exists...
if ($this->sql_column_exists($table, $column))
{
$result = $this->sql_column_remove($table, $column, true);
if ($sqlite)
{
$sqlite_data[$table]['drop_columns'][] = $result;
}
else if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
}
// Add primary keys?
if (!empty($schema_changes['add_primary_keys']))
{
foreach ($schema_changes['add_primary_keys'] as $table => $columns)
{
$result = $this->sql_create_primary_key($table, $columns, true);
if ($sqlite)
{
$sqlite_data[$table]['primary_key'] = $result;
}
else if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
// Add unqiue indexes?
if (!empty($schema_changes['add_unique_index']))
{
foreach ($schema_changes['add_unique_index'] as $table => $index_array)
{
foreach ($index_array as $index_name => $column)
{
if ($this->sql_unique_index_exists($table, $index_name))
{
continue;
}
$result = $this->sql_create_unique_index($table, $index_name, $column);
if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
// Add indexes?
if (!empty($schema_changes['add_index']))
{
foreach ($schema_changes['add_index'] as $table => $index_array)
{
foreach ($index_array as $index_name => $column)
{
if ($this->sql_index_exists($table, $index_name))
{
continue;
}
$result = $this->sql_create_index($table, $index_name, $column);
if ($this->return_statements)
{
$statements = array_merge($statements, $result);
}
}
}
}
if ($sqlite)
{
foreach ($sqlite_data as $table_name => $sql_schema_changes)
{
// Create temporary table with original data
$statements[] = 'begin';
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table_name}'
ORDER BY type DESC, name;";
$result = $this->db->sql_query($sql);
if (!$result)
{
continue;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
// Create a backup table and populate it, destroy the existing one
$statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
$statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
$statements[] = 'DROP TABLE ' . $table_name;
// Get the columns...
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$plain_table_cols = trim($matches[1]);
$new_table_cols = preg_split('/,(?![\s\w]+\))/m', $plain_table_cols);
$column_list = array();
foreach ($new_table_cols as $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY')
{
continue;
}
$column_list[] = $entities[0];
}
// note down the primary key notation because sqlite only supports adding it to the end for the new table
$primary_key = false;
$_new_cols = array();
foreach ($new_table_cols as $key => $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY')
{
$primary_key = $declaration;
continue;
}
$_new_cols[] = $declaration;
}
$new_table_cols = $_new_cols;
// First of all... change columns
if (!empty($sql_schema_changes['change_columns']))
{
foreach ($sql_schema_changes['change_columns'] as $column_sql)
{
foreach ($new_table_cols as $key => $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if (strpos($column_sql, $entities[0] . ' ') === 0)
{
$new_table_cols[$key] = $column_sql;
}
}
}
}
if (!empty($sql_schema_changes['add_columns']))
{
foreach ($sql_schema_changes['add_columns'] as $column_sql)
{
$new_table_cols[] = $column_sql;
}
}
// Now drop them...
if (!empty($sql_schema_changes['drop_columns']))
{
foreach ($sql_schema_changes['drop_columns'] as $column_name)
{
// Remove from column list...
$new_column_list = array();
foreach ($column_list as $key => $value)
{
if ($value === $column_name)
{
continue;
}
$new_column_list[] = $value;
}
$column_list = $new_column_list;
// Remove from table...
$_new_cols = array();
foreach ($new_table_cols as $key => $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if (strpos($column_name . ' ', $entities[0] . ' ') === 0)
{
continue;
}
$_new_cols[] = $declaration;
}
$new_table_cols = $_new_cols;
}
}
// Primary key...
if (!empty($sql_schema_changes['primary_key']))
{
$new_table_cols[] = 'PRIMARY KEY (' . implode(', ', $sql_schema_changes['primary_key']) . ')';
}
// Add a new one or the old primary key
else if ($primary_key !== false)
{
$new_table_cols[] = $primary_key;
}
$columns = implode(',', $column_list);
// create a new table and fill it up. destroy the temp one
$statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $new_table_cols) . ');';
$statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
$statements[] = 'DROP TABLE ' . $table_name . '_temp';
$statements[] = 'commit';
}
}
if ($this->return_statements)
{
return $statements;
}
}
/**
* Check if a specified column exist
*
* @param string $table Table to check the column at
* @param string $column_name The column to check
*
* @return bool True if column exists, else false
*/
function sql_column_exists($table, $column_name)
{
switch ($this->sql_layer)
{
case 'mysql_40':
case 'mysql_41':
$sql = "SHOW COLUMNS FROM $table";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// lower case just in case
if (strtolower($row['Field']) == $column_name)
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
break;
// PostgreSQL has a way of doing this in a much simpler way but would
// not allow us to support all versions of PostgreSQL
case 'postgres':
$sql = "SELECT a.attname
FROM pg_class c, pg_attribute a
WHERE c.relname = '{$table}'
AND a.attnum > 0
AND a.attrelid = c.oid";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// lower case just in case
if (strtolower($row['attname']) == $column_name)
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
break;
// same deal with PostgreSQL, we must perform more complex operations than
// we technically could
case 'mssql':
case 'mssqlnative':
$sql = "SELECT c.name
FROM syscolumns c
LEFT JOIN sysobjects o ON c.id = o.id
WHERE o.name = '{$table}'";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// lower case just in case
if (strtolower($row['name']) == $column_name)
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
break;
case 'oracle':
$sql = "SELECT column_name
FROM user_tab_columns
WHERE LOWER(table_name) = '" . strtolower($table) . "'";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// lower case just in case
if (strtolower($row['column_name']) == $column_name)
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
break;
case 'firebird':
$sql = "SELECT RDB\$FIELD_NAME as FNAME
FROM RDB\$RELATION_FIELDS
WHERE RDB\$RELATION_NAME = '" . strtoupper($table) . "'";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// lower case just in case
if (strtolower($row['fname']) == $column_name)
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
break;
// ugh, SQLite
case 'sqlite':
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table}'";
$result = $this->db->sql_query($sql);
if (!$result)
{
return false;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$cols = trim($matches[1]);
$col_array = preg_split('/,(?![\s\w]+\))/m', $cols);
foreach ($col_array as $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY')
{
continue;
}
if (strtolower($entities[0]) == $column_name)
{
return true;
}
}
return false;
break;
}
}
/**
* Check if a specified index exists in table. Does not return PRIMARY KEY and UNIQUE indexes.
*
* @param string $table_name Table to check the index at
* @param string $index_name The index name to check
*
* @return bool True if index exists, else false
*/
function sql_index_exists($table_name, $index_name)
{
if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative')
{
$sql = "EXEC sp_statistics '$table_name'";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
if ($row['TYPE'] == 3)
{
if (strtolower($row['INDEX_NAME']) == strtolower($index_name))
{
$this->db->sql_freeresult($result);
return true;
}
}
}
$this->db->sql_freeresult($result);
return false;
}
switch ($this->sql_layer)
{
case 'firebird':
$sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name
FROM RDB\$INDICES
WHERE RDB\$RELATION_NAME = '" . strtoupper($table_name) . "'
AND RDB\$UNIQUE_FLAG IS NULL
AND RDB\$FOREIGN_KEY IS NULL";
$col = 'index_name';
break;
case 'postgres':
$sql = "SELECT ic.relname as index_name
FROM pg_class bc, pg_class ic, pg_index i
WHERE (bc.oid = i.indrelid)
AND (ic.oid = i.indexrelid)
AND (bc.relname = '" . $table_name . "')
AND (i.indisunique != 't')
AND (i.indisprimary != 't')";
$col = 'index_name';
break;
case 'mysql_40':
case 'mysql_41':
$sql = 'SHOW KEYS
FROM ' . $table_name;
$col = 'Key_name';
break;
case 'oracle':
$sql = "SELECT index_name
FROM user_indexes
WHERE table_name = '" . strtoupper($table_name) . "'
AND generated = 'N'
AND uniqueness = 'NONUNIQUE'";
$col = 'index_name';
break;
case 'sqlite':
$sql = "PRAGMA index_list('" . $table_name . "');";
$col = 'name';
break;
}
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && !$row['Non_unique'])
{
continue;
}
// These DBMS prefix index name with the table name
switch ($this->sql_layer)
{
case 'firebird':
case 'oracle':
case 'postgres':
case 'sqlite':
$row[$col] = substr($row[$col], strlen($table_name) + 1);
break;
}
if (strtolower($row[$col]) == strtolower($index_name))
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
}
/**
* Check if a specified UNIQUE index exists in table.
*
* @param string $table_name Table to check the index at
* @param string $index_name The index name to check
*
* @return bool True if index exists, else false
*/
function sql_unique_index_exists($table_name, $index_name)
{
if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative')
{
$sql = "EXEC sp_statistics '$table_name'";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// Usually NON_UNIQUE is the column we want to check, but we allow for both
if ($row['TYPE'] == 3)
{
if (strtolower($row['INDEX_NAME']) == strtolower($index_name))
{
$this->db->sql_freeresult($result);
return true;
}
}
}
$this->db->sql_freeresult($result);
return false;
}
switch ($this->sql_layer)
{
case 'firebird':
$sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name
FROM RDB\$INDICES
WHERE RDB\$RELATION_NAME = '" . strtoupper($table_name) . "'
AND RDB\$UNIQUE_FLAG IS NOT NULL
AND RDB\$FOREIGN_KEY IS NULL";
$col = 'index_name';
break;
case 'postgres':
$sql = "SELECT ic.relname as index_name, i.indisunique
FROM pg_class bc, pg_class ic, pg_index i
WHERE (bc.oid = i.indrelid)
AND (ic.oid = i.indexrelid)
AND (bc.relname = '" . $table_name . "')
AND (i.indisprimary != 't')";
$col = 'index_name';
break;
case 'mysql_40':
case 'mysql_41':
$sql = 'SHOW KEYS
FROM ' . $table_name;
$col = 'Key_name';
break;
case 'oracle':
$sql = "SELECT index_name, table_owner
FROM user_indexes
WHERE table_name = '" . strtoupper($table_name) . "'
AND generated = 'N'
AND uniqueness = 'UNIQUE'";
$col = 'index_name';
break;
case 'sqlite':
$sql = "PRAGMA index_list('" . $table_name . "');";
$col = 'name';
break;
}
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && ($row['Non_unique'] || $row[$col] == 'PRIMARY'))
{
continue;
}
if ($this->sql_layer == 'sqlite' && !$row['unique'])
{
continue;
}
if ($this->sql_layer == 'postgres' && $row['indisunique'] != 't')
{
continue;
}
// These DBMS prefix index name with the table name
switch ($this->sql_layer)
{
case 'oracle':
// Two cases here... prefixed with U_[table_owner] and not prefixed with table_name
if (strpos($row[$col], 'U_') === 0)
{
$row[$col] = substr($row[$col], strlen('U_' . $row['table_owner']) + 1);
}
else if (strpos($row[$col], strtoupper($table_name)) === 0)
{
$row[$col] = substr($row[$col], strlen($table_name) + 1);
}
break;
case 'firebird':
case 'postgres':
case 'sqlite':
$row[$col] = substr($row[$col], strlen($table_name) + 1);
break;
}
if (strtolower($row[$col]) == strtolower($index_name))
{
$this->db->sql_freeresult($result);
return true;
}
}
$this->db->sql_freeresult($result);
return false;
}
/**
* Private method for performing sql statements (either execute them or return them)
* @access private
*/
function _sql_run_sql($statements)
{
if ($this->return_statements)
{
return $statements;
}
// We could add error handling here...
foreach ($statements as $sql)
{
if ($sql === 'begin')
{
$this->db->sql_transaction('begin');
}
else if ($sql === 'commit')
{
$this->db->sql_transaction('commit');
}
else
{
$this->db->sql_query($sql);
}
}
return true;
}
/**
* Function to prepare some column information for better usage
* @access private
*/
function sql_prepare_column_data($table_name, $column_name, $column_data)
{
// Get type
if (strpos($column_data[0], ':') !== false)
{
list($orig_column_type, $column_length) = explode(':', $column_data[0]);
if (!is_array($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']))
{
$column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'], $column_length);
}
else
{
if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule']))
{
switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][0])
{
case 'div':
$column_length /= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][1];
$column_length = ceil($column_length);
$column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length);
break;
}
}
if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit']))
{
switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][0])
{
case 'mult':
$column_length *= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][1];
if ($column_length > $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][2])
{
$column_type = $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][3];
}
else
{
$column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length);
}
break;
}
}
}
$orig_column_type .= ':';
}
else
{
$orig_column_type = $column_data[0];
$column_type = $this->dbms_type_map[$this->sql_layer][$column_data[0]];
}
// Adjust default value if db-dependant specified
if (is_array($column_data[1]))
{
$column_data[1] = (isset($column_data[1][$this->sql_layer])) ? $column_data[1][$this->sql_layer] : $column_data[1]['default'];
}
$sql = '';
$return_array = array();
switch ($this->sql_layer)
{
case 'firebird':
$sql .= " {$column_type} ";
$return_array['column_type_sql_type'] = " {$column_type} ";
if (!is_null($column_data[1]))
{
$sql .= 'DEFAULT ' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' ';
$return_array['column_type_sql_default'] = ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' ';
}
$sql .= 'NOT NULL';
// This is a UNICODE column and thus should be given it's fair share
if (preg_match('/^X?STEXT_UNI|VCHAR_(CI|UNI:?)/', $column_data[0]))
{
$sql .= ' COLLATE UNICODE';
}
$return_array['auto_increment'] = false;
if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
{
$return_array['auto_increment'] = true;
}
break;
case 'mssql':
case 'mssqlnative':
$sql .= " {$column_type} ";
$sql_default = " {$column_type} ";
// For adding columns we need the default definition
if (!is_null($column_data[1]))
{
// For hexadecimal values do not use single quotes
if (strpos($column_data[1], '0x') === 0)
{
$return_array['default'] = 'DEFAULT (' . $column_data[1] . ') ';
$sql_default .= $return_array['default'];
}
else
{
$return_array['default'] = 'DEFAULT (' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ') ';
$sql_default .= $return_array['default'];
}
}
if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
{
// $sql .= 'IDENTITY (1, 1) ';
$sql_default .= 'IDENTITY (1, 1) ';
}
$return_array['textimage'] = $column_type === '[text]';
$sql .= 'NOT NULL';
$sql_default .= 'NOT NULL';
$return_array['column_type_sql_default'] = $sql_default;
break;
case 'mysql_40':
case 'mysql_41':
$sql .= " {$column_type} ";
// For hexadecimal values do not use single quotes
if (!is_null($column_data[1]) && substr($column_type, -4) !== 'text' && substr($column_type, -4) !== 'blob')
{
$sql .= (strpos($column_data[1], '0x') === 0) ? "DEFAULT {$column_data[1]} " : "DEFAULT '{$column_data[1]}' ";
}
$sql .= 'NOT NULL';
if (isset($column_data[2]))
{
if ($column_data[2] == 'auto_increment')
{
$sql .= ' auto_increment';
}
else if ($this->sql_layer === 'mysql_41' && $column_data[2] == 'true_sort')
{
$sql .= ' COLLATE utf8_unicode_ci';
}
}
break;
case 'oracle':
$sql .= " {$column_type} ";
$sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : '';
// In Oracle empty strings ('') are treated as NULL.
// Therefore in oracle we allow NULL's for all DEFAULT '' entries
// Oracle does not like setting NOT NULL on a column that is already NOT NULL (this happens only on number fields)
if (!preg_match('/number/i', $column_type))
{
$sql .= ($column_data[1] === '') ? '' : 'NOT NULL';
}
$return_array['auto_increment'] = false;
if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
{
$return_array['auto_increment'] = true;
}
break;
case 'postgres':
$return_array['column_type'] = $column_type;
$sql .= " {$column_type} ";
$return_array['auto_increment'] = false;
if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
{
$default_val = "nextval('{$table_name}_seq')";
$return_array['auto_increment'] = true;
}
else if (!is_null($column_data[1]))
{
$default_val = "'" . $column_data[1] . "'";
$return_array['null'] = 'NOT NULL';
$sql .= 'NOT NULL ';
}
$return_array['default'] = $default_val;
$sql .= "DEFAULT {$default_val}";
// Unsigned? Then add a CHECK contraint
if (in_array($orig_column_type, $this->unsigned_types))
{
$return_array['constraint'] = "CHECK ({$column_name} >= 0)";
$sql .= " CHECK ({$column_name} >= 0)";
}
break;
case 'sqlite':
$return_array['primary_key_set'] = false;
if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
{
$sql .= ' INTEGER PRIMARY KEY';
$return_array['primary_key_set'] = true;
}
else
{
$sql .= ' ' . $column_type;
}
$sql .= ' NOT NULL ';
$sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}'" : '';
break;
}
$return_array['column_type_sql'] = $sql;
return $return_array;
}
/**
* Add new column
*/
function sql_column_add($table_name, $column_name, $column_data, $inline = false)
{
$column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data);
$statements = array();
switch ($this->sql_layer)
{
case 'firebird':
// Does not support AFTER statement, only POSITION (and there you need the column position)
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD "' . strtoupper($column_name) . '" ' . $column_data['column_type_sql'];
break;
case 'mssql':
case 'mssqlnative':
// Does not support AFTER, only through temporary table
$statements[] = 'ALTER TABLE [' . $table_name . '] ADD [' . $column_name . '] ' . $column_data['column_type_sql_default'];
break;
case 'mysql_40':
case 'mysql_41':
$after = (!empty($column_data['after'])) ? ' AFTER ' . $column_data['after'] : '';
$statements[] = 'ALTER TABLE `' . $table_name . '` ADD COLUMN `' . $column_name . '` ' . $column_data['column_type_sql'] . $after;
break;
case 'oracle':
// Does not support AFTER, only through temporary table
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql'];
break;
case 'postgres':
// Does not support AFTER, only through temporary table
if (version_compare($this->db->sql_server_info(true), '8.0', '>='))
{
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type_sql'];
}
else
{
// old versions cannot add columns with default and null information
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type'] . ' ' . $column_data['constraint'];
if (isset($column_data['null']))
{
if ($column_data['null'] == 'NOT NULL')
{
$statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET NOT NULL';
}
}
if (isset($column_data['default']))
{
$statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default'];
}
}
break;
case 'sqlite':
if ($inline && $this->return_statements)
{
return $column_name . ' ' . $column_data['column_type_sql'];
}
if (version_compare(sqlite_libversion(), '3.0') == -1)
{
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table_name}'
ORDER BY type DESC, name;";
$result = $this->db->sql_query($sql);
if (!$result)
{
break;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
$statements[] = 'begin';
// Create a backup table and populate it, destroy the existing one
$statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
$statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
$statements[] = 'DROP TABLE ' . $table_name;
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$new_table_cols = trim($matches[1]);
$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
$column_list = array();
foreach ($old_table_cols as $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY')
{
continue;
}
$column_list[] = $entities[0];
}
$columns = implode(',', $column_list);
$new_table_cols = $column_name . ' ' . $column_data['column_type_sql'] . ',' . $new_table_cols;
// create a new table and fill it up. destroy the temp one
$statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');';
$statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
$statements[] = 'DROP TABLE ' . $table_name . '_temp';
$statements[] = 'commit';
}
else
{
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' [' . $column_data['column_type_sql'] . ']';
}
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Drop column
*/
function sql_column_remove($table_name, $column_name, $inline = false)
{
$statements = array();
switch ($this->sql_layer)
{
case 'firebird':
$statements[] = 'ALTER TABLE ' . $table_name . ' DROP "' . strtoupper($column_name) . '"';
break;
case 'mssql':
case 'mssqlnative':
$statements[] = 'ALTER TABLE [' . $table_name . '] DROP COLUMN [' . $column_name . ']';
break;
case 'mysql_40':
case 'mysql_41':
$statements[] = 'ALTER TABLE `' . $table_name . '` DROP COLUMN `' . $column_name . '`';
break;
case 'oracle':
$statements[] = 'ALTER TABLE ' . $table_name . ' DROP ' . $column_name;
break;
case 'postgres':
$statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN "' . $column_name . '"';
break;
case 'sqlite':
if ($inline && $this->return_statements)
{
return $column_name;
}
if (version_compare(sqlite_libversion(), '3.0') == -1)
{
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table_name}'
ORDER BY type DESC, name;";
$result = $this->db->sql_query($sql);
if (!$result)
{
break;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
$statements[] = 'begin';
// Create a backup table and populate it, destroy the existing one
$statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
$statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
$statements[] = 'DROP TABLE ' . $table_name;
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$new_table_cols = trim($matches[1]);
$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
$column_list = array();
foreach ($old_table_cols as $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY' || $entities[0] === $column_name)
{
continue;
}
$column_list[] = $entities[0];
}
$columns = implode(',', $column_list);
$new_table_cols = $new_table_cols = preg_replace('/' . $column_name . '[^,]+(?:,|$)/m', '', $new_table_cols);
// create a new table and fill it up. destroy the temp one
$statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');';
$statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
$statements[] = 'DROP TABLE ' . $table_name . '_temp';
$statements[] = 'commit';
}
else
{
$statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN ' . $column_name;
}
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Drop Index
*/
function sql_index_drop($table_name, $index_name)
{
$statements = array();
switch ($this->sql_layer)
{
case 'mssql':
case 'mssqlnative':
$statements[] = 'DROP INDEX ' . $table_name . '.' . $index_name;
break;
case 'mysql_40':
case 'mysql_41':
$statements[] = 'DROP INDEX ' . $index_name . ' ON ' . $table_name;
break;
case 'firebird':
case 'oracle':
case 'postgres':
case 'sqlite':
$statements[] = 'DROP INDEX ' . $table_name . '_' . $index_name;
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Add primary key
*/
function sql_create_primary_key($table_name, $column, $inline = false)
{
$statements = array();
switch ($this->sql_layer)
{
case 'firebird':
case 'postgres':
case 'mysql_40':
case 'mysql_41':
$statements[] = 'ALTER TABLE ' . $table_name . ' ADD PRIMARY KEY (' . implode(', ', $column) . ')';
break;
case 'mssql':
case 'mssqlnative':
$sql = "ALTER TABLE [{$table_name}] WITH NOCHECK ADD ";
$sql .= "CONSTRAINT [PK_{$table_name}] PRIMARY KEY CLUSTERED (";
$sql .= '[' . implode("],\n\t\t[", $column) . ']';
$sql .= ') ON [PRIMARY]';
$statements[] = $sql;
break;
case 'oracle':
$statements[] = 'ALTER TABLE ' . $table_name . 'add CONSTRAINT pk_' . $table_name . ' PRIMARY KEY (' . implode(', ', $column) . ')';
break;
case 'sqlite':
if ($inline && $this->return_statements)
{
return $column;
}
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table_name}'
ORDER BY type DESC, name;";
$result = $this->db->sql_query($sql);
if (!$result)
{
break;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
$statements[] = 'begin';
// Create a backup table and populate it, destroy the existing one
$statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
$statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
$statements[] = 'DROP TABLE ' . $table_name;
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$new_table_cols = trim($matches[1]);
$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
$column_list = array();
foreach ($old_table_cols as $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
if ($entities[0] == 'PRIMARY')
{
continue;
}
$column_list[] = $entities[0];
}
$columns = implode(',', $column_list);
// create a new table and fill it up. destroy the temp one
$statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ', PRIMARY KEY (' . implode(', ', $column) . '));';
$statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
$statements[] = 'DROP TABLE ' . $table_name . '_temp';
$statements[] = 'commit';
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Add unique index
*/
function sql_create_unique_index($table_name, $index_name, $column)
{
$statements = array();
switch ($this->sql_layer)
{
case 'firebird':
case 'postgres':
case 'oracle':
case 'sqlite':
$statements[] = 'CREATE UNIQUE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
break;
case 'mysql_40':
case 'mysql_41':
$statements[] = 'CREATE UNIQUE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
break;
case 'mssql':
case 'mssqlnative':
$statements[] = 'CREATE UNIQUE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]';
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Add index
*/
function sql_create_index($table_name, $index_name, $column)
{
$statements = array();
// remove index length unless MySQL4
if ('mysql_40' != $this->sql_layer)
{
$column = preg_replace('#:.*$#', '', $column);
}
switch ($this->sql_layer)
{
case 'firebird':
case 'postgres':
case 'oracle':
case 'sqlite':
$statements[] = 'CREATE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
break;
case 'mysql_40':
// add index size to definition as required by MySQL4
foreach ($column as $i => $col)
{
if (false !== strpos($col, ':'))
{
list($col, $index_size) = explode(':', $col);
$column[$i] = "$col($index_size)";
}
}
// no break
case 'mysql_41':
$statements[] = 'CREATE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
break;
case 'mssql':
case 'mssqlnative':
$statements[] = 'CREATE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]';
break;
}
return $this->_sql_run_sql($statements);
}
/**
* Change column type (not name!)
*/
function sql_column_change($table_name, $column_name, $column_data, $inline = false)
{
$column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data);
$statements = array();
switch ($this->sql_layer)
{
case 'firebird':
// Change type...
if (!empty($column_data['column_type_sql_default']))
{
$statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" TYPE ' . ' ' . $column_data['column_type_sql_type'];
$statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" SET DEFAULT ' . ' ' . $column_data['column_type_sql_default'];
}
else
{
// TODO: try to change pkey without removing trigger, generator or constraints. ATM this query may fail.
$statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" TYPE ' . ' ' . $column_data['column_type_sql_type'];
}
break;
case 'mssql':
case 'mssqlnative':
$statements[] = 'ALTER TABLE [' . $table_name . '] ALTER COLUMN [' . $column_name . '] ' . $column_data['column_type_sql'];
if (!empty($column_data['default']))
{
// Using TRANSACT-SQL for this statement because we do not want to have colliding data if statements are executed at a later stage
$statements[] = "DECLARE @drop_default_name VARCHAR(100), @cmd VARCHAR(1000)
SET @drop_default_name =
(SELECT so.name FROM sysobjects so
JOIN sysconstraints sc ON so.id = sc.constid
WHERE object_name(so.parent_obj) = '{$table_name}'
AND so.xtype = 'D'
AND sc.colid = (SELECT colid FROM syscolumns
WHERE id = object_id('{$table_name}')
AND name = '{$column_name}'))
IF @drop_default_name <> ''
BEGIN
SET @cmd = 'ALTER TABLE [{$table_name}] DROP CONSTRAINT [' + @drop_default_name + ']'
EXEC(@cmd)
END
SET @cmd = 'ALTER TABLE [{$table_name}] ADD CONSTRAINT [DF_{$table_name}_{$column_name}_1] {$column_data['default']} FOR [{$column_name}]'
EXEC(@cmd)";
}
break;
case 'mysql_40':
case 'mysql_41':
$statements[] = 'ALTER TABLE `' . $table_name . '` CHANGE `' . $column_name . '` `' . $column_name . '` ' . $column_data['column_type_sql'];
break;
case 'oracle':
$statements[] = 'ALTER TABLE ' . $table_name . ' MODIFY ' . $column_name . ' ' . $column_data['column_type_sql'];
break;
case 'postgres':
$sql = 'ALTER TABLE ' . $table_name . ' ';
$sql_array = array();
$sql_array[] = 'ALTER COLUMN ' . $column_name . ' TYPE ' . $column_data['column_type'];
if (isset($column_data['null']))
{
if ($column_data['null'] == 'NOT NULL')
{
$sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET NOT NULL';
}
else if ($column_data['null'] == 'NULL')
{
$sql_array[] = 'ALTER COLUMN ' . $column_name . ' DROP NOT NULL';
}
}
if (isset($column_data['default']))
{
$sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default'];
}
// we don't want to double up on constraints if we change different number data types
if (isset($column_data['constraint']))
{
$constraint_sql = "SELECT consrc as constraint_data
FROM pg_constraint, pg_class bc
WHERE conrelid = bc.oid
AND bc.relname = '{$table_name}'
AND NOT EXISTS (
SELECT *
FROM pg_constraint as c, pg_inherits as i
WHERE i.inhrelid = pg_constraint.conrelid
AND c.conname = pg_constraint.conname
AND c.consrc = pg_constraint.consrc
AND c.conrelid = i.inhparent
)";
$constraint_exists = false;
$result = $this->db->sql_query($constraint_sql);
while ($row = $this->db->sql_fetchrow($result))
{
if (trim($row['constraint_data']) == trim($column_data['constraint']))
{
$constraint_exists = true;
break;
}
}
$this->db->sql_freeresult($result);
if (!$constraint_exists)
{
$sql_array[] = 'ADD ' . $column_data['constraint'];
}
}
$sql .= implode(', ', $sql_array);
$statements[] = $sql;
break;
case 'sqlite':
if ($inline && $this->return_statements)
{
return $column_name . ' ' . $column_data['column_type_sql'];
}
$sql = "SELECT sql
FROM sqlite_master
WHERE type = 'table'
AND name = '{$table_name}'
ORDER BY type DESC, name;";
$result = $this->db->sql_query($sql);
if (!$result)
{
break;
}
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
$statements[] = 'begin';
// Create a temp table and populate it, destroy the existing one
$statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
$statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
$statements[] = 'DROP TABLE ' . $table_name;
preg_match('#\((.*)\)#s', $row['sql'], $matches);
$new_table_cols = trim($matches[1]);
$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
$column_list = array();
foreach ($old_table_cols as $key => $declaration)
{
$entities = preg_split('#\s+#', trim($declaration));
$column_list[] = $entities[0];
if ($entities[0] == $column_name)
{
$old_table_cols[$key] = $column_name . ' ' . $column_data['column_type_sql'];
}
}
$columns = implode(',', $column_list);
// create a new table and fill it up. destroy the temp one
$statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $old_table_cols) . ');';
$statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
$statements[] = 'DROP TABLE ' . $table_name . '_temp';
$statements[] = 'commit';
break;
}
return $this->_sql_run_sql($statements);
}
}
|