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