recode.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #!/usr/bin/env perl -w
  2. # -*- Mode: perl; indent-tabs-mode: nil -*-
  3. #
  4. # The contents of this file are subject to the Mozilla Public
  5. # License Version 1.1 (the "License"); you may not use this file
  6. # except in compliance with the License. You may obtain a copy of
  7. # the License at http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS
  10. # IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  11. # implied. See the License for the specific language governing
  12. # rights and limitations under the License.
  13. #
  14. # The Original Code is the Bugzilla Bug Tracking System.
  15. #
  16. # The Initial Developer of the Original Code is Everything Solved.
  17. # Portions created by Everything Solved are Copyright (C) 2006
  18. # Everything Solved. All Rights Reserved.
  19. #
  20. # Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>
  21. use strict;
  22. use lib qw(. lib);
  23. use Bugzilla;
  24. use Bugzilla::Constants;
  25. use Digest::MD5 qw(md5_base64);
  26. use Encode qw(encode decode resolve_alias is_utf8);
  27. use Encode::Guess;
  28. use Getopt::Long;
  29. use Pod::Usage;
  30. #############
  31. # Constants #
  32. #############
  33. use constant IGNORE_ENCODINGS => qw(utf8 ascii iso-8859-1);
  34. use constant MAX_STRING_LEN => 25;
  35. # For certain tables, we can't automatically determine their Primary Key.
  36. # So, we specify it here as a string.
  37. use constant SPECIAL_KEYS => {
  38. bugs_activity => 'bug_id,bug_when,fieldid',
  39. profile_setting => 'user_id,setting_name',
  40. profiles_activity => 'userid,profiles_when,fieldid',
  41. setting_value => 'name,value',
  42. # longdescs didn't used to have a PK, before 2.20.
  43. longdescs => 'bug_id,bug_when',
  44. # The 2.16 versions table lacked a PK
  45. versions => 'product_id,value',
  46. # These are all for earlier versions of Bugzilla. On a modern
  47. # version of Bugzilla, this script will ignore these (thanks to
  48. # code further down).
  49. components => 'program,value',
  50. products => 'product',
  51. };
  52. ###############
  53. # Subroutines #
  54. ###############
  55. # "truncate" is a file operation in perl, so we can't use that name.
  56. sub trunc {
  57. my ($str, $should_truncate) = @_;
  58. return $str if !$should_truncate;
  59. my $truncated = substr($str, 0, MAX_STRING_LEN);
  60. if (length($truncated) ne length($str)) {
  61. $truncated .= '...';
  62. }
  63. return $truncated;
  64. }
  65. sub do_guess {
  66. my ($data) = @_;
  67. my $encoding = detect($data);
  68. $encoding = resolve_alias($encoding) if $encoding;
  69. # Encode::Detect is bad at detecting certain charsets, but Encode::Guess
  70. # is better at them. Here's the details:
  71. # shiftjis, big5-eten, euc-kr, and euc-jp: (Encode::Detect
  72. # tends to accidentally mis-detect UTF-8 strings as being
  73. # these encodings.)
  74. my @utf8_accidental = qw(shiftjis big5-eten euc-kr euc-jp);
  75. if ($encoding && grep($_ eq $encoding, @utf8_accidental)) {
  76. $encoding = undef;
  77. my $decoder = guess_encoding($data, @utf8_accidental);
  78. $encoding = $decoder->name if ref $decoder;
  79. }
  80. # Encode::Detect sometimes mis-detects various ISO encodings as iso-8859-8,
  81. # but Encode::Guess can usually tell which one it is.
  82. if ($encoding && $encoding eq 'iso-8859-8') {
  83. my $decoded_as = guess_iso($data, 'iso-8859-8',
  84. # These are ordered this way because it gives the most
  85. # accurate results.
  86. qw(iso-8859-7 iso-8859-2));
  87. $encoding = $decoded_as if $decoded_as;
  88. }
  89. # Workaround for WebKit Bug 9630 which caused WebKit nightly builds
  90. # to send non-breaking space characters (0xA0) when submitting
  91. # textarea content to Bugzilla.
  92. if (!$encoding) {
  93. my $decoder = guess_encoding($data, qw(cp1252));
  94. $encoding = $decoder->name if ref $decoder;
  95. }
  96. return $encoding;
  97. }
  98. # A helper for do_guess.
  99. sub guess_iso {
  100. my ($data, $versus, @isos) = @_;
  101. my $encoding;
  102. foreach my $iso (@isos) {
  103. my $decoder = guess_encoding($data, ($iso, $versus));
  104. if (ref $decoder) {
  105. $encoding = $decoder->name if ref $decoder;
  106. last;
  107. }
  108. }
  109. return $encoding;
  110. }
  111. sub is_valid_utf8 {
  112. my ($str) = @_;
  113. Encode::_utf8_on($str);
  114. return is_utf8($str, 1);
  115. }
  116. ###############
  117. # Main Script #
  118. ###############
  119. my %switch;
  120. GetOptions(\%switch, 'dry-run', 'guess', 'charset=s', 'show-failures',
  121. 'overrides=s', 'truncate!', 'help|h');
  122. pod2usage({ -verbose => 1 }) if $switch{'help'};
  123. # You have to specify at least one of these switches.
  124. pod2usage({ -verbose => 0 }) if (!$switch{'charset'} && !$switch{'guess'});
  125. if (exists $switch{'charset'}) {
  126. $switch{'charset'} = resolve_alias($switch{'charset'})
  127. || die "'$switch{charset}' is not a valid charset.";
  128. }
  129. if ($switch{'guess'}) {
  130. # Encode::Detect::Detector doesn't seem to return a true value.
  131. # So we have to check if we can run detect.
  132. if (!eval { require Encode::Detect::Detector }) {
  133. my $root = ROOT_USER;
  134. print STDERR <<EOT;
  135. Using --guess requires that Encode::Detect be installed. To install
  136. Encode::Detect, run the following command:
  137. $^X install-module.pl Encode::Detect
  138. EOT
  139. exit;
  140. }
  141. import Encode::Detect::Detector qw(detect);
  142. }
  143. my %overrides;
  144. if (exists $switch{'overrides'}) {
  145. my $file = new IO::File($switch{'overrides'}, 'r')
  146. || die "$switch{overrides}: $!";
  147. my @lines = $file->getlines();
  148. $file->close();
  149. foreach my $line (@lines) {
  150. chomp($line);
  151. my ($digest, $encoding) = split(' ', $line);
  152. $overrides{$digest} = $encoding;
  153. }
  154. }
  155. my $dbh = Bugzilla->dbh;
  156. if ($dbh->isa('Bugzilla::DB::Mysql')) {
  157. # Get the actual current encoding of the DB.
  158. my $collation_data = $dbh->selectrow_arrayref(
  159. "SHOW VARIABLES LIKE 'character_set_database'");
  160. my $db_charset = $collation_data->[1];
  161. # Set our connection encoding to *that* encoding, so that MySQL
  162. # correctly accepts our changes.
  163. $dbh->do("SET NAMES $db_charset");
  164. # Make the database give us raw bytes.
  165. $dbh->do('SET character_set_results = NULL')
  166. }
  167. $dbh->begin_work;
  168. foreach my $table ($dbh->bz_table_list_real) {
  169. my @columns = $dbh->bz_table_columns($table);
  170. my $pk = SPECIAL_KEYS->{$table};
  171. if ($pk) {
  172. # Assure that we're on a version of Bugzilla where those keys
  173. # actually exist.
  174. foreach my $column (split ',', $pk) {
  175. $pk = undef if !$dbh->bz_column_info($table, $column);
  176. }
  177. }
  178. # Figure out the primary key.
  179. foreach my $column (@columns) {
  180. my $def = $dbh->bz_column_info($table, $column);
  181. $pk = $column if $def->{PRIMARYKEY};
  182. }
  183. # If there's no PK, it's defined by a UNIQUE index.
  184. if (!$pk) {
  185. foreach my $column (@columns) {
  186. my $index = $dbh->bz_index_info($table, "${table}_${column}_idx");
  187. if ($index && ref($index) eq 'HASH') {
  188. $pk = join(',', @{$index->{FIELDS}})
  189. if $index->{TYPE} eq 'UNIQUE';
  190. }
  191. }
  192. }
  193. my $should_truncate = exists $switch{'truncate'} ? $switch{'truncate'} : 1;
  194. foreach my $column (@columns) {
  195. my $def = $dbh->bz_column_info($table, $column);
  196. # If this is a text column, it may need work.
  197. if ($def->{TYPE} =~ /text|char/i) {
  198. # If there's still no PK, we're upgrading from 2.14 or earlier.
  199. # We can't reliably determine the PK (or at least, I don't want to
  200. # maintain code to record what the PK was at all points in history).
  201. # So instead we just use the field itself.
  202. $pk = $column if !$pk;
  203. print "Converting $table.$column...\n";
  204. my $sth = $dbh->prepare("SELECT $column, $pk FROM $table
  205. WHERE $column IS NOT NULL
  206. AND $column != ''");
  207. my @pk_array = map {"$_ = ?"} split(',', $pk);
  208. my $pk_where = join(' AND ', @pk_array);
  209. my $update_sth = $dbh->prepare(
  210. "UPDATE $table SET $column = ? WHERE $pk_where");
  211. $sth->execute();
  212. while (my @result = $sth->fetchrow_array) {
  213. my $data = shift @result;
  214. # Wide characters cause md5_base64() to die.
  215. my $digest_data = utf8::is_utf8($data)
  216. ? Encode::encode_utf8($data) : $data;
  217. my $digest = md5_base64($digest_data);
  218. my @primary_keys = reverse split(',', $pk);
  219. # We copy the array so that we can pop things from it without
  220. # affecting the original.
  221. my @pk_data = @result;
  222. my $pk_line = join (', ',
  223. map { "$_ = " . pop @pk_data } @primary_keys);
  224. my $encoding;
  225. if ($switch{'guess'}) {
  226. $encoding = do_guess($data);
  227. # We only show failures if they don't appear to be
  228. # ASCII.
  229. if ($switch{'show-failures'} && !$encoding
  230. && !is_valid_utf8($data) && !$overrides{$digest})
  231. {
  232. my $truncated = trunc($data, $should_truncate);
  233. print "Row: [$pk_line]\n",
  234. "Failed to guess: Key: $digest",
  235. " DATA: $truncated\n";
  236. }
  237. # If we fail a guess, and the data is valid UTF-8,
  238. # just assume we failed because it's UTF-8.
  239. next if is_valid_utf8($data);
  240. }
  241. # If we couldn't detect the charset (or were instructed
  242. # not to try), we fall back to --charset. If there's no
  243. # fallback, we just do nothing.
  244. if (!$encoding && $switch{'charset'}) {
  245. $encoding = $switch{'charset'};
  246. }
  247. $encoding = $overrides{$digest} if $overrides{$digest};
  248. # We only fix it if it's not ASCII or UTF-8 already.
  249. if ($encoding && !grep($_ eq $encoding, IGNORE_ENCODINGS)) {
  250. my $decoded = encode('utf8', decode($encoding, $data));
  251. if ($switch{'dry-run'} && $data ne $decoded) {
  252. print "Row: [$pk_line]\n",
  253. "From: [" . trunc($data, $should_truncate) . "] Key: $digest\n",
  254. "To: [" . trunc($decoded, $should_truncate) . "]",
  255. " Encoding : $encoding\n";
  256. }
  257. else {
  258. $update_sth->execute($decoded, @result);
  259. }
  260. }
  261. } # while (my @result = $sth->fetchrow_array)
  262. } # if ($column->{TYPE} =~ /text|char/i)
  263. } # foreach my $column (@columns)
  264. }
  265. $dbh->commit;
  266. __END__
  267. =head1 NAME
  268. recode.pl - Converts a database from one encoding (or multiple encodings)
  269. to UTF-8.
  270. =head1 SYNOPSIS
  271. contrib/recode.pl [--guess [--show-failures]] [--charset=iso-8859-2]
  272. [--overrides=file_name] [--[no-]truncate]
  273. --dry-run Don't modify the database.
  274. --charset Primary charset your data is currently in. This can be
  275. optionally omitted if you do --guess.
  276. --guess Try to guess the charset of the data.
  277. --show-failures If we fail to guess, show where we failed.
  278. --overrides Specify a file containing overrides. See --help
  279. for more info.
  280. --[no-]truncate Truncate from/to string output (default: yes).
  281. --help Display detailed help.
  282. If you aren't sure what to do, try:
  283. contrib/recode.pl --guess --charset=cp1252
  284. =head1 OPTIONS
  285. =over
  286. =item --dry-run
  287. Don't modify the database, just print out what the conversions will be.
  288. recode.pl will print out a Key for each item. You can use this in the
  289. overrides file, described below.
  290. =item --guess
  291. If your database is in multiple different encodings, specify this switch
  292. and recode.pl will do its best to determine the original charset of the data.
  293. The detection is usually very reliable.
  294. If recode.pl cannot guess the charset, it will leave the data alone, unless
  295. you've specified --charset.
  296. =item --charset=charset-name
  297. If you do not specify --guess, then your database is converted
  298. from this character set into the UTF-8.
  299. If you have specified --guess, recode.pl will use this charset as
  300. a fallback--when it cannot guess the charset of a particular piece
  301. of data, it will guess that the data is in this charset and convert
  302. it from this charset to UTF-8.
  303. charset-name must be a charset that is known to perl's Encode
  304. module. To see a list of available charsets, do:
  305. C<perl -MEncode -e 'print join("\n", Encode-E<gt>encodings(":all"))'>
  306. =item --show-failures
  307. If --guess fails to guess a charset, print out the data it failed on.
  308. =item --overrides=file_name
  309. This is a way of specifying certain encodings to override the encodings of
  310. --guess. The file is a series of lines. The line should start with the Key
  311. from --dry-run, and then a space, and then the encoding you'd like to use.
  312. =item --[no-]truncate
  313. This specifies whether the from/to text that is converted should be
  314. truncated or not. The default is to truncate the text.
  315. =back