Tools/Mobipocket.pm

filter: Statementstmt 82.3% 28 / 34 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 90.9% 10 / 11 Podpod n/a totaltotal 84.4% 38 / 45 CC 1 SCAR 1.1
CC
1
Cov
82%
import
2.0
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
« Tools/EReader.pm ↑ Summary Tools/BISG.pm »
1 package EBook::Tools::Mobipocket;
2 1 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 #use warnings::unused;
4 #use 5.010; # Needed for smart-match operator
5 #v5.10 feature use removed until 5.10 is standard on MacOSX and Debian
6 1 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use version 0.74; our $VERSION = qv("0.5.0");
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Perl Critic overrides:
10 ## no critic (Package variable)
11 # Double-sigils are needed for lexical variables in clear print statements
12 ## no critic (Double-sigil dereference)
13 # Mixed case subs and the variable %record are inherited from Palm::PDB
14 ## no critic (ProhibitAmbiguousNames)
15 ## no critic (ProhibitMixedCaseSubs)
16  
17 require Exporter;
18 1 ▶use base qw(Exporter Palm::Raw);
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 our @EXPORT_OK;
21 @EXPORT_OK = qw (
22 &find_mobidedrm
23 &find_mobigen
24 &parse_mobi_exth
25 &parse_mobi_header
26 &parse_mobi_language
27 &pid_append_checksum
28 &pid_is_valid
29 &pukall_cipher_1
30 &system_mobidedrm
31 &system_mobigen
32 &unpack_mobi_language
33 );
34 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
35  
36 sub import ## no critic (Always unpack @_ first)
37 0 ▶{
Subroutine import: not called CC=1 SCAR=6.9
38 0 &Palm::PDB::RegisterPDBHandlers( __PACKAGE__, [ "MOBI", "BOOK" ], );
39 0 &Palm::PDB::RegisterPRCHandlers( __PACKAGE__, [ "MOBI", "BOOK" ], );
40 0 EBook::Tools::Mobipocket->export_to_level(1, @_);
41 0 return;
42 }
43  
44 =head1 NAME
45  
46 EBook::Tools::Mobipocket - Palm::PDB handler for manipulating the Mobipocket format.
47  
48 =head1 SYNOPSIS
49  
50 use EBook::Tools::Mobipocket qw(:all);
51 my $mobi = EBook::Tools::Mobipocket->new();
52 $mobi->Load('filename.prc');
53 print "Title: ",$mobi->{title},"\n";
54 print "Author: ",$mobi->{header}{exth}{author},"\n";
55 print "Language: ",$mobi->{header}{mobi}{language},"\n";
56  
57 my $mobigen = find_mobigen();
58 system_mobigen('myfile.opf');
59  
60 =head1 DEPENDENCIES
61  
62 =over
63  
64 =item * C<Bit::Vector>
65  
66 =item * C<Compress::Zlib>
67  
68 =item * C<HTML::Tree>
69  
70 =item * C<Image::Size>
71  
72 =item * C<List::MoreUtils>
73  
74 =item * C<P5-Palm>
75  
76 =item * C<String::CRC32>
77  
78 =back
79  
80 =cut
81  
82  
83 1 ▶use Bit::Vector;
Subroutine BEGIN: called CC=1 SCAR=0.0
84 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
85 1 ▶use Compress::Zlib;
Subroutine BEGIN: called CC=1 SCAR=0.0
86 0 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
87 use EBook::Tools::PalmDoc qw(parse_palmdoc_header uncompress_palmdoc);
88 use Encode;
89 use Fcntl qw(SEEK_CUR SEEK_SET);
90 use File::Basename qw(dirname fileparse);
91 use File::Path; # Exports 'mkpath' and 'rmtree'
92 use HTML::TreeBuilder;
93 use Image::Size;
94 use List::Util qw(min);
95 use List::MoreUtils qw(uniq);
96 use Palm::PDB;
97 use Palm::Raw();
98 use String::CRC32();
99  
100  
101 our %exthtypes = (
102 1 => 'drm_server_id',
103 2 => 'drm_commerce_id',
104 3 => 'drm_ebookbase_book_id',
105 100 => 'author',
106 101 => 'publisher',
107 102 => 'imprint',
108 103 => 'description',
109 104 => 'isbn',
110 105 => 'subject',
111 106 => 'publicationdate',
112 107 => 'review',
113 108 => 'contributor',
114 109 => 'rights',
115 110 => 'subjectcode',
116 111 => 'type',
117 112 => 'source',
118 113 => 'asin',
119 114 => 'versionnumber',
120 115 => 'sample',
121 116 => 'startreading',
122 117 => 'adult',
123 118 => 'retailprice',
124 119 => 'currency',
125 120 => '120',
126 200 => '200',
127 201 => 'coveroffset',
128 202 => 'thumboffset',
129 203 => 'hasfakecover',
130 204 => '204',
131 205 => '205',
132 206 => '206',
133 207 => '207',
134 208 => '208',
135 209 => '209',
136 210 => '210',
137 300 => '300',
138 401 => 'clippinglimit',
139 402 => 'publisherlimit',
140 403 => '403',
141 501 => 'cdetype',
142 502 => 'lastupdatetime',
143 503 => 'updatedtitle',
144 );
145  
146 # A subset of %exthtypes where the value is an integer, not a string
147 our %exth_is_int = (
148 114 => 'versionnumber',
149 115 => 'sample',
150 201 => 'coveroffset',
151 202 => 'thumboffset',
152 203 => 'hasfakecover',
153 204 => '204',
154 205 => '205',
155 206 => '206',
156 207 => '207',
157 300 => '300',
158 401 => 'clippinglimit',
159 403 => '403',
160 );
161  
162 # A subset of %exthtypes where the value could conceivably show up
163 # several times
164 our %exth_repeats = (
165 101 => 'publisher',
166 104 => 'isbn',
167 105 => 'subject',
168 108 => 'contributor',
169 110 => 'subjectcode',
170 );
171  
172  
173 our %mobilangcode;
174 $mobilangcode{0}{0} = '';
175 $mobilangcode{54}{0} = 'af'; # Afrikaans
176 $mobilangcode{28}{0} = 'sq'; # Albanian
177 $mobilangcode{1}{0} = 'ar'; # Arabic
178 $mobilangcode{1}{20} = 'ar-dz'; # Arabic (Algeria)
179 $mobilangcode{1}{60} = 'ar-bh'; # Arabic (Bahrain)
180 $mobilangcode{1}{12} = 'ar-eg'; # Arabic (Egypt)
181 #$mobilangcode{1}{??} = 'ar-iq'; # Arabic (Iraq) -- Mobipocket broken
182 $mobilangcode{1}{44} = 'ar-jo'; # Arabic (Jordan)
183 $mobilangcode{1}{52} = 'ar-kw'; # Arabic (Kuwait)
184 $mobilangcode{1}{48} = 'ar-lb'; # Arabic (Lebanon)
185 #$mobilangcode{1}{??} = 'ar-ly'; # Arabic (Libya) -- Mobipocket broken
186 $mobilangcode{1}{24} = 'ar-ma'; # Arabic (Morocco)
187 $mobilangcode{1}{32} = 'ar-om'; # Arabic (Oman)
188 $mobilangcode{1}{64} = 'ar-qa'; # Arabic (Qatar)
189 $mobilangcode{1}{4} = 'ar-sa'; # Arabic (Saudi Arabia)
190 $mobilangcode{1}{40} = 'ar-sy'; # Arabic (Syria)
191 $mobilangcode{1}{28} = 'ar-tn'; # Arabic (Tunisia)
192 $mobilangcode{1}{56} = 'ar-ae'; # Arabic (United Arab Emirates)
193 $mobilangcode{1}{36} = 'ar-ye'; # Arabic (Yemen)
194 $mobilangcode{43}{0} = 'hy'; # Armenian
195 $mobilangcode{77}{0} = 'as'; # Assamese
196 $mobilangcode{44}{0} = 'az'; # "Azeri (IANA: Azerbaijani)
197 #$mobilangcode{44}{??} = 'az-cyrl'; # "Azeri (Cyrillic)" -- Mobipocket broken
198 #$mobilangcode{44}{??} = 'az-latn'; # "Azeri (Latin)" -- Mobipocket broken
199 $mobilangcode{45}{0} = 'eu'; # Basque
200 $mobilangcode{35}{0} = 'be'; # Belarusian
201 $mobilangcode{69}{0} = 'bn'; # Bengali
202 $mobilangcode{2}{0} = 'bg'; # Bulgarian
203 $mobilangcode{3}{0} = 'ca'; # Catalan
204 $mobilangcode{4}{0} = 'zh'; # Chinese
205 $mobilangcode{4}{12} = 'zh-hk'; # Chinese (Hong Kong)
206 $mobilangcode{4}{8} = 'zh-cn'; # Chinese (PRC)
207 $mobilangcode{4}{16} = 'zh-sg'; # Chinese (Singapore)
208 $mobilangcode{4}{4} = 'zh-tw'; # Chinese (Taiwan)
209 $mobilangcode{26}{0} = 'hr'; # Croatian
210 $mobilangcode{5}{0} = 'cs'; # Czech
211 $mobilangcode{6}{0} = 'da'; # Danish
212 $mobilangcode{19}{0} = 'nl'; # Dutch / Flemish
213 $mobilangcode{19}{8} = 'nl-be'; # Dutch (Belgium)
214 $mobilangcode{9}{0} = 'en'; # English
215 $mobilangcode{9}{12} = 'en-au'; # English (Australia)
216 $mobilangcode{9}{40} = 'en-bz'; # English (Belize)
217 $mobilangcode{9}{16} = 'en-ca'; # English (Canada)
218 $mobilangcode{9}{24} = 'en-ie'; # English (Ireland)
219 $mobilangcode{9}{32} = 'en-jm'; # English (Jamaica)
220 $mobilangcode{9}{20} = 'en-nz'; # English (New Zealand)
221 $mobilangcode{9}{52} = 'en-ph'; # English (Philippines)
222 $mobilangcode{9}{28} = 'en-za'; # English (South Africa)
223 $mobilangcode{9}{44} = 'en-tt'; # English (Trinidad)
224 $mobilangcode{9}{8} = 'en-gb'; # English (United Kingdom)
225 $mobilangcode{9}{4} = 'en-us'; # English (United States)
226 $mobilangcode{9}{48} = 'en-zw'; # English (Zimbabwe)
227 $mobilangcode{37}{0} = 'et'; # Estonian
228 $mobilangcode{56}{0} = 'fo'; # Faroese
229 $mobilangcode{41}{0} = 'fa'; # Farsi / Persian
230 $mobilangcode{11}{0} = 'fi'; # Finnish
231 $mobilangcode{12}{0} = 'fr'; # French
232 $mobilangcode{12}{4} = 'fr'; # French (Mobipocket bug?)
233 $mobilangcode{12}{8} = 'fr-be'; # French (Belgium)
234 $mobilangcode{12}{12} = 'fr-ca'; # French (Canada)
235 $mobilangcode{12}{20} = 'fr-lu'; # French (Luxembourg)
236 $mobilangcode{12}{24} = 'fr-mc'; # French (Monaco)
237 $mobilangcode{12}{16} = 'fr-ch'; # French (Switzerland)
238 $mobilangcode{55}{0} = 'ka'; # Georgian
239 $mobilangcode{7}{0} = 'de'; # German
240 $mobilangcode{7}{12} = 'de-at'; # German (Austria)
241 $mobilangcode{7}{20} = 'de-li'; # German (Liechtenstein)
242 $mobilangcode{7}{16} = 'de-lu'; # German (Luxembourg)
243 $mobilangcode{7}{8} = 'de-ch'; # German (Switzerland)
244 $mobilangcode{8}{0} = 'el'; # Greek, Modern (1453-)
245 $mobilangcode{71}{0} = 'gu'; # Gujarati
246 $mobilangcode{13}{0} = 'he'; # Hebrew (also code 'iw'?)
247 $mobilangcode{57}{0} = 'hi'; # Hindi
248 $mobilangcode{14}{0} = 'hu'; # Hungarian
249 $mobilangcode{15}{0} = 'is'; # Icelandic
250 $mobilangcode{33}{0} = 'id'; # Indonesian
251 $mobilangcode{16}{0} = 'it'; # Italian
252 $mobilangcode{16}{4} = 'it'; # Italian (Mobipocket bug?)
253 $mobilangcode{16}{8} = 'it-ch'; # Italian (Switzerland)
254 $mobilangcode{17}{0} = 'ja'; # Japanese
255 $mobilangcode{75}{0} = 'kn'; # Kannada
256 $mobilangcode{63}{0} = 'kk'; # Kazakh
257 $mobilangcode{87}{0} = 'x-kok'; # Konkani (real language code is 'kok'?)
258 $mobilangcode{18}{0} = 'ko'; # Korean
259 $mobilangcode{38}{0} = 'lv'; # Latvian
260 $mobilangcode{39}{0} = 'lt'; # Lithuanian
261 $mobilangcode{47}{0} = 'mk'; # Macedonian
262 $mobilangcode{62}{0} = 'ms'; # Malay
263 #$mobilangcode{62}{??} = 'ms-bn'; # Malay (Brunei Darussalam) -- not supported
264 #$mobilangcode{62}{??} = 'ms-my'; # Malay (Malaysia) -- Mobipocket bug
265 $mobilangcode{76}{0} = 'ml'; # Malayalam
266 $mobilangcode{58}{0} = 'mt'; # Maltese
267 $mobilangcode{78}{0} = 'mr'; # Marathi
268 $mobilangcode{97}{0} = 'ne'; # Nepali
269 $mobilangcode{20}{0} = 'no'; # Norwegian
270 #$mobilangcode{??}{??} = 'nb'; # Norwegian Bokml (Mobipocket not supported)
271 #$mobilangcode{??}{??} = 'nn'; # Norwegian Nynorsk (Mobipocket not supported)
272 $mobilangcode{72}{0} = 'or'; # Oriya
273 $mobilangcode{21}{0} = 'pl'; # Polish
274 $mobilangcode{22}{0} = 'pt'; # Portuguese
275 $mobilangcode{22}{8} = 'pt'; # Portuguese (Mobipocket bug?)
276 $mobilangcode{22}{4} = 'pt-br'; # Portuguese (Brazil)
277 $mobilangcode{70}{0} = 'pa'; # Punjabi
278 $mobilangcode{23}{0} = 'rm'; # "Rhaeto-Romanic" (IANA: Romansh)
279 $mobilangcode{24}{0} = 'ro'; # Romanian
280 #$mobilangcode{24}{??} = 'ro-mo'; # Romanian (Moldova) (Mobipocket output is 0)
281 $mobilangcode{25}{0} = 'ru'; # Russian
282 #$mobilangcode{25}{??} = 'ru-mo'; # Russian (Moldova) (Mobipocket output is 0)
283 $mobilangcode{59}{0} = 'sz'; # "Sami (Lappish)" (not an IANA language code)
284 # IANA code for "Northern Sami" is 'se'
285 # 'SZ' is the IANA region code for Swaziland
286 $mobilangcode{79}{0} = 'sa'; # Sanskrit
287 $mobilangcode{26}{12} = 'sr'; # Serbian -- Mobipocket Cyrillic/Latin distinction broken
288 #$mobilangcode{26}{12} = 'sr-cyrl'; # Serbian (Cyrillic) (Mobipocket bug)
289 #$mobilangcode{26}{12} = 'sr-latn'; # Serbian (Latin) (Mobipocket bug)
290 $mobilangcode{27}{0} = 'sk'; # Slovak
291 $mobilangcode{36}{0} = 'sl'; # Slovenian
292 $mobilangcode{46}{0} = 'sb'; # "Sorbian" (not an IANA language code)
293 # 'SB' is IANA region code for 'Solomon Islands'
294 # Lower Sorbian = 'dsb'
295 # Upper Sorbian = 'hsb'
296 # Sorbian Languages = 'wen'
297 $mobilangcode{10}{0} = 'es'; # Spanish
298 $mobilangcode{10}{4} = 'es'; # Spanish (Mobipocket bug?)
299 $mobilangcode{10}{44} = 'es-ar'; # Spanish (Argentina)
300 $mobilangcode{10}{64} = 'es-bo'; # Spanish (Bolivia)
301 $mobilangcode{10}{52} = 'es-cl'; # Spanish (Chile)
302 $mobilangcode{10}{36} = 'es-co'; # Spanish (Colombia)
303 $mobilangcode{10}{20} = 'es-cr'; # Spanish (Costa Rica)
304 $mobilangcode{10}{28} = 'es-do'; # Spanish (Dominican Republic)
305 $mobilangcode{10}{48} = 'es-ec'; # Spanish (Ecuador)
306 $mobilangcode{10}{68} = 'es-sv'; # Spanish (El Salvador)
307 $mobilangcode{10}{16} = 'es-gt'; # Spanish (Guatemala)
308 $mobilangcode{10}{72} = 'es-hn'; # Spanish (Honduras)
309 $mobilangcode{10}{8} = 'es-mx'; # Spanish (Mexico)
310 $mobilangcode{10}{76} = 'es-ni'; # Spanish (Nicaragua)
311 $mobilangcode{10}{24} = 'es-pa'; # Spanish (Panama)
312 $mobilangcode{10}{60} = 'es-py'; # Spanish (Paraguay)
313 $mobilangcode{10}{40} = 'es-pe'; # Spanish (Peru)
314 $mobilangcode{10}{80} = 'es-pr'; # Spanish (Puerto Rico)
315 $mobilangcode{10}{56} = 'es-uy'; # Spanish (Uruguay)
316 $mobilangcode{10}{32} = 'es-ve'; # Spanish (Venezuela)
317 $mobilangcode{48}{0} = 'sx'; # "Sutu" (not an IANA language code)
318 # "Sutu" is another name for "Southern Sotho"?
319 # IANA code for "Southern Sotho" is 'st'
320 $mobilangcode{65}{0} = 'sw'; # Swahili
321 $mobilangcode{29}{0} = 'sv'; # Swedish
322 $mobilangcode{29}{8} = 'sv-fi'; # Swedish (Finland)
323 $mobilangcode{73}{0} = 'ta'; # Tamil
324 $mobilangcode{68}{0} = 'tt'; # Tatar
325 $mobilangcode{74}{0} = 'te'; # Telugu
326 $mobilangcode{30}{0} = 'th'; # Thai
327 $mobilangcode{49}{0} = 'ts'; # Tsonga
328 $mobilangcode{50}{0} = 'tn'; # Tswana
329 $mobilangcode{31}{0} = 'tr'; # Turkish
330 $mobilangcode{34}{0} = 'uk'; # Ukrainian
331 $mobilangcode{32}{0} = 'ur'; # Urdu
332 $mobilangcode{67}{0} = 'uz'; # Uzbek
333 $mobilangcode{67}{8} = 'uz'; # Uzbek (Mobipocket bug?)
334 #$mobilangcode{67}{??} = 'uz-cyrl'; # Uzbek (Cyrillic)
335 #$mobilangcode{67}{??} = 'uz-latn'; # Uzbek (Latin)
336 $mobilangcode{42}{0} = 'vi'; # Vietnamese
337 $mobilangcode{52}{0} = 'xh'; # Xhosa
338 $mobilangcode{53}{0} = 'zu'; # Zulu
339  
340 our $mobigen_cmd = '';
341 our $mobidedrm_cmd = '';
342  
343 my %pdbencoding = (
344 '1252' => 'Windows-1252',
345 '65001' => 'UTF-8',
346 );
347  
348  
349 #################################
350 ########## CONSTRUCTOR ##########
351 #################################
352  
353 =head1 CONSTRUCTOR
354  
355 =head2 C<new()>
356  
357 Instantiates a new Ebook::Tools::Mobipocket object.
358  
359 =cut
360  
361 sub new ## no critic (Always unpack @_ first)
362 {
363 my $class = shift;
364 my $self = $class->SUPER::new(@_);
365  
366 $self->{'creator'} = 'BOOK';
367 $self->{'type'} = 'MOBI';
368  
369 $self->{attributes}{resource} = 0;
370  
371 $self->{appinfo} = undef;
372 $self->{sort} = undef;
373 $self->{records} = [];
374  
375 $self->{header} = {};
376 $self->{encoding} = 1252;
377 $self->{text} = '';
378 $self->{imagedata} = {};
379 $self->{unknowndata} = {};
380 $self->{recindexlinks} = {};
381 $self->{recindex} = 1; # Image index used to keep track of which image
382 # record maps to which link. This has to start
383 # at 1 to match what mobipocket does with the
384 # recindex attributes in the text
385  
386 $self->{title} = '';
387 $self->{author} = '';
388 $self->{rights} = '';
389 $self->{publisher} = '';
390 $self->{isbn} = '';
391  
392 return $self;
393 }
394  
395  
396 ######################################
397 ########## ACCESSOR METHODS ##########
398 ######################################
399  
400 =head1 ACCESSOR METHODS
401  
402 =head2 C<drm()>
403  
404 Returns 1 if the C<drmoffset> header value is neither C<0> nor
405 C<0xffffffff>. Returns undef if C<drmoffset> is undefined. Returns 0
406 otherwise.
407  
408 =cut
409  
410 sub drm :method
411 {
412 my $self = shift;
413 my $drmoffset = $self->{header}{mobi}{drmoffset};
414 return unless(defined $drmoffset);
415 return 1 if( $drmoffset && ($drmoffset != hex("0xffffffff")) );
416 return 0;
417 }
418  
419  
420 =head2 C<text()>
421  
422 Returns the text of the file
423  
424 =cut
425  
426 sub text :method
427 {
428 my $self = shift;
429 my $subname = ( caller(0) )[3];
430 debug(2,"DEBUG[",$subname,"]");
431  
432 my $length = length($self->{text});
433  
434 debug(2,"WARNING: actual text length (",$length,
435 ") does not match specified text length (",
436 $self->{header}{palm}{textlength},")")
437 unless($length == $self->{header}{palm}{textlength});
438  
439 return $self->{text};
440 }
441  
442  
443 =head2 C<write_images()>
444  
445 Writes each image record to the disk.
446  
447 Returns the number of images written.
448  
449 =cut
450  
451 sub write_images :method
452 {
453 my $self = shift;
454 my $subname = ( caller(0) )[3];
455 debug(3,"DEBUG[",$subname,"]");
456  
457 my %imagedata = %{$self->{imagedata}};
458  
459 foreach my $image (sort keys %imagedata)
460 {
461 debug(1,"Writing image '",$image,"' [",
462 length(${$imagedata{$image}})," bytes]");
463 open(my $fh,">:raw",$image)
464 or croak("Unable to open '",$image,"' to write image\n");
465 print {*$fh} ${$imagedata{$image}};
466 close($fh)
467 or croak("Unable to close image file '",$image,"'\n");
468 }
469 return scalar(keys %imagedata);
470 }
471  
472  
473 =head2 C<write_text($filename)>
474  
475 Writes the book text to disk with the given filename. This filename
476 must match the filename given to L</fix_html()> for the internal links
477 to be consistent.
478  
479 Croaks if C<$filename> is not specified.
480  
481 Returns 1 on success, or undef if there was no text to write.
482  
483 =cut
484  
485 sub write_text :method
486 {
487 my $self = shift;
488 my $filename = shift;
489 my $subname = ( caller(0) )[3];
490 debug(3,"DEBUG[",$subname,"]");
491  
492 croak($subname,"(): no filename specified.\n")
493 unless($filename);
494 return unless($$self{text});
495  
496 debug(1,"DEBUG: writing text to '",$filename,
497 "', encoding ",$pdbencoding{$self->{encoding}});
498  
499 open(my $fh,">",$filename)
500 or croak($subname,"(): unable to open '",$filename,"' for writing!\n");
501 binmode($fh);
502 print {*$fh} $self->{text};
503 close($fh)
504 or croak($subname,"(): unable to close '",$filename,"'!\n");
505  
506 croak($subname,"(): failed to generate any text")
507 if(-z $filename);
508  
509 return 1;
510 }
511  
512  
513 =head2 C<write_unknown_records()>
514  
515 Writes each unidentified record to disk with a filename in the format of
516 'raw-record-####', where #### is the record number (not the record ID).
517  
518 Returns the number of records written.
519  
520 =cut
521  
522 sub write_unknown_records :method
523 {
524 my $self = shift;
525 my $subname = ( caller(0) )[3];
526 debug(3,"DEBUG[",$subname,"]");
527  
528 my %unknowndata = %{$self->{unknowndata}};
529  
530 foreach my $rec (sort { $a <=> $b } keys %unknowndata)
531 {
532 my $recstring = sprintf("%04d",$rec);
533 debug(1,"Dumping raw record ",$recstring);
534 my $rawname = "raw-record-" . $recstring;
535 open(my $fh,">:raw",$rawname)
536 or croak("Unable to open '",$rawname,"' to write raw record\n");
537 print {*$fh} $$self{unknowndata}{$rec};
538 close($fh)
539 or croak("Unable to close raw record file '",$rawname,"'\n");
540 }
541 return scalar(keys %unknowndata);
542 }
543  
544  
545 ######################################
546 ########## MODIFIER METHODS ##########
547 ######################################
548  
549 =head1 MODIFIER METHODS
550  
551 These methods have two naming/capitalization schemes -- methods
552 directly related to the subclassing of Palm::PDB use its MethodName
553 capitalization style. Any other methods are
554 lowercase_with_underscores for consistency with the rest of
555 EBook::Tools.
556  
557  
558 =head2 C<Load($filename)>
559  
560 Sets C<< $self->{filename} >> and then loads and parses the file specified
561 by C<$filename>, calling L</ParseRecord(%record)> on every record
562 found.
563  
564 If DictionaryHuffman compression is detected, text records will be
565 left untouched during the ParseRecord pass, and
566 L</uncompress_dictionaryhuffman_records()> will be called after the
567 initial parsing pass is complete.
568  
569 =cut
570  
571 sub Load :method
572 {
573 my $self = shift;
574 my $filename = shift;
575 my $retval;
576  
577 $self->{filename} = $filename;
578 $retval = $self->SUPER::Load($filename);
579 if($self->{header}{palm}{compression} == 17480)
580 {
581 $self->uncompress_dictionaryhuffman_records();
582 }
583 return $retval;
584 }
585  
586  
587 =head2 C<ParseRecord(%record)>
588  
589 Parses PDB records, updating the object attributes. This method is
590 called automatically on every database record during C<Load()>.
591  
592 =cut
593  
594 sub ParseRecord :method ## no critic (Always unpack @_ first)
595 {
596 ## The long if-elsif chain is the best logic for record number handling
597 ## no critic (Cascading if-elsif chain)
598 my $self = shift;
599 my %record = @_;
600 my $subname = ( caller(0) )[3];
601 debug(3,"DEBUG[",$subname,"]");
602  
603 my $currentrecord;
604 if(!defined $$self{records})
605 {
606 $currentrecord = 0;
607 }
608 else
609 {
610 $currentrecord = scalar @{$$self{records}};
611 }
612  
613 my $data = $record{data};
614 my $compression = $$self{header}{palm}{compression};
615 my $recordtext;
616  
617 # If a DATP record exists, it may have the same record number
618 # as 'lastimagerecord'?
619 my @afterimage;
620 push(@afterimage,$self->{header}{mobi}{lastimagerecord}+1)
621 if($self->{header}{mobi}{lastimagerecord});
622 push(@afterimage,$self->{header}{mobi}{datprecord})
623 if($self->{header}{mobi}{datprecord});
624  
625 # Several things can come after INDX records, but some of them can
626 # have record offsets of 0
627 my @afterindx;
628 push(@afterindx,$self->{header}{mobi}{huffrecord})
629 if($self->{header}{mobi}{huffrecord});
630 push(@afterindx,$self->{header}{mobi}{firstimagerecord})
631 if($self->{header}{mobi}{firstimagerecord});
632 push(@afterindx,$self->{header}{mobi}{datprecord})
633 if($self->{header}{mobi}{datprecord});
634  
635 if($currentrecord == 0)
636 {
637 $self->ParseRecord0($data);
638 }
639 elsif($currentrecord < $$self{header}{mobi}{indxrecord}
640 && $currentrecord < $$self{header}{mobi}{firstimagerecord})
641 {
642 # Text records come immediately after the header record, but
643 # the distinction between indxrecord and firstimagerecord is
644 # not clear. Sometimes images show up at one, and sometimes
645 # the other.
646  
647 if($self->drm)
648 {
649 debug(3,"DEBUG: record ",$currentrecord,
650 " is DRM-protected text, skipping");
651 }
652 elsif($compression == 17480)
653 {
654 # HUFF/CDIC-compressed text is skipped on the first pass,
655 # since uncompressing it requires data from records that
656 # aren't parsed until later.
657 debug(3,"DEBUG: record ",$currentrecord,
658 " is HUFF/CDIC-compressed, handled in second pass");
659 }
660 else
661 {
662 debug(3,"DEBUG: record ",$currentrecord,
663 " is uncompressed or PalmDoc-compressed text");
664 $self->ParseRecordText(\$data);
665 }
666 }
667 elsif($currentrecord >= $$self{header}{mobi}{indxrecord}
668 && $currentrecord < min(@afterindx))
669 {
670 # INDX records are not understood.
671 debug(1,"DEBUG: record ",$currentrecord," is INDX record [",
672 length($data)," bytes starting with '",
673 substr($record{data},0,4),"']");
674 $$self{unknowndata}{$currentrecord} = $data;
675 }
676 elsif($currentrecord >= $$self{header}{mobi}{huffrecord}
677 && $currentrecord <
678 ($$self{header}{mobi}{huffrecord}
679 + $$self{header}{mobi}{huffreccnt}) )
680 {
681 my $recordtype = substr($data,0,4);
682 if($recordtype eq 'HUFF')
683 {
684 $self->ParseRecordHUFF(\$data);
685 }
686 elsif($recordtype eq 'CDIC')
687 {
688 $self->ParseRecordCDIC(\$data);
689 }
690 else
691 {
692 debug(1,"WARNING: record ",$currentrecord,
693 " expected HUFF/CDIC record, but found ",
694 length($data)," bytes starting with '",
695 $recordtype,"'");
696 }
697 }
698 elsif($currentrecord >= $$self{header}{mobi}{firstimagerecord}
699 && $currentrecord < min(@afterimage) )
700 {
701 my ($imagex,undef,$imagetype) = imgsize(\$data);
702 if(defined($imagex) && $imagetype)
703 {
704 $self->ParseRecordImage(\$data);
705 }
706 else
707 {
708 debug(1,"DEBUG: record ",$currentrecord,
709 " is not imagedata, but ",length($data),
710 " bytes starting with '", substr($data,0,4),"'");
711 $$self{unknowndata}{$currentrecord} = $data;
712 }
713 }
714 elsif($currentrecord >= $$self{header}{mobi}{datprecord}
715 && $currentrecord <
716 $$self{header}{mobi}{datprecord} + $$self{header}{mobi}{datpreccnt})
717 {
718 # DATP records not understood
719 my $recordid = substr($data,0,4);
720 if($recordid eq 'DATP')
721 {
722 debug(2,"DEBUG: record ",$currentrecord," is DATP record");
723 }
724 else
725 {
726 debug(1,"DEBUG: record ",$currentrecord," isn't DATP record?");
727 }
728 $$self{unknowndata}{$currentrecord} = $data;
729 }
730 elsif($currentrecord == $$self{header}{mobi}{flisrecord})
731 {
732 my $recordid = substr($data,0,4);
733 if($recordid eq 'FLIS')
734 {
735 debug(2,"DEBUG: record ",$currentrecord," is FLIS record");
736 }
737 else
738 {
739 debug(1,"DEBUG: record ",$currentrecord," isn't FLIS record?");
740 }
741 $$self{unknowndata}{$currentrecord} = $data;
742 }
743 elsif($currentrecord == $$self{header}{mobi}{fcisrecord})
744 {
745 my $recordid = substr($data,0,4);
746 if($recordid eq 'FCIS')
747 {
748 debug(2,"DEBUG: record ",$currentrecord," is FCIS record");
749 }
750 else
751 {
752 debug(1,"DEBUG: record ",$currentrecord," isn't FCIS record?");
753 }
754 $$self{unknowndata}{$currentrecord} = $data;
755 }
756 else
757 {
758 $recordtext = uncompress($record{data});
759 $recordtext = uncompress_palmdoc($record{data}) unless($recordtext);
760 if($recordtext)
761 {
762 debug(1,"DEBUG: record ",$currentrecord," has extra text:");
763 debug(1," '",$recordtext,"'");
764 $$self{unknowndata}{$currentrecord} = $recordtext;
765 }
766 else
767 {
768 debug(1,"DEBUG: record ",$currentrecord," is unknown (",
769 length($data)," bytes starting with '",
770 substr($record{data},0,4),"')");
771 $$self{unknowndata}{$currentrecord} = $data;
772 }
773 }
774  
775 return \%record;
776 }
777  
778  
779 =head2 C<ParseRecord0($data)>
780  
781 Parses the header record and places the parsed values into the hashref
782 C<< $self->{header}{palm} >>, the hashref C<< $self->{header}{mobi} >>,
783 and C<< $self->{header}{exth} >> by calling L</parse_palmdoc_header()>,
784 L</parse_mobi_header()>, and L</parse_mobi_exth()> respectively.
785  
786 =cut
787  
788 sub ParseRecord0 :method
789 {
790 my $self = shift;
791 my $data = shift;
792 my $subname = ( caller(0) )[3];
793 debug(2,"DEBUG[",$subname,"]");
794  
795 my $headerdata; # used for holding temporary data segments
796 my $headersize; # size of variable-length header data
797 my %headermobi;
798  
799 my @list;
800  
801 # First 16 bytes are a slightly modified palmdoc header
802 # See http://wiki.mobileread.com/wiki/MOBI
803 $headerdata = substr($data,0,16);
804 $$self{header}{palm} = parse_palmdoc_header($headerdata);
805  
806 # Find out how long the Mobipocket header actually is
807 $headerdata = substr($data,16,8);
808 @list = unpack("a4N",$headerdata);
809 croak($subname,
810 "(): Unrecognized Mobipocket header ID '",$list[0],
811 "' (expected 'MOBI')")
812 unless($list[0] eq 'MOBI');
813 $headersize = $list[1];
814 croak($subname,"(): unable to determine Mobipocket header size")
815 unless($list[1]);
816  
817 # Unpack the full Mobipocket header
818 $headerdata = substr($data,16,$headersize);
819 %headermobi = %{parse_mobi_header($headerdata)};
820 $$self{header}{mobi} = \%headermobi;
821 $$self{encoding} = $headermobi{encoding};
822  
823 if($headermobi{exthflags} & 0x040) # If bit 6 is set, EXTH exists
824 {
825 debug(2,"DEBUG: Unpacking EXTH data at record 0 offset ",
826 $headersize+16);
827 $headerdata = substr($data,$headersize+16);
828 $$self{header}{exth} = parse_mobi_exth($headerdata);
829 }
830  
831 if($headermobi{titleoffset} && $headermobi{titlelength})
832 {
833 # This is a better guess at the title than the one
834 # derived from $pdb->name
835 $$self{title} =
836 substr($data,$headermobi{titleoffset},$headermobi{titlelength});
837 debug(1,"DEBUG: Extracted title '",$$self{title},"'");
838 }
839  
840 return 1;
841 }
842  
843  
844 =head2 C<ParseRecordCDIC(\$data)>
845  
846 Parses a CDIC record. Takes as a sole argument a reference to the
847 data of the record.
848  
849 =head3 Record format
850  
851 =over
852  
853 =item * Offset 0: Record identifier
854  
855 4 bytes, always 'CDIC'
856  
857 =item * Offset 4: Header length
858  
859 4 bytes, big-endian long int, always = 16
860  
861 =item * Offset 8: Index count
862  
863 4 bytes, big-endian long int, marks the number of big-endian short
864 ints immediately following the header used as index points into the
865 dictionary data
866  
867 =item * Offset 12: Codelength
868  
869 4 bytes, big-endian long int, number of code bits
870  
871 =item * Offset 16: Indexes
872  
873 A number of big-endian short ints used as index points into the
874 dictionary data
875  
876 =item * Offset ??: Dictionary data
877  
878 Dictionary result strings immediately following the indexes
879  
880 =back
881  
882 =cut
883  
884 sub ParseRecordCDIC
885 {
886 my $self = shift;
887 my $dataref = shift;
888 my $subname = ( caller(0) )[3];
889 debug(3,"DEBUG[",$subname,"]");
890  
891 my $currentrecord = scalar @{$self->{records}};
892 my %cdic;
893 my @cdics;
894 my $size = length($$dataref);
895 my @list = unpack('a4NNN',substr($$dataref,0,16));
896 my $recordid = $list[0];
897 my $headerlength = $list[1];
898 my $indexcount = $list[2];
899 my $codelength = $list[3];
900  
901 if($recordid ne 'CDIC')
902 {
903 debug(1,"DEBUG: record ",$currentrecord,
904 " does not have CDIC header (found '",$recordid,"')");
905 $$self{unknowndata}{$currentrecord} = $$dataref;
906 $self->{huff} = {};
907 }
908 elsif($headerlength != 16)
909 {
910 debug(1,"DEBUG: record ",$currentrecord,
911 " is CDIC record with unexpected header length (",
912 $headerlength,", expected 16");
913 $$self{unknowndata}{$currentrecord} = $$dataref;
914 $self->{huff} = {};
915 }
916 elsif(!$codelength)
917 {
918 debug(1,"DEBUG: record ",$currentrecord,
919 " is CDIC record with zero codelength!");
920 $$self{unknowndata}{$currentrecord} = $$dataref;
921 $self->{huff} = {};
922 }
923 elsif($headerlength + (1 << $codelength) >= $size)
924 {
925 debug(1,"DEBUG: record ",$currentrecord,
926 " is CDIC record too short for its codelength (",
927 $size," bytes, codelength=",$codelength,")");
928 $$self{unknowndata}{$currentrecord} = $$dataref;
929 $self->{huff} = {};
930 }
931 elsif($self->{huff}->{codelength}
932 && $self->{huff}->{codelength} != $codelength)
933 {
934 debug(1,"DEBUG: record ",$currentrecord,
935 " is CDIC record with a new codelength (",
936 $codelength," bits, previous was ",
937 $self->{huff}->{codelength});
938 $$self{unknowndata}{$currentrecord} = $$dataref;
939 $self->{huff} = {};
940 }
941 else
942 {
943 my @indexes = unpack("n$indexcount",substr($$dataref,16,$indexcount*2));
944 $cdic{id} = $recordid;
945 $cdic{indexes} = \@indexes;
946 $cdic{data} = $$dataref;
947 $cdic{codelength} = $codelength;
948 $self->{huff}->{codelength} = $codelength;
949  
950 @cdics = @{$self->{cdics}} if($self->{cdics});
951  
952 push(@cdics,\%cdic);
953 $self->{cdics} = \@cdics;
954 debug(1,"DEBUG: record ",$currentrecord," is CDIC record ",
955 $#cdics, " [",length($$dataref)," bytes,",
956 " indexcount=",$indexcount,
957 " codelength=",$codelength,"]");
958 }
959 return 1;
960 }
961  
962  
963 =head2 C<ParseRecordHUFF(\$data)>
964  
965 Parses a HUFF record. Takes as a sole argument a reference to the
966 data of the record.
967  
968 =head3 Record format
969  
970 =over
971  
972 =item * Offset 0: Record identifier
973  
974 4 bytes, always 'HUFF'
975  
976 =item * Offset 4: Header length
977  
978 4 bytes, big-endian long int, always = 24
979  
980 =item * Offset 8: Cache table (big-endian) offset
981  
982 4 bytes, big-endian long int, always = 24
983  
984 =item * Offset 12: Base table (big-endian) offset
985  
986 4 bytes, big-endian long int, always = 1048
987  
988 =item * Offset 16: Cache table (little-endian) offset
989  
990 4 bytes, big-endian long int, always = 1304
991  
992 =item * Offset 20: Base table (little-endian) offset
993  
994 4 bytes, big-endian long int, always = 2328
995  
996 =item * Offset 24: Cache table (big-endian)
997  
998 1024 bytes, 256 big-endian long ints
999  
1000 This is a look up table for the length and decoding of short
1001 codewords. If the codeword represented by the 8 bits is unique, then
1002 bit 7 (0x80) will be set, and the low 5 bits are the length in bits of
1003 the code. The high three bytes partially represent the final symbol.
1004  
1005 If bit 7 is clear, then the code is looked up in the base table
1006  
1007 =item * Offset 1048: Base table (big-endian)
1008  
1009 256 bytes, 64 big-endian long ints
1010  
1011 This is where the codeword is looked up if it isn't found in the cache
1012 table.
1013  
1014 =item * Offset 1304: Cache table (little-endian)
1015  
1016 1024 bytes, 256 little-endian long ints.
1017  
1018 This contains exactly the same data as in the cache table at offset
1019 24, except that all of the values are stored in little-endian format
1020 instead of big-endian.
1021  
1022 Presumably this is for a speed advantage on slow little-endian
1023 processors. This module uses only the big-endian tables.
1024  
1025 =item * Offset 2328: Base table (little-endian)
1026  
1027 256 bytes, 64 little-endian long ints
1028  
1029 This contains exactly the same data as in the base table at offset
1030 1048, except that all of the values are stored in little-endian format
1031 instead of big-endian.
1032  
1033 Presumably this is for a speed advantage on slow little-endian
1034 processors. This module uses only the big-endian tables.
1035  
1036 =back
1037  
1038 =cut
1039  
1040  
1041 sub ParseRecordHUFF
1042 {
1043 my $self = shift;
1044 my $dataref = shift;
1045 my $subname = ( caller(0) )[3];
1046 debug(3,"DEBUG[",$subname,"]");
1047  
1048 my $currentrecord = scalar @{$self->{records}};
1049 my $size = length($$dataref);
1050 my %huff;
1051 my (@cache,@lecache);
1052 my (@basetable,@lebasetable);
1053 my $headerlength;
1054 my $codelength;
1055  
1056 my @list = unpack('a4NNNNN',substr($$dataref,0,24));
1057 $huff{id} = $list[0];
1058 $huff{headerlength} = $list[1];
1059 $huff{cacheoffset} = $list[2];
1060 $huff{baseoffset} = $list[3];
1061 $huff{lecacheoffset} = $list[4];
1062 $huff{lebaseoffset} = $list[5];
1063  
1064 $huff{data} = $$dataref;
1065 $huff{bitpos} = 0;
1066  
1067 if($huff{id} ne 'HUFF')
1068 {
1069 debug(1,"DEBUG: record ",$currentrecord,
1070 " does not have HUFF header (found '",$huff{id},"')");
1071 $$self{unknowndata}{$currentrecord} = $$dataref;
1072 return;
1073 }
1074 if($size < 2584)
1075 {
1076 debug(1,"WARNING: record ",$currentrecord,
1077 " is HUFF record with unexpected size (",
1078 $size," bytes, expected at least 2584");
1079 $$self{unknowndata}{$currentrecord} = $$dataref;
1080 return;
1081 }
1082 if($size < $huff{lebaseoffset} + 256)
1083 {
1084 debug(1,"WARNING: recoord ",$currentrecord,
1085 "is HUFF record too short to read all data (",
1086 $size," bytes, lebaseoffset=",$huff{lebaseoffset});
1087 $$self{unknowndata}{$currentrecord} = $$dataref;
1088 return;
1089 }
1090  
1091 @cache = unpack('N[256]',
1092 substr($$dataref,$huff{cacheoffset},256*4));
1093 $huff{cache} = \@cache;
1094  
1095 @basetable = unpack('N[64]',
1096 substr($$dataref,$huff{baseoffset},64*4));
1097 $huff{basetable} = \@basetable;
1098  
1099 # Little-endian versions aren't used, but are checked against
1100 # big-endian for corruption
1101 @lecache = unpack('V[256]',
1102 substr($$dataref,$huff{lecacheoffset},256*4));
1103 @lebasetable = unpack('V[64]',
1104 substr($$dataref,$huff{lebaseoffset},64*4));
1105  
1106 # Testing to see if the big-endian and little-endian tables are
1107 # identical is really only efficient with the smart-match operator,
1108 # which requires Perl 5.10 or later.
1109 #
1110 # Use of 5.10 features is being delayed until 5.10 is standard on
1111 # MacOSX and Debian.
1112 #
1113 # unless(@cache ~~ @lecache)
1114 # {
1115 # debug(1,"WARNING: big-endian and little-endian HUFF cache",
1116 # " tables are different in record ",$currentrecord,"!");
1117 # }
1118 # unless(@basetable ~~ @lebasetable)
1119 # {
1120 # debug(1,"WARNING: big-endian and little-endian HUFF base",
1121 # " tables are different in record ",$currentrecord,"!");
1122 # }
1123  
1124  
1125 if($huff{headerlength} != 24)
1126 {
1127 debug(1,"DEBUG: record ",$currentrecord,
1128 " is HUFF record with unexpected header length (",
1129 $huff{headerlength},", expected 24");
1130 $$self{unknowndata}{$currentrecord} = $$dataref;
1131 }
1132 elsif($huff{cacheoffset} != 24)
1133 {
1134 deubg(1,"DEBUG: record ",$currentrecord,
1135 " is HUFF record with unexpected cache offset (",
1136 $huff{cacheoffset}," expected 24");
1137 $$self{unknowndata}{$currentrecord} = $$dataref;
1138 }
1139 elsif($huff{baseoffset} != 1048)
1140 {
1141 debug(1,"DEBUG: record ",$currentrecord,
1142 " is HUFF record with unexpected base table offset (",
1143 $huff{baseoffset}," expected 1048)");
1144 $$self{unknowndata}{$currentrecord} = $$dataref;
1145 }
1146 else
1147 {
1148 $self->{huff} = \%huff;
1149 debug(2,"DEBUG: record ",$currentrecord," is HUFF record [",
1150 length($$dataref)," bytes,",
1151 " cacheoffset=",$huff{cacheoffset},
1152 " baseoffset=",$huff{baseoffset},
1153 " lecacheoffset=",$huff{lecacheoffset},
1154 " lebaseoffset=",$huff{lebaseoffset},"]");
1155 }
1156 return 1;
1157 }
1158  
1159  
1160 =head2 C<ParseRecordImage(\$dataref)>
1161  
1162 Parses image records, updating object attributes, most notably adding
1163 the image data to the hash C<< $self->{imagedata} >>, adding the image
1164 filename to C<< $self->{recindexlinks} >>, and incrementing
1165 C<< $self->{recindex} >>.
1166  
1167 Takes as an argument a reference to the record data. Croaks if it
1168 isn't provided, or isn't a reference.
1169  
1170 This is called automatically by L</ParseRecord()> and
1171 L</ParseResource()> as needed.
1172  
1173 =cut
1174  
1175 sub ParseRecordImage :method
1176 {
1177 my $self = shift;
1178 my $dataref = shift;
1179 my $subname = ( caller(0) )[3];
1180 debug(3,"DEBUG[",$subname,"]");
1181  
1182 croak($subname,"(): no image data provided\n") unless($dataref);
1183 croak($subname,"(): image data is not a reference\n") unless(ref $dataref);
1184  
1185 $$self{recindex} = 1 unless(defined $$self{recindex});
1186  
1187 my $currentrecord = scalar @{$$self{records}};
1188 my ($imagex,$imagey,$imagetype) = imgsize($dataref);
1189 my $idxstring = sprintf("%04d",$$self{recindex});
1190 my $imagename = $$self{name} . '-' . $idxstring . '.' . lc($imagetype);
1191  
1192 debug(1,"DEBUG: record ",$currentrecord," is image '",$imagename,
1193 "' (",$imagex," x ",$imagey,")");
1194 $$self{imagedata}{$imagename} = $dataref;
1195 $$self{recindexlinks}{$$self{recindex}} = $imagename;
1196 $$self{recindex}++;
1197 return 1;
1198 }
1199  
1200  
1201 =head2 C<ParseRecordText(\$dataref)>
1202  
1203 Parses text records, updating object attributes, most notably
1204 appending text to C<< $self->{text} >>. Takes as an argument a reference
1205 to the record data.
1206  
1207 This is called automatically by L</ParseRecord()> and
1208 L</ParseResource()> as needed.
1209  
1210 =cut
1211  
1212 sub ParseRecordText :method
1213 {
1214 my $self = shift;
1215 my $dataref = shift;
1216 my $subname = ( caller(0) )[3];
1217 debug(3,"DEBUG[",$subname,"]");
1218  
1219 my $currentrecord = scalar @{$$self{records}};
1220 my $compression = $$self{header}{palm}{compression};
1221 my $recordtext;
1222 my $extradatasize;
1223  
1224 debug(3,"DEBUG: extradataflags = ",$$self{header}{mobi}{extradataflags});
1225 if( $$self{header}{mobi}{extradataflags} )
1226 {
1227 $extradatasize = record_extradata_size(
1228 dataref => $dataref,
1229 extradataflags => $$self{header}{mobi}{extradataflags}
1230 );
1231 }
1232  
1233 if($compression == 1) # No compression
1234 {
1235 debug(3,"DEBUG: No compression on record ",$currentrecord);
1236 if($extradatasize)
1237 {
1238 $recordtext = substr($$dataref,0,length($$dataref)-$extradatasize);
1239 debug(3,"DEBUG: skipping ",$extradatasize," bytes at end of record ",
1240 $currentrecord);
1241 }
1242 else
1243 {
1244 $recordtext = $$dataref;
1245 }
1246 }
1247 elsif($compression == 2) # PalmDoc compression
1248 {
1249 my %args;
1250 if($extradatasize)
1251 {
1252 $args{trailing} = $extradatasize;
1253 debug(3,"DEBUG: skipping ",$extradatasize," bytes at end of record ",
1254 $currentrecord);
1255 }
1256 $recordtext = uncompress_palmdoc($$dataref,%args);
1257 }
1258 elsif($compression == 17480) # 'Dictionary Huffman' compression
1259 {
1260 # This has to be handled in a separate pass, as decompression
1261 # requires data from records not yet parsed.
1262 debug(3,"DEBUG: record ",$currentrecord,
1263 " is HUFF/CDIC-compressed text, deferring decompression");
1264 return 1;
1265 }
1266 else
1267 {
1268 croak($subname,"(): unknown compression value (",
1269 $compression,")\n");
1270 }
1271  
1272 if($recordtext)
1273 {
1274 $self->{text} .= $recordtext;
1275 debug(3,"DEBUG: parsed text record ",$currentrecord);
1276 }
1277 else
1278 {
1279 debug(1,"DEBUG: record ",$currentrecord,
1280 " could not be parsed (",
1281 length($$dataref)," bytes starting with '",
1282 substr($$dataref,0,4),"')");
1283 $$self{unknowndata}{$currentrecord} = $$dataref;
1284 }
1285 return 1;
1286 }
1287  
1288  
1289 =head2 fix_html(%args)
1290  
1291 Takes raw Mobipocket text and replaces the custom tags and file
1292 position anchors
1293  
1294 =head3 Arguments
1295  
1296 =over
1297  
1298 =item * C<filename>
1299  
1300 The name of the output HTML file (used in generating hrefs). The
1301 procedure croaks if this is not supplied.
1302  
1303 =item * C<nonewlines> (optional)
1304  
1305 If this is set to true, the procedure will not attempt to insert
1306 newlines for readability. This will leave the output in a single
1307 unreadable line, but has the advantage of reducing the processing
1308 time, especially useful if tidy is going to be run on the output
1309 anyway.
1310  
1311 =back
1312  
1313 =cut
1314  
1315 sub fix_html :method ## no critic (Always unpack @_ first)
1316 {
1317 my $self = shift;
1318 my (%args) = @_;
1319 my $subname = ( caller(0) )[3];
1320 debug(2,"DEBUG[",$subname,"]");
1321 my %valid_args = (
1322 'filename' => 1,
1323 'nonewlines' => 1,
1324 );
1325 foreach my $arg (keys %args)
1326 {
1327 croak($subname,"(): invalid argument '",$arg,"'")
1328 if(!$valid_args{$arg});
1329 }
1330 my $filename = $args{filename};
1331 my $encoding = $$self{encoding} || 1252;
1332 croak($subname,"(): no text found")
1333 unless($$self{text});
1334 croak($subname,"(): no filename supplied")
1335 unless($filename);
1336  
1337 my $tree;
1338 my @elements;
1339 my $head_element;
1340 my $element;
1341 my $recindex;
1342 my $link;
1343  
1344 # The very first thing that has to be done is map out all of the
1345 # filepos references and generate anchors at the referenced
1346 # positions. This must be done first because any other
1347 # modifications to the text will invalidate those positions.
1348 $self->fix_html_filepos();
1349  
1350 # Convert or remove the Mobipocket-specific tags
1351 $self->{text} =~ s#<mbp:pagebreak [\s\n]*
1352 #<br style="page-break-after: always" #gix;
1353 $self->{text} =~ s#</mbp:pagebreak>##gix;
1354 $self->{text} =~ s#</?mbp:nu>##gix;
1355 $self->{text} =~ s#</?mbp:section>##gix;
1356 $self->{text} =~ s#</?mbp:frameset##gix;
1357 $self->{text} =~ s#</?mbp:slave-frame##gix;
1358  
1359  
1360 # More complex alterations will require a HTML tree
1361 $tree = HTML::TreeBuilder->new();
1362 $tree->ignore_unknown(0);
1363 $tree->no_expand_entities(1);
1364 $tree->store_comments(1);
1365  
1366 # If the encoding is UTF-8, we have to note it specially before
1367 # the parse or the parser will break
1368 if($encoding == 65001) {
1369 $tree->utf8_mode(1);
1370 }
1371 $tree->parse($self->{text});
1372 $tree->eof();
1373  
1374 # Update contents of <head>
1375 $head_element = $tree->find('head');
1376 if(! $head_element) {
1377 $self->add_warning("No <head> element found in Mobipocket HTML!");
1378 }
1379 else {
1380 # Fix missing <title>
1381 $element = $head_element->find('title');
1382 if(! $element) {
1383 debug(1,"DEBUG: title element missing, creating as '",
1384 $self->{title},"'");
1385 $head_element->push_content(['title',$self->{title}]);
1386 }
1387 else {
1388 if(! $element->as_trimmed_text) {
1389 debug(1,"DEBUG: title is empty, setting to '",$self->{title},"'");
1390 $element->replace_with($self->{title});
1391 }
1392 }
1393  
1394 # Set UTF8 content type if necessary
1395 if($encoding == 65001) {
1396 $head_element->push_content(
1397 [ 'meta',
1398 {'http-equiv' => 'Content-type'},
1399 {'content' => 'text/html;charset=UTF-8' },
1400 ]);
1401 }
1402 }
1403  
1404 # Replace img recindex links with img src links
1405 debug(2,"DEBUG: converting img recindex attributes");
1406 @elements = $tree->find('img');
1407 foreach my $el (@elements)
1408 {
1409 $recindex = $el->attr('recindex') + 0;
1410 debug(3,"DEBUG: converting recindex ",$recindex," to src='",
1411 $self->{recindexlinks}{$recindex},"'");
1412 $el->attr('recindex',undef);
1413 $el->attr('hirecindex',undef);
1414 $el->attr('lorecindex',undef);
1415 $el->attr('src',$self->{recindexlinks}{$recindex});
1416 }
1417  
1418 # Replace filepos attributes with href attributes
1419 debug(2,"DEBUG: converting filepos attributes");
1420 @elements = $tree->look_down('filepos',qr/.*/x);
1421 foreach my $el (@elements)
1422 {
1423 $link = $el->attr('filepos');
1424 if($link)
1425 {
1426 debug(3,"DEBUG: converting filepos ",$link," to href");
1427 $link = '#fp' . $link;
1428 $el->attr('href',$link);
1429 $el->attr('filepos',undef);
1430 }
1431 }
1432  
1433 debug(2,"DEBUG: converting HTML tree");
1434 # We don't bother specifying an indent here, as the resulting
1435 # formatting is still broken and we have to insert newlines later
1436 # anyway.
1437 #
1438 # TODO: experiment with using Mojo::DOM instead
1439 $self->{text} = $tree->as_HTML(undef,'',{});
1440  
1441 croak($subname,"(): HTML tree output is empty")
1442 unless($self->{text});
1443  
1444 # Strip embedded nulls
1445 debug(2,"DEBUG: stripping nulls");
1446 $self->{text} =~ s/\0//gx;
1447  
1448 # HTML::TreeBuilder will not insert all appropriate newlines even
1449 # specifying indents in as_HTML, so add some back in for
1450 # readability even if tidy isn't called
1451 #
1452 # This is unfortunately quite slow.
1453 unless($args{nonewlines}) {
1454 debug(1,"DEBUG: adding newlines");
1455 $self->{text} =~ s#<(body|html)> \s* \n?
1456 #<$1>\n#gix;
1457 $self->{text} =~ s#\n? <div
1458 #\n<div#gix;
1459 $self->{text} =~ s#</div> \s* \n?
1460 #</div>\n#gix;
1461 $self->{text} =~ s#</h(\d)> \s* \n?
1462 #</h$1>\n#gix;
1463 $self->{text} =~ s#</head> \s* \n?
1464 #</head>\n#gix;
1465 $self->{text} =~ s#\n? <(br|p)([\s>])
1466 #\n<$1$2#gix;
1467 $self->{text} =~ s#</p>\s*
1468 #</p>\n#gix;
1469 }
1470  
1471 return 1;
1472 }
1473  
1474  
1475 =head2 C<fix_html_filepos()>
1476  
1477 Takes the raw HTML text of the object and replaces the filepos
1478 anchors. This has to be called before any other action that modifies
1479 the text, or the filepos positions will not be valid.
1480  
1481 Returns 1 if successful, undef if there was no text to fix.
1482  
1483 This is called automatically by L</fix_html()>.
1484  
1485 =cut
1486  
1487 sub fix_html_filepos :method
1488 {
1489 # There doesn't appear to be any clearer way of handling this
1490 # than the if-elsif chain.
1491 ## no critic (Cascading if-elsif chain)
1492 my $self = shift;
1493 my $subname = ( caller(0) )[3];
1494 debug(2,"DEBUG[",$subname,"]");
1495  
1496 my @filepos = ($$self{text} =~ /filepos="?([0-9]+)/gix);
1497 my $length = length($$self{text});
1498 return unless($length);
1499 my $atpos;
1500  
1501 debug(1,"DEBUG: creating filepos anchors");
1502 foreach my $pos (uniq reverse sort @filepos)
1503 {
1504 # First, see if we're pointing to a position outside the text
1505 if($pos >= $length-4)
1506 {
1507 debug(1,"DEBUG: filepos ",$pos," outside text, skipping");
1508 next;
1509 }
1510  
1511 # Second, figure out what we're dealing with at the filepos
1512 # offset indicated
1513 $atpos = substr($$self{text},$pos,5);
1514 if($atpos =~ /^<mbp/ix)
1515 {
1516 # Mobipocket-specific element
1517 # Insert a whole new <a id> here
1518 debug(2,"DEBUG: filepos ",$pos," points to '<mbp',",
1519 " creating new anchor");
1520 substr($$self{text},$pos,4,'<a id="fp' . $pos . '"></a><mbp');
1521 }
1522 elsif($atpos =~ /^<(a|p)[ >]/ix)
1523 {
1524 # 1-character block-level elements
1525 debug(2,"DEBUG: filepos ",$pos," points to '",$1,"', updating id");
1526 substr($$self{text},$pos,2,"<$1 id=\"fp" . $pos . '"');
1527 }
1528 elsif($atpos =~ /^<(h\d)[ >]/ix)
1529 {
1530 # 2-character block-level elements
1531 debug(2,"DEBUG: filepos ",$pos," points to '",$1,"', updating id");
1532 substr($$self{text},$pos,3,"<$1 id=\"fp" . $pos . '"');
1533 }
1534 elsif($atpos =~ /^<(div)[ >]/ix)
1535 {
1536 # 3-character block-level elements
1537 debug(2,"DEBUG: filepos ",$pos," points to '",$1,"', updating id");
1538 substr($$self{text},$pos,4,"<$1 id=\"fp" . $pos . '"');
1539 }
1540 elsif($atpos =~ /^</ix)
1541 {
1542 # All other elements
1543 debug(2,"DEBUG: filepos ",$pos," points to '",$atpos,
1544 "', creating new anchor");
1545 substr($$self{text},$pos,1,'<a id="fp' . $pos . '"></a><');
1546 }
1547 else
1548 {
1549 # Not an element
1550 carp("WARNING: filepos ",$pos," pointing to '",$atpos,
1551 "' not handled!");
1552 }
1553 }
1554 return 1;
1555 }
1556  
1557  
1558 =head2 C<uncompress_dictionaryhuffman_records()>
1559  
1560 Uncompresses all text records using
1561 L</uncompress_dictionaryhuffman()>. This destroys the existing
1562 contents of $self->{text} if any.
1563  
1564 This method is called automatically at the end of C<Load()> if
1565 DictionaryHuffman encoding is detected.
1566  
1567 =cut
1568  
1569 sub uncompress_dictionaryhuffman_records :method
1570 {
1571 my $self = shift;
1572 my $subname = ( caller(0) )[3];
1573 debug(2,"DEBUG[",$subname,"]");
1574  
1575 my $huffdata = $self->{huff};
1576 croak($subname,"(): no HUFF record found!\n") unless($huffdata);
1577  
1578 my $lasttextrecord = min($self->{header}{mobi}{indxrecord},
1579 $self->{header}{mobi}{firstimagerecord}) - 1;
1580 my $compressed;
1581  
1582 if($self->{text})
1583 {
1584 debug(1,"WARNING: re-parsing HUFF/CDIC-compressed text destroys",
1585 " existing uncompressed text.");
1586 }
1587  
1588 $self->{text} = '';
1589  
1590 foreach my $recoffset (1 .. $lasttextrecord)
1591 {
1592 local $OUTPUT_AUTOFLUSH = 1;
1593 print "Uncompressing record ",$recoffset,"/",$lasttextrecord,"\r"
1594 if($recoffset % 10 == 0);
1595 $compressed = $self->{records}->[$recoffset]->{data};
1596 croak($subname,"(): no data found in record ",$recoffset,"!\n")
1597 unless($compressed);
1598 $self->{text} .= uncompress_dictionaryhuffman(
1599 data => $compressed,
1600 huff => $self->{huff},
1601 cdics => $self->{cdics});
1602 }
1603 print "Finished uncompressing text.\n";
1604 return 1;
1605 }
1606  
1607  
1608 ################################
1609 ########## PROCEDURES ##########
1610 ################################
1611  
1612 =head1 PROCEDURES
1613  
1614 All procedures are exportable, but none are exported by default. All
1615 procedures can be exported by using the ":all" tag.
1616  
1617  
1618 =head2 C<find_mobidedrm()>
1619  
1620 Attempts to locate a copy of the MobiDeDrm script by searching PATH
1621 and looking in the EBook::Tools user configuration directory (see
1622 L<EBook::Tools/userconfigdir()>.
1623  
1624 Returns the complete path to the script, or undef if nothing was found.
1625  
1626 This will use package variable C<$mobidedrm_cmd> as its first guess,
1627 and set that variable to the return value as well.
1628  
1629 =cut
1630  
1631 sub find_mobidedrm
1632 {
1633 my $subname = ( caller(0) )[3];
1634 debug(2,"DEBUG[",$subname,"]");
1635  
1636 my @guesses;
1637 my $retval;
1638 my $confdir = userconfigdir();
1639 my $pattern = qr/^ MobiDeDrm(-\d+\.\d+)(.py)? $/ix;
1640  
1641 if($mobidedrm_cmd and -f $mobidedrm_cmd) { return $mobidedrm_cmd; }
1642 $mobidedrm_cmd = find_in_path($pattern,$confdir);
1643 debug(1,"DEBUG: found mobidedrm as '",$mobidedrm_cmd,"'");
1644 return $mobidedrm_cmd;
1645 }
1646  
1647  
1648 =head2 C<find_mobigen()>
1649  
1650 Attempts to locate the mobigen executable by making a test execution
1651 on predicted locations (including just checking PATH) and looking in
1652 the EBook::Tools user configuration directory (see
1653 L<EBook::Tools/userconfigdir()>.
1654  
1655 Returns the system command used for a successful invocation, or undef
1656 if nothing worked.
1657  
1658 This will use package variable C<$mobigen_cmd> as its first guess, and
1659 set that variable to the return value as well.
1660  
1661 =cut
1662  
1663 sub find_mobigen
1664 {
1665 my $subname = ( caller(0) )[3];
1666 debug(2,"DEBUG[",$subname,"]");
1667  
1668 my @mobigen_guesses;
1669 my $retval;
1670 my $confdir = userconfigdir();
1671  
1672 if($OSNAME eq 'MSWin32')
1673 {
1674 @mobigen_guesses = (
1675 'kindlegen',
1676 'mobigen',
1677 'C:\Program Files\Mobipocket.com\kindlegen',
1678 'C:\Program Files\Mobipocket.com\mobigen',
1679 );
1680 if($confdir)
1681 {
1682 push(@mobigen_guesses,
1683 $confdir . '\kindlegen',
1684 $confdir . '\mobigen');
1685 }
1686 }
1687 else
1688 {
1689 @mobigen_guesses = (
1690 'kindlegen',
1691 'mobigen',
1692 'mobigen_linux',
1693 );
1694 if($confdir)
1695 {
1696 push(@mobigen_guesses,
1697 $confdir . "/kindlegen",
1698 $confdir . "/mobigen_linux",
1699 $confdir . "/mobigen");
1700 }
1701 }
1702 unshift(@mobigen_guesses,$mobigen_cmd)
1703 if($mobigen_cmd);
1704 undef($mobigen_cmd);
1705  
1706 foreach my $guess (@mobigen_guesses)
1707 {
1708 no warnings 'exec';
1709 `$guess`;
1710 # MS Windows may use 256 for a not-found code instead of -1
1711 if($? != -1 && $? != 256)
1712 {
1713 debug(2,'DEBUG: `',$guess,'` returned ',$?);
1714 $mobigen_cmd = $guess;
1715 last;
1716 }
1717 }
1718  
1719 if($mobigen_cmd)
1720 {
1721 debug(1,"DEBUG: Found mobigen as '",$mobigen_cmd,"'");
1722 return $mobigen_cmd;
1723 }
1724 else { return; }
1725 }
1726  
1727  
1728 =head2 C<parse_mobi_exth($headerdata)>
1729  
1730 Takes as an argument a scalar containing the variable-length
1731 Mobipocket EXTH data from the first record. Returns an array of
1732 hashes, each hash containing the data from one EXTH record with values
1733 from that data keyed to recognizable names.
1734  
1735 If C<$headerdata> doesn't appear to be an EXTH header, carps a warning
1736 and returns an empty list.
1737  
1738 See:
1739  
1740 http://wiki.mobileread.com/wiki/MOBI
1741  
1742 =head3 Hash keys
1743  
1744 =over
1745  
1746 =item * C<type>
1747  
1748 A numeric value indicating the type of EXTH data in the record. See
1749 package variable C<%exthtypes>.
1750  
1751 =item * C<length>
1752  
1753 The length of the C<data> value in bytes
1754  
1755 =item * C<data>
1756  
1757 The data of the record.
1758  
1759 =back
1760  
1761 =cut
1762  
1763 sub parse_mobi_exth
1764 {
1765 my ($headerdata) = @_;
1766 my $subname = ( caller(0) )[3];
1767 debug(2,"DEBUG[",$subname,"]");
1768  
1769 croak($subname,"(): no header data provided")
1770 unless($headerdata);
1771  
1772 my $length = length($headerdata);
1773 my @list;
1774 my $chunk;
1775 my @exthrecords = ();
1776  
1777 my $offset;
1778 my $recordcnt;
1779  
1780  
1781 $chunk = substr($headerdata,0,12);
1782 @list = unpack("a4NN",$chunk);
1783 if($list[0] ne 'EXTH')
1784 {
1785 debug(1,"(): Unrecognized Mobipocket EXTH ID '",$list[0],
1786 "' (expected 'EXTH')");
1787 return @exthrecords;
1788 }
1789 # The EXTH data never seems to be as long as remaining data after
1790 # the Mobipocket main header, so only check to see if it is
1791 # shorter, not equal
1792 if($length < $list[1])
1793 {
1794 debug(1,"EXTH header specified length ",$list[1]," but found ",
1795 $length," bytes.\n");
1796 }
1797  
1798 $recordcnt = $list[2];
1799 unless($recordcnt)
1800 {
1801 debug(1,"EXTH flag set, but no EXTH records present");
1802 return @exthrecords;
1803 }
1804  
1805 $offset = 12;
1806 debug(2,"DEBUG: Examining ",$recordcnt," EXTH records");
1807 foreach my $recordpos (1 .. $recordcnt)
1808 {
1809 my %exthrecord;
1810  
1811 $chunk = substr($headerdata,$offset,8);
1812 $offset += 8;
1813 @list = unpack("NN",$chunk);
1814 $exthrecord{type} = $list[0];
1815 $exthrecord{length} = $list[1] - 8;
1816  
1817 unless($exthtypes{$exthrecord{type}})
1818 {
1819 carp($subname,"(): EXTH record ",$recordpos," has unknown type ",
1820 $exthrecord{type},"\n");
1821 $offset += $exthrecord{length};
1822 next;
1823 }
1824 unless($exthrecord{length})
1825 {
1826 carp($subname,"(): EXTH record ",$recordpos," has zero length\n");
1827 next;
1828 }
1829 if( ($exthrecord{length} + $offset) > $length )
1830 {
1831 carp($subname,"(): EXTH record ",$recordpos,
1832 " longer than available data");
1833 last;
1834 }
1835 $exthrecord{data} = substr($headerdata,$offset,$exthrecord{length});
1836 debug(2,"DEBUG: EXTH record ",$recordpos," [",
1837 $exthtypes{$exthrecord{type}},"] has ",
1838 $exthrecord{length}, " bytes");
1839 push(@exthrecords,\%exthrecord);
1840 $offset += $exthrecord{length};
1841 }
1842 debug(1,"DEBUG: Found ",$#exthrecords+1," EXTH records");
1843 debug(1,"DEBUG: Found ",$length - $offset,
1844 " remaining bytes of data at EXTH offset ",$offset);
1845 return \@exthrecords;
1846 }
1847  
1848  
1849 =head2 parse_mobi_header($headerdata)
1850  
1851 Takes as an argument a scalar containing the variable-length
1852 Mobipocket-specific header data from the first record. Returns a hash
1853 containing values from that data keyed to recognizable names.
1854  
1855 See:
1856  
1857 http://wiki.mobileread.com/wiki/MOBI
1858  
1859 =head3 keys
1860  
1861 The returned hash will have the following keys (documented in the
1862 order in which they are encountered in the header):
1863  
1864 =over
1865  
1866 =item C<identifier>
1867  
1868 This should always be the string 'MOBI'. If it isn't, the procedure
1869 croaks.
1870  
1871 =item C<headerlength>
1872  
1873 This is the size of the complete header. If this value is different
1874 from the length of the argument, the procedure croaks.
1875  
1876 =item C<type>
1877  
1878 A numeric code indicating what category of Mobipocket file this is.
1879  
1880 =item C<encoding>
1881  
1882 A numeric code representing the encoding. Expected values are '1252'
1883 (for Windows-1252) and '65001 (for UTF-8).
1884  
1885 The procedure carps a warning if an unexpected value is encountered.
1886  
1887 =item C<uniqueid>
1888  
1889 This is thought to be a unique ID for the book, but its actual use is
1890 unknown.
1891  
1892 Use with caution. This key may be renamed in the future if more
1893 information is found.
1894  
1895 =item C<version>
1896  
1897 This is thought to be the Mobipocket format version. A second version
1898 code shows up again later as C<version2> which is usually the same on
1899 unprotected books but different on DRMd books.
1900  
1901 Use with caution. This key may be renamed in the future if more
1902 information is found.
1903  
1904 =item C<reserved>
1905  
1906 40 bytes of reserved data.
1907  
1908 Use with caution. This key may be renamed in the future if more
1909 information is found.
1910  
1911 =item C<indxrecord>
1912  
1913 This is thought to be the record offset to the first 'INDX' record, so
1914 named for its first four letters.
1915  
1916 Use with caution. This key may be renamed in the future if more
1917 information is found.
1918  
1919 =item C<titleoffset>
1920  
1921 Offset in record 0 (not from start of file) of the full title of the
1922 book.
1923  
1924 =item C<titlelength>
1925  
1926 Length in bytes of the full title of the book
1927  
1928 =item C<languageunknown>
1929  
1930 16 bits of unknown data thought to be related to the book language.
1931  
1932 Use with caution. This key may be renamed in the future if more
1933 information is found.
1934  
1935 =item C<language>
1936  
1937 A pseudo-IANA language code string representing the main book language
1938 (i.e. the value of <dc:language>). See C<%mobilangcodes> for an exact
1939 map of raw values to this string and notes on non-compliant results.
1940  
1941 =item C<dilanguageunknown>
1942  
1943 16 bits of unknown data thought to be related to the dictionary input
1944 language.
1945  
1946 Use with caution. This key may be renamed in the future if more
1947 information is found.
1948  
1949 =item C<dilanguage>
1950  
1951 A pseudo-IANA language code string for the DictionaryInLanguage
1952 element. See C<%mobilangcodes> for an exact map of raw values to this
1953 string and notes on non-compliant results.
1954  
1955 =item C<dolanguageunknown>
1956  
1957 16 bits of unknown data thought to be related to the dictionary output
1958 language.
1959  
1960 Use with caution. This key may be renamed in the future if more
1961 information is found.
1962  
1963 =item C<dolanguage>
1964  
1965 A pseudo-IANA language code string for the DictionaryOutLanguage
1966 element. See C<%mobilangcodes> for an exact map of raw values to this
1967 string and notes on non-compliant results.
1968  
1969 =item C<version2>
1970  
1971 This is another Mobipocket format version related to DRM. If no DRM
1972 is present, it should be the same as C<version>.
1973  
1974 Use with caution. This key may be renamed in the future if more
1975 information is found.
1976  
1977 =item C<firstimagerecord>
1978  
1979 This is thought to be an index to the first record containing image
1980 data. If there are no images in the book, this value will be
1981 4294967295 (0xffffffff)
1982  
1983 Use with caution. This key may be renamed in the future if more
1984 information is found.
1985  
1986 =item C<huffrecord>
1987  
1988 This is thought to be the record offset to the 'HUFF' record, used in
1989 HUFF/CDIC decompression.
1990  
1991 Use with caution. This key may be renamed in the future if more
1992 information is found.
1993  
1994 =item C<huffreccnt>
1995  
1996 This is thought to be the number of HUFF and CDIC records, starting at
1997 C<huffrecord>.
1998  
1999 Use with caution. This key may be renamed in the future if more
2000 information is found.
2001  
2002 =item C<datprecord>
2003  
2004 This is thought to be the record offset to the first 'DATP' record, so
2005 named for its first four letters.
2006  
2007 Use with caution. This key may be renamed in the future if more
2008 information is found.
2009  
2010 =item C<datpreccnt>
2011  
2012 This is thought to be the number of 'DATP' records present.
2013  
2014 Use with caution. This key may be renamed in the future if more
2015 information is found.
2016  
2017 =item C<exthflags>
2018  
2019 A 32-bit bitfield related to the Mobipocket EXTH data. If bit 6
2020 (0x40) is set, then there is at least one EXTH record.
2021  
2022  
2023 =item C<unknown116>
2024  
2025 36 bytes of unknown data at offset 116. This value will be undefined
2026 if the header data was not long enough to contain it.
2027  
2028 Use with caution. This key may be renamed in the future if more
2029 information is found.
2030  
2031  
2032 =item C<drmoffset>
2033  
2034 A number thought to be the byte offset inside of the record 0 data in
2035 which DRM data can be found. If present and no DRM is set, contains
2036 either the value 0xFFFFFFFF (normal books) or 0x00000000 (samples).
2037 This value will be undefined if the header data was not long enough to
2038 contain it.
2039  
2040 Use with caution. This key may be renamed in the future if more
2041 information is found.
2042  
2043  
2044 =item C<drmcount>
2045  
2046 A number thought to be related to DRM.
2047  
2048 This value will be undefined if the header data was not long enough to
2049 contain it.
2050  
2051 Use with caution. This key may be renamed in the future if more
2052 information is found.
2053  
2054  
2055 =item C<drmsize>
2056  
2057 A number thought to be the size of the data in bytes after
2058 C<drmoffset> containing DRM keys.
2059  
2060 This value will be undefined if the header data was not long enough to
2061 contain it.
2062  
2063 Use with caution. This key may be renamed in the future if more
2064 information is found.
2065  
2066  
2067 =item C<drmflags>
2068  
2069 A number thought to be related to DRM.
2070  
2071 This value will be undefined if the header data was not long enough to
2072 contain it.
2073  
2074 Use with caution. This key may be renamed in the future if more
2075 information is found.
2076  
2077  
2078 =item C<unknown168>
2079  
2080 32 bits of unknown data at offset 168, usually zeroes. This value
2081 will be undefined if the header data was not long enough to contain
2082 it.
2083  
2084 Use with caution. This key may be renamed in the future if more
2085 information is found.
2086  
2087 =item C<unknown172>
2088  
2089 32 bits of unknown data at offset 172, usually zeroes. This value
2090 will be undefined if the header data was not long enough to contain
2091 it.
2092  
2093 Use with caution. This key may be renamed in the future if more
2094 information is found.
2095  
2096 =item C<unknown176>
2097  
2098 16 bits of unknown data at offset 176. This value will be undefined
2099 if the header data was not long enough to contain it.
2100  
2101 Use with caution. This key may be renamed in the future if more
2102 information is found.
2103  
2104 =item C<lastimagerecord>
2105  
2106 This is thought to be an index to the last record containing image
2107 data. If there are no images in the book, this value will be 65535
2108 (0xffff).
2109  
2110 Use with caution. This key may be renamed in the future if more
2111 information is found.
2112  
2113 =item C<unknown180>
2114  
2115 32 bits of unknown data at offset 180. This value will be undefined
2116 if the header data was not long enough to contain it.
2117  
2118 Use with caution. This key may be renamed in the future if more
2119 information is found.
2120  
2121 =item C<fcisrecord>
2122  
2123 This is thought to be an index to a 'FCIS' record, so named because
2124 those are always the first four characters when the record data is
2125 decompressed using uncompress_palmdoc().
2126  
2127 This value will be undefined if the header data was not long enough to
2128 contain it.
2129  
2130 Use with caution. This key may be renamed in the future if more
2131 information is found.
2132  
2133 =item C<unknown188>
2134  
2135 32 bits of unknown data at offset 188. This value will be undefined
2136 if the header data was not long enough to contain it.
2137  
2138 Use with caution. This key may be renamed in the future if more
2139 information is found.
2140  
2141 =item C<flisrecord>
2142  
2143 This is thought to be an index to a 'FLIS' record, so named because
2144 those are always the first four characters when the record data is
2145 decompressed using uncompress_palmdoc().
2146  
2147 This value will be undefined if the header data was not long enough to
2148 contain it.
2149  
2150 Use with caution. This key may be renamed in the future if more
2151 information is found.
2152  
2153 =item C<unknown196>
2154  
2155 32 bits of unknown data at offset 180. This value will be undefined
2156 if the header data was not long enough to contain it.
2157  
2158 Use with caution. This key may be renamed in the future if more
2159 information is found.
2160  
2161 =item C<unknown200>
2162  
2163 Unknown data of unknown length running to the end of the header. This
2164 value will be undefined if the header data was not long enough to
2165 contain it.
2166  
2167 Use with caution. This key may be renamed in the future if more
2168 information is found.
2169  
2170 =item C<extradataflags>
2171  
2172 Two bytes sometimes found inside of C<unknown200>, used to determine
2173 if extra data has been appended to each text record that should not be
2174 used in decompression.
2175  
2176 =back
2177  
2178 =cut
2179  
2180 sub parse_mobi_header ## no critic (ProhibitExcessComplexity)
2181 {
2182 # There's no way to refactor this without breaking up chunks into
2183 # separate subroutines, which is a bad idea.
2184 my ($headerdata) = @_;
2185 my $subname = ( caller(0) )[3];
2186 debug(2,"DEBUG[",$subname,"]");
2187  
2188 croak($subname,"(): no header data provided")
2189 unless($headerdata);
2190  
2191 my $length = length($headerdata);
2192 my @enckeys = keys(%pdbencoding);
2193 my $chunk; # current chunk of headerdata being unpacked
2194 my @list; # temporary holding area for unpacked data
2195 my %header; # header hash to return;
2196 my $hexstring; # hexadecimal debugging output string
2197  
2198 croak($subname,"(): header data is too short! (only ",$length," bytes)")
2199 if($length < 116);
2200  
2201 # The Mobipocket header data is large enough that it's easier to
2202 # deal with when handled in smaller chunks
2203  
2204 # First chunk is 24 bytes before reserved block
2205 $chunk = substr($headerdata,0,24);
2206 @list = unpack("a4NNNNN",$chunk);
2207 if($list[0] ne 'MOBI')
2208 {
2209 croak($subname,
2210 "(): Unrecognized Mobipocket header ID '",$list[0],
2211 "' (expected 'MOBI')");
2212 }
2213 if($list[1] != $length)
2214 {
2215 croak($subname,
2216 "(): header specified length ",$list[1]," but found ",
2217 $length," bytes.");
2218 }
2219  
2220 $header{identifier} = $list[0]; # Bytes 00-04 (16-20)
2221 $header{headerlength} = $list[1]; # Bytes 04-08 (20-24)
2222 $header{type} = $list[2];
2223 $header{encoding} = $list[3];
2224 $header{uniqueid} = $list[4];
2225 $header{version} = $list[5];
2226  
2227 if(!defined $pdbencoding{$header{encoding}})
2228 {
2229 carp($subname,"(): unknown encoding '",$header{encoding},"'");
2230 }
2231 else
2232 {
2233 debug(1,"DEBUG: Found encoding ",$pdbencoding{$header{encoding}});
2234 }
2235  
2236 # Second chunk is 40 bytes of reserved data, usually all 0xff
2237 $header{reserved} = substr($headerdata,24,40);
2238 $hexstring = hexstring($header{reserved});
2239 debug(2,"DEBUG: reserved data: 0x",$hexstring)
2240 if($hexstring ne ('ff' x 40));
2241  
2242 # Third chunk is 12 bytes up to the language block
2243 $chunk = substr($headerdata,64,12);
2244 @list = unpack("NNN",$chunk);
2245 $header{indxrecord} = $list[0];
2246 $header{titleoffset} = $list[1];
2247 $header{titlelength} = $list[2];
2248  
2249 # Fourth chunk is 12 bytes containing the language codes
2250 $chunk = substr($headerdata,76,12);
2251 @list = unpack("nCCnCCnCC",$chunk);
2252 $header{languageunknown} = $list[0];
2253 $header{language} = parse_mobi_language($list[2],$list[1]);
2254 $header{dilanguageunknown} = $list[3];
2255 $header{dilanguage} = parse_mobi_language($list[5],$list[4]);
2256 $header{dolanguageunknown} = $list[6];
2257 $header{dolanguage} = parse_mobi_language($list[8],$list[7]);
2258  
2259 # Fifth chunk is 8 bytes until next unknown block
2260 $chunk = substr($headerdata,88,8);
2261 @list = unpack("NN",$chunk);
2262 $header{version2} = $list[0];
2263 $header{firstimagerecord} = $list[1];
2264  
2265 debug(2,"DEBUG: INDX record: ",$header{indxrecord});
2266 if($header{firstimagerecord} == 0xffffffff)
2267 {
2268 debug(2,"DEBUG: no image records present");
2269 }
2270 else
2271 {
2272 debug(2,"DEBUG: first image record: ",$header{firstimagerecord});
2273 }
2274  
2275 # Sixth chunk is HUFF/CDIC and DATP record offsets
2276 $chunk = substr($headerdata,96,16);
2277 @list = unpack("NNNN",$chunk);
2278 $header{huffrecord} = $list[0];
2279 $header{huffreccnt} = $list[1];
2280 $header{datprecord} = $list[2];
2281 $header{datpreccnt} = $list[3];
2282  
2283 # Seventh and last chunk guaranteed to be present is the EXTH
2284 # bitfield
2285 $chunk = substr($headerdata,112,4);
2286 $header{exthflags} = unpack("N",$chunk);
2287  
2288 # Remaining chunks are only parsed if the header is long enough
2289  
2290 # Eighth chunk is 36 bytes of unknown data
2291 if($length >= 152)
2292 {
2293 $header{unknown116} = substr($headerdata,116,32);
2294 $header{unknown148} = unpack('N',substr($headerdata,148,4));
2295 }
2296  
2297 # Ninth chunk is 16 bytes of DRM-related data
2298 if($length >= 168)
2299 {
2300 $chunk = substr($headerdata,152,16);
2301 @list = unpack("NNNN",$chunk);
2302 $header{drmoffset} = $list[0]; # Offset 152 - 155
2303 $header{drmcount} = $list[1]; # Offset 156 - 159
2304 $header{drmsize} = $list[2]; # Offset 160 - 163
2305 $header{drmflags} = $list[3]; # Offset 164 - 167
2306 debug(1,"DEBUG: Found DRM offset ",
2307 sprintf("0x%08x",$header{drmoffset}));
2308 }
2309  
2310 # Tenth chunk is 8 bytes of unknown data, usually zeroes
2311 if($length >= 176)
2312 {
2313 $chunk = substr($headerdata,168,8);
2314 @list = unpack('NN',$chunk);
2315 $header{unknown168} = $list[0];
2316 $header{unknown172} = $list[1];
2317 }
2318  
2319 # Eleventh chunk is 2 16-bit values and 5 32-bit values, usually nonzero
2320 if($length >= 200)
2321 {
2322 $chunk = substr($headerdata,176,24);
2323 @list = unpack("nnNNNNN",$chunk);
2324 $header{unknown176} = $list[0];
2325 $header{lastimagerecord} = $list[1];
2326 $header{unknown180} = $list[2];
2327 $header{fcisrecord} = $list[3];
2328 $header{unknown188} = $list[4];
2329 $header{flisrecord} = $list[5];
2330 $header{unknown196} = $list[6];
2331 }
2332  
2333 # Last possible chunk is unknown data lasting to the end
2334 # of the header.
2335 if($length >= 201)
2336 {
2337 $header{unknown200} = substr($headerdata,200,$length-200);
2338 debug(2,"DEBUG: Found ",$length-200,
2339 " bytes of unknown final data in Mobipocket header");
2340 debug(2," 0x",hexstring($header{unknown200}));
2341 }
2342  
2343 # Part of that unknown data is the Extra Data Flags
2344 #
2345 # This is 16 bits used to determine if extra data has been stuffed
2346 # at the end of each record that should not be used in
2347 # decompression.
2348 if($length >= 228)
2349 {
2350 $chunk = substr($headerdata,226,2);
2351 $header{extradataflags} = unpack("n",$chunk);
2352 debug(2,"DEBUG: Found Extra Data Flags in Mobipocket header");
2353 debug(2," 0x",hexstring($chunk));
2354 }
2355  
2356 foreach my $key (sort keys %header)
2357 {
2358 no warnings;
2359 my $value;
2360 if(length($header{$key}) <= 4)
2361 {
2362 $value = $header{$key};
2363 }
2364 elsif(length($header{$key}) > 10)
2365 {
2366 $value = '0x' . hexstring($header{$key});
2367 }
2368 elsif(int($header{$key}) > 0x04ff)
2369 {
2370 $value = sprintf("0x%08x",$header{$key});
2371 }
2372 else
2373 {
2374 $value = $header{$key};
2375 }
2376 debug(2,'DEBUG: mobi{',$key,'}=',$value);
2377 }
2378 return \%header;
2379 }
2380  
2381  
2382 =head2 C<parse_mobi_language($languagecode, $regioncode)>
2383  
2384 Takes the integer values C<$languagecode> and C<$regioncode> unpacked from
2385 the Mobipocket header and returns a language string mostly (but not
2386 entirely) conformant to the IANA language subtag registry codes.
2387  
2388 Croaks if C<$languagecode> is not provided. If C<$regioncode> is not
2389 provided or not recognized, it is disregarded and the base language
2390 string (with no region or script) is returned.
2391  
2392 If C<$languagecode> is not provided, the sub croaks. If it isn't
2393 recognized, a warning is carped and the sub returns undef. Note that
2394 0,0 is a recognized code returning an empty string.
2395  
2396 See C<%mobilanguagecodes> for an exact map of values. Note that the
2397 bottom two bits of the region code appear to be unused (i.e. the
2398 values are all multiples of 4).
2399  
2400 =cut
2401  
2402 sub parse_mobi_language
2403 {
2404 my ($languagecode,$regioncode) = @_;
2405 my $subname = ( caller(0) )[3];
2406 debug(3,"DEBUG[",$subname,"]");
2407  
2408 croak($subname,"(): no language code provided\n")
2409 unless(defined $languagecode);
2410  
2411 my $language = $mobilangcode{$languagecode}{$regioncode};
2412  
2413 if(defined $language)
2414 {
2415 debug(2,"DEBUG: found language '",$language,"'",
2416 " (language code ",$languagecode,",",
2417 " region code ",$regioncode,")");
2418 }
2419 else
2420 {
2421 debug(1,"DEBUG: language code ",$languagecode,
2422 ", region code ",$regioncode," not known",
2423 " -- ignoring region code");
2424 $language = $mobilangcode{$languagecode}{0};
2425 if(!$language)
2426 {
2427 carp("WARNING: language code ",$languagecode,
2428 " not recognized!\n");
2429 }
2430 else
2431 {
2432 debug(1,"DEBUG: found downgraded language '",$language,"'",
2433 " (language code ",$languagecode,",",
2434 " region code 0)");
2435 }
2436 } # if($language) / else
2437 return $language;
2438 }
2439  
2440  
2441 =head2 C<pid_append_checksum($pid)>
2442  
2443 Computes the Mobipocket PID checksum used as the final two bytes of
2444 the PID and appends them to C<$pid>, returning the merged string.
2445  
2446 Used by L</pid_is_valid($pid)>.
2447  
2448 =cut
2449  
2450 sub pid_append_checksum
2451 {
2452 my $pid = shift;
2453 my $subname = ( caller(0) )[3];
2454 debug(2,"DEBUG[",$subname,"]");
2455  
2456 my $retval = $pid;
2457 my $crc;
2458 my $byte;
2459 my $pos;
2460  
2461 my $letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
2462 my $length = length($letters);
2463 $crc = ~ String::CRC32::crc32($pid,-1);
2464 $crc = $crc & 0xffffffff;
2465 $crc = $crc ^ ($crc >> 16);
2466 for(0 .. 1)
2467 {
2468 $byte = $crc & 0xff;
2469 $pos = (int($byte / $length)) ^ ($byte % $length);
2470 $retval .= substr($letters,$pos % $length,1);
2471 $crc >>= 8;
2472 }
2473 return $retval;
2474 }
2475  
2476  
2477 =head2 C<pid_is_valid($pid)>
2478  
2479 Returns 1 if the PID is a valid Mobipocket/Kindle PID and 0 otherwise.
2480  
2481 This is determined by first ensuring that C<$pid> is exactly ten bytes
2482 long, and then stripping the final two bytes normally used as a
2483 checksum and recomputing them, returning 1 only if they are recomputed
2484 correctly.
2485  
2486 =cut
2487  
2488 sub pid_is_valid
2489 {
2490 my $pid = shift;
2491 my $subname = ( caller(0) )[3];
2492 debug(2,"DEBUG[",$subname,"]");
2493  
2494 return 0 unless($pid);
2495  
2496 my $pid2 = pid_append_checksum(substr($pid,0,-2));
2497  
2498 return 0 unless(length($pid) == 10);
2499 if($pid eq $pid2) { return 1; }
2500 else { return 0; }
2501 }
2502  
2503  
2504 =head2 C<pukall_cipher_1(%args)>
2505  
2506 This is a COMPLETELY UNTESTED implementation of the Pukall Cipher 1
2507 algorithm used for encryption and decryption in Mobipocket files. It
2508 is a 128-bit stream cipher. For more information and alternate
2509 implementations, see L<http://membres.lycos.fr/pc1/>.
2510  
2511 Use at your own risk. Bug reports appreciated.
2512  
2513 =head3 Arguments
2514  
2515 =over
2516  
2517 =item * C<key>
2518  
2519 16-byte encryption key. This must be provided, and must be exactly 16
2520 bytes, or the procedure will croak.
2521  
2522 =item * C<input>
2523  
2524 Input data to be either encrypted or decrypted. If this is not
2525 provided, the procedure croaks.
2526  
2527 =item * C<encrypt> (optional)
2528  
2529 If set to true, the cipher will be used to encrypt the input data. If
2530 not set, or set to false, the cipher will be used to decrypt the input
2531 data.
2532  
2533 =back
2534  
2535 =cut
2536  
2537 sub pukall_cipher_1
2538 {
2539 my %args = @_;
2540 my $subname = ( caller(0) )[3];
2541 debug(2,"DEBUG[",$subname,"]");
2542  
2543 my %valid_args = (
2544 'key' => 1,
2545 'input' => 1,
2546 'encrypt' => 1,
2547 );
2548 foreach my $arg (keys %args)
2549 {
2550 croak($subname,"(): invalid argument '",$arg,"'")
2551 if(!$valid_args{$arg});
2552 }
2553  
2554 croak($subname,"(): no key provided!\n")
2555 unless(defined $args{key});
2556 croak($subname,"(): no input provided!\n")
2557 unless(defined $args{input});
2558  
2559 my $key = $args{key};
2560 my $keylength = length($key);
2561 my $encrypt = $args{encrypt} || 0;
2562 my $input = $args{input};
2563 my $output = '';
2564  
2565 croak($subname,"(): Invalid key length (expected 16, got ",
2566 $keylength,")!\n")
2567 unless($keylength == 16);
2568  
2569 my @keyarray;
2570 my $key_xor = 0;
2571 my $sum1 = 0;
2572 my $sum2 = 0;
2573 my $byte;
2574 my $byte_xor;
2575 my $temp_xor;
2576  
2577 foreach my $pos (0 .. 7)
2578 {
2579 $byte = ord(substr($key,$pos*2,1) << 8) | ord(substr($key,$pos*2+1,1));
2580 $keyarray[$pos] = $byte;
2581 }
2582  
2583 foreach my $offset ( 0 .. length($input) )
2584 {
2585 $temp_xor = 0;
2586 $byte_xor = 0;
2587 foreach my $keypos (0 .. 7)
2588 {
2589 $temp_xor ^= $keyarray[$keypos];
2590 $sum2 = ($sum2 + $keypos) * 20021 + $sum1;
2591 $sum1 = ($temp_xor * 346) & 0xFFFF;
2592 $sum2 = ($sum1 + $sum2) & 0xFFFF;
2593 $temp_xor = ($temp_xor * 20021 + 1) & 0xFFFF;
2594 $byte_xor ^= $temp_xor ^ $sum2;
2595 }
2596 $byte = ord(substr($input,$offset,1));
2597 if($encrypt) { $key_xor = $byte * 257; }
2598 $byte = (($byte ^ ($byte_xor >> 8)) ^ $byte_xor) & 0xFF;
2599 if(!$encrypt) { $key_xor = $byte * 257; };
2600 foreach my $keypos (0 .. 7)
2601 {
2602 $keyarray[$keypos] ^= $key_xor;
2603 }
2604 $output .= chr($byte);
2605 }
2606 return $output;
2607 }
2608  
2609  
2610 =head2 C<record_extradata_size(%args)>
2611  
2612 This checks the end of a text record for extra data that should not be
2613 made part of decompression and returns the total size of all data
2614 fields.
2615  
2616 =head3 Arguments
2617  
2618 =over
2619  
2620 =item * C<dataref>
2621  
2622 A reference to the record data
2623  
2624 =item * C<extradataflags>
2625  
2626 16 bits worth of flags indicating which extra data fields are present.
2627  
2628 =back
2629  
2630 =cut
2631  
2632 sub record_extradata_size
2633 {
2634 my %args = @_;
2635 my $subname = ( caller(0) )[3];
2636 debug(3,"DEBUG[",$subname,"]");
2637  
2638 my %valid_args = (
2639 'dataref' => 1,
2640 'extradataflags' => 1,
2641 );
2642 foreach my $arg (keys %args)
2643 {
2644 croak($subname,"(): invalid argument '",$arg,"'")
2645 if(!$valid_args{$arg});
2646 }
2647  
2648 my $dataref = $args{dataref};
2649 croak($subname,"(): no record data provided!\n")
2650 unless(defined $dataref);
2651 croak($subname,"(): record data is not a reference\n") unless(ref $dataref);
2652 croak($subname,"(): no extra data flags provided!\n")
2653 unless(defined $args{extradataflags});
2654  
2655 my $datalength = length($$dataref);
2656  
2657 my $totalsize = 0;
2658 my $trailpos = 0;
2659  
2660 foreach my $flagbit (reverse 0..15)
2661 {
2662 if($args{extradataflags} & (1 << $flagbit))
2663 {
2664 my $bitpos = 0;
2665 my $startpos = $trailpos;
2666 my $traildata;
2667 my $trailsize = 0;
2668 my $byte;
2669  
2670 # Bit 0 is the multi-byte character overlap flag, and has
2671 # a different format from all other flags, where the size
2672 # is the first two bits of the last unparsed byte of
2673 # record data (i.e. the extra data bytes closest to the
2674 # actual record text), plus one for the byte containing
2675 # the size itself.
2676 if($flagbit == 0)
2677 {
2678 $trailpos += 1;
2679 $trailsize = ord(substr($$dataref,$datalength-$trailpos,1)) & 0x03;
2680 $trailsize += 1; # The above line doesn't include the size byte itself
2681 debug(3,"DEBUG: ",$trailsize," bytes of trailing data at flagbit ",
2682 $flagbit,", startpos ",$startpos);
2683 $totalsize += $trailsize;
2684 last;
2685 }
2686  
2687 # For all other bits, the size is a backward-encoded
2688 # variable-width integer at the end of the record data.
2689 do
2690 {
2691 $trailpos += 1;
2692 $byte = ord(substr($$dataref,$datalength-$trailpos,1));
2693 $trailsize |= (($byte & 0x7f) << $bitpos);
2694 $bitpos += 7;
2695 }
2696 while( !($byte & 0x80) && ($bitpos < 28) && ($trailpos < $datalength) );
2697 $traildata = substr($$dataref,$datalength-$trailsize,$trailsize);
2698 debug(3,"DEBUG: ",$trailsize," bytes of trailing data at flagbit ",
2699 $flagbit,", startpos ",$startpos);
2700 $totalsize += $trailsize;
2701 }
2702 }
2703 return $totalsize;
2704 }
2705  
2706  
2707 =head2 C<system_mobidedrm(%args)>
2708  
2709 Runs python on a copy of C<MobiDeDrm.py> if it is available (not
2710 included with this distribution) to downconvert a Mobipocket file.
2711  
2712 Returns the output filename on success, or undef otherwise.
2713  
2714  
2715 =head3 Arguments
2716  
2717 =over
2718  
2719 =item * C<infile>
2720  
2721 The input filename. If not specified or invalid, the procedure
2722 returns undef.
2723  
2724 =item * C<outfile>
2725  
2726 The output filename. If not specified, the program will use a name
2727 based on the input file, appending '-nodrm' to the basename and
2728 keeping the extension. In the special case of Mobipocket files ending
2729 in '-sm', the '-sm' portion of the basename is simply removed, and
2730 nothing else is appended.
2731  
2732 =item * C<pid>
2733  
2734 The PID to use to decrypt the file. If not specified or invalid, the
2735 procedure returns undef.
2736  
2737 =back
2738  
2739 =cut
2740  
2741 sub system_mobidedrm
2742 {
2743 my %args = @_;
2744 my $subname = ( caller(0) )[3];
2745 debug(2,"DEBUG[",$subname,"]");
2746  
2747 my %valid_args = (
2748 'infile' => 1,
2749 'outfile' => 1,
2750 'pid' => 1,
2751 );
2752 foreach my $arg (keys %args)
2753 {
2754 croak($subname,"(): invalid argument '",$arg,"'")
2755 if(!$valid_args{$arg});
2756 }
2757  
2758 if(!$args{infile})
2759 {
2760 debug(1,$subname,"(): no input file specified!");
2761 return;
2762 }
2763  
2764 if(! -f $args{infile})
2765 {
2766 debug(1,$subname,"(): input file '",$args{infile},"' not found!");
2767 return;
2768 }
2769  
2770 if(! pid_is_valid($args{pid}))
2771 {
2772 debug(1,$subname,"(): pid '",$args{pid},"' is not valid!");
2773 return;
2774 }
2775  
2776 if( !find_mobidedrm() )
2777 {
2778 debug(1,$subname,"(): MobiDeDRM is not available!");
2779 return;
2780 }
2781  
2782 my $outfile = $args{outfile};
2783 my $suffix;
2784 if(!$outfile)
2785 {
2786 ($outfile,undef,$suffix) = fileparse($args{infile},'\.\w+$');
2787 if($outfile =~ /-sm$/ix)
2788 {
2789 $outfile =~ s/-sm$//ix;
2790 $outfile .= $suffix;
2791 }
2792 else
2793 {
2794 $outfile .= '-nodrm' . $suffix;
2795 }
2796 }
2797  
2798 my $retval = system('python',$mobidedrm_cmd,
2799 $args{infile},$outfile,$args{pid});
2800  
2801 if($retval == -1 or $retval == 256)
2802 {
2803 debug(1,$subname,"(): python not available!");
2804 return;
2805 }
2806  
2807 if(-z $outfile)
2808 {
2809 debug(1,$subname,"(): MobiDeDRM produced 0-sized output!");
2810 unlink($outfile);
2811 return;
2812 }
2813 return $outfile;
2814 }
2815  
2816  
2817 =head2 C<system_mobigen(%args)>
2818  
2819 Runs C<mobigen> to convert OPF, HTML, or ePub input into a Mobipocket
2820 .prc/.mobi book. The procedure L<find_mobigen()> is called to locate
2821 the executable.
2822  
2823 Returns the return value from mobigen, or undef if no filename was
2824 specified or the file did not exist. Also returns undef if mobigen
2825 could not be found.
2826  
2827 =head3 Arguments
2828  
2829 =over
2830  
2831 =item * C<infile>
2832  
2833 The input filename. If not specified or invalid, the procedure
2834 returns undef.
2835  
2836 =item * C<outfile>
2837  
2838 The output filename. The mobigen executable will choose its own
2839 filename for direct output, but if this argument is specified, the
2840 output file will be renamed to the specified filename instead.
2841  
2842 If not specified, the default output will be left in place.
2843  
2844 =item * C<dir>
2845  
2846 The directory in which to place the output file. The mobigen
2847 executable itself will always place its output into the current
2848 working directory, but if this argument is specified, the output file
2849 will be moved into the specified directory, creating that directory if
2850 necessary.
2851  
2852 =item * C<compression>
2853  
2854 Compression level from 0-2, where 0 is no compression, 1 is PalmDoc
2855 compression, and 2 is HUFF/CDIC compression. If not specified,
2856 defaults to 1 (PalmDoc compression).
2857  
2858 =back
2859  
2860 =cut
2861  
2862 sub system_mobigen
2863 {
2864 my %args = @_;
2865 my $subname = ( caller(0) )[3];
2866 debug(2,"DEBUG[",$subname,"]");
2867  
2868 my %valid_args = (
2869 'infile' => 1,
2870 'outfile' => 1,
2871 'dir' => 1,
2872 'compression' => 1,
2873 );
2874 foreach my $arg (keys %args)
2875 {
2876 croak($subname,"(): invalid argument '",$arg,"'")
2877 if(!$valid_args{$arg});
2878 }
2879  
2880 if(!$args{infile})
2881 {
2882 debug(1,$subname,"(): no input file specified!");
2883 return;
2884 }
2885  
2886 if(! -f $args{infile})
2887 {
2888 debug(1,$subname,"(): input file '",$args{infile},"' not found!");
2889 return;
2890 }
2891  
2892 find_mobigen();
2893 if(!$mobigen_cmd)
2894 {
2895 debug(1,$subname,"(): mobigen command not specified!");
2896 return;
2897 }
2898  
2899 my @mobigen = ($mobigen_cmd);
2900 my $mobigenoutput = fileparse($args{infile},'\.\w+$') . '.mobi';
2901 my $outfile = $args{outfile} || $mobigenoutput;
2902 my $compression = $args{compression};
2903 my $retval;
2904  
2905 if(defined $compression)
2906 {
2907 unless($compression >= 0 and $compression <= 2)
2908 {
2909 croak($subname,"(): invalid compression level ",
2910 $compression,"!\n");
2911 }
2912 }
2913 else { $compression = 1; }
2914  
2915 push(@mobigen,"-c$compression",$args{infile});
2916 debug(2,"DEBUG: Compiling '",$args{infile},"' into '",$mobigenoutput,
2917 "' using compression level ",$compression);
2918  
2919 $retval = system(@mobigen);
2920 if($retval)
2921 {
2922 debug(1,"WARNING: mobigen exited ",$retval);
2923 }
2924 if(! -f $mobigenoutput)
2925 {
2926 carp($subname,"(): expected output file '",$mobigenoutput,
2927 "' not found!\n");
2928 }
2929 if($args{outfile})
2930 {
2931 rename($mobigenoutput,$args{outfile})
2932 or carp($subname,"(): unable to rename '",$mobigenoutput,"' to '",
2933 $args{outfile},"'!\n");
2934 }
2935 if($args{dir})
2936 {
2937 if(! -d $args{dir})
2938 {
2939 mkpath($args{dir})
2940 or carp($subname,"(): unable to create directory '",
2941 $args{dir},"'!\n");
2942 }
2943 rename($outfile,"$args{dir}/$outfile")
2944 or carp($subname,"(): unable to move '",$outfile,"' into '",
2945 $args{dir},"'!\n");
2946 }
2947 return $retval;
2948 }
2949  
2950  
2951 =head2 C<uncompress_dictionaryhuffman(%args)>
2952  
2953 Uncompresses text compressed with the DictionaryHuffman compression
2954 scheme.
2955  
2956 =head3 Arguments
2957  
2958 =over
2959  
2960 =item * C<data>
2961  
2962 A scalar containing the compressed data to uncompress.
2963  
2964 =item * C<huff>
2965  
2966 A hashref pointing to the HUFF record data
2967  
2968 =item * C<cdics>
2969  
2970 An arrayref pointing to the CDIC record data
2971  
2972 =item * C<depth>
2973  
2974 The current depth of the huffman tree, currently only used in
2975 debugging.
2976  
2977 =back
2978  
2979 =cut
2980  
2981 sub uncompress_dictionaryhuffman
2982 {
2983 my (%args) = @_;
2984 my $subname = (caller(0))[3];
2985 debug(3,"DEBUG[",$subname,"]");
2986  
2987 my %valid_args = (
2988 'data' => 1,
2989 'huff' => 1,
2990 'cdics' => 1,
2991 'depth' => 1,
2992 );
2993 foreach my $arg (keys %args)
2994 {
2995 croak($subname,"(): invalid argument '",$arg,"'")
2996 if(!$valid_args{$arg});
2997 }
2998  
2999 croak($subname,"(): no data provided!\n")
3000 unless($args{data});
3001  
3002 # Why does $data have to be zero-terminated this way? Sometimes it
3003 # runs out of bits otherwise, though.
3004 my $data = $args{data} . "\x00\x00";
3005 my $octets = length($data);
3006 my $depth = $args{depth} || 0;
3007 debug(3,"DEBUG: uncompressing ",$octets," octets at depth ",$depth);
3008  
3009 my $huffref = $args{huff};
3010 my $cdicref = $args{cdics};
3011 my $cdic;
3012 my $dataoffset = 0;
3013 my ($bits, $nextbits);
3014 my ($cacheoffset, $cacheval);
3015  
3016 my $codeword; # CDIC codeword
3017 my $codebits; # Extra bits at the end of $codeword
3018 my $codelength; # number of bits in the code
3019 my $index; # CDIC index key
3020  
3021 my $branch;
3022 my $branchcode;
3023 my $branchsize;
3024 my $branchoffset;
3025  
3026 my $text = '';
3027  
3028 my $bitsize = length($data) * 8;
3029 my $bitvector = Bit::Vector->new($bitsize);
3030 my $bitoffset;
3031 my $bitpos = 0;
3032  
3033 # Unfortunately, the bitstream needs to be processed from left to
3034 # right, and Bit::Vector really likes to process from right to
3035 # left, so we have to process by chunk instead of using
3036 # Block_Store
3037 while($bitpos < $bitsize)
3038 {
3039 $bitoffset = $bitsize-$bitpos;
3040 $bits = unpack('C',substr($data,$dataoffset,1));
3041 $bitvector->Chunk_Store(8,$bitoffset-8,$bits);
3042 $dataoffset++;
3043 $bitpos += 8;
3044 }
3045  
3046  
3047 # Debugging code inside the loop is commented out because each
3048 # subroutine call incurs substantial overhead (even when the
3049 # debugging level is low enough that nothing is printed).
3050  
3051 $bitpos = 0;
3052 do
3053 {
3054 $bitoffset = $bitsize-$bitpos;
3055 # debug(4,"\nDEBUG: DEPTH ",$depth," BITPOS ",$bitpos,
3056 # " [bitoffset=",$bitoffset,"]");
3057 $nextbits = min(8,$bitoffset);
3058 $cacheoffset = $bitvector->Chunk_Read($nextbits,$bitoffset-$nextbits);
3059 if($cacheoffset > $#{$huffref->{cache}})
3060 {
3061 croak($subname,"(): invalid HUFF cache offset ",$cacheoffset,
3062 " found at bit position ",$bitpos,"!\n");
3063 #return $text;
3064 }
3065 $cacheval = $huffref->{cache}->[$cacheoffset];
3066 # debug(4,"## cacheval[",$cacheoffset,"]=",$cacheval);
3067 $codelength = $cacheval & 0x1F; # low 5 bits
3068 # debug(4,"## codelength=",$codelength);
3069 if(!$codelength)
3070 {
3071 croak($subname,"(): HUFF cache found zero codelength",
3072 " at bit position ",$bitpos,"!\n");
3073 #return $text;
3074 }
3075  
3076 $nextbits = min(32,$bitoffset);
3077 $bits = $bitvector->Chunk_Read($nextbits,$bitoffset-$nextbits);
3078 # debug(4,"## bits=",sprintf("%0${nextbits}b",$bits));
3079  
3080 if(!$bits)
3081 {
3082 # debug(2,"DEBUG: no more data, returning from depth ",
3083 # $depth," with:");
3084 # debug(2," '",excerpt_line($text),"'");
3085 return $text;
3086 }
3087 if($codelength > $bitoffset)
3088 {
3089 carp($subname,"():\n",
3090 "WARNING: ran out of bits at depth ",$depth,"!\n");
3091  
3092 if($bits)
3093 {
3094 carp($subname,"():\n",
3095 "supposedly out of bits, but bit data still exists!\n");
3096 }
3097 # debug(2,"DEBUG: returning from depth ",$depth," with '",$text,"'");
3098 return $text;
3099 }
3100  
3101 $codebits = $bitvector->Chunk_Read($codelength,$bitoffset-$codelength);
3102 # debug(4,"## codebits=",$codebits);
3103 if($cacheval & 0x80)
3104 {
3105 # Codeword is unique and in the short codewords cache
3106 $codeword = ($cacheval >> 8) - $codebits;
3107 }
3108 unless($cacheval & 0x80)
3109 {
3110 # Code is not in the cache, must be looked up from base
3111 # table. The problem is, the codelength is not known, so
3112 # we have to iterate through the basetable adding bits to
3113 # the code until the code is larger than the table value.
3114 #
3115 # There has to be a better way to do this?
3116 # debug(4,"## code not in cache");
3117 while($codebits < $huffref->{basetable}->[($codelength-1)*2])
3118 {
3119 $codelength++;
3120 # debug(4,"## codelength extended to ",$codelength);
3121 $codebits = $bitvector->Chunk_Read($codelength,$bitoffset-$codelength);
3122 }
3123 $codeword = $huffref->{basetable}->[($codelength-1)*2+1];
3124 $codeword -= $codebits;
3125 }
3126 # debug(4,"## codeword=",$codeword);
3127 $cdic = $codeword >> $huffref->{codelength};
3128 if($cdic > $#{$cdicref})
3129 {
3130 croak($subname,"(): \n HUFF entry referenced invalid CDIC ",$cdic,
3131 " at bit position ",$bitpos,", depth ",$depth,"!\n");
3132 #return $text;
3133 }
3134  
3135 # debug(4,"## cdic=",$cdic);
3136 $index = $codeword - ($cdic << $huffref->{codelength});
3137 # debug(4,"## cdic[",$cdic,"][",$index,"]=",
3138 # $cdicref->[$cdic]->{indexes}->[$index]);
3139 $branchoffset = 16 + $cdicref->[$cdic]->{indexes}->[$index];
3140 # debug(4,"## branchoffset=",$branchoffset);
3141  
3142 # 15 lowest bits of $branchcode are the size of the leaf in
3143 # bytes -- however, only sizes 1-127 are ever used?
3144 # 16th bit is set if the leaf is the end of the tree and no
3145 # recursion is needed
3146 $branchcode = unpack('n',substr($cdicref->[$cdic]->{data},
3147 $branchoffset,2) );
3148 $branchsize = $branchcode & 0x7fff;
3149 # debug(4,"## branchcode=",$branchcode," branchsize=",$branchsize,
3150 # " branchcode&0x8000=",$branchcode & 0x8000);
3151 if(!$branchsize || $branchsize > 127)
3152 {
3153 carp($subname,"():\n",
3154 " HUFF branch at bit position ",$bitpos,", depth ",$depth,
3155 " has size ",$branchsize," (expected 1-127)\n");
3156 }
3157 $branch = substr($cdicref->[$cdic]->{data},$branchoffset+2,$branchsize);
3158 if($branchcode & 0x8000)
3159 {
3160 # End of tree. Append branch to text.
3161 # debug(4,"## branch='",$branch,"'");
3162 $text .= $branch;
3163 }
3164 else
3165 {
3166 # debug(2,"DEBUG: recursing at depth ",$depth,
3167 # " with:");
3168 # debug(2," '",excerpt_line($text),"'");
3169 $text .= uncompress_dictionaryhuffman(
3170 data => $branch,
3171 huff => $args{huff},
3172 cdics => $args{cdics},
3173 depth => $depth + 1);
3174 }
3175 $bitpos += $codelength;
3176 } while($bitpos < length($data) * 8);
3177 # debug(2,"DEBUG: returning from depth ",$depth," with:");
3178 # debug(2," '",excerpt_line($text),"'");
3179 return $text;
3180 }
3181  
3182  
3183 =head2 C<unpack_mobi_language($data)>
3184  
3185 Takes as an argument 4 bytes of data. If less data is provided, the
3186 sub croaks. If more, a debug warning is provided, but the sub
3187 continues.
3188  
3189 In scalar context returns a language string mostly (but not entirely)
3190 conformant to the IANA language subtag registry codes.
3191  
3192 In list context, returns the language string, an unknown code integer,
3193 a region code integer, and a language code integer, with the last
3194 three being directly unpacked values.
3195  
3196 See C<%mobilangcodes> for an exact map of values. Note that the
3197 bottom two bits of the region code appear to be unused (i.e. the
3198 values are all multiples of 4). The unknown code integer appears to
3199 be unused, and is generally zero.
3200  
3201 The original implementation by Mobipocket may have been via
3202 Microsoft's .NET CultureInfo class. See:
3203 L<http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(VS.71).aspx>
3204  
3205 =cut
3206  
3207 sub unpack_mobi_language
3208 {
3209 my $data = shift;
3210  
3211 my $subname = ( caller(0) )[3];
3212 debug(2,"DEBUG[",$subname,"]");
3213  
3214 croak($subname,"(): no language data provided")
3215 unless($data);
3216  
3217 croak($subname,"(): language data is too short (only ",length($data),
3218 " bytes, need 4\n")
3219 if(length($data) < 4);
3220  
3221 debug(1,$subname,"(): expected 4 bytes of data, but received ",
3222 length($data))
3223 if(length($data) > 4);
3224  
3225 my ($unknowncode,$regioncode,$languagecode) = unpack('nCC',$data);
3226 my $language = parse_mobi_language($languagecode,$regioncode);
3227  
3228 my @returnlist = ($language,$unknowncode,$regioncode,$languagecode);
3229 if(wantarray) { return @returnlist; }
3230 else { return $returnlist[0]; }
3231 }
3232  
3233  
3234 ########## END CODE ##########
3235  
3236 =head1 BUGS AND LIMITATIONS
3237  
3238 =over
3239  
3240 =item * Unpacking DRM-protected text isn't supported. Although
3241 infrastructure may be added later to make use of external helpers and
3242 plugins, direct DRM support will never be added to the main code for
3243 legal reasons.
3244  
3245 =item * Repacking a .prc without fully extracting to OPF and
3246 completely converting back isn't supported. This will have to be
3247 implemented before an interface to perform minor metadata alterations
3248 can be implemented.
3249  
3250 =item * Mobipocket HUFF/CDIC decoding (used mostly on dictionaries)
3251 isn't well documented.
3252  
3253 =item * Not all Mobipocket data is understood, so a conversion from
3254 OPF to Mobipocket .prc back to OPF will not result in all data being
3255 retained. Patches welcome.
3256  
3257 =item * Mobipocket INDX, DATP, FCIS, and FLIS records are not
3258 understood and are completely ignored
3259  
3260 =item * Mobipocket EXTH subjectcode records may not end up attached to
3261 the correct subject element if the number of subject records differs
3262 from the number of subjectcode records. This is because the
3263 Mobipocket format leaves the EXTH subjectcode records completely
3264 unlinked from the subject records, and there is no way to detect if a
3265 subject with no associated subjectcode comes before a subject with an
3266 associated subjectcode.
3267  
3268 Fortunately, this should rarely be a problem with real data, as
3269 Mobipocket Creator only allows a single subject to be set, and the
3270 only other way to have a subjectcode attached to a subject is to
3271 manually edit the OPF file and insert an additional dc:Subject element
3272 with a BASICCode attribute.
3273  
3274 Mobipocket has indicated that they may move data currently in their
3275 custom elements and attributes to the standard <meta> elements in a
3276 future release, so this problem may become moot then.
3277  
3278 =back
3279  
3280 =head1 AUTHOR
3281  
3282 Zed Pobre <zed@debian.org>
3283  
3284 =head1 LICENSE AND COPYRIGHT
3285  
3286 Copyright 2008 Zed Pobre
3287  
3288 Licensed to the public under the terms of the GNU GPL, version 2
3289  
3290 =cut
3291  
3292 1;
« Tools/EReader.pm ↑ Summary Tools/BISG.pm »