aboutsummaryrefslogtreecommitdiffstats
path: root/find-provides.in
blob: 64ad4798dc0ab63daf3166dd2b2c13a6427ce60d (plain)
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
#!/bin/bash

# This script reads filenames from STDIN and outputs any relevant provides
# information that needs to be included in the package.

filelist=`sed "s/['\"]/\\\&/g"`

solist=$(echo "$filelist" | egrep -v "^/lib/ld\.so|/usr/lib(64)?/gcj/" | egrep '(/usr(/X11R6)?)?/lib(64)?/.*\.so' | \
	xargs file -L 2>/dev/null | grep "ELF.*shared object" | cut -d: -f1)
pythonlist=
tcllist=
rubygemlist=$(echo "$filelist"| egrep "\.gemspec$")                                                                                                         
mavenlist=$(echo "$filelist" |egrep '/usr/share/maven-fragments/*')
osgilist=$(echo "$filelist" |egrep "^(.*\.jar|((/usr/lib(64)|/usr/share).*/MANIFEST.MF))")

# fix parsing output of objdump when localized (mga#7883):
export LC_ALL=C

#
# --- Alpha does not mark 64bit dependencies
case `uname -m` in
  alpha*)	mark64="" ;;
  *)		mark64="()(64bit)" ;;
esac

#
# --- Library sonames and weak symbol versions (from glibc).
for f in $solist; do
    soname=$(objdump -p $f 2>/dev/null | awk '/SONAME/ {print $2}')

    lib64=`if file -L $f 2>/dev/null | \
	grep "ELF 64-bit" >/dev/null; then echo "$mark64"; fi`
    if [ "$soname" != "" ]; then
	if [ ! -L $f ]; then
	    echo $soname$lib64
	    objdump -p $f 2>/dev/null | awk '
		BEGIN { START=0 ; }
		/Version definitions:/ { START=1; }
		/^[0-9]/ && (START==1) { print $4; }
		/^$/ { START=0; }
	    ' | \
		grep -v $soname | \
		while read symbol ; do
		    echo "$soname($symbol)`echo $lib64 | sed 's/()//'`"
		done
	fi
    else
	echo ${f##*/}$lib64
    fi
done | sort -u

#
# --- If libperl.so is found in buildroot, we provide perlapi-<version>
if [ -n "`echo $filelist | grep -e '/CORE/libperl\.so'`" ]; then
    for i in $filelist; do
        if [ -n "`echo $i | grep -e '/CORE/libperl\.so\$'`" ]; then
            perlpath=$i
            version=${i/CORE*/}
            version=$(echo $version| sed -e 's!/$!!' -e 's!/[^/]*$!!' -e 's!.*/!!')
            minor=$(echo $version| sed -e 's!^.*\.!!')
            major=$(echo $version| sed -e 's!\.[0-9]*$!!')
            if [ -n "$version" ] && [ -n "$minor" ]; then
               for i in $(seq 0 $minor); do echo "perlapi-$major.$i"; done
            fi
        fi
    done
fi

#
# --- Perl modules.
[ -x @RPMVENDORDIR@/perl.prov ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/perl.prov | grep 'perl([[:upper:]]' | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/perl.prov failed' >&2 && exit 1

#
# --- Python modules.
[ -x @RPMVENDORDIR@/pythoneggs.py -a -n "$filelist" ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/pythoneggs.py --provides | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/pythoneggs.py failed' >&2 && exit 1

#
# --- Tcl modules.
[ -x @RPMVENDORDIR@/tcl.prov -a -n "$tcllist" ] &&
    echo "$tcllist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/tcl.prov | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/tcl.prov failed' >&2 && exit 1

#
# --- Php modules.
[ -x @RPMVENDORDIR@/php.prov ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/php.prov | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/php.prov failed' >&2 && exit 1

#
# --- Kernel modules.
[ -x @RPMVENDORDIR@/kmod.prov ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/kmod.prov | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/kmod.prov failed' >&2 && exit 1

#
# --- Pkgconfig deps
[ -x @RPMVENDORDIR@/pkgconfigdeps.sh ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/pkgconfigdeps.sh -P | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/pkgconfigdeps.sh failed' >&2 && exit 1

#
# --- mimehandler
[ -x @RPMLIBDIR@/desktop-file.prov ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMLIBDIR@/desktop-file.prov --provides | sort -u \
        && test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMLIBDIR@/desktop-file.prov failed' >&2 && exit 1

#
# --- fonts
[ -x @RPMLIBDIR@/fontconfig.prov ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMLIBDIR@/fontconfig.prov --provides | sort -u

#
# --- typelib() gobject-introspection bindings
[ -x @RPMVENDORDIR@/gi-find-deps.sh ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/gi-find-deps.sh -P | sort -u \
        && test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/gi-find-deps.sh failed' >&2 && exit 1

if [ -n "$LIBTOOLDEP" ]; then
#
# --- libtooldep deps
[ -x @RPMLIBDIR@/libtooldeps.sh ] &&
    echo "$filelist" | tr '[:blank:]' \\n | @RPMLIBDIR@/libtooldeps.sh -P | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/libtooldeps.sh failed' >&2 && exit 1

fi

#
# --- Ruby gems
[ -x /usr/bin/ruby -a -x @RPMVENDORDIR@/rubygems.rb -a -n "$rubygemlist" ] &&
    echo $rubygemlist | tr '[:blank:]' \\n | @RPMVENDORDIR@/rubygems.rb --provides | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/rubygems.rb failed' >&2 && exit 1

#
# --- .so files.
for i in `echo $filelist | tr '[:blank:]' "\n" | egrep '(/usr(/X11R6)?)?/lib(|64)(/gcc(-lib)?/.+)?/[^/]+\.so$'`; do
    objd=`objdump -p ${i} | grep SONAME`
    [ -h ${i} -a -n "${objd}" ] && \
    lib64=`if file -L $i 2>/dev/null | grep "ELF 64-bit" >/dev/null; then echo "(64bit)"; fi` && \
    echo ${objd} | perl -p -e "s/.*SONAME\s+(\S+)\.so.*/devel(\1$lib64)/g"
done | sort -u

#
# --- mono provides
if [ -x /usr/bin/mono-find-provides ]; then
echo $filelist | tr '[:blank:]' '\n' | /usr/bin/mono-find-provides \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: /usr/bin/mono-find-provides failed' >&2 && exit 1
fi


#
# --- haskell provides
if [ -x /usr/bin/haskell-find-provides ]; then
echo $filelist | tr '[:blank:]' '\n' | /usr/bin/haskell-find-provides \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: /usr/bin/haskell-find-provides failed' >&2 && exit 1
fi

#
# --- gstreamer modules.
[ -x @RPMVENDORDIR@/gstreamer.prov ] &&
    echo "$solist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/gstreamer.prov | sort -u \
    	&& test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/gstreamer.prov failed' >&2 && exit 1

[ -x @RPMVENDORDIR@/gstreamer1.0.prov ] &&
    echo "$solist" | tr '[:blank:]' \\n | @RPMVENDORDIR@/gstreamer1.0.prov | sort -u \
        && test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMVENDORDIR@/gstreamer1.0.prov failed' >&2 && exit 1

#
# --- osgi provides
if [ -x @RPMLIBDIR@/osgi.prov ];then
  if [ ! -z "$osgilist" ]; then
    echo "$osgilist" | tr '[:blank:]' '\n' | @RPMLIBDIR@/osgi.prov \
      && test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMLIBDIR@/osgi.prov failed' >&2 && exit 1
  fi
fi

#
# --- maven provides
if [ -x @RPMLIBDIR@/maven.prov ];then
  if [ ! -z "$mavenlist" ]; then
    echo "$mavenlist" | tr '[:blank:]' '\n' | @RPMLIBDIR@/maven.prov \
        && test ${PIPESTATUS[2]} -ne 0 && echo 'error: @RPMLIBDIR@/maven.prov failed' >&2 && exit 1
  fi
fi

exit 0
n475' href='#n475'>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
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>
#                 Noel Cragg <noel@red-bean.com>

package Bugzilla::Install::DB;

# NOTE: This package may "use" any modules that it likes,
# localconfig is available, and params are up to date. 

use strict;

use Bugzilla::Bug qw(is_open_state);
use Bugzilla::Constants;
use Bugzilla::Hook;
use Bugzilla::Util;
use Bugzilla::Series;

use Date::Parse;
use Date::Format;
use IO::File;

use base qw(Exporter);
our @EXPORT_OK = qw(
    indicate_progress
);

sub indicate_progress {
    my ($params) = @_;
    my $current = $params->{current};
    my $total   = $params->{total};
    my $every   = $params->{every} || 1;

    print "." if !($current % $every);
    if ($current % ($every * 60) == 0) {
        print "$current/$total (" . int($current * 100 / $total) . "%)\n";
    }
}

# NOTE: This is NOT the function for general table updates. See
# update_table_definitions for that. This is only for the fielddefs table.
sub update_fielddefs_definition {
    my $dbh = Bugzilla->dbh;

    # 2005-02-21 - LpSolit@gmail.com - Bug 279910
    # qacontact_accessible and assignee_accessible field names no longer exist
    # in the 'bugs' table. Their corresponding entries in the 'bugs_activity'
    # table should therefore be marked as obsolete, meaning that they cannot
    # be used anymore when querying the database - they are not deleted in
    # order to keep track of these fields in the activity table.
    if (!$dbh->bz_column_info('fielddefs', 'obsolete')) {
        $dbh->bz_add_column('fielddefs', 'obsolete',
            {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});
        print "Marking qacontact_accessible and assignee_accessible as",
              " obsolete fields...\n";
        $dbh->do("UPDATE fielddefs SET obsolete = 1
                  WHERE name = 'qacontact_accessible'
                        OR name = 'assignee_accessible'");
    }

    # 2005-08-10 Myk Melez <myk@mozilla.org> bug 287325
    # Record each field's type and whether or not it's a custom field,
    # in fielddefs.
    $dbh->bz_add_column('fielddefs', 'type',
                        {TYPE => 'INT2', NOTNULL => 1, DEFAULT => 0});
    $dbh->bz_add_column('fielddefs', 'custom',
        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});

    $dbh->bz_add_column('fielddefs', 'enter_bug',
        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});

    # Change the name of the fieldid column to id, so that fielddefs
    # can use Bugzilla::Object easily. We have to do this up here, because
    # otherwise adding these field definitions will fail.
    $dbh->bz_rename_column('fielddefs', 'fieldid', 'id');

    # If the largest fielddefs sortkey is less than 100, then
    # we're using the old sorting system, and we should convert
    # it to the new one before adding any new definitions.
    if (!$dbh->selectrow_arrayref(
            'SELECT COUNT(id) FROM fielddefs WHERE sortkey >= 100'))
    {
        print "Updating the sortkeys for the fielddefs table...\n";
        my $field_ids = $dbh->selectcol_arrayref(
            'SELECT id FROM fielddefs ORDER BY sortkey');
        my $sortkey = 100;
        foreach my $field_id (@$field_ids) {
            $dbh->do('UPDATE fielddefs SET sortkey = ? WHERE id = ?',
                     undef, $sortkey, $field_id);
            $sortkey += 100;
        }
    }

    # Remember, this is not the function for adding general table changes.
    # That is below. Add new changes to the fielddefs table above this
    # comment.
}

# Small changes can be put directly into this function.
# However, larger changes (more than three or four lines) should
# go into their own private subroutine, and you should call that
# subroutine from this function. That keeps this function readable.
#
# This function runs in historical order--from upgrades that older
# installations need, to upgrades that newer installations need.
# The order of items inside this function should only be changed if 
# absolutely necessary.
#
# The subroutines should have long, descriptive names, so that you
# can easily see what is being done, just by reading this function.
#
# This function is mostly self-documenting. If you're curious about
# what each of the added/removed columns does, you should see the schema 
# docs at:
# http://www.ravenbrook.com/project/p4dti/tool/cgi/bugzilla-schema/
#
# When you add a change, you should only add a comment if you want
# to describe why the change was made. You don't need to describe
# the purpose of a column.
#
sub update_table_definitions {
    my $dbh = Bugzilla->dbh;
    _update_pre_checksetup_bugzillas();

    $dbh->bz_add_column('attachments', 'submitter_id',
                        {TYPE => 'INT3', NOTNULL => 1}, 0); 

    $dbh->bz_rename_column('bugs_activity', 'when', 'bug_when');

    _add_bug_vote_cache();
    _update_product_name_definition();
    _add_bug_keyword_cache();

    $dbh->bz_add_column('profiles', 'disabledtext',
                        {TYPE => 'MEDIUMTEXT', NOTNULL => 1}, '');

    _populate_longdescs();
    _update_bugs_activity_field_to_fieldid();

    if (!$dbh->bz_column_info('bugs', 'lastdiffed')) {
        $dbh->bz_add_column('bugs', 'lastdiffed', {TYPE =>'DATETIME'});
        $dbh->do('UPDATE bugs SET lastdiffed = NOW()');
    }

    _add_unique_login_name_index_to_profiles();

    $dbh->bz_add_column('profiles', 'mybugslink', 
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'});

    _update_component_user_fields_to_ids();

    $dbh->bz_add_column('bugs', 'everconfirmed',
                        {TYPE => 'BOOLEAN', NOTNULL => 1}, 1);

    $dbh->bz_add_column('products', 'maxvotesperbug',
                        {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '10000'});
    $dbh->bz_add_column('products', 'votestoconfirm',
                        {TYPE => 'INT2', NOTNULL => 1}, 0);

    _populate_milestones_table();

    # 2000-03-22 Changed the default value for target_milestone to be "---"
    # (which is still not quite correct, but much better than what it was
    # doing), and made the size of the value field in the milestones table match
    # the size of the target_milestone field in the bugs table.
    $dbh->bz_alter_column('bugs', 'target_milestone',
        {TYPE => 'varchar(20)', NOTNULL => 1, DEFAULT => "'---'"});
    $dbh->bz_alter_column('milestones', 'value',
                          {TYPE => 'varchar(20)', NOTNULL => 1});

    _add_products_defaultmilestone();

    # 2000-03-24 Added unique indexes into the cc and keyword tables.  This
    # prevents certain database inconsistencies, and, moreover, is required for
    # new generalized list code to work.
    if (!$dbh->bz_index_info('cc', 'cc_bug_id_idx')
        || !$dbh->bz_index_info('cc', 'cc_bug_id_idx')->{TYPE})
    {
        $dbh->bz_drop_index('cc', 'cc_bug_id_idx');
        $dbh->bz_add_index('cc', 'cc_bug_id_idx',
                           {TYPE => 'UNIQUE', FIELDS => [qw(bug_id who)]});
    }
    if (!$dbh->bz_index_info('keywords', 'keywords_bug_id_idx')
        || !$dbh->bz_index_info('keywords', 'keywords_bug_id_idx')->{TYPE})
    {
        $dbh->bz_drop_index('keywords', 'keywords_bug_id_idx');
        $dbh->bz_add_index('keywords', 'keywords_bug_id_idx',
            {TYPE => 'UNIQUE', FIELDS => [qw(bug_id keywordid)]});
    }

    _copy_from_comments_to_longdescs();
    _populate_duplicates_table();

    if (!$dbh->bz_column_info('email_setting', 'user_id')) {
        $dbh->bz_add_column('profiles', 'emailflags', {TYPE => 'MEDIUMTEXT'});
    }

    $dbh->bz_add_column('groups', 'isactive',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'});

    $dbh->bz_add_column('attachments', 'isobsolete',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});

    $dbh->bz_drop_column("profiles", "emailnotification");
    $dbh->bz_drop_column("profiles", "newemailtech");

    # 2003-11-19; chicks@chicks.net; bug 225973: fix field size to accommodate
    # wider algorithms such as Blowfish. Note that this needs to be run
    # before recrypting passwords in the following block.
    $dbh->bz_alter_column('profiles', 'cryptpassword',
                          {TYPE => 'varchar(128)'});

    _recrypt_plaintext_passwords();

    # 2001-06-15 kiko@async.com.br - Change bug:version size to avoid
    # truncates re http://bugzilla.mozilla.org/show_bug.cgi?id=9352
    $dbh->bz_alter_column('bugs', 'version',
                          {TYPE => 'varchar(64)', NOTNULL => 1});

    _update_bugs_activity_to_only_record_changes();

    # bug 90933: Make disabledtext NOT NULL
    if (!$dbh->bz_column_info('profiles', 'disabledtext')->{NOTNULL}) {
        $dbh->bz_alter_column("profiles", "disabledtext",
                              {TYPE => 'MEDIUMTEXT', NOTNULL => 1}, '');
    }

    $dbh->bz_add_column("bugs", "reporter_accessible",
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'});
    $dbh->bz_add_column("bugs", "cclist_accessible",
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'});

    $dbh->bz_add_column("bugs_activity", "attach_id", {TYPE => 'INT3'});

    _delete_logincookies_cryptpassword_and_handle_invalid_cookies();

    # qacontact/assignee should always be able to see bugs: bug 97471
    $dbh->bz_drop_column("bugs", "qacontact_accessible");
    $dbh->bz_drop_column("bugs", "assignee_accessible");

    # 2002-02-20 jeff.hedlund@matrixsi.com - bug 24789 time tracking
    $dbh->bz_add_column("longdescs", "work_time",
                        {TYPE => 'decimal(5,2)', NOTNULL => 1, DEFAULT => '0'});
    $dbh->bz_add_column("bugs", "estimated_time",
                        {TYPE => 'decimal(5,2)', NOTNULL => 1, DEFAULT => '0'});
    $dbh->bz_add_column("bugs", "remaining_time",
                        {TYPE => 'decimal(5,2)', NOTNULL => 1, DEFAULT => '0'});
    $dbh->bz_add_column("bugs", "deadline", {TYPE => 'DATETIME'});

    _use_ip_instead_of_hostname_in_logincookies();

    $dbh->bz_add_column('longdescs', 'isprivate',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});
    $dbh->bz_add_column('attachments', 'isprivate',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});

    $dbh->bz_add_column("bugs", "alias", {TYPE => "varchar(20)"});
    $dbh->bz_add_index('bugs', 'bugs_alias_idx',
                       {TYPE => 'UNIQUE', FIELDS => [qw(alias)]});

    _move_quips_into_db();

    $dbh->bz_drop_column("namedqueries", "watchfordiffs");

    _use_ids_for_products_and_components();
    _convert_groups_system_from_groupset();
    _convert_attachment_statuses_to_flags();
    _remove_spaces_and_commas_from_flagtypes();
    _setup_usebuggroups_backward_compatibility();
    _remove_user_series_map();

    # 2006-08-03 remi_zara@mac.com bug 346241, make series.creator nullable
    # This must happen before calling _copy_old_charts_into_database().
    if ($dbh->bz_column_info('series', 'creator')->{NOTNULL}) {
        $dbh->bz_alter_column('series', 'creator', {TYPE => 'INT3'});
        $dbh->do("UPDATE series SET creator = NULL WHERE creator = 0");
    }

    _copy_old_charts_into_database();

    _add_user_group_map_grant_type();
    _add_group_group_map_grant_type();

    $dbh->bz_add_column("profiles", "extern_id", {TYPE => 'varchar(64)'});

    $dbh->bz_add_column('flagtypes', 'grant_group_id', {TYPE => 'INT3'});
    $dbh->bz_add_column('flagtypes', 'request_group_id', {TYPE => 'INT3'});

    # mailto is no longer just userids
    $dbh->bz_rename_column('whine_schedules', 'mailto_userid', 'mailto');
    $dbh->bz_add_column('whine_schedules', 'mailto_type',
        {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '0'});

    _add_longdescs_already_wrapped();

    # Moved enum types to separate tables so we need change the old enum 
    # types to standard varchars in the bugs table.
    $dbh->bz_alter_column('bugs', 'bug_status',
                          {TYPE => 'varchar(64)', NOTNULL => 1});
    # 2005-03-23 Tomas.Kopal@altap.cz - add default value to resolution,
    # bug 286695
    $dbh->bz_alter_column('bugs', 'resolution',
        {TYPE => 'varchar(64)', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_alter_column('bugs', 'priority',
                          {TYPE => 'varchar(64)', NOTNULL => 1});
    $dbh->bz_alter_column('bugs', 'bug_severity',
                          {TYPE => 'varchar(64)', NOTNULL => 1});
    $dbh->bz_alter_column('bugs', 'rep_platform',
                          {TYPE => 'varchar(64)', NOTNULL => 1}, '');
    $dbh->bz_alter_column('bugs', 'op_sys',
                          {TYPE => 'varchar(64)', NOTNULL => 1});

    # When migrating quips from the '$datadir/comments' file to the DB,
    # the user ID should be NULL instead of 0 (which is an invalid user ID).
    if ($dbh->bz_column_info('quips', 'userid')->{NOTNULL}) {
        $dbh->bz_alter_column('quips', 'userid', {TYPE => 'INT3'});
        print "Changing owner to NULL for quips where the owner is",
              " unknown...\n";
        $dbh->do('UPDATE quips SET userid = NULL WHERE userid = 0');
    }

    # Right now, we only create the "thetext" index on MySQL.
    if ($dbh->isa('Bugzilla::DB::Mysql')) {
        $dbh->bz_add_index('longdescs', 'longdescs_thetext_idx',
                           {TYPE => 'FULLTEXT', FIELDS => [qw(thetext)]});
    }

    _convert_attachments_filename_from_mediumtext();

    $dbh->bz_add_column('quips', 'approved',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'});

    # 2002-12-20 Bug 180870 - remove manual shadowdb replication code
    $dbh->bz_drop_table("shadowlog");

    _rename_votes_count_and_force_group_refresh();

    # 2004/02/15 - Summaries shouldn't be null - see bug 220232
    if (!exists $dbh->bz_column_info('bugs', 'short_desc')->{NOTNULL}) {
        $dbh->bz_alter_column('bugs', 'short_desc',
                              {TYPE => 'MEDIUMTEXT', NOTNULL => 1}, '');
    }

    $dbh->bz_add_column('products', 'classification_id',
                        {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '1'});

    _fix_group_with_empty_name();

    $dbh->bz_add_index('bugs_activity', 'bugs_activity_who_idx', [qw(who)]);

    # Add defaults for some fields that should have them but didn't.
    $dbh->bz_alter_column('bugs', 'status_whiteboard',
        {TYPE => 'MEDIUMTEXT', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_alter_column('bugs', 'keywords',
        {TYPE => 'MEDIUMTEXT', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_alter_column('bugs', 'votes',
                          {TYPE => 'INT3', NOTNULL => 1, DEFAULT => '0'});

    $dbh->bz_alter_column('bugs', 'lastdiffed', {TYPE => 'DATETIME'});

    # 2005-03-09 qa_contact should be NULL instead of 0, bug 285534
    if ($dbh->bz_column_info('bugs', 'qa_contact')->{NOTNULL}) {
        $dbh->bz_alter_column('bugs', 'qa_contact', {TYPE => 'INT3'});
        $dbh->do("UPDATE bugs SET qa_contact = NULL WHERE qa_contact = 0");
    }

    # 2005-03-27 initialqacontact should be NULL instead of 0, bug 287483
    if ($dbh->bz_column_info('components', 'initialqacontact')->{NOTNULL}) {
        $dbh->bz_alter_column('components', 'initialqacontact', 
                              {TYPE => 'INT3'});
        $dbh->do("UPDATE components SET initialqacontact = NULL " .
                  "WHERE initialqacontact = 0");
    }

    _migrate_email_prefs_to_new_table();
    _initialize_dependency_tree_changes_email_pref();
    _change_all_mysql_booleans_to_tinyint();

    # make classification_id field type be consistent with DB:Schema
    $dbh->bz_alter_column('products', 'classification_id',
                          {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '1'});

    # initialowner was accidentally NULL when we checked-in Schema,
    # when it really should be NOT NULL.
    $dbh->bz_alter_column('components', 'initialowner',
                          {TYPE => 'INT3', NOTNULL => 1}, 0);

    # 2005-03-28 - bug 238800 - index flags.type_id for editflagtypes.cgi
    $dbh->bz_add_index('flags', 'flags_type_id_idx', [qw(type_id)]);

    # For a short time, the flags_type_id_idx was misnamed in upgraded installs.
    $dbh->bz_drop_index('flags', 'type_id');

    # 2005-04-28 - LpSolit@gmail.com - Bug 7233: add an index to versions
    $dbh->bz_alter_column('versions', 'value',
                          {TYPE => 'varchar(64)', NOTNULL => 1});
    _add_versions_product_id_index();

    if (!exists $dbh->bz_column_info('milestones', 'sortkey')->{DEFAULT}) {
        $dbh->bz_alter_column('milestones', 'sortkey',
                              {TYPE => 'INT2', NOTNULL => 1, DEFAULT => 0});
    }

    # 2005-06-14 - LpSolit@gmail.com - Bug 292544
    $dbh->bz_alter_column('bugs', 'creation_ts', {TYPE => 'DATETIME'});

    _fix_whine_queries_title_and_op_sys_value();
    _fix_attachments_submitter_id_idx();
    _copy_attachments_thedata_to_attach_data();
    _fix_broken_all_closed_series();

    # 2005-08-14 bugreport@peshkin.net -- Bug 304583
    # Get rid of leftover DERIVED group permissions
    use constant GRANT_DERIVED => 1;
    $dbh->do("DELETE FROM user_group_map WHERE grant_type = " . GRANT_DERIVED);

    # PUBLIC is a reserved word in Oracle.
    $dbh->bz_rename_column('series', 'public', 'is_public');

    # 2005-09-28 bugreport@peshkin.net Bug 149504
    $dbh->bz_add_column('attachments', 'isurl',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 0});

    # 2005-10-21 LpSolit@gmail.com - Bug 313020
    $dbh->bz_add_column('namedqueries', 'query_type',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 0});

    # 2005-11-04 LpSolit@gmail.com - Bug 305927
    $dbh->bz_alter_column('groups', 'userregexp',
                          {TYPE => 'TINYTEXT', NOTNULL => 1, DEFAULT => "''"});

    # 2005-09-26 - olav@bkor.dhs.org - Bug 119524
    $dbh->bz_alter_column('logincookies', 'cookie',
        {TYPE => 'varchar(16)', PRIMARYKEY => 1, NOTNULL => 1}); 

    _clean_control_characters_from_short_desc();
    
    # 2005-12-07 altlst@sonic.net -- Bug 225221
    $dbh->bz_add_column('longdescs', 'comment_id',
        {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1});

    _stop_storing_inactive_flags();
    _change_short_desc_from_mediumtext_to_varchar();

    # 2006-07-01 wurblzap@gmail.com -- Bug 69000
    $dbh->bz_add_column('namedqueries', 'id',
        {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1});
    _move_namedqueries_linkinfooter_to_its_own_table();

    _add_classifications_sortkey();
    _move_data_nomail_into_db();

    # The products table lacked sensible defaults.
    $dbh->bz_alter_column('products', 'milestoneurl',
                          {TYPE => 'TINYTEXT', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_alter_column('products', 'disallownew',
                          {TYPE => 'BOOLEAN', NOTNULL => 1,  DEFAULT => 0});
    $dbh->bz_alter_column('products', 'votesperuser', 
                          {TYPE => 'INT2', NOTNULL => 1, DEFAULT => 0});
    $dbh->bz_alter_column('products', 'votestoconfirm',
                          {TYPE => 'INT2', NOTNULL => 1, DEFAULT => 0});

    # 2006-08-04 LpSolit@gmail.com - Bug 305941
    $dbh->bz_drop_column('profiles', 'refreshed_when');
    $dbh->bz_drop_column('groups', 'last_changed');

    # 2006-08-06 LpSolit@gmail.com - Bug 347521
    $dbh->bz_alter_column('flagtypes', 'id',
          {TYPE => 'SMALLSERIAL', NOTNULL => 1, PRIMARYKEY => 1});

    $dbh->bz_alter_column('keyworddefs', 'id',
        {TYPE => 'SMALLSERIAL', NOTNULL => 1, PRIMARYKEY => 1});

    # 2006-08-19 LpSolit@gmail.com - Bug 87795
    $dbh->bz_alter_column('tokens', 'userid', {TYPE => 'INT3'});

    $dbh->bz_drop_index('bugs', 'bugs_short_desc_idx');

    # The profiles table was missing some defaults.
    $dbh->bz_alter_column('profiles', 'disabledtext',
        {TYPE => 'MEDIUMTEXT', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_alter_column('profiles', 'realname',
        {TYPE => 'varchar(255)', NOTNULL => 1, DEFAULT => "''"});

    _update_longdescs_who_index();

    $dbh->bz_add_column('setting', 'subclass', {TYPE => 'varchar(32)'});

    $dbh->bz_alter_column('longdescs', 'thetext', 
        { TYPE => 'MEDIUMTEXT', NOTNULL => 1 }, '');

    # 2006-10-20 LpSolit@gmail.com - Bug 189627
    $dbh->bz_add_column('group_control_map', 'editcomponents',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});
    $dbh->bz_add_column('group_control_map', 'editbugs',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});
    $dbh->bz_add_column('group_control_map', 'canconfirm',
                        {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'FALSE'});

    # 2006-11-07 LpSolit@gmail.com - Bug 353656
    $dbh->bz_add_column('longdescs', 'type',
                        {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '0'});
    $dbh->bz_add_column('longdescs', 'extra_data', {TYPE => 'varchar(255)'});

    $dbh->bz_add_column('versions', 'id', 
        {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1});
    $dbh->bz_add_column('milestones', 'id',
        {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1});

    ################################################################
    # New --TABLE-- changes should go *** A B O V E *** this point #
    ################################################################

    Bugzilla::Hook::process('install-update_db');
}

# Subroutines should be ordered in the order that they are called.
# Thus, newer subroutines should be at the bottom.

sub _update_pre_checksetup_bugzillas {
    my $dbh = Bugzilla->dbh;
    # really old fields that were added before checksetup.pl existed
    # but aren't in very old bugzilla's (like 2.1)
    # Steve Stock (sstock@iconnect-inc.com)

    $dbh->bz_add_column('bugs', 'target_milestone',
        {TYPE => 'varchar(20)', NOTNULL => 1, DEFAULT => "'---'"});
    $dbh->bz_add_column('bugs', 'qa_contact', {TYPE => 'INT3'});
    $dbh->bz_add_column('bugs', 'status_whiteboard',
                       {TYPE => 'MEDIUMTEXT', NOTNULL => 1, DEFAULT => "''"});
    $dbh->bz_add_column('products', 'disallownew',
                        {TYPE => 'BOOLEAN', NOTNULL => 1}, 0);
    $dbh->bz_add_column('products', 'milestoneurl',
                        {TYPE => 'TINYTEXT', NOTNULL => 1}, '');
    $dbh->bz_add_column('components', 'initialqacontact',
                        {TYPE => 'TINYTEXT'});
    $dbh->bz_add_column('components', 'description',
                        {TYPE => 'MEDIUMTEXT', NOTNULL => 1}, '');
}

sub _add_bug_vote_cache {
    my $dbh = Bugzilla->dbh;
    # 1999-10-11 Restructured voting database to add a cached value in each 
    # bug recording how many total votes that bug has.  While I'm at it, 
    # I removed the unused "area" field from the bugs database.  It is 
    # distressing to realize that the bugs table has reached the maximum 
    # number of indices allowed by MySQL (16), which may make future 
    # enhancements awkward.
    # (P.S. All is not lost; it appears that the latest betas of MySQL 
    # support a new table format which will allow 32 indices.)

    $dbh->bz_drop_column('bugs', 'area');
    if (!$dbh->bz_column_info('bugs', 'votes')) {
        $dbh->bz_add_column('bugs', 'votes', {TYPE => 'INT3', NOTNULL => 1,
                                              DEFAULT => 0});
        $dbh->bz_add_index('bugs', 'bugs_votes_idx', [qw(votes)]);
    }
    $dbh->bz_add_column('products', 'votesperuser',
                        {TYPE => 'INT2', NOTNULL => 1}, 0);
}

sub _update_product_name_definition {
    my $dbh = Bugzilla->dbh;
    # The product name used to be very different in various tables.
    #
    # It was   varchar(16)   in bugs
    #          tinytext      in components
    #          tinytext      in products
    #          tinytext      in versions
    #
    # tinytext is equivalent to varchar(255), which is quite huge, so I change
    # them all to varchar(64).

    # Only do this if these fields still exist - they're removed in
    # a later change
    if ($dbh->bz_column_info('products', 'product')) {
        $dbh->bz_alter_column('bugs',       'product',
                             {TYPE => 'varchar(64)', NOTNULL => 1});
        $dbh->bz_alter_column('components', 'program', {TYPE => 'varchar(64)'});
        $dbh->bz_alter_column('products',   'product', {TYPE => 'varchar(64)'});
        $dbh->bz_alter_column('versions',   'program',
                              {TYPE => 'varchar(64)', NOTNULL => 1});
    }
}

sub _add_bug_keyword_cache {
    my $dbh = Bugzilla->dbh;
    # 2000-01-16 Added a "keywords" field to the bugs table, which
    # contains a string copy of the entries of the keywords table for this
    # bug.  This is so that I can easily sort and display a keywords
    # column in bug lists.

    if (!$dbh->bz_column_info('bugs', 'keywords')) {
        $dbh->bz_add_column('bugs', 'keywords',
            {TYPE => 'MEDIUMTEXT', NOTNULL => 1, DEFAULT => "''"});

        my @kwords;
        print "Making sure 'keywords' field of table 'bugs' is empty...\n";
        $dbh->do("UPDATE bugs SET keywords = '' WHERE keywords != ''");
        print "Repopulating 'keywords' field of table 'bugs'...\n";
        my $sth = $dbh->prepare("SELECT keywords.bug_id, keyworddefs.name " .
                                  "FROM keywords, keyworddefs " .
                                 "WHERE keyworddefs.id = keywords.keywordid " .
                              "ORDER BY keywords.bug_id, keyworddefs.name");
        $sth->execute;
        my @list;
        my $bugid = 0;
        my @row;
        while (1) {
            my ($b, $k) = ($sth->fetchrow_array());
            if (!defined $b || $b ne $bugid) {
                if (@list) {
                    $dbh->do("UPDATE bugs SET keywords = " .
                             $dbh->quote(join(', ', @list)) .
                             " WHERE bug_id = $bugid");
                }
                last if !$b;
                $bugid = $b;
                @list = ();
            }
            push(@list, $k);
        }
    }
}

# A helper for the function below.
sub _write_one_longdesc {
    my ($id, $who, $when, $buffer) = (@_);
    my $dbh = Bugzilla->dbh;
    $buffer = trim($buffer);
    return if !$buffer;
    $dbh->do("INSERT INTO longdescs (bug_id, who, bug_when, thetext)
                   VALUES (?,?,?,?)", undef, $id, $who, 
             time2str("%Y/%m/%d %H:%M:%S", $when), $buffer);
}

sub _populate_longdescs {
    my $dbh = Bugzilla->dbh;
    # 2000-01-20 Added a new "longdescs" table, which is supposed to have 
    # all the long descriptions in it, replacing the old long_desc field 
    # in the bugs table. The below hideous code populates this new table 
    # with things from the old field, with ugly parsing and heuristics.

    if ($dbh->bz_column_info('bugs', 'long_desc')) {
        my ($total) = $dbh->selectrow_array("SELECT COUNT(*) FROM bugs");

        print "Populating new long_desc table. This is slow. There are",
              " $total\nbugs to process; a line of dots will be printed",
              " for each 50.\n\n";
        local $| = 1;

        $dbh->bz_lock_tables('bugs write', 'longdescs write', 'profiles write',
                             'bz_schema WRITE');

        $dbh->do('DELETE FROM longdescs');

        my $sth = $dbh->prepare("SELECT bug_id, creation_ts, reporter,
                                        long_desc FROM bugs ORDER BY bug_id");
        $sth->execute();
        my $count = 0;
        while (my ($id, $createtime, $reporterid, $desc) = 
                   $sth->fetchrow_array()) 
        {
            $count++;
            indicate_progress({ total => $total, current => $count });
            $desc =~ s/\r//g;
            my $who = $reporterid;
            my $when = str2time($createtime);
            my $buffer = "";
            foreach my $line (split(/\n/, $desc)) {
                $line =~ s/\s+$//g; # Trim trailing whitespace.
                if ($line =~ /^------- Additional Comments From ([^\s]+)\s+(\d.+\d)\s+-------$/) 
                {
                    my $name = $1;
                    my $date = str2time($2);
                    # Oy, what a hack.  The creation time is accurate to the
                    # second. But the long text only contains things accurate
                    # to the And so, if someone makes a comment within a 
                    # minute of the original bug creation, then the comment can
                    # come *before* the bug creation.  So, we add 59 seconds to
                    # the time of all comments, so that they are always 
                    # considered to have happened at the *end* of the given
                    # minute, not the beginning.
                    $date += 59;
                    if ($date >= $when) {
                        _write_one_longdesc($id, $who, $when, $buffer);
                        $buffer = "";
                        $when = $date;
                        my $s2 = $dbh->prepare("SELECT userid FROM profiles " .
                                                "WHERE login_name = ?");
                        $s2->execute($name);
                        ($who) = ($s2->fetchrow_array());

                        if (!$who) {
                            # This username doesn't exist.  Maybe someone
                            # renamed him or something.  Invent a new profile
                            # entry disabled, just to represent him.
                            $dbh->do("INSERT INTO profiles (login_name, 
                                      cryptpassword, disabledtext) 
                                      VALUES (?,?,?)", undef, $name, '*',
                                      "Account created only to maintain"
                                      . " database integrity");
                            $who = $dbh->bz_last_key('profiles', 'userid');
                        }
                        next;
                    }
                }
                $buffer .= $line . "\n";
            }
            _write_one_longdesc($id, $who, $when, $buffer);
        } # while loop

        print "\n\n";
        $dbh->bz_drop_column('bugs', 'long_desc');
        $dbh->bz_unlock_tables();
    } # main if
}

sub _update_bugs_activity_field_to_fieldid {
    my $dbh = Bugzilla->dbh;

    # 2000-01-18 Added a new table fielddefs that records information about the
    # different fields we keep an activity log on.  The bugs_activity table
    # now has a pointer into that table instead of recording the name directly.
    if ($dbh->bz_column_info('bugs_activity', 'field')) {
        $dbh->bz_add_column('bugs_activity', 'fieldid',
                            {TYPE => 'INT3', NOTNULL => 1}, 0);

        $dbh->bz_add_index('bugs_activity', 'bugs_activity_fieldid_idx',
                           [qw(fieldid)]);
        print "Populating new bugs_activity.fieldid field...\n";

        $dbh->bz_lock_tables('bugs_activity WRITE', 'fielddefs WRITE');


        my $ids = $dbh->selectall_arrayref(
            'SELECT DISTINCT fielddefs.id, bugs_activity.field
               FROM bugs_activity LEFT JOIN fielddefs 
                    ON bugs_activity.field = fielddefs.name', {Slice=>{}});

        foreach my $item (@$ids) {
            my $id    = $item->{id};
            my $field = $item->{field};
            # If the id is NULL
            if (!$id) {
                $dbh->do("INSERT INTO fielddefs (name, description) VALUES " .
                         "(?, ?)", undef, $field, $field);
                $id = $dbh->bz_last_key('fielddefs', 'id');
            }
            $dbh->do("UPDATE bugs_activity SET fieldid = ? WHERE field = ?",
                     undef, $id, $field);
        }
        $dbh->bz_unlock_tables();

        $dbh->bz_drop_column('bugs_activity', 'field');
    }
}

sub _add_unique_login_name_index_to_profiles {
    my $dbh = Bugzilla->dbh;

    # 2000-01-22 The "login_name" field in the "profiles" table was not
    # declared to be unique.  Sure enough, somehow, I got 22 duplicated entries
    # in my database.  This code detects that, cleans up the duplicates, and
    # then tweaks the table to declare the field to be unique.  What a pain.
    if (!$dbh->bz_index_info('profiles', 'profiles_login_name_idx')
        || !$dbh->bz_index_info('profiles', 'profiles_login_name_idx')->{TYPE})
    {
        print "Searching for duplicate entries in the profiles table...\n";
        while (1) {
            # This code is weird in that it loops around and keeps doing this
            # select again.  That's because I'm paranoid about deleting entries
            # out from under us in the profiles table.  Things get weird if
            # there are *three* or more entries for the same user...
            my $sth = $dbh->prepare("SELECT p1.userid, p2.userid, p1.login_name
                                       FROM profiles AS p1, profiles AS p2
                                      WHERE p1.userid < p2.userid
                                            AND p1.login_name = p2.login_name
                                   ORDER BY p1.login_name");
            $sth->execute();
            my ($u1, $u2, $n) = ($sth->fetchrow_array);
            last if !$u1;

            print "Both $u1 & $u2 are ids for $n!  Merging $u2 into $u1...\n";
            foreach my $i (["bugs", "reporter"],
                           ["bugs", "assigned_to"],
                           ["bugs", "qa_contact"],
                           ["attachments", "submitter_id"],
                           ["bugs_activity", "who"],
                           ["cc", "who"],
                           ["votes", "who"],
                           ["longdescs", "who"]) {
                my ($table, $field) = (@$i);
                print "   Updating $table.$field...\n";
                $dbh->do("UPDATE $table SET $field = $u1 " .
                          "WHERE $field = $u2");
            }
            $dbh->do("DELETE FROM profiles WHERE userid = $u2");
        }
        print "OK, changing index type to prevent duplicates in the",
              " future...\n";

        $dbh->bz_drop_index('profiles', 'profiles_login_name_idx');
        $dbh->bz_add_index('profiles', 'profiles_login_name_idx',
                           {TYPE => 'UNIQUE', FIELDS => [qw(login_name)]});
    }
}

sub _update_component_user_fields_to_ids {
    my $dbh = Bugzilla->dbh;

    # components.initialowner
    my $comp_init_owner = $dbh->bz_column_info('components', 'initialowner');
    if ($comp_init_owner && $comp_init_owner->{TYPE} eq 'TINYTEXT') {
        my $sth = $dbh->prepare("SELECT program, value, initialowner
                                   FROM components");
        $sth->execute();
        while (my ($program, $value, $initialowner) = $sth->fetchrow_array()) {
            my ($id) = $dbh->selectrow_array(
                "SELECT userid FROM profiles WHERE login_name = ?",
                undef, $initialowner);

            unless (defined $id) {
                print "Warning: You have an invalid default assignee",
                      " '$initialowner'\n in component '$value' of program",
                      " '$program'!\n";
                $id = 0;
            }

            $dbh->do("UPDATE components SET initialowner = ?
                       WHERE program = ? AND value = ?", undef,
                     $id, $program, $value);
        }
        $dbh->bz_alter_column('components','initialowner',{TYPE => 'INT3'});
    }

    # components.initialqacontact
    my $comp_init_qa = $dbh->bz_column_info('components', 'initialqacontact');
    if ($comp_init_qa && $comp_init_qa->{TYPE} eq 'TINYTEXT') {
        my $sth = $dbh->prepare("SELECT program, value, initialqacontact
                                   FROM components");
        $sth->execute();
        while (my ($program, $value, $initialqacontact) = 
                   $sth->fetchrow_array()) 
        {
            my ($id) = $dbh->selectrow_array(
                "SELECT userid FROM profiles WHERE login_name = ?",
                undef, $initialqacontact);

            unless (defined $id) {
                if ($initialqacontact) {
                    print "Warning: You have an invalid default QA contact",
                          " $initialqacontact' in program '$program',",
                          " component '$value'!\n";
                }
                $id = 0;
            }

            $dbh->do("UPDATE components SET initialqacontact = ?
                       WHERE program = ? AND value = ?", undef,
                     $id, $program, $value);
        }

        $dbh->bz_alter_column('components','initialqacontact',{TYPE => 'INT3'});
    }
}

sub _populate_milestones_table {
    my $dbh = Bugzilla->dbh;
    # 2000-03-21 Adding a table for target milestones to
    # database - matthew@zeroknowledge.com
    # If the milestones table is empty, and we're still back in a Bugzilla
    # that has a bugs.product field, that means that we just created
    # the milestones table and it needs to be populated.
    my $milestones_exist = $dbh->selectrow_array(
        "SELECT DISTINCT 1 FROM milestones");
    if (!$milestones_exist && $dbh->bz_column_info('bugs', 'product')) {
        print "Replacing blank milestones...\n";

        $dbh->do("UPDATE bugs
                     SET target_milestone = '---'
                   WHERE target_milestone = ' '");

        # If we are upgrading from 2.8 or earlier, we will have *created*
        # the milestones table with a product_id field, but Bugzilla expects
        # it to have a "product" field. So we change the field backward so
        # other code can run. The change will be reversed later in checksetup.
        if ($dbh->bz_column_info('milestones', 'product_id')) {
            # Dropping the column leaves us with a milestones_product_id_idx
            # index that is only on the "value" column. We need to drop the
            # whole index so that it can be correctly re-created later.
            $dbh->bz_drop_index('milestones', 'milestones_product_id_idx');
            $dbh->bz_drop_column('milestones', 'product_id');
            $dbh->bz_add_column('milestones', 'product',
                                {TYPE => 'varchar(64)', NOTNULL => 1}, '');
        }

        # Populate the milestone table with all existing values in the database
        my $sth = $dbh->prepare("SELECT DISTINCT target_milestone, product 
                                   FROM bugs");
        $sth->execute();

        print "Populating milestones table...\n";

        while (my ($value, $product) = $sth->fetchrow_array()) {
            # check if the value already exists
            my $sortkey = substr($value, 1);
            if ($sortkey !~ /^\d+$/) {
                $sortkey = 0;
            } else {
                $sortkey *= 10;
            }
            my $ms_exists = $dbh->selectrow_array(
                "SELECT value FROM milestones
                  WHERE value = ? AND product = ?", undef, $value, $product);

            if (!$ms_exists) {
                $dbh->do("INSERT INTO milestones(value, product, sortkey) 
                          VALUES (?,?,?)", undef, $value, $product, $sortkey);
            }
        }
    }
}

sub _add_products_defaultmilestone {
    my $dbh = Bugzilla->dbh;

    # 2000-03-23 Added a defaultmilestone field to the products table, so that
    # we know which milestone to initially assign bugs to.
    if (!$dbh->bz_column_info('products', 'defaultmilestone')) {
        $dbh->bz_add_column('products', 'defaultmilestone',
                 {TYPE => 'varchar(20)', NOTNULL => 1, DEFAULT => "'---'"});
        my $sth = $dbh->prepare(
            "SELECT product, defaultmilestone FROM products");
        $sth->execute();
        while (my ($product, $default_ms) = $sth->fetchrow_array()) {
            my $exists = $dbh->selectrow_array(
                "SELECT value FROM milestones
                  WHERE value = ? AND product = ?", 
                undef, $default_ms, $product);
            if (!$exists) {
                $dbh->do("INSERT INTO milestones(value, product) " .
                         "VALUES (?, ?)", undef, $default_ms, $product);
            }
        }
    }
}

sub _copy_from_comments_to_longdescs {
    my $dbh = Bugzilla->dbh;
    # 2000-11-27 For Bugzilla 2.5 and later. Copy data from 'comments' to
    # 'longdescs' - the new name of the comments table.
    if ($dbh->bz_table_info('comments')) {
        my $quoted_when = $dbh->quote_identifier('when');
        $dbh->do("INSERT INTO longdescs (bug_when, bug_id, who, thetext)
                  SELECT $quoted_when, bug_id, who, comment
                    FROM comments");
        $dbh->bz_drop_table("comments");
    }
}

sub _populate_duplicates_table {
    my $dbh = Bugzilla->dbh;
    # 2000-07-15 Added duplicates table so Bugzilla tracks duplicates in a
    # better way than it used to. This code searches the comments to populate
    # the table initially. It's executed if the table is empty; if it's 
    # empty because there are no dupes (as opposed to having just created 
    # the table) it won't have any effect anyway, so it doesn't matter.
    my ($dups_exist) = $dbh->selectrow_array(
        "SELECT DISTINCT 1 FROM duplicates");
    # We also check against a schema change that happened later.
    if (!$dups_exist && !$dbh->bz_column_info('groups', 'isactive')) {
        # populate table
        print "Populating duplicates table from comments...\n";

        my $sth = $dbh->prepare(
             "SELECT longdescs.bug_id, thetext
                FROM longdescs LEFT JOIN bugs 
                     ON longdescs.bug_id = bugs.bug_id
               WHERE (" . $dbh->sql_regexp("thetext", 
                          "'[.*.]{3} This bug has been marked as a duplicate"
                          . " of [[:digit:]]+ [.*.]{3}'") 
                  . ")
                     AND resolution = 'DUPLICATE'
            ORDER BY longdescs.bug_when");
        $sth->execute();

        my (%dupes, $key);
        # Because of the way hashes work, this loop removes all but the 
        # last dupe resolution found for a given bug.
        while (my ($dupe, $dupe_of) = $sth->fetchrow_array()) {
            $dupes{$dupe} = $dupe_of;
        }

        foreach $key (keys(%dupes)){
            $dupes{$key} =~ /^.*\*\*\* This bug has been marked as a duplicate of (\d+) \*\*\*$/ms;
            $dupes{$key} = $1;
            $dbh->do("INSERT INTO duplicates VALUES(?, ?)", undef,
                     $dupes{$key},  $key);
            #        BugItsADupeOf  Dupe
        }
    }
}

sub _recrypt_plaintext_passwords {
    my $dbh = Bugzilla->dbh;
    # 2001-06-12; myk@mozilla.org; bugs 74032, 77473:
    # Recrypt passwords using Perl &crypt instead of the mysql equivalent
    # and delete plaintext passwords from the database.
    if ($dbh->bz_column_info('profiles', 'password')) {

        print <<ENDTEXT;
Your current installation of Bugzilla stores passwords in plaintext
in the database and uses mysql's encrypt function instead of Perl's
crypt function to crypt passwords.  Passwords are now going to be
re-crypted with the Perl function, and plaintext passwords will be
deleted from the database.  This could take a while if your
installation has many users.
ENDTEXT

        # Re-crypt everyone's password.
        my $sth = $dbh->prepare("SELECT userid, password FROM profiles");
        $sth->execute();

        my $total = $sth->rows;
        my $i = 1;

        print "Fixing passwords...\n";
        while (my ($userid, $password) = $sth->fetchrow_array()) {
            my $cryptpassword = $dbh->quote(bz_crypt($password));
            $dbh->do("UPDATE profiles " .
                        "SET cryptpassword = $cryptpassword " .
                      "WHERE userid = $userid");
            indicate_progress({ total => $total, current => $i, every => 10 });
        }
        print "\n";

        # Drop the plaintext password field.
        $dbh->bz_drop_column('profiles', 'password');
    }
}

sub _update_bugs_activity_to_only_record_changes {
    my $dbh = Bugzilla->dbh;
    # 2001-07-20 jake@bugzilla.org - Change bugs_activity to only record changes
    #  http://bugzilla.mozilla.org/show_bug.cgi?id=55161
    if ($dbh->bz_column_info('bugs_activity', 'oldvalue')) {
        $dbh->bz_add_column("bugs_activity", "removed", {TYPE => "TINYTEXT"});
        $dbh->bz_add_column("bugs_activity", "added", {TYPE => "TINYTEXT"});

        # Need to get field id's for the fields that have multiple values
        my @multi;
        foreach my $f ("cc", "dependson", "blocked", "keywords") {
            my $sth = $dbh->prepare("SELECT id " .
                                    "FROM fielddefs " .
                                    "WHERE name = '$f'");
            $sth->execute();
            my ($fid) = $sth->fetchrow_array();
            push (@multi, $fid);
        }

        # Now we need to process the bugs_activity table and reformat the data
        print "Fixing activity log...\n";
        my $sth = $dbh->prepare("SELECT bug_id, who, bug_when, fieldid,
                                oldvalue, newvalue FROM bugs_activity");
        $sth->execute;
        my $i = 0;
        my $total = $sth->rows;
        while (my ($bug_id, $who, $bug_when, $fieldid, $oldvalue, $newvalue) 
                   = $sth->fetchrow_array()) 
        {
            $i++;
            indicate_progress({ total => $total, current => $i, every => 10 });
            # Make sure (old|new)value isn't null (to suppress warnings)
            $oldvalue ||= "";
            $newvalue ||= "";
            my ($added, $removed) = "";
            if (grep ($_ eq $fieldid, @multi)) {
                $oldvalue =~ s/[\s,]+/ /g;
                $newvalue =~ s/[\s,]+/ /g;
                my @old = split(" ", $oldvalue);
                my @new = split(" ", $newvalue);
                my (@add, @remove) = ();
                # Find values that were "added"
                foreach my $value(@new) {
                    if (! grep ($_ eq $value, @old)) {
                        push (@add, $value);
                    }
                }
                # Find values that were removed
                foreach my $value(@old) {
                    if (! grep ($_ eq $value, @new)) {
                        push (@remove, $value);
                    }
                }
                $added = join (", ", @add);
                $removed = join (", ", @remove);
                # If we can't determine what changed, put a ? in both fields
                unless ($added || $removed) {
                    $added = "?";
                    $removed = "?";
                }
                # If the original field (old|new)value was full, then this
                # could be incomplete data.
                if (length($oldvalue) == 255 || length($newvalue) == 255) {
                    $added = "? $added";
                    $removed = "? $removed";
                }
            } else {
                $removed = $oldvalue;
                $added = $newvalue;
            }
            $added = $dbh->quote($added);
            $removed = $dbh->quote($removed);
            $dbh->do("UPDATE bugs_activity 
                         SET removed = $removed, added = $added
                       WHERE bug_id = $bug_id AND who = $who
                             AND bug_when = '$bug_when' 
                             AND fieldid = $fieldid");
        }
        print "\n";
        $dbh->bz_drop_column("bugs_activity", "oldvalue");
        $dbh->bz_drop_column("bugs_activity", "newvalue");
    }
}

sub _delete_logincookies_cryptpassword_and_handle_invalid_cookies {
    my $dbh = Bugzilla->dbh;
    # 2002-02-04 bbaetz@student.usyd.edu.au bug 95732
    # Remove logincookies.cryptpassword, and delete entries which become
    # invalid
    if ($dbh->bz_column_info("logincookies", "cryptpassword")) {
        # We need to delete any cookies which are invalid before dropping the
        # column
        print "Removing invalid login cookies...\n";

        # mysql doesn't support DELETE with multi-table queries, so we have
        # to iterate
        my $sth = $dbh->prepare("SELECT cookie FROM logincookies, profiles " .
                                "WHERE logincookies.cryptpassword != " .
                                "profiles.cryptpassword AND " .
                                "logincookies.userid = profiles.userid");
        $sth->execute();
        while (my ($cookie) = $sth->fetchrow_array()) {
            $dbh->do("DELETE FROM logincookies WHERE cookie = $cookie");
        }

        $dbh->bz_drop_column("logincookies", "cryptpassword");
    }
}

sub _use_ip_instead_of_hostname_in_logincookies {
    my $dbh = Bugzilla->dbh;

    # 2002-03-15 bbaetz@student.usyd.edu.au - bug 129466
    # 2002-05-13 preed@sigkill.com - bug 129446 patch backported to the
    #  BUGZILLA-2_14_1-BRANCH as a security blocker for the 2.14.2 release
    #
    # Use the ip, not the hostname, in the logincookies table
    if ($dbh->bz_column_info("logincookies", "hostname")) {
        # We've changed what we match against, so all entries are now invalid
        $dbh->do("DELETE FROM logincookies");

        # Now update the logincookies schema
        $dbh->bz_drop_column("logincookies", "hostname");
        $dbh->bz_add_column("logincookies", "ipaddr",
                            {TYPE => 'varchar(40)', NOTNULL => 1}, '');
    }
}

sub _move_quips_into_db {
    my $dbh = Bugzilla->dbh;
    my $datadir = bz_locations->{'datadir'};
    # 2002-07-15 davef@tetsubo.com - bug 67950
    # Move quips to the db.
    if (-e "$datadir/comments") {
        print "Populating quips table from $datadir/comments...\n";
        my $comments = new IO::File("$datadir/comments", 'r')
            || die "$datadir/comments: $!";
        $comments->untaint;
        while (<$comments>) {
            chomp;
            $dbh->do("INSERT INTO quips (quip) VALUES (?)", undef, $_);
        }

        print <<EOT;

Quips are now stored in the database, rather than in an external file.
The quips previously stored in $datadir/comments have been copied into
the database, and that file has been renamed to $datadir/comments.bak
You may delete the renamed file once you have confirmed that all your
quips were moved successfully.

EOT
        $comments->close;
        rename("$datadir/comments", "$datadir/comments.bak")
            || warn "Failed to rename: $!";
    }
}

sub _use_ids_for_products_and_components {
    my $dbh = Bugzilla->dbh;
    # 2002-08-12 jake@bugzilla.org/bbaetz@student.usyd.edu.au - bug 43600
    # Use integer IDs for products and components.
    if ($dbh->bz_column_info("products", "product")) {
        print "Updating database to use product IDs.\n";

        # First, we need to remove possible NULL entries
        # NULLs may exist, but won't have been used, since all the uses of them
        # are in NOT NULL fields in other tables
        $dbh->do("DELETE FROM products WHERE product IS NULL");
        $dbh->do("DELETE FROM components WHERE value IS NULL");

        $dbh->bz_add_column("products", "id",
            {TYPE => 'SMALLSERIAL', NOTNULL => 1, PRIMARYKEY => 1});
        $dbh->bz_add_column("components", "product_id",
            {TYPE => 'INT2', NOTNULL => 1}, 0);
        $dbh->bz_add_column("versions", "product_id",
            {TYPE => 'INT2', NOTNULL => 1}, 0);
        $dbh->bz_add_column("milestones", "product_id",
            {TYPE => 'INT2', NOTNULL => 1}, 0);
        $dbh->bz_add_column("bugs", "product_id",
            {TYPE => 'INT2', NOTNULL => 1}, 0);

        # The attachstatusdefs table was added in version 2.15, but 
        # removed again in early 2.17.  If it exists now, we still need 
        # to perform this change with product_id because the code later on
        # which converts the attachment statuses to flags depends on it.
        # But we need to avoid this if the user is upgrading from 2.14
        # or earlier (because it won't be there to convert).
        if ($dbh->bz_table_info("attachstatusdefs")) {
            $dbh->bz_add_column("attachstatusdefs", "product_id",
                {TYPE => 'INT2', NOTNULL => 1}, 0);
        }

        my %products;
        my $sth = $dbh->prepare("SELECT id, product FROM products");
        $sth->execute;
        while (my ($product_id, $product) = $sth->fetchrow_array()) {
            if (exists $products{$product}) {
                print "Ignoring duplicate product $product\n";
                $dbh->do("DELETE FROM products WHERE id = $product_id");
                next;
            }
            $products{$product} = 1;
            $dbh->do("UPDATE components SET product_id = $product_id " .
                     "WHERE program = " . $dbh->quote($product));
            $dbh->do("UPDATE versions SET product_id = $product_id " .
                     "WHERE program = " . $dbh->quote($product));
            $dbh->do("UPDATE milestones SET product_id = $product_id " .
                     "WHERE product = " . $dbh->quote($product));
            $dbh->do("UPDATE bugs SET product_id = $product_id " .
                     "WHERE product = " . $dbh->quote($product));
            $dbh->do("UPDATE attachstatusdefs SET product_id = $product_id " .
                     "WHERE product = " . $dbh->quote($product))
                if $dbh->bz_table_info("attachstatusdefs");
        }

        print "Updating the database to use component IDs.\n";

        $dbh->bz_add_column("components", "id",
            {TYPE => 'SMALLSERIAL', NOTNULL => 1, PRIMARYKEY => 1});
        $dbh->bz_add_column("bugs", "component_id",
                            {TYPE => 'INT2', NOTNULL => 1}, 0);

        my %components;
        $sth = $dbh->prepare("SELECT id, value, product_id FROM components");
        $sth->execute;
        while (my ($component_id, $component, $product_id) 
            = $sth->fetchrow_array()) 
        {
            if (exists $components{$component}) {
                if (exists $components{$component}{$product_id}) {
                    print "Ignoring duplicate component $component for",
                          " product $product_id\n";
                    $dbh->do("DELETE FROM components WHERE id = $component_id");
                    next;
                }
            } else {
                $components{$component} = {};
            }
            $components{$component}{$product_id} = 1;
            $dbh->do("UPDATE bugs SET component_id = $component_id " .
                      "WHERE component = " . $dbh->quote($component) .
                       " AND product_id = $product_id");
        }
        print "Fixing Indexes and Uniqueness.\n";
        $dbh->bz_drop_index('milestones', 'milestones_product_idx');

        $dbh->bz_add_index('milestones', 'milestones_product_id_idx',
            {TYPE => 'UNIQUE', FIELDS => [qw(product_id value)]});

        $dbh->bz_drop_index('bugs', 'bugs_product_idx');
        $dbh->bz_add_index('bugs', 'bugs_product_id_idx', [qw(product_id)]);
        $dbh->bz_drop_index('bugs', 'bugs_component_idx');
        $dbh->bz_add_index('bugs', 'bugs_component_id_idx', [qw(component_id)]);

        print "Removing, renaming, and retyping old product and",
              " component fields.\n";
        $dbh->bz_drop_column("components", "program");
        $dbh->bz_drop_column("versions", "program");
        $dbh->bz_drop_column("milestones", "product");
        $dbh->bz_drop_column("bugs", "product");
        $dbh->bz_drop_column("bugs", "component");
        $dbh->bz_drop_column("attachstatusdefs", "product")
            if $dbh->bz_table_info("attachstatusdefs");
        $dbh->bz_rename_column("products", "product", "name");
        $dbh->bz_alter_column("products", "name",
                              {TYPE => 'varchar(64)', NOTNULL => 1});
        $dbh->bz_rename_column("components", "value", "name");
        $dbh->bz_alter_column("components", "name",
                              {TYPE => 'varchar(64)', NOTNULL => 1});

        print "Adding indexes for products and components tables.\n";
        $dbh->bz_add_index('products', 'products_name_idx',
                           {TYPE => 'UNIQUE', FIELDS => [qw(name)]});
        $dbh->bz_add_index('components', 'components_product_id_idx',
            {TYPE => 'UNIQUE', FIELDS => [qw(product_id name)]});
        $dbh->bz_add_index('components', 'components_name_idx', [qw(name)]);
    }
}

# Helper for the below function.
#
# _list_bits(arg) returns a list of UNKNOWN<n> if the group
# has been deleted for all bits set in arg. When the activity
# records are converted from groupset numbers to lists of
# group names, _list_bits is used to fill in a list of references
# to groupset bits for groups that no longer exist.
sub _list_bits {
    my ($num) = @_;
    my $dbh = Bugzilla->dbh;
    my @res;
    my $curr = 1;
    while (1) {
        # Convert a big integer to a list of bits
        my $sth = $dbh->prepare("SELECT ($num & ~$curr) > 0,
                                        ($num & $curr),
                                        ($num & ~$curr),
                                        $curr << 1");
        $sth->execute;
        my ($more, $thisbit, $remain, $nval) = $sth->fetchrow_array;
        push @res,"UNKNOWN<$curr>" if ($thisbit);
        $curr = $nval;
        $num = $remain;
        last if !$more;
    }
    return @res;
}

sub _convert_groups_system_from_groupset {
    my $dbh = Bugzilla->dbh;
    # 2002-09-22 - bugreport@peshkin.net - bug 157756
    #
    # If the whole groups system is new, but the installation isn't,
    # convert all the old groupset groups, etc...
    #
    # This requires:
    # 1) define groups ids in group table
    # 2) populate user_group_map with grants from old groupsets 
    #    and blessgroupsets
    # 3) populate bug_group_map with data converted from old bug groupsets
    # 4) convert activity logs to use group names instead of numbers
    # 5) identify the admin from the old all-ones groupset

    # The groups system needs to be converted if groupset exists
    if ($dbh->bz_column_info("profiles", "groupset")) {
        # Some mysql versions will promote any unique key to primary key
        # so all unique keys are removed first and then added back in
        $dbh->bz_drop_index('groups', 'groups_bit_idx');
        $dbh->bz_drop_index('groups', 'groups_name_idx');
        if ($dbh->primary_key(undef, undef, 'groups')) {
            $dbh->do("ALTER TABLE groups DROP PRIMARY KEY");
        }

        $dbh->bz_add_column('groups', 'id',
            {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1});

        $dbh->bz_add_index('groups', 'groups_name_idx',
                           {TYPE => 'UNIQUE', FIELDS => [qw(name)]});

        # Convert all existing groupset records to map entries before removing
        # groupset fields or removing "bit" from groups.
        my $sth = $dbh->prepare("SELECT bit, id FROM groups WHERE bit > 0");
        $sth->execute();
        while (my ($bit, $gid) = $sth->fetchrow_array) {
            # Create user_group_map membership grants for old groupsets.
            # Get each user with the old groupset bit set
            my $sth2 = $dbh->prepare("SELECT userid FROM profiles
                                       WHERE (groupset & $bit) != 0");
            $sth2->execute();
            while (my ($uid) = $sth2->fetchrow_array) {
                # Check to see if the user is already a member of the group
                # and, if not, insert a new record.
                my $query = "SELECT user_id FROM user_group_map
                              WHERE group_id = $gid AND user_id = $uid
                                    AND isbless = 0";
                my $sth3 = $dbh->prepare($query);
                $sth3->execute();
                if ( !$sth3->fetchrow_array() ) {
                    $dbh->do("INSERT INTO user_group_map
                              (user_id, group_id, isbless, grant_type)
                              VALUES ($uid, $gid, 0, " . GRANT_DIRECT . ")");
                }
            }
            # Create user can bless group grants for old groupsets, but only
            # if we're upgrading from a Bugzilla that had blessing.
            if($dbh->bz_column_info('profiles', 'blessgroupset')) {
                # Get each user with the old blessgroupset bit set
                $sth2 = $dbh->prepare("SELECT userid FROM profiles
                                        WHERE (blessgroupset & $bit) != 0");
                $sth2->execute();
                while (my ($uid) = $sth2->fetchrow_array) {
                    $dbh->do("INSERT INTO user_group_map
                              (user_id, group_id, isbless, grant_type)
                              VALUES ($uid, $gid, 1, " . GRANT_DIRECT . ")");
                }
            }
            # Create bug_group_map records for old groupsets.
            # Get each bug with the old group bit set.
            $sth2 = $dbh->prepare("SELECT bug_id FROM bugs
                                    WHERE (groupset & $bit) != 0");
            $sth2->execute();
            while (my ($bug_id) = $sth2->fetchrow_array) {
               # Insert the bug, group pair into the bug_group_map.
                $dbh->do("INSERT INTO bug_group_map (bug_id, group_id)
                          VALUES ($bug_id, $gid)");
            }
        }
        # Replace old activity log groupset records with lists of names 
        # of groups.
        $sth = $dbh->prepare("SELECT id FROM fielddefs
                               WHERE name = " . $dbh->quote('bug_group'));
        $sth->execute();
        my ($bgfid) = $sth->fetchrow_array;
        # Get the field id for the old groupset field
        $sth = $dbh->prepare("SELECT id FROM fielddefs
                               WHERE name = " . $dbh->quote('groupset'));
        $sth->execute();
        my ($gsid) = $sth->fetchrow_array;
        # Get all bugs_activity records from groupset changes
        if ($gsid) {
            $sth = $dbh->prepare("SELECT bug_id, bug_when, who, added, removed
                                    FROM bugs_activity WHERE fieldid = $gsid");
            $sth->execute();
            while (my ($bug_id, $bug_when, $who, $added, $removed) = 
                       $sth->fetchrow_array) 
            {
                $added ||= 0;
                $removed ||= 0;
                # Get names of groups added.
                my $sth2 = $dbh->prepare("SELECT name FROM groups
                                           WHERE (bit & $added) != 0
                                                 AND (bit & $removed) = 0");
                $sth2->execute();
                my @logadd;
                while (my ($n) = $sth2->fetchrow_array) {
                    push @logadd, $n;
                }
                # Get names of groups removed.
                $sth2 = $dbh->prepare("SELECT name FROM groups
                                        WHERE (bit & $removed) != 0
                                              AND (bit & $added) = 0");
                $sth2->execute();
                my @logrem;
                while (my ($n) = $sth2->fetchrow_array) {
                    push @logrem, $n;
                }
                # Get list of group bits added that correspond to 
                # missing groups.
                $sth2 = $dbh->prepare("SELECT ($added & ~BIT_OR(bit)) 
                                         FROM groups");
                $sth2->execute();
                my ($miss) = $sth2->fetchrow_array;
                if ($miss) {
                    push @logadd, _list_bits($miss);
                    print "\nWARNING - GROUPSET ACTIVITY ON BUG $bug_id",
                          " CONTAINS DELETED GROUPS\n";
                }
                # Get list of group bits deleted that correspond to 
                # missing groups.
                $sth2 = $dbh->prepare("SELECT ($removed & ~BIT_OR(bit)) 
                                         FROM groups");
                $sth2->execute();
                ($miss) = $sth2->fetchrow_array;
                if ($miss) {
                    push @logrem, _list_bits($miss);
                    print "\nWARNING - GROUPSET ACTIVITY ON BUG $bug_id",
                          " CONTAINS DELETED GROUPS\n";
                }
                my $logr = "";
                my $loga = "";
                $logr = join(", ", @logrem) . '?' if @logrem;
                $loga = join(", ", @logadd) . '?' if @logadd;
                # Replace to old activity record with the converted data.
                $dbh->do("UPDATE bugs_activity SET fieldid = $bgfid, added = " .
                          $dbh->quote($loga) . ", removed = " .
                          $dbh->quote($logr) .
                         " WHERE bug_id = $bug_id AND bug_when = " .
                          $dbh->quote($bug_when) .
                         " AND who = $who AND fieldid = $gsid");
            }
            # Replace groupset changes with group name changes in
            # profiles_activity. Get profiles_activity records for groupset.
            $sth = $dbh->prepare(
                 "SELECT userid, profiles_when, who, newvalue, oldvalue " .
                   "FROM profiles_activity " .
                  "WHERE fieldid = $gsid");
            $sth->execute();
            while (my ($uid, $uwhen, $uwho, $added, $removed) = 
                       $sth->fetchrow_array) 
            {
                $added ||= 0;
                $removed ||= 0;
                # Get names of groups added.
                my $sth2 = $dbh->prepare("SELECT name FROM groups
                                           WHERE (bit & $added) != 0
                                                 AND (bit & $removed) = 0");
                $sth2->execute();
                my @logadd;
                while (my ($n) = $sth2->fetchrow_array) {
                    push @logadd, $n;
                }
                # Get names of groups removed.
                $sth2 = $dbh->prepare("SELECT name FROM groups
                                        WHERE (bit & $removed) != 0
                                              AND (bit & $added) = 0");
                $sth2->execute();
                my @logrem;
                while (my ($n) = $sth2->fetchrow_array) {
                    push @logrem, $n;
                }
                my $ladd = "";
                my $lrem = "";
                $ladd = join(", ", @logadd) . '?' if @logadd;
                $lrem = join(", ", @logrem) . '?' if @logrem;
                # Replace profiles_activity record for groupset change
                # with group list.
                $dbh->do("UPDATE profiles_activity " .
                            "SET fieldid = $bgfid, newvalue = " .
                          $dbh->quote($ladd) . ", oldvalue = " .
                          $dbh->quote($lrem) .
                         " WHERE userid = $uid AND profiles_when = " .
                          $dbh->quote($uwhen) .
                               " AND who = $uwho AND fieldid = $gsid");
            }
        }

        # Identify admin group.
        my ($admin_gid) = $dbh->selectrow_array(
            "SELECT id FROM groups WHERE name = 'admin'");
        if (!$admin_gid) {
            $dbh->do(q{INSERT INTO groups (name, description)
                                   VALUES ('admin', 'Administrators')});
            $admin_gid = $dbh->bz_last_key('groups', 'id');
        }
        # Find current admins
        my @admins;
        # Don't lose admins from DBs where Bug 157704 applies
        $sth = $dbh->prepare(
               "SELECT userid, (groupset & 65536), login_name " .
                 "FROM profiles " .
                "WHERE (groupset | 65536) = 9223372036854775807");
        $sth->execute();
        while ( my ($userid, $iscomplete, $login_name) 
                    = $sth->fetchrow_array() ) 
        {
            # existing administrators are made members of group "admin"
            print "\nWARNING - $login_name IS AN ADMIN IN SPITE OF BUG",
                  " 157704\n\n" if (!$iscomplete);
            push(@admins, $userid) unless grep($_ eq $userid, @admins);
        }
        # Now make all those users admins directly. They were already
        # added to every other group, above, because of their groupset.
        foreach my $admin_id (@admins) {
            $dbh->do("INSERT INTO user_group_map
                                  (user_id, group_id, isbless, grant_type)
                           VALUES (?, ?, ?, ?)", 
                      undef, $admin_id, $admin_gid, $_, GRANT_DIRECT)
                foreach (0, 1);
        }

        $dbh->bz_drop_column('profiles','groupset');
        $dbh->bz_drop_column('profiles','blessgroupset');
        $dbh->bz_drop_column('bugs','groupset');
        $dbh->bz_drop_column('groups','bit');
        $dbh->do("DELETE FROM fielddefs WHERE name = " 
            . $dbh->quote('groupset'));
    }
}

sub _convert_attachment_statuses_to_flags {
    my $dbh = Bugzilla->dbh;

    # September 2002 myk@mozilla.org bug 98801
    # Convert the attachment statuses tables into flags tables.
    if ($dbh->bz_table_info("attachstatuses") 
        && $dbh->bz_table_info("attachstatusdefs")) 
    {
        print "Converting attachment statuses to flags...\n";

        # Get IDs for the old attachment status and new flag fields.
        my ($old_field_id) = $dbh->selectrow_array(
            "SELECT id FROM fielddefs WHERE name='attachstatusdefs.name'")
            || 0;
        my ($new_field_id) = $dbh->selectrow_array(
            "SELECT id FROM fielddefs WHERE name = 'flagtypes.name'");

        # Convert attachment status definitions to flag types.  If more than one
        # status has the same name and description, it is merged into a single
        # status with multiple inclusion records.     

        my $sth = $dbh->prepare(
            "SELECT id, name, description, sortkey, product_id  
               FROM attachstatusdefs");

        # status definition IDs indexed by name/description
        my $def_ids = {};

        # merged IDs and the IDs they were merged into.  The key is the old ID,
        # the value is the new one.  This allows us to give statuses the right
        # ID when we convert them over to flags.  This map includes IDs that
        # weren't merged (in this case the old and new IDs are the same), since
        # it makes the code simpler.
        my $def_id_map = {};

        $sth->execute();
        while (my ($id, $name, $desc, $sortkey, $prod_id) = 
                   $sth->fetchrow_array()) 
        {
            my $key = $name . $desc;
            if (!$def_ids->{$key}) {
                $def_ids->{$key} = $id;
                my $quoted_name = $dbh->quote($name);
                my $quoted_desc = $dbh->quote($desc);
                $dbh->do("INSERT INTO flagtypes (id, name, description, 
                                                 sortkey, target_type) 
                          VALUES ($id, $quoted_name, $quoted_desc, 
                                  $sortkey,'a')");
            }
            $def_id_map->{$id} = $def_ids->{$key};
            $dbh->do("INSERT INTO flaginclusions (type_id, product_id)
                      VALUES ($def_id_map->{$id}, $prod_id)");
        }

        # Note: even though we've converted status definitions, we still
        # can't drop the table because we need it to convert the statuses 
        # themselves.

        # Convert attachment statuses to flags.  To do this we select 
        # the statuses from the status table and then, for each one, 
        # figure out who set it and when they set it from the bugs 
        # activity table.
        my $id = 0;
        $sth = $dbh->prepare(
            "SELECT attachstatuses.attach_id, attachstatusdefs.id,
                    attachstatusdefs.name, attachments.bug_id
               FROM attachstatuses, attachstatusdefs, attachments
              WHERE attachstatuses.statusid = attachstatusdefs.id
                    AND attachstatuses.attach_id = attachments.attach_id");

        # a query to determine when the attachment status was set and who set it
        my $sth2 = $dbh->prepare("SELECT added, who, bug_when
                                    FROM bugs_activity
                                   WHERE bug_id = ? AND attach_id = ?
                                         AND fieldid = $old_field_id
                                ORDER BY bug_when DESC");

        $sth->execute();
        while (my ($attach_id, $def_id, $status, $bug_id) = 
                   $sth->fetchrow_array()) 
        {
            ++$id;

            # Determine when the attachment status was set and who set it.
            # We should always be able to find out this info from the bug
            # activity, but we fall back to default values just in case.
            $sth2->execute($bug_id, $attach_id);
            my ($added, $who, $when);
            while (($added, $who, $when) = $sth2->fetchrow_array()) {
                last if $added =~ /(^|[, ]+)\Q$status\E([, ]+|$)/;
            }
            $who = $dbh->quote($who); # "NULL" by default if $who is undefined
            $when = $when ? $dbh->quote($when) : "NOW()";


            $dbh->do("INSERT INTO flags (id, type_id, status, bug_id, 
                      attach_id, creation_date, modification_date, 
                      requestee_id, setter_id)
                      VALUES ($id, $def_id_map->{$def_id}, '+', $bug_id,
                              $attach_id, $when, $when, NULL, $who)");
        }

        # Now that we've converted both tables we can drop them.
        $dbh->bz_drop_table("attachstatuses");
        $dbh->bz_drop_table("attachstatusdefs");

        # Convert activity records for attachment statuses into records 
        # for flags.
        $sth = $dbh->prepare("SELECT attach_id, who, bug_when, added, 
                                     removed 
                                FROM bugs_activity 
                               WHERE fieldid = $old_field_id");
        $sth->execute();
        while (my ($attach_id, $who, $when, $old_added, $old_removed) =
                   $sth->fetchrow_array())
        {
            my @additions = split(/[, ]+/, $old_added);
            @additions = map("$_+", @additions);
            my $new_added = $dbh->quote(join(", ", @additions));

            my @removals = split(/[, ]+/, $old_removed);
            @removals = map("$_+", @removals);
            my $new_removed = $dbh->quote(join(", ", @removals));

            $old_added = $dbh->quote($old_added);
            $old_removed = $dbh->quote($old_removed);
            $who = $dbh->quote($who);
            $when = $dbh->quote($when);

            $dbh->do("UPDATE bugs_activity SET fieldid = $new_field_id, " .
                     "added = $new_added, removed = $new_removed " .
                     "WHERE attach_id = $attach_id AND who = $who " .
                     "AND bug_when = $when AND fieldid = $old_field_id " .
                     "AND added = $old_added AND removed = $old_removed");
        }

        # Remove the attachment status field from the field definitions.
        $dbh->do("DELETE FROM fielddefs WHERE name='attachstatusdefs.name'");

        print "done.\n";
    }
}

sub _remove_spaces_and_commas_from_flagtypes {
    my $dbh = Bugzilla->dbh;
    # Get all names and IDs, to find broken ones and to
    # check for collisions when renaming.
    my $sth = $dbh->prepare("SELECT name, id FROM flagtypes");
    $sth->execute();

    my %flagtypes;
    my @badflagnames; 
    # find broken flagtype names, and populate a hash table
    # to check for collisions.
    while (my ($name, $id) = $sth->fetchrow_array()) {
        $flagtypes{$name} = $id;
        if ($name =~ /[ ,]/) {
            push(@badflagnames, $name);
        }
    }
    if (@badflagnames) {
        print "Removing spaces and commas from flag names...\n";
        my ($flagname, $tryflagname);
        my $sth = $dbh->prepare("UPDATE flagtypes SET name = ? WHERE id = ?");
        foreach $flagname (@badflagnames) {
            print "  Bad flag type name \"$flagname\" ...\n";
            # find a new name for this flagtype.
            ($tryflagname = $flagname) =~ tr/ ,/__/;
            # avoid collisions with existing flagtype names.
            while (defined($flagtypes{$tryflagname})) {
                print "  ... can't rename as \"$tryflagname\" ...\n";
                $tryflagname .= "'";
                if (length($tryflagname) > 50) {
                    my $lastchanceflagname = (substr $tryflagname, 0, 47) . '...';
                    if (defined($flagtypes{$lastchanceflagname})) {
                        print "  ... last attempt as \"$lastchanceflagname\" still failed.'\n",
                              "Rename the flag by hand and run checksetup.pl again.\n";
                        die("Bad flag type name $flagname");
                    }
                    $tryflagname = $lastchanceflagname;
                }
            }
            $sth->execute($tryflagname, $flagtypes{$flagname});
            print "  renamed flag type \"$flagname\" as \"$tryflagname\"\n";
            $flagtypes{$tryflagname} = $flagtypes{$flagname};
            delete $flagtypes{$flagname};
        }
        print "... done.\n";
    }
}

sub _setup_usebuggroups_backward_compatibility {
    my $dbh = Bugzilla->dbh;
    # 2002-11-24 - bugreport@peshkin.net - bug 147275
    #
    # If group_control_map is empty, backward-compatibility
    # usebuggroups-equivalent records should be created.
    my $entry = Bugzilla->params->{'useentrygroupdefault'};
    my ($maps_exist) = $dbh->selectrow_array(
        "SELECT DISTINCT 1 FROM group_control_map");
    if (!$maps_exist) {
        # Initially populate group_control_map.
        # First, get all the existing products and their groups.
        my $sth = $dbh->prepare("SELECT groups.id, products.id, groups.name,
                                        products.name 
                                  FROM groups, products
                                 WHERE isbuggroup != 0");
        $sth->execute();
        while (my ($groupid, $productid, $groupname, $productname)
                = $sth->fetchrow_array()) 
        {
            if ($groupname eq $productname) {
                # Product and group have same name.
                $dbh->do("INSERT INTO group_control_map " .