blib/lib/EBook/Tools.pm

filter: Statementstmt 96.4% 55 / 57 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 19 / 19 Podpod n/a totaltotal 97.3% 74 / 76 CC 1 SCAR 0.2
CC
1
Cov
96%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/EBook/Tools/Unpack.pm ↑ Summary
1 package EBook::Tools;
2 10 ▶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 5.010; # Needed for smart-match operator
4 #v5.10 feature use removed until 5.10 is standard on MacOSX and Debian
5 10 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use version 0.74; our $VERSION = qv("0.4.9");
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 #use warnings::unused;
9  
10 # Perl Critic overrides:
11 ## no critic (Package variable)
12 # RequireBriefOpen seems to be way too brief to be useful
13 ## no critic (RequireBriefOpen)
14 # Double-sigils are needed for lexical filehandles in clear print statements
15 ## no critic (Double-sigil dereference)
16 our $debug = 0;
17  
18  
19  
20 =head1 NAME
21  
22 EBook::Tools - Object class for manipulating and generating E-books
23  
24  
25 =head1 DESCRIPTION
26  
27 This module provides an object interface and a number of related
28 procedures intended to create or modify documents centered around the
29 International Digital Publishing Forum (IDPF) standards, currently
30 both OEBPS v1.2 and OPS/OPF v2.0.
31  
32 =cut
33  
34 =head1 SYNOPSIS
35  
36 use EBook::Tools qw(split_metadata system_tidy_xml);
37 $EBook::Tools::tidysafety = 2;
38  
39 my $opffile = split_metadata('ebook.html');
40 my $otheropffile = 'alternate.opf';
41 my $retval = system_tidy_xml($opffile,'tidy-backup.xml');
42 my $ebook = EBook::Tools->new($opffile);
43 $ebook->fix_opf20;
44 $ebook->fix_misc;
45 $ebook->print;
46 $ebook->save;
47  
48 $ebook->init($otheropffile);
49 $ebook->fix_oeb12;
50 $ebook->gen_epub;
51  
52  
53 =head1 DEPENDENCIES
54  
55 =head2 Perl Modules
56  
57 =over
58  
59 =item Archive::Zip
60  
61 =item Data::UUID (or OSSP::UUID)
62  
63 =item Date::Manip
64  
65 Note that Date::Manip will die on MS Windows system unless the
66 TZ environment variable is set in a specific manner. See:
67  
68 http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES
69  
70 =item File::MimeInfo
71  
72 =item HTML::Parser
73  
74 =item Tie::IxHash
75  
76 =item Time::Local
77  
78 =item XML::Twig
79  
80 =back
81  
82 =head2 Other Programs
83  
84 =over
85  
86 =item Tidy
87  
88 The command "tidy" needs to be available, and ideally on the path. If
89 it isn't on the path, package variable L</$tidycmd> can be set to its
90 absolute path. If tidy cannot be found, L</system_tidy_xml()> and
91 L</system_tidy_xhtml()> will be nonfunctional.
92  
93 =back
94  
95 =cut
96  
97  
98 require Exporter;
99 10 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
100  
101 our @EXPORT_OK;
102 @EXPORT_OK = qw (
103 &create_epub_container
104 &create_epub_mimetype
105 &debug
106 &excerpt_line
107 &fix_datestring
108 &find_in_path
109 &find_links
110 &find_opffile
111 &hexstring
112 &get_container_rootfile
113 &print_memory
114 &split_metadata
115 &split_pre
116 &strip_script
117 &system_tidy_xml
118 &system_tidy_xhtml
119 &trim
120 &twigelt_create_uuid
121 &twigelt_fix_oeb12_atts
122 &twigelt_fix_opf20_atts
123 &twigelt_is_author
124 &usedir
125 &userconfigdir
126 &ymd_validate
127 );
128 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
129  
130 # OSSP::UUID will provide Data::UUID on systems such as Debian that do
131 # not distribute the original Data::UUID.
132 10 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
133  
134 10 ▶use Archive::Zip qw( :CONSTANTS :ERROR_CODES );
Subroutine BEGIN: called CC=1 SCAR=0.0
135 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
136 10 ▶use Cwd qw(getcwd realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
137 10 ▶use Date::Manip;
Subroutine BEGIN: called CC=1 SCAR=0.0
138 10 ▶use File::Basename qw(basename dirname fileparse);
Subroutine BEGIN: called CC=1 SCAR=0.0
139 # File::MimeInfo::Magic gets *.css right, but detects all html as
140 # text/html, even if it has an XML header.
141 10 ▶use File::MimeInfo::Magic;
Subroutine BEGIN: called CC=1 SCAR=0.0
142 # File::MMagic gets text/xml right (though it still doesn't properly
143 # detect XHTML), but detects CSS as x-system, and has a number of
144 # other weird bugs.
145 #use File::MMagic;
146 10 ▶use File::Path; # Exports 'mkpath' and 'rmtree'
Subroutine BEGIN: called CC=1 SCAR=0.0
147 10 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
148 10 ▶use HTML::Entities qw(decode_entities _decode_entities %entity2char);
Subroutine BEGIN: called CC=1 SCAR=0.0
149 #use HTML::Tidy;
150 10 ▶use Tie::IxHash;
Subroutine BEGIN: called CC=1 SCAR=0.0
151 10 ▶use Time::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
152 10 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
153  
154 =head1 CONFIGURABLE PACKAGE VARIABLES
155  
156 =over
157  
158 =item C<%dcelements12>
159  
160 A tied IxHash mapping an all-lowercase list of Dublin Core metadata
161 element names to the capitalization dictated by the OEB 1.2
162 specification, used by the fix_oeb12() and fix_oeb12_dcmeta() methods.
163 Changing the tags in this list will change the tags recognized and
164 placed inside the <dc-metadata> element.
165  
166 Order is preserved and significant -- fix_oeb12 will output DC
167 metadata elements in the same order as in this hash, though order for
168 tags of the same name is preserved from the input file.
169  
170 =item C<%dcelements20>
171  
172 A tied IxHash mapping an all-lowercase list of Dublin Core metadata
173 element names to the all-lowercase form dictated by the OPF 2.0
174 specification (which means it maps the all-lowercase tags to
175 themselves). It is used by the fix_opf20() and fix_opf20_dcmeta()
176 methods. Changing the tags in this list will change the tags
177 recognized and placed directly under the <metadata> element.
178  
179 Order is preserved and significant -- fix_opf20 will output DC
180 metadata elements in the same order as in this hash, though order for
181 tags of the same name is preserved from the input file.
182  
183 =item C<%nonxmlentity2char>
184  
185 This is the %entity2char conversion map from HTML::Entities with the 5
186 pre-defined XML entities (amp, gt, lt, quot, apos) removed. This is
187 used during by L</init()> to sanitize the OPF file data before
188 parsing. This hash can be modified to allow and convert other
189 non-standard entities to unicode characters. See HTML::Entities for
190 details.
191  
192 =item C<%publishermap>
193  
194 A hash mapping known variants of publisher names to a canonical form,
195 used by L</fix_publisher()>, and thus also indirectly by
196 L</fix_misc()>.
197  
198 Keys should be entered in lowercase. The hash can also be set empty
199 to prevent fix_publisher() from taking any action at all.
200  
201 =item C<%relatorcodes>
202  
203 A hash mapping the MARC Relator Codes (see:
204 http://www.loc.gov/marc/relators/relacode.html) to their descriptive
205 names.
206  
207 =item C<$tidycmd>
208  
209 The tidy executable name. This has to be a fully qualified pathname
210 if tidy isn't on the path. Defaults to 'tidy'.
211  
212 =item C<$tidyxhtmlerrors>
213  
214 The name of the error output file from system_tidy_xhtml(). Defaults
215 to 'tidyxhtml-errors.txt'
216  
217 =item C<$tidyxmlerrors>
218  
219 The name of the error output file from system_tidy_xml(). Defaults to
220 'tidyxml-errors.txt'
221  
222 =item C<$tidysafety>
223  
224 The safety level to use when running tidy (default is 1). Potential
225 values are:
226  
227 =over
228  
229 =item C<$tidysafety < 1>:
230  
231 No checks performed, no error files kept, works like a clean tidy -m
232  
233 This setting is DANGEROUS!
234  
235 =item C<$tidysafety == 1>:
236  
237 Overwrites original file if there were no errors, but even if there
238 were warnings. Keeps a log of errors, but not warnings.
239  
240 =item C<$tidysafety == 2>:
241  
242 Overwrites original file if there were no errors, but even if there
243 were warnings. Keeps a log of both errors and warnings.
244  
245 =item C<$tidysafety == 3>:
246  
247 Overwrites original file only if there were no errors or warnings.
248 Keeps a log of both errors and warnings.
249  
250 =item C<$tidysafety >= 4>:
251  
252 Never overwrites original file. Keeps a log of both errors and
253 warnings.
254  
255 =back
256  
257 =item C<%validspecs>
258  
259 A hash mapping valid specification strings to themselves, primarily
260 used to undefine unrecognized values. Default valid values are 'OEB12'
261 and 'OPF20'.
262  
263 =back
264  
265 =cut
266  
267 our $mobi2htmlcmd = 'mobi2html';
268 our $tidycmd = 'tidy'; # Specify full pathname if not on path
269 our $tidyxhtmlerrors = 'tidyxhtml-errors.txt';
270 our $tidyxmlerrors = 'tidyxml-errors.txt';
271 our $tidysafety = 1;
272  
273  
274 our $utf8xmldec = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
275 our $oeb12doctype =
276 '<!DOCTYPE package' . "\n" .
277 ' PUBLIC "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN"' . "\n" .
278 ' "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd">' . "\n";
279 our $opf20package =
280 '<package version="2.0" xmlns="http://www.idpf.org/2007/opf">' . "\n";
281  
282 our %dcelements12;
283 tie %dcelements12, 'Tie::IxHash', (
284 "dc:identifier" => "dc:Identifier",
285 "dc:title" => "dc:Title",
286 "dc:creator" => "dc:Creator",
287 "dc:contributor" => "dc:Contributor",
288 "dc:subject" => "dc:Subject",
289 "dc:description" => "dc:Description",
290 "dc:publisher" => "dc:Publisher",
291 "dc:date" => "dc:Date",
292 "dc:type" => "dc:Type",
293 "dc:format" => "dc:Format",
294 "dc:source" => "dc:Source",
295 "dc:language" => "dc:Language",
296 "dc:relation" => "dc:Relation",
297 "dc:coverage" => "dc:Coverage",
298 "dc:rights" => "dc:Rights",
299 "dc:copyrights" => "dc:Rights"
300 );
301  
302 our %dcelements20;
303 tie %dcelements20, 'Tie::IxHash', (
304 "dc:identifier" => "dc:identifier",
305 "dc:title" => "dc:title",
306 "dc:creator" => "dc:creator",
307 "dc:contributor" => "dc:contributor",
308 "dc:subject" => "dc:subject",
309 "dc:description" => "dc:description",
310 "dc:publisher" => "dc:publisher",
311 "dc:date" => "dc:date",
312 "dc:type" => "dc:type",
313 "dc:format" => "dc:format",
314 "dc:source" => "dc:source",
315 "dc:language" => "dc:language",
316 "dc:relation" => "dc:relation",
317 "dc:coverage" => "dc:coverage",
318 "dc:rights" => "dc:rights",
319 "dc:copyrights" => "dc:rights"
320 );
321  
322 our %mobibooktypes = (
323 'Default' => undef,
324 'eBook' => 'text/x-oeb1-document',
325 'eNews' => 'application/x-mobipocket-subscription',
326 'News feed' => 'application/x-mobipocket-subscription-feed',
327 'News magazine' => 'application/x-mobipocket-subscription-magazine',
328 'Images' => 'image/gif',
329 'Microsoft Word document' => 'application/msword',
330 'Microsoft Excel sheet' => 'application/vnd.ms-excel',
331 'Microsoft Powerpoint presentation' => 'application/vnd.ms-powerpoint',
332 'Plain text' => 'text/plain',
333 'HTML' => 'text/html',
334 'Mobipocket game' => 'application/vnd.mobipocket-game',
335 'Franklin game' => 'application/vnd.mobipocket-franklin-ua-game'
336 );
337  
338 our %publishermap = (
339 'ace' => 'Ace Books',
340 'acebooks' => 'Ace Books',
341 'ace books' => 'Ace Books',
342 'baen' => 'Baen Publishing Enterprises',
343 'baen publishing' => 'Baen Publishing Enterprises',
344 'ballantine' => 'Ballantine Books',
345 'ballantine books' => 'Ballantine Books',
346 'barnes and noble' => 'Barnes and Noble Publishing',
347 'barnesandnoble.com' => 'Barnes and Noble Publishing',
348 'cpan' => 'CPAN',
349 'delrey' => 'Del Rey Books',
350 'del rey' => 'Del Rey Books',
351 'del rey books' => 'Del Rey Books',
352 'e-reads' => 'E-Reads',
353 'ereads' => 'E-Reads',
354 'ereads.com' => 'E-Reads',
355 'www.ereads.com' => 'E-Reads',
356 'feedbooks' => 'Feedbooks',
357 'feedbooks (www.feedbooks.com)' => 'Feedbooks',
358 'www.feedbooks.com' => 'Feedbooks',
359 'fictionwise' => 'Fictionwise',
360 'fictionwise.com' => 'Fictionwise',
361 'www.fictionwise.com' => 'Fictionwise',
362 'harmony' => 'Harmony Books',
363 'harmony books' => 'Harmony Books',
364 'harpercollins' => 'HarperCollins',
365 'harper collins' => 'HarperCollins',
366 'harper-collins' => 'HarperCollins',
367 'manybooks' => 'ManyBooks',
368 'manybooks.net' => 'ManyBooks',
369 'project gutenberg' => 'Project Gutenberg',
370 'gutenberg' => 'Project Gutenberg',
371 'gutenberg.org' => 'Project Gutenberg',
372 'www.gutenberg.org' => 'Project Gutenberg',
373 'randomhouse' => 'Random House',
374 'randomhouse.co.uk' => 'Random House',
375 'www.randomhouse.co.uk' => 'Random House',
376 'random-house.com' => 'Random House',
377 'www.random-house.com' => 'Random House',
378 'rosetta' => 'Rosetta Books',
379 'rosettabooks' => 'Rosetta Books',
380 'rosetta books' => 'Rosetta Books',
381 'siren' => 'Siren Publishing',
382 'siren publishing' => 'Siren Publishing',
383 'wildside' => 'Wildside Press',
384 'wildside press' => 'Wildside Press',
385 );
386  
387  
388 our %nonxmlentity2char = %entity2char;
389 delete($nonxmlentity2char{'amp'});
390 delete($nonxmlentity2char{'gt'});
391 delete($nonxmlentity2char{'lt'});
392 delete($nonxmlentity2char{'quot'});
393 delete($nonxmlentity2char{'apos'});
394  
395 our %relatorcodes = (
396 'act' => 'Actor',
397 'adp' => 'Adapter',
398 'ann' => 'Annotator',
399 'ant' => 'Bibliographic antecedent',
400 'app' => 'Applicant',
401 'arc' => 'Architect',
402 'arr' => 'Arranger',
403 'art' => 'Artist',
404 'asg' => 'Assignee',
405 'asn' => 'Associated name',
406 'att' => 'Attributed name',
407 'aui' => 'Author of introduction',
408 'aus' => 'Author of screenplay',
409 'aut' => 'Author',
410 'bdd' => 'Binding designer',
411 'bjd' => 'Bookjacket designer',
412 'bkd' => 'Book designer',
413 'bkp' => 'Book producer',
414 'bnd' => 'Binder',
415 'bpd' => 'Bookplate designer',
416 'bsl' => 'Bookseller',
417 'chr' => 'Choreographer',
418 'cli' => 'Client',
419 'cll' => 'Calligrapher',
420 'clt' => 'Collotyper',
421 'cmm' => 'Commentator',
422 'cmp' => 'Composer',
423 'cmt' => 'Compositor',
424 'cnd' => 'Conductor',
425 'cns' => 'Censor',
426 'coe' => 'Contestant-appellee',
427 'col' => 'Collector',
428 'com' => 'Compiler',
429 'cos' => 'Contestant',
430 'cot' => 'Contestant-appellant',
431 'cpe' => 'Complainant-appellee',
432 'cph' => 'Copyright holder',
433 'cpl' => 'Complainant',
434 'cpt' => 'Complainant-appellant',
435 'crp' => 'Correspondent',
436 'crr' => 'Corrector',
437 'cst' => 'Costume designer',
438 'cte' => 'Contestee-appellee',
439 'ctg' => 'Cartographer',
440 'cts' => 'Contestee',
441 'ctt' => 'Contestee-appellant',
442 'dfd' => 'Defendant',
443 'dfe' => 'Defendant-appellee',
444 'dft' => 'Defendant-appellant',
445 'dln' => 'Delineator',
446 'dnc' => 'Dancer',
447 'dnr' => 'Donor',
448 'dpt' => 'Depositor',
449 'drt' => 'Director',
450 'dsr' => 'Designer',
451 'dst' => 'Distributor',
452 'dte' => 'Dedicatee',
453 'dto' => 'Dedicator',
454 'dub' => 'Dubious author',
455 'edt' => 'Editor',
456 'egr' => 'Engraver',
457 'elt' => 'Electrotyper',
458 'eng' => 'Engineer',
459 'etr' => 'Etcher',
460 'flm' => 'Film editor',
461 'fmo' => 'Former owner',
462 'fnd' => 'Funder/Sponsor',
463 'frg' => 'Forger',
464 'grt' => 'Graphic technician (discontinued code)',
465 'hnr' => 'Honoree',
466 'ill' => 'Illustrator',
467 'ilu' => 'Illuminator',
468 'ins' => 'Inscriber',
469 'inv' => 'Inventor',
470 'itr' => 'Instrumentalist',
471 'ive' => 'Interviewee',
472 'ivr' => 'Interviewer',
473 'lbt' => 'Librettist',
474 'lee' => 'Libelee-appellee',
475 'lel' => 'Libelee',
476 'len' => 'Lender',
477 'let' => 'Libelee-appellant',
478 'lie' => 'Libelant-appellee',
479 'lil' => 'Libelant',
480 'lit' => 'Libelant-appellant',
481 'lse' => 'Licensee',
482 'lso' => 'Licensor',
483 'ltg' => 'Lithographer',
484 'lyr' => 'Lyricist',
485 'mon' => 'Monitor/Contractor',
486 'mte' => 'Metal-engraver',
487 'nrt' => 'Narrator',
488 'org' => 'Originator',
489 'oth' => 'Other',
490 'pbl' => 'Publisher',
491 'pfr' => 'Proofreader',
492 'pht' => 'Photographer',
493 'plt' => 'Platemaker',
494 'pop' => 'Printer of plates',
495 'ppm' => 'Papermaker',
496 'prd' => 'Production personnel',
497 'prf' => 'Performer',
498 'pro' => 'Producer',
499 'prt' => 'Printer',
500 'pte' => 'Plaintiff-appellee',
501 'ptf' => 'Plaintiff',
502 'pth' => 'Patent holder',
503 'ptt' => 'Plaintiff-appellant',
504 'rbr' => 'Rubricator',
505 'rce' => 'Recording engineer',
506 'rcp' => 'Recipient',
507 'rse' => 'Respondent-appellee',
508 'rsp' => 'Respondent',
509 'rst' => 'Respondent-appellant',
510 'sce' => 'Scenarist',
511 'scr' => 'Scribe',
512 'scl' => 'Sculptor',
513 'sec' => 'Secretary',
514 'sgn' => 'Signer',
515 'srv' => 'Surveyor',
516 'str' => 'Stereotyper',
517 'trc' => 'Transcriber',
518 'trl' => 'Translator',
519 'tyd' => 'Type designer',
520 'tyg' => 'Typographer',
521 'voc' => 'Vocalist',
522 'wam' => 'Writer of accompanying material',
523 'wde' => 'Wood-engraver',
524 'wit' => 'Witness',
525 );
526  
527 our %validspecs = (
528 'OEB12' => 'OEB12',
529 'OPF20' => 'OPF20',
530 'MOBI12' => 'MOBI12',
531 );
532  
533  
534 #####################################################
535 ########## CONSTRUCTORS AND INITIALIZATION ##########
536 #####################################################
537  
538 my %rwfields = (
539 'opffile' => 'string',
540 'spec' => 'string',
541 );
542 my %rofields = (
543 'twig' => 'scalar',
544 'twigroot' => 'scalar',
545 'errors' => 'arrayref',
546 'warnings' => 'arrayref',
547 );
548 my %privatefields = (
549 );
550  
551 # A simple 'use fields' will not work here: use takes place inside
552 # BEGIN {}, so the @...fields variables won't exist.
553 require fields;
554 fields->import(
555 keys(%rwfields),keys(%rofields),keys(%privatefields)
556 );
557  
558  
559 =head1 CONSTRUCTORS AND INITIALIZATION
560  
561 =head2 C<new($filename)>
562  
563 Instantiates a new EBook::Tools object. If C<$filename> is specified,
564 it will also immediately initialize itself via the C<init> method.
565  
566 =cut
567  
568 sub new ## no critic (Always unpack @_ first)
569 {
570 my $self = shift;
571 my $class = ref($self) || $self;
572 my ($filename) = @_;
573 my $subname = (caller(0))[3];
574 debug(2,"DEBUG[",$subname,"]");
575  
576 $self = fields::new($class);
577  
578 if($filename)
579 {
580 debug(2,"DEBUG: new object from '",$filename,"'");
581 $self->init($filename);
582 }
583 return $self;
584 }
585  
586  
587 =head2 C<init($filename)>
588  
589 Initializes the object from an existing OPF file. If C<$filename> is
590 specified and exists, the OEB object will be set to read and write to
591 that file before attempting to initialize. Otherwise, if the object
592 currently points to an OPF file it will use that name. If there is no
593 OPF filename data, and C<$filename> was not specified, it will make a
594 last-ditch attempt to find an OPF file first by looking in
595 META-INF/container.xml, and if nothing is found there, by looking in
596 the current directory for a single OPF file.
597  
598 If no such files or found (or more than one is found), the
599 initialization croaks.
600  
601 =cut
602  
603 sub init :method ## no critic (Always unpack @_ first)
604 {
605 my $self = shift;
606 my ($filename) = @_;
607 my $fh_opffile;
608 my $opfstring;
609 my $subname = (caller(0))[3];
610 croak($subname . "() called as a procedure") unless(ref $self);
611 debug(2,"DEBUG[",$subname,"]");
612  
613 if($filename) { $self->{opffile} = $filename; }
614  
615 if(!$self->{opffile})
616 {
617 $opfstring = find_opffile();
618 $self->{opffile} = $opfstring if($opfstring);
619 }
620  
621 if(!$self->{opffile})
622 {
623 croak($subname,"(): Unable to find an OPF file to work with!\n");
624 }
625  
626 if(! -f $self->{opffile})
627 {
628 croak($subname,"(): '",$self->{opffile},
629 "' does not exist or is not a regular file!")
630 }
631  
632 if(-z $self->{opffile})
633 {
634 croak("OPF file '",$self->{opffile},"' has zero size!");
635 }
636  
637 debug(2,"DEBUG: init using '",$self->{opffile},"'");
638  
639 # Initialize the twig before use
640 $self->{twig} = XML::Twig->new(
641 keep_atts_order => 1,
642 output_encoding => 'utf-8',
643 pretty_print => 'record'
644 );
645  
646 # Read and decode entities before parsing to avoid parsing errors
647 open($fh_opffile,'<:utf8',$self->{opffile})
648 or croak($subname,"(): failed to open '",$self->{opffile},
649 "' for reading!");
650 read($fh_opffile,$opfstring,-s $self->opffile)
651 or croak($subname,"(): failed to read from '",$self->{opffile},"'!");
652 close($fh_opffile)
653 or croak($subname,"(): failed to close '",$self->{opffile},"'!");
654  
655 # We use _decode_entities and the custom hash to decode, but also
656 # see below for the regexp
657 _decode_entities($opfstring,\%nonxmlentity2char);
658  
659 # This runs decode_entities on the substring containing just the
660 # entity for every entity *except* the 5 predefined internal
661 # entities. It seems to be about the same speed as running
662 # _decode_entities on a small file, but having the hash map as a
663 # package variable has additional utility, so that technique gets
664 # used instead.
665 # $opfstring =~
666 # s/(&
667 # (?! (?:lt|gt|quot|apos|amp);
668 # )\w+;
669 # )
670 # / decode_entities($1) /gex;
671  
672 $self->{twig}->parse($opfstring);
673 $self->{twigroot} = $self->{twig}->root;
674 $self->twigcheck;
675 debug(2,"DEBUG[/",$subname,"]");
676 return $self;
677 }
678  
679  
680 =head2 C<init_blank(%args)>
681  
682 Initializes an object containing nothing more than the basic OPF
683 framework, suitable for adding new documents when creating an e-book
684 from scratch.
685  
686 =head3 Arguments
687  
688 C<init_blank> takes up to three optional named arguments:
689  
690 =over
691  
692 =item C<opffile>
693  
694 This specifies the OPF filename to use. If not specified, defaults to
695 the name of the current working directory with ".opf" appended
696  
697 =item C<author>
698  
699 This specifies the content of the initial dc:creator element. If not
700 specified, defaults to "Unknown Author".
701  
702 =item C<title>
703  
704 This specifies the content of the initial dc:title element. If not
705 specified, defaults to "Unknown Title".
706  
707 =back
708  
709 =head3 Example
710  
711 init_blank('opffile' => 'newfile.opf',
712 'title' => 'The Great Unknown');
713  
714 =cut
715  
716 sub init_blank :method ## no critic (Always unpack @_ first)
717 {
718 my $self = shift;
719 my (%args) = @_;
720 my $subname = ( caller(0) )[3];
721 croak($subname . "() called as a procedure") unless(ref $self);
722 debug(2,"DEBUG[",$subname,"]");
723  
724  
725 my %valid_args = (
726 'opffile' => 1,
727 'author' => 1,
728 'title' => 1,
729 );
730 foreach my $arg (keys %args)
731 {
732 croak($subname,"(): invalid argument '",$arg,"'")
733 if(!$valid_args{$arg});
734 }
735  
736 $args{opffile} ||= basename(getcwd) . ".opf";
737  
738 my $author = $args{author} || 'Unknown Author';
739 my $title = $args{title} || 'Unknown Title';
740 my $metadata;
741 my $element;
742  
743 $self->{opffile} = $args{opffile};
744 $self->{twig} = XML::Twig->new(
745 keep_atts_order => 1,
746 output_encoding => 'utf-8',
747 pretty_print => 'record'
748 );
749  
750 $element = XML::Twig::Elt->new('package');
751 $self->{twig}->set_root($element);
752 $self->{twigroot} = $self->{twig}->root;
753 $metadata = $self->{twigroot}->insert_new_elt('first_child','metadata');
754  
755 # dc:identifier
756 $self->fix_packageid;
757  
758 # dc:title
759 $element = $metadata->insert_new_elt('last_child','dc:title');
760 $element->set_text($title);
761  
762 # dc:creator (author)
763 $element = $metadata->insert_new_elt('last_child','dc:creator');
764 $element->set_att('opf:role','aut');
765 $element->set_text($author);
766  
767 $self->fix_opf20;
768 return 1;
769 }
770  
771  
772 ######################################
773 ########## ACCESSOR METHODS ##########
774 ######################################
775  
776 =head1 ACCESSOR METHODS
777  
778 The following methods return data deeper in the structure than the
779 auto-accessors, but still do not modify any object data or files.
780  
781  
782 =head2 C<adult()>
783  
784 Returns the text of the Mobipocket-specific <Adult> element, if it
785 exists. Expected values are 'yes' and undef.
786  
787 =cut
788  
789 sub adult :method
790 {
791 my $self = shift;
792 my $subname = ( caller(0) )[3];
793 croak($subname . "() called as a procedure") unless(ref $self);
794 debug(2,"DEBUG[",$subname,"]");
795 $self->twigcheck;
796  
797 my $twigroot = $self->{twigroot};
798  
799 my $element = $twigroot->first_descendant(qr/^adult$/ix);
800 return unless($element);
801  
802 if($element->text) { return $element->text; }
803 else { return; }
804 }
805  
806  
807 =head2 C<contributor_list()>
808  
809 Returns a list containing the text of all dc:contributor elements
810 (case-insensitive) or undef if none are found.
811  
812 In scalar context, returns the first contributor, not the last.
813  
814 =cut
815  
816 sub contributor_list :method
817 {
818 my $self = shift;
819 my $subname = ( caller(0) )[3];
820 croak($subname . "() called as a procedure") unless(ref $self);
821 debug(2,"DEBUG[",$subname,"]");
822 $self->twigcheck;
823  
824 my @retval = ();
825 my $twigroot = $self->{twigroot};
826  
827 my @elements = $twigroot->descendants(qr/dc:contributor/ix);
828 return unless(@elements);
829  
830 foreach my $el (@elements)
831 {
832 push(@retval,$el->text) if($el->text);
833 }
834 return unless(@retval);
835 if(wantarray) { return @retval; }
836 else { return $retval[0]; }
837 }
838  
839  
840 =head2 C<date_list(%args)>
841  
842 Returns the text of all dc:date elements (case-insensitive) matching
843 the specified attributes.
844  
845 In scalar context, returns the first match, not the last.
846  
847 Returns undef if no matches are found.
848  
849 =head3 Arguments
850  
851 =over
852  
853 =item * C<id> - 'id' attribute that must be matched exactly for the
854 result to be added to the list
855  
856 =item * C<event> 'opf:event' or 'event' attribute that must be
857 matched exactly for the result to be added to the list
858  
859 =back
860  
861 If both arguments are specified a value is added to the list if it
862 matches either one (i.e. the logic is OR).
863  
864 =cut
865  
866 sub date_list :method ## no critic (Always unpack @_ first)
867 {
868 my $self = shift;
869 my (%args) = @_;
870 my %valid_args = (
871 'id' => 1,
872 'event' => 1,
873 );
874 my $subname = ( caller(0) )[3];
875 croak($subname . "() called as a procedure") unless(ref $self);
876 debug(2,"DEBUG[",$subname,"]");
877 $self->twigcheck();
878 foreach my $arg (keys %args)
879 {
880 croak($subname,"(): invalid argument '",$arg,"'")
881 if(!$valid_args{$arg});
882 }
883  
884 my @elements = $self->{twigroot}->descendants(qr/^ dc:date $/ix);
885 my @list = ();
886 my $id;
887 my $scheme;
888 foreach my $el (@elements)
889 {
890 if($args{id})
891 {
892 $id = $el->att('id') || '';
893 if($id eq $args{id})
894 {
895 push(@list,$el->text);
896 next;
897 }
898 }
899 if($args{event})
900 {
901 $scheme = $el->att('opf:event') || $el->att('event') || '';
902 if($scheme eq $args{event})
903 {
904 push(@list,$el->text);
905 next;
906 }
907 }
908 next if($args{id} || $args{event});
909 push(@list,$el->text);
910 }
911 return unless(@list);
912 if(wantarray) { return @list; }
913 else { return $list[0]; }
914 }
915  
916  
917 =head2 C<description()>
918  
919 Returns the description of the e-book, if set, or undef otherwise.
920  
921 =cut
922  
923 sub description :method
924 {
925 my $self = shift;
926 my $subname = ( caller(0) )[3];
927 croak($subname . "() called as a procedure") unless(ref $self);
928 debug(2,"DEBUG[",$subname,"]");
929 $self->twigcheck;
930  
931 my $twigroot = $self->{twigroot};
932  
933 my $element = $twigroot->first_descendant(qr/^dc:description$/ix);
934 return unless($element);
935  
936 if($element->text) { return $element->text; }
937 else { return; }
938 }
939  
940  
941 =head2 C<element_list(%args)>
942  
943 Returns a list containing the text values of all elements matching the
944 specified criteria.
945  
946 =head3 Arguments
947  
948 =over
949  
950 =item * C<cond>
951  
952 The L<XML::Twig> search condition used to find the elements.
953 Typically this is just the GI (tag) of the element you wish to find,
954 but it can also be a C<qr//> expression, coderef, or anything else
955 that XML::Twig can work with. See the XML::Twig documentation for
956 details.
957  
958 If this is not specified, an error is added and the method returns
959 undef.
960  
961 =item * C<id> (optional)
962  
963 'id' attribute that must be matched exactly for the
964 result to be added to the list
965  
966 =item * C<scheme> (optional)
967  
968 'opf:scheme' or 'scheme' attribute that must be
969 matched exactly for the result to be added to the list
970  
971 =item * C<event> (optional)
972  
973 'opf:event' or 'event' attribute that must be matched exactly for the
974 result to be added to the list
975  
976 =back
977  
978 If more than one of the arguments C<id>, C<scheme>, or C<event> are
979 specified a value is added to the list if it matches any one (i.e. the
980 logic is OR).
981  
982 =cut
983  
984 sub element_list :method ## no critic (Always unpack @_ first)
985 {
986 my $self = shift;
987 my (%args) = @_;
988 my %valid_args = (
989 'cond' => 1,
990 'id' => 1,
991 'scheme' => 1,
992 );
993 my $subname = ( caller(0) )[3];
994 croak($subname . "() called as a procedure") unless(ref $self);
995 debug(2,"DEBUG[",$subname,"]");
996 $self->twigcheck();
997 foreach my $arg (keys %args)
998 {
999 croak($subname,"(): invalid argument '",$arg,"'")
1000 if(!$valid_args{$arg});
1001 }
1002 unless($args{cond})
1003 {
1004 $self->add_error($subname,"(): no search condition specified");
1005 return;
1006 }
1007  
1008 my @elements = $self->{twigroot}->descendants($args{cond});
1009 my @list = ();
1010 my $id;
1011 my $scheme;
1012 foreach my $el (@elements)
1013 {
1014 if($args{id})
1015 {
1016 $id = $el->att('id') || '';
1017 if($id eq $args{id})
1018 {
1019 push(@list,$el->text);
1020 next;
1021 }
1022 }
1023 if($args{event})
1024 {
1025 $scheme = $el->att('opf:event') || $el->att('event') || '';
1026 if($scheme eq $args{event})
1027 {
1028 push(@list,$el->text);
1029 next;
1030 }
1031 }
1032 if($args{scheme})
1033 {
1034 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
1035 if($scheme eq $args{scheme})
1036 {
1037 push(@list,$el->text);
1038 next;
1039 }
1040 }
1041 next if($args{id} || $args{event} || $args{scheme});
1042 push(@list,$el->text);
1043 }
1044 return unless(@list);
1045 if(wantarray) { return @list; }
1046 else { return $list[0]; }
1047 }
1048  
1049  
1050 =head2 C<errors()>
1051  
1052 Returns an arrayref containing any generated error messages.
1053  
1054 =cut
1055  
1056 sub errors :method
1057 {
1058 my $self = shift;
1059 my $subname = ( caller(0) )[3];
1060 croak($subname . "() called as a procedure") unless(ref $self);
1061 debug(2,"DEBUG[",$subname,"]");
1062 return $self->{errors};
1063 }
1064  
1065  
1066 =head2 C<identifier()>
1067  
1068 Returns the text of the dc:identifier element pointed to by the
1069 'unique-identifier' attribute of the root 'package' element, or undef
1070 if it could not be located.
1071  
1072 =cut
1073  
1074 sub identifier :method
1075 {
1076 my $self = shift;
1077 my $subname = ( caller(0) )[3];
1078 croak($subname . "() called as a procedure") unless(ref $self);
1079 debug(2,"DEBUG[",$subname,"]");
1080 $self->twigcheck;
1081  
1082 my $identid = $self->{twigroot}->att('unique-identifier');
1083 return unless($identid);
1084  
1085 my $identifier = $self->{twig}->first_elt("*[\@id='$identid']");
1086 return unless($identifier);
1087  
1088 my $idtext = $identifier->text;
1089 return unless($idtext);
1090  
1091 return($idtext);
1092 }
1093  
1094  
1095 =head2 C<isbn_list(%args)>
1096  
1097 Returns a list of all ISBNs matching the specified attributes. See
1098 L</twigelt_is_isbn()> for a detailed description of how the ISBN
1099 elements are found.
1100  
1101 Returns undef if no matches are found.
1102  
1103 In scalar context returns the first match, not the last.
1104  
1105 See also L</isbns(%args)>.
1106  
1107 =head3 Arguments
1108  
1109 =over
1110  
1111 =item * C<id> (optional)
1112  
1113 'id' attribute that must be matched exactly for the
1114 result to be added to the list
1115  
1116 =item * C<scheme> (optional)
1117  
1118 'opf:scheme' or 'scheme' attribute that must be
1119 matched exactly for the result to be added to the list
1120  
1121 =back
1122  
1123 If both arguments are specified a value is added to the list if it
1124 matches either one (i.e. the logic is OR).
1125  
1126 =cut
1127  
1128 sub isbn_list :method ## no critic (Always unpack @_ first)
1129 {
1130 my $self = shift;
1131 my (%args) = @_;
1132 my %valid_args = (
1133 'id' => 1,
1134 'scheme' => 1,
1135 );
1136 my $subname = ( caller(0) )[3];
1137 croak($subname . "() called as a procedure") unless(ref $self);
1138 debug(2,"DEBUG[",$subname,"]");
1139 $self->twigcheck();
1140 foreach my $arg (keys %args)
1141 {
1142 croak($subname,"(): invalid argument '",$arg,"'")
1143 if(!$valid_args{$arg});
1144 }
1145  
1146 my @list = $self->element_list(cond => \&twigelt_is_isbn,
1147 %args);
1148 return unless(@list);
1149 if(wantarray) { return @list; }
1150 else { return $list[0]; }
1151 }
1152  
1153  
1154 =head2 C<isbns(%args)>
1155  
1156 Returns all of the ISBN identifiers matching the specificied
1157 attributes as a list of hashrefs, with one hash per ISBN identifier
1158 presented in the order that the identifiers are found. The hash keys
1159 are 'id' (containing the value of the 'id' attribute), 'scheme'
1160 (containing the value of either the 'opf:scheme' or 'scheme'
1161 attribute, whichever is found first), and 'isbn' (containing the text
1162 of the element).
1163  
1164 If no entries are found, returns undef.
1165  
1166 In scalar context returns the first match, not the last.
1167  
1168 See also L</isbn_list(%args)>.
1169  
1170 =head3 Arguments
1171  
1172 C<isbns()> takes two optional named arguments:
1173  
1174 =over
1175  
1176 =item * C<id> - 'id' attribute that must be matched exactly for the
1177 result to be added to the list
1178  
1179 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute that must be
1180 matched exactly for the result to be added to the list
1181  
1182 =back
1183  
1184 If both arguments are specified a value is added to the list if it
1185 matches either one (i.e. the logic is OR).
1186  
1187 =cut
1188  
1189 sub isbns :method ## no critic (Always unpack @_ first)
1190 {
1191 my $self = shift;
1192 my (%args) = @_;
1193 my %valid_args = (
1194 'id' => 1,
1195 'scheme' => 1,
1196 );
1197 my $subname = ( caller(0) )[3];
1198 croak($subname . "() called as a procedure") unless(ref $self);
1199 debug(2,"DEBUG[",$subname,"]");
1200 $self->twigcheck();
1201 foreach my $arg (keys %args)
1202 {
1203 croak($subname,"(): invalid argument '",$arg,"'")
1204 if(!$valid_args{$arg});
1205 }
1206  
1207 my @elements = $self->{twigroot}->descendants(\&twigelt_is_isbn);
1208 my @list = ();
1209 my $id;
1210 my $scheme;
1211 foreach my $el (@elements)
1212 {
1213 if($args{id})
1214 {
1215 $id = $el->att('id') || '';
1216 if($id eq $args{id})
1217 {
1218 push(@list,
1219 {
1220 'isbn' => $el->text,
1221 'id' => $el->att('id'),
1222 'scheme' => $el->att('scheme'),
1223 });
1224 next;
1225 }
1226 }
1227 if($args{scheme})
1228 {
1229 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
1230 if($scheme eq $args{scheme})
1231 {
1232 push(@list,
1233 {
1234 'isbn' => $el->text,
1235 'id' => $el->att('id'),
1236 'scheme' => $el->att('scheme'),
1237 });
1238 next;
1239 }
1240 }
1241 next if($args{id} || $args{scheme});
1242 $scheme = $el->att('opf:scheme') || $el->att('scheme');
1243 push(@list,
1244 {
1245 'isbn' => $el->text,
1246 'id' => $el->att('id'),
1247 'scheme' => $scheme,
1248 });
1249 }
1250 return unless(@list);
1251 if(wantarray) { return @list; }
1252 else { return $list[0]; }
1253 }
1254  
1255  
1256 =head2 C<languages()>
1257  
1258 Returns a list containing the text of all dc:language
1259 (case-insensitive) entries, or undef if none are found.
1260  
1261 In scalar context returns the first match, not the last.
1262  
1263 =cut
1264  
1265 sub languages :method
1266 {
1267 my $self = shift;
1268 my $subname = ( caller(0) )[3];
1269 croak($subname . "() called as a procedure") unless(ref $self);
1270 debug(2,"DEBUG[",$subname,"]");
1271 $self->twigcheck;
1272  
1273 my @retval = ();
1274 my @elements = $self->{twigroot}->descendants(qr/^dc:language$/ix);
1275 foreach my $el (@elements)
1276 {
1277 push(@retval,$el->text) if($el->text);
1278 }
1279 return unless(@retval);
1280 if(wantarray) { return @retval; }
1281 else { return $retval[0]; }
1282 }
1283  
1284  
1285 =head2 C<manifest(%args)>
1286  
1287 Returns all of the items in the manifest as a list of hashrefs, with
1288 one hash per manifest item in the order that they appear, where the
1289 hash keys are 'id', 'href', and 'media-type', each returning the
1290 appropriate attribute, if any.
1291  
1292 In scalar context, returns the first match, not the last.
1293  
1294 =head3 Arguments
1295  
1296 C<manifest()> takes four optional named arguments:
1297  
1298 =over
1299  
1300 =item * C<id> - 'id' attribute to match
1301  
1302 =item * C<href> - 'href' attribute to match
1303  
1304 =item * C<mtype> - 'media-type' attribute to match
1305  
1306 =item * C<logic> - logic to use (valid values are 'and' or 'or', default: 'and')
1307  
1308 =back
1309  
1310 If any of the named arguments are specified, C<manifest()> will return
1311 only items matching the specified criteria. This is an exact
1312 case-sensitive match, but it can (especially in the case of mtype)
1313 still return multiple elements.
1314  
1315 =head3 Return values
1316  
1317 Returns undef if there is no <manifest> element directly underneath
1318 <package>, or if <manifest> contains no items.
1319  
1320 =head3 See also
1321  
1322 L</manifest_hrefs()>, L</spine()>
1323  
1324 =head3 Example
1325  
1326 @manifest = $ebook->manifest(id => 'ncx',
1327 mtype => 'text/xml',
1328 logic => 'or');
1329  
1330 =cut
1331  
1332 sub manifest :method ## no critic (Always unpack @_ first)
1333 {
1334 my $self = shift;
1335 my (%args) = @_;
1336 my %valid_args = (
1337 'id' => 1,
1338 'href' => 1,
1339 'mtype' => 1,
1340 'logic' => 1
1341 );
1342 my %valid_logic = (
1343 'and' => 1,
1344 'or' => 1
1345 );
1346 my $subname = ( caller(0) )[3];
1347 croak($subname . "() called as a procedure") unless(ref $self);
1348 debug(2,"DEBUG[",$subname,"]");
1349 $self->twigcheck();
1350  
1351 foreach my $arg (keys %args)
1352 {
1353 croak($subname,"(): invalid argument '",$arg,"'")
1354 if(!$valid_args{$arg});
1355 }
1356 if($args{logic})
1357 {
1358 croak($subname,
1359 "(): logic must be 'and' or 'or' (got '",$args{logic},"')")
1360 if(!$valid_logic{$args{logic}});
1361 }
1362 else { $args{logic} = 'and'; }
1363  
1364 debug(1,"DEBUG: manifest() called with '",join(" ",keys(%args)),"'");
1365  
1366 my @elements;
1367 my @retarray;
1368 my $cond;
1369  
1370 if($args{id})
1371 {
1372 debug(1,"DEBUG: manifest searching on id");
1373 $cond = "item[\@id='$args{id}'";
1374 }
1375 if($args{href})
1376 {
1377 debug(1,"DEBUG: manifest searching on href");
1378 if($cond) { $cond .= " $args{logic} \@href='$args{href}'"; }
1379 else { $cond = "item[\@href='$args{href}'"; }
1380 }
1381 if($args{mtype})
1382 {
1383 debug(1,"DEBUG: manifest searching on mtype");
1384 if($cond) { $cond .= " $args{logic} \@media-type='$args{mtype}'"; }
1385 else { $cond = "item[\@media-type='$args{mtype}'"; }
1386 }
1387 if($cond) { $cond .= "]"; }
1388 else { $cond = "item"; }
1389  
1390 my $manifest = $self->{twigroot}->first_child('manifest');
1391 return unless($manifest);
1392  
1393 debug(1,"DEBUG: manifest search condition = '",$cond,"'");
1394 @elements = $manifest->children($cond);
1395 return unless(@elements);
1396  
1397 foreach my $el (@elements)
1398 {
1399 push(@retarray,
1400 {
1401 'id' => $el->id,
1402 'href' => $el->att('href'),
1403 'media-type' => $el->att('media-type')
1404 });
1405 }
1406 if(wantarray) { return @retarray; }
1407 else { return $retarray[0]; }
1408 }
1409  
1410  
1411 =head2 C<manifest_hrefs()>
1412  
1413 Returns a list of all of the hrefs in the current OPF manifest, or the
1414 empty list if none are found.
1415  
1416 In scalar context returns the first href, not the last.
1417  
1418 See also: C<manifest()>, C<spine_idrefs()>
1419  
1420 =cut
1421  
1422 sub manifest_hrefs :method
1423 {
1424 my $self = shift;
1425 my $subname = ( caller(0) )[3];
1426 croak($subname . "() called as a procedure") unless(ref $self);
1427 debug(2,"DEBUG[",$subname,"]");
1428 $self->twigcheck();
1429  
1430 my @items;
1431 my $href;
1432 my $manifest;
1433 my @retval = ();
1434  
1435 $manifest = $self->{twigroot}->first_child('manifest');
1436 if(! $manifest) { return @retval; }
1437  
1438 @items = $manifest->descendants('item');
1439 foreach my $item (@items)
1440 {
1441 $href = $item->att('href');
1442 debug(3,"DEBUG: '",$href,"' has mime-type '",mimetype($href),"'")
1443 if($href);
1444 push(@retval,$href) if($href);
1445 }
1446 debug(2,"DEBUG[/",$subname,"]");
1447 if(wantarray) { return @retval; }
1448 else { return $retval[0]; }
1449 }
1450  
1451  
1452 =head2 C<opffile()>
1453  
1454 Returns the name of the file where the OPF metadata will be stored or
1455 undef if no value is found..
1456  
1457 =cut
1458  
1459 sub opffile :method
1460 {
1461 my $self = shift;
1462 my $subname = ( caller(0) )[3];
1463 croak($subname . "() called as a procedure") unless(ref $self);
1464 debug(2,"DEBUG[",$subname,"]");
1465 return unless($self->{opffile});
1466 return $self->{opffile};
1467 }
1468  
1469  
1470 =head2 C<primary_author()>
1471  
1472 Finds the primary author of the book, defined as the first
1473 'dc:creator' entry (case-insensitive) where either the attribute
1474 opf:role="aut" or role="aut", or the first 'dc:creator' entry if no
1475 entries with either attribute can be found. Entries must actually
1476 have text to be considered.
1477  
1478 In list context, returns a two-item list, the first of which is the
1479 text of the entry (the author name), and the second element of which
1480 is the value of the 'opf:file-as' or 'file-as' attribute (where
1481 'opf:file-as' is given precedence if both are present).
1482  
1483 In scalar context, returns the text of the entry (the author name).
1484  
1485 If no entries are found, returns undef.
1486  
1487 Uses L</twigelt_is_author()> in the first half of the search.
1488  
1489 =head3 Example
1490  
1491 my ($fileas, $author) = $ebook->primary_author;
1492 my $author = $ebook->primary_author;
1493  
1494 =cut
1495  
1496 sub primary_author :method
1497 {
1498 my $self = shift;
1499 my $subname = ( caller(0) )[3];
1500 croak($subname . "() called as a procedure") unless(ref $self);
1501 debug(2,"DEBUG[",$subname,"]");
1502  
1503 my $twigroot = $self->{twigroot};
1504 my $element;
1505 my $fileas;
1506  
1507 $element = $twigroot->first_descendant(\&twigelt_is_author);
1508 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
1509 carp("##DEBUG: primary_author not found") unless($element->text);
1510 return unless($element);
1511 return unless($element->text);
1512 $fileas = $element->att('opf:file-as');
1513 $fileas = $element->att('file-as') unless($fileas);
1514 if(wantarray) { return ($element->text, $fileas); }
1515 else { return $element->text; }
1516 }
1517  
1518  
1519 =head2 C<print_errors()>
1520  
1521 Prints the current list of errors to STDERR.
1522  
1523 =cut
1524  
1525 sub print_errors :method
1526 {
1527 my $self = shift;
1528 my $subname = ( caller(0) )[3];
1529 croak($subname . "() called as a procedure") unless(ref $self);
1530 debug(2,"DEBUG[",$subname,"]");
1531  
1532 my $errorref = $self->{errors};
1533  
1534 if(!$self->errors)
1535 {
1536 debug(1,"DEBUG: no errors found!");
1537 return 1;
1538 }
1539  
1540  
1541 foreach my $error (@$errorref)
1542 {
1543 print "ERROR: ",$error,"\n";
1544 }
1545 return 1;
1546 }
1547  
1548  
1549 =head2 C<print_warnings()>
1550  
1551 Prints the current list of warnings to STDERR.
1552  
1553 =cut
1554  
1555 sub print_warnings :method
1556 {
1557 my $self = shift;
1558 my $subname = ( caller(0) )[3];
1559 croak($subname . "() called as a procedure") unless(ref $self);
1560 debug(2,"DEBUG[",$subname,"]");
1561  
1562 my $warningref = $self->{warnings};
1563  
1564 if(!$self->warnings)
1565 {
1566 debug(2,"DEBUG: no warnings found!");
1567 return 1;
1568 }
1569  
1570  
1571 foreach my $warning (@$warningref)
1572 {
1573 print "WARNING: ",$warning,"\n";
1574 }
1575 return 1;
1576 }
1577  
1578  
1579 =head2 C<print_opf()>
1580  
1581 Prints the OPF file to the default filehandle
1582  
1583 =cut
1584  
1585 sub print_opf :method
1586 {
1587 my $self = shift;
1588 my $filehandle = shift;
1589 my $subname = ( caller(0) )[3];
1590 croak($subname . "() called as a procedure") unless(ref $self);
1591 debug(2,"DEBUG[",$subname,"]");
1592  
1593 if(defined $filehandle) { $self->{twig}->print($filehandle); }
1594 else { $self->{twig}->print; }
1595 return 1;
1596 }
1597  
1598  
1599 =head2 C<publishers()>
1600  
1601 Returns a list containing the text of all dc:publisher
1602 (case-insensitive) entries, or undef if none are found.
1603  
1604 In scalar context returns the first match, not the last.
1605  
1606 =cut
1607  
1608 sub publishers :method
1609 {
1610 my $self = shift;
1611 my $subname = ( caller(0) )[3];
1612 croak($subname . "() called as a procedure") unless(ref $self);
1613 debug(2,"DEBUG[",$subname,"]");
1614 $self->twigcheck;
1615  
1616 my @pubs = ();
1617 my @elements = $self->{twigroot}->descendants(qr/^dc:publisher$/ix);
1618 foreach my $el (@elements)
1619 {
1620 push(@pubs,$el->text) if($el->text);
1621 }
1622 return unless(@pubs);
1623 if(wantarray) { return @pubs; }
1624 else { return $pubs[0]; }
1625 }
1626  
1627  
1628 =head2 C<retailprice()>
1629  
1630 Returns a two-scalar list, the first scalar being the text of the
1631 Mobipocket-specific <SRP> element, if it exists, and the second being
1632 the 'Currency' attribute of that element, if it exists.
1633  
1634 In scalar context, returns just the text (price).
1635  
1636 Returns undef if the SRP element is not found.
1637  
1638 =cut
1639  
1640 sub retailprice :method
1641 {
1642 my $self = shift;
1643 my $subname = ( caller(0) )[3];
1644 croak($subname . "() called as a procedure") unless(ref $self);
1645 debug(2,"DEBUG[",$subname,"]");
1646 $self->twigcheck;
1647  
1648 my $twigroot = $self->{twigroot};
1649  
1650 my $element = $twigroot->first_descendant(qr/^ SRP $/ix);
1651 return unless($element);
1652 if(wantarray) { return ($element->text,$element->att('Currency')); }
1653 else { return $element->text };
1654 }
1655  
1656  
1657 =head2 C<review()>
1658  
1659 Returns the text of the Mobipocket-specific <Review> element, if it
1660 exists. Returns undef if one is not found.
1661  
1662 =cut
1663  
1664 sub review :method
1665 {
1666 my $self = shift;
1667 my $subname = ( caller(0) )[3];
1668 croak($subname . "() called as a procedure") unless(ref $self);
1669 debug(2,"DEBUG[",$subname,"]");
1670 $self->twigcheck;
1671  
1672 my $twigroot = $self->{twigroot};
1673  
1674 my $element = $twigroot->first_descendant(qr/^review$/ix);
1675 return unless($element);
1676 return $element->text;
1677 }
1678  
1679  
1680 =head2 C<rights('id' => 'identifier')>
1681  
1682 Returns a list containing the text of all of dc:rights or
1683 dc:copyrights (case-insensitive) entries in the e-book, or undef if
1684 none are found.
1685  
1686 In scalar context returns the first match, not the last.
1687  
1688 If the optional named argument 'id' is specified, it will only return
1689 entries where the id attribute matches the specified identifier.
1690 Although this still returns a list, if more than one entry is found, a
1691 warning is logged.
1692  
1693 Note that dc:copyrights is not a valid Dublin Core element -- it is
1694 included only because some broken Mobipocket books use it.
1695  
1696 =cut
1697  
1698 sub rights :method ## no critic (Always unpack @_ first)
1699 {
1700 my $self = shift;
1701 my (%args) = @_;
1702 my $subname = ( caller(0) )[3];
1703 croak($subname . "() called as a procedure") unless(ref $self);
1704 debug(2,"DEBUG[",$subname,"]");
1705 $self->twigcheck;
1706  
1707 my %valid_args = (
1708 'id' => 1,
1709 );
1710 foreach my $arg (keys %args)
1711 {
1712 croak($subname,"(): invalid argument '",$arg,"'")
1713 if(!$valid_args{$arg});
1714 }
1715  
1716  
1717 my @rights = ();
1718 my $id = $args{id};
1719 my @elements = $self->{twigroot}->descendants(qr/^dc:(copy)?rights$/ix);
1720  
1721 foreach my $element (@elements)
1722 {
1723 if($id)
1724 {
1725 next if($element->att('id') ne $id);
1726 push @rights,$element->text if($element->text);
1727 }
1728 else { push @rights,$element->text if($element->text); }
1729 }
1730  
1731 if($id)
1732 {
1733 add_warning($subname
1734 . "(): More than one rights entry found with id '"
1735 . $id ."'" )
1736 if(scalar(@rights) > 1);
1737 }
1738 return unless(@rights);
1739 if(wantarray) { return @rights; }
1740 else { return $rights[0]; }
1741 }
1742  
1743  
1744 =head2 C<search_knownuids()>
1745  
1746 Searches the OPF twig for the first dc:identifier (case-insensitive)
1747 element with an ID matching known UID IDs.
1748  
1749 Returns the ID if a match is found, undef otherwise
1750  
1751 =cut
1752  
1753 sub search_knownuids :method ## no critic (Always unpack @_ first)
1754 {
1755 my $self = shift;
1756 my $subname = ( caller(0) )[3];
1757 croak($subname . "() called as a procedure") unless(ref $self);
1758 debug(2,"DEBUG[",$subname,"]");
1759  
1760 my @elements;
1761  
1762 @elements = $self->{twigroot}->descendants(\&twigelt_is_knownuid);
1763 return unless(@elements);
1764 debug(1,"DEBUG: found known UID '",$elements[0]->id,"'");
1765 return $elements[0]->id;
1766 }
1767  
1768  
1769 =head2 C<search_knownuidschemes()>
1770  
1771 Searches descendants of the OPF twig element for the first
1772 <dc:identifier> or <dc:Identifier> subelement with the attribute
1773 'scheme' or 'opf:scheme' matching a known list of schemes for unique
1774 IDs
1775  
1776 NOTE: this is NOT a case-insensitive search! If you have to deal with
1777 really bizarre input, make sure that you run L</fix_oeb12()> or
1778 L</fix_opf20()> before calling L</fix_packageid()> or L</fix_misc()>.
1779  
1780 Returns the ID if a match is found, undef otherwise.
1781  
1782 =cut
1783  
1784 sub search_knownuidschemes :method ## no critic (Always unpack @_ first)
1785 {
1786 my $self = shift;
1787 my ($gi) = @_;
1788 if(!$gi) { $gi = 'dc:identifier'; }
1789 my $subname = ( caller(0) )[3];
1790 croak($subname . "() called as a procedure") unless(ref $self);
1791 debug(2,"DEBUG[",$subname,"]");
1792 $self->twigcheck;
1793  
1794 my $topelement = $self->{twigroot};
1795  
1796 my @knownuidschemes = (
1797 'GUID',
1798 'UUID',
1799 'FWID',
1800 );
1801  
1802 # Creating a regexp to search on works, but doesn't let you
1803 # specify priority. For that, you really do have to loop.
1804 # my $schemeregexp = "(" . join('|',@knownuidschemes) . ")";
1805  
1806 my @elems;
1807 my $id;
1808  
1809 my $retval = undef;
1810  
1811 foreach my $scheme (@knownuidschemes)
1812 {
1813 debug(2,"DEBUG: searching for scheme='",$scheme,"'");
1814 @elems = $topelement->descendants(
1815 "dc:identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
1816 );
1817 push @elems, $topelement->descendants(
1818 "dc:Identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
1819 );
1820 foreach my $elem (@elems)
1821 {
1822 debug(2,"DEBUG: working on scheme '",$scheme,"'");
1823 if(defined $elem)
1824 {
1825 if($scheme eq 'FWID')
1826 {
1827 # Fictionwise has a screwy output that sets the ID
1828 # equal to the text. Fix the ID to just be 'FWID'
1829 debug(1,"DEBUG: fixing FWID");
1830 $elem->set_id('FWID');
1831 }
1832  
1833 $id = $elem->id;
1834 unless(defined $id)
1835 {
1836 debug(1,"DEBUG: assigning ID from scheme '",$scheme,"'");
1837 $id = uc($scheme);
1838 $elem->set_id($id);
1839 }
1840 $retval = $id;
1841 debug(1,"DEBUG: found Package ID: ",$id);
1842 last;
1843 } # if(defined $elem)
1844 } # foreach my $elem (@elems)
1845 last if(defined $retval);
1846 }
1847 debug(2,"[/",$subname,"]");
1848 return $retval;
1849 }
1850  
1851  
1852 =head2 C<spec()>
1853  
1854 Returns the version of the OEB specification currently in use. Valid
1855 values are C<OEB12> and C<OPF20>. This value will default to undef
1856 until C<fix_oeb12> or C<fix_opf20> is called, as there is no way for
1857 the object to know what specification is being conformed to (if any)
1858 until it attempts to enforce it.
1859  
1860 =cut
1861  
1862 sub spec :method
1863 {
1864 my $self = shift;
1865 my $subname = ( caller(0) )[3];
1866 croak($subname . "() called as a procedure") unless(ref $self);
1867 debug(2,"DEBUG[",$subname,"]");
1868 return $self->{spec};
1869 }
1870  
1871  
1872 =head2 C<spine()>
1873  
1874 Returns all of the manifest items referenced in the spine as a list of
1875 hashrefs, with one hash per manifest item in the order that they
1876 appear, where the hash keys are 'id', 'href', and 'media-type', each
1877 returning the appropriate attribute, if any.
1878  
1879 In scalar context, returns the first item, not the last.
1880  
1881 Returns undef if there is no <spine> element directly underneath
1882 <package>, or if <spine> contains no itemrefs. If <spine> exists, but
1883 <manifest> does not, or a spine itemref exists but points an ID not
1884 found in the manifest, spine() logs an error and returns undef.
1885  
1886 See also: L</spine_idrefs()>, L</manifest()>
1887  
1888 =cut
1889  
1890 sub spine :method
1891 {
1892 my $self = shift;
1893 my $subname = ( caller(0) )[3];
1894 croak($subname . "() called as a procedure") unless(ref $self);
1895 debug(2,"DEBUG[",$subname,"]");
1896 $self->twigcheck();
1897  
1898 my $spine = $self->{twigroot}->first_child('spine');
1899 return unless($spine);
1900 my @spinerefs;
1901 my $idref;
1902 my $element;
1903 my @retarray;
1904  
1905 my $manifest = $self->{twigroot}->first_child('manifest');
1906 if(!$manifest)
1907 {
1908 $self->add_error(
1909 $subname . "(): <spine> found without <manifest>"
1910 );
1911 debug(1,"DEBUG: <spine> found without <manifest>!");
1912 return;
1913 }
1914  
1915 @spinerefs = $spine->children('itemref');
1916 return unless(@spinerefs);
1917  
1918 foreach my $spineref (@spinerefs)
1919 {
1920 $idref = $spineref->att('idref');
1921 if(!$idref)
1922 {
1923 $self->add_warning(
1924 $subname . "(): <itemref> found with no idref -- skipping"
1925 );
1926 debug(1,"DEBUG: <itemref> found with no idref -- skipping");
1927 next;
1928 }
1929 $element = $manifest->first_child("item[\@id='$idref']");
1930 if(!$element)
1931 {
1932 $self->add_error(
1933 $subname ."(): id '" . $idref . "' not found in manifest!"
1934 );
1935 debug(1,"DEBUG: id '",$idref," not found in manifest!");
1936 return;
1937 }
1938 push(@retarray,
1939 {
1940 'id' => $element->id,
1941 'href' => $element->att('href'),
1942 'media-type' => $element->att('media-type')
1943 });
1944 }
1945 if(wantarray) { return @retarray; }
1946 else { return $retarray[0]; }
1947 }
1948  
1949  
1950 =head2 C<spine_idrefs()>
1951  
1952 Returns a list of all of the idrefs in the current OPF spine, or the
1953 empty list if none are found.
1954  
1955 In scalar context, returns the first idref, not the last.
1956  
1957 See also: L</spine()>, L</manifest_hrefs()>
1958  
1959 =cut
1960  
1961 sub spine_idrefs :method
1962 {
1963 my $self = shift;
1964 my $subname = ( caller(0) )[3];
1965 croak($subname . "() called as a procedure") unless(ref $self);
1966 debug(2,"DEBUG[",$subname,"]");
1967 $self->twigcheck();
1968  
1969 my $spine = $self->{twigroot}->first_child('spine');;
1970 my @retval = ();
1971 my @itemrefs;
1972 my $idref;
1973  
1974 if(! $spine) { return @retval; }
1975  
1976 @itemrefs = $spine->children('itemref');
1977 foreach my $item (@itemrefs)
1978 {
1979 $idref = $item->att('idref');
1980 push(@retval,$idref) if($idref);
1981 }
1982 if(wantarray) { return @retval; }
1983 else { return $retval[0]; }
1984 }
1985  
1986  
1987 =head2 C<subject_list()>
1988  
1989 Returns a list containing the text of all dc:subject elements or undef
1990 if none are found.
1991  
1992 In scalar context, returns the first subject, not the last.
1993  
1994 =cut
1995  
1996 sub subject_list :method
1997 {
1998 my $self = shift;
1999 my $subname = ( caller(0) )[3];
2000 croak($subname . "() called as a procedure") unless(ref $self);
2001 debug(2,"DEBUG[",$subname,"]");
2002 $self->twigcheck;
2003  
2004 my @retval = ();
2005 my $twigroot = $self->{twigroot};
2006  
2007 my @subjects = $twigroot->descendants(qr/dc:subject/ix);
2008 return unless(@subjects);
2009  
2010 foreach my $subject (@subjects)
2011 {
2012 push(@retval,$subject->text) if($subject->text);
2013 }
2014 return unless(@retval);
2015 if(wantarray) { return @retval; }
2016 else { return $retval[0]; }
2017 }
2018  
2019  
2020 =head2 C<title()>
2021  
2022 Returns the title of the e-book, or undef if no dc:title element
2023 (case-insensitive) exists. If a dc:title element exists, but contains
2024 no text, returns an empty string.
2025  
2026 =cut
2027  
2028 sub title :method
2029 {
2030 my $self = shift;
2031 my $subname = ( caller(0) )[3];
2032 croak($subname . "() called as a procedure") unless(ref $self);
2033 debug(2,"DEBUG[",$subname,"]");
2034 $self->twigcheck;
2035  
2036 my $twigroot = $self->{twigroot};
2037  
2038 my $element = $twigroot->first_descendant(qr/^dc:title$/ix);
2039 return unless($element);
2040 return ($element->text || '');
2041 }
2042  
2043  
2044 =head2 C<twig()>
2045  
2046 Returns the raw L<XML::Twig> object used to store the OPF metadata.
2047  
2048 Although this twig can be manipulated via the standard XML::Twig
2049 methods, doing so requires caution and is not recommended. In
2050 particular, changing the root element from here will cause the
2051 EBook::Tools internal twig and twigroot attributes to become unlinked
2052 and the result of any subsequent action is not defined.
2053  
2054 =cut
2055  
2056 sub twig :method
2057 {
2058 my $self = shift;
2059 my $subname = ( caller(0) )[3];
2060 croak($subname . "() called as a procedure") unless(ref $self);
2061 debug(2,"DEBUG[",$subname,"]");
2062 return $self->{twig};
2063 }
2064  
2065  
2066 =head2 C<twigcheck()>
2067  
2068 Croaks showing the calling location unless C<$self> has both a twig and a
2069 twigroot, and the twigroot is <package>. Used as a sanity check for
2070 methods that use twig or twigroot.
2071  
2072 =cut
2073  
2074 sub twigcheck :method
2075 {
2076 my $self = shift;
2077 my $subname = ( caller(0) )[3];
2078 croak($subname . "() called as a procedure") unless(ref $self);
2079 debug(3,"DEBUG[",$subname,"]");
2080  
2081 my @calledfrom = caller(1);
2082 croak("twigcheck called from unknown location") if(!@calledfrom);
2083  
2084 croak($calledfrom[3],"(): undefined twig")
2085 if(!$self->{twig});
2086 croak($calledfrom[3],"(): twig isn't a XML::Twig")
2087 if( (ref $self->{twig}) ne 'XML::Twig' );
2088 croak($calledfrom[3],"(): twig root missing")
2089 if(!$self->{twigroot});
2090 croak($calledfrom[3],"(): twig root isn't a XML::Twig::Elt")
2091 if( (ref $self->{twigroot}) ne 'XML::Twig::Elt' );
2092 croak($calledfrom[3],"(): twig root is '" . $self->{twigroot}->gi
2093 . "' (needs to be 'package')")
2094 if($self->{twigroot}->gi ne 'package');
2095 debug(3,"DEBUG[/",$subname,"]");
2096 return 1;
2097 }
2098  
2099  
2100 =head2 C<twigroot()>
2101  
2102 Returns the raw L<XML::Twig> root element used to store the OPF
2103 metadata.
2104  
2105 This twig element can be manipulated via the standard XML::Twig::Elt
2106 methods, but care should be taken not to attempt to cut this element
2107 from its twig as doing so will cause the EBook::Tools internal twig
2108 and twigroot attributes to become unlinked and the result of any
2109 subsequent action is not defined.
2110  
2111 =cut
2112  
2113 sub twigroot :method
2114 {
2115 my $self = shift;
2116 my $subname = ( caller(0) )[3];
2117 croak($subname . "() called as a procedure") unless(ref $self);
2118 debug(2,"DEBUG[",$subname,"]");
2119 return $self->{twigroot};
2120 }
2121  
2122  
2123 =head2 C<warnings()>
2124  
2125 Returns an arrayref containing any generated warning messages.
2126  
2127 =cut
2128  
2129 sub warnings :method
2130 {
2131 my $self = shift;
2132 my $subname = ( caller(0) )[3];
2133 croak($subname . "() called as a procedure") unless(ref $self);
2134 debug(2,"DEBUG[",$subname,"]");
2135 return $self->{warnings};
2136 }
2137  
2138  
2139 ######################################
2140 ########## MODIFIER METHODS ##########
2141 ######################################
2142  
2143 =head1 MODIFIER METHODS
2144  
2145 Unless otherwise specified, all modifier methods return undef if an
2146 error was added to the error list, and true otherwise (even if a
2147 warning was added to the warning list).
2148  
2149  
2150 =head2 C<add_document($href,$id,$mediatype)>
2151  
2152 Adds a document to the OPF manifest and spine, creating <manifest> and
2153 <spine> if necessary. To add an item only to the OPF manifest, see
2154 add_item().
2155  
2156 =head3 Arguments
2157  
2158 =over
2159  
2160 =item C<$href>
2161  
2162 The href to the document in question. Usually, this is just a
2163 filename (or relative path and filename) of a file in the current
2164 working directory. If you are planning to eventually generate a .epub
2165 book, all hrefs MUST be in or below the current working directory.
2166  
2167 The method returns undef if $href is not defined or empty.
2168  
2169 =item C<$id>
2170  
2171 The XML ID to use. If not specified, defaults to the href with
2172 invalid characters removed.
2173  
2174 This must be unique not only to the manifest list, but to every
2175 element in the OPF file. If a duplicate ID exists, the method sets an
2176 error and returns undef.
2177  
2178 =item C<$mediatype> (optional)
2179  
2180 The mime type of the document. If not specified, will attempt to
2181 autodetect the mime type, and if that fails, will default to
2182 'application/xhtml+xml'.
2183  
2184 =back
2185  
2186 =cut
2187  
2188 sub add_document :method ## no critic (Always unpack @_ first)
2189 {
2190 my $self = shift;
2191 my ($href,$id,$mediatype) = @_;
2192 my $subname = (caller(0))[3];
2193 croak($subname . "() called as a procedure") unless(ref $self);
2194 debug(2,"DEBUG[",$subname,"]");
2195 $self->twigcheck();
2196  
2197 $href = trim($href);
2198 return unless($href);
2199  
2200 my $twig = $self->{twig};
2201 my $topelement = $self->{twigroot};
2202 my $element;
2203  
2204 $id = $href unless($id);
2205 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
2206 $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars
2207  
2208 $element = $twig->first_elt("*[\@id='$id']");
2209 if($element)
2210 {
2211 $self->add_error(
2212 $subname . "(): ID '" . $id . "' already exists"
2213 . " (in a '" . $element->gi ."' tag)"
2214 );
2215 return;
2216 }
2217  
2218 if(!$mediatype)
2219 {
2220 my $mimetype = mimetype($href);
2221 if($mimetype) { $mediatype = $mimetype; }
2222 else { $mediatype = "application/xhtml+xml"; }
2223 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,"'");
2224 }
2225  
2226 my $manifest = $topelement->first_child('manifest');
2227 $manifest = $topelement->insert_new_elt('last_child','manifest')
2228 if(!$manifest);
2229 my $spine = $topelement->first_child('spine');
2230 $spine = $topelement->insert_new_elt('last_child','spine')
2231 if(!$spine);
2232  
2233 my $item = $manifest->insert_new_elt('last_child','item');
2234 $item->set_id($id);
2235 $item->set_att(
2236 'href' => $href,
2237 'media-type' => $mediatype
2238 );
2239  
2240 my $itemref = $spine->insert_new_elt('last_child','itemref');
2241 $itemref->set_att('idref' => $id);
2242  
2243 return 1;
2244 }
2245  
2246  
2247 =head2 C<add_error(@errors)>
2248  
2249 Adds @errors to the list of object errors. Each member of
2250 @errors should be a string containing the entire text of the
2251 error, with no ending newline.
2252  
2253 SEE ALSO: L</add_warning()>, L</clear_errors()>, L</clear_warnerr()>
2254  
2255 =cut
2256  
2257 sub add_error :method ## no critic (Always unpack @_ first)
2258 {
2259 my $self = shift;
2260 my (@newerror) = @_;
2261 my $subname = (caller(0))[3];
2262 croak($subname . "() called as a procedure") unless(ref $self);
2263 debug(3,"DEBUG[",$subname,"]");
2264  
2265 my $currenterrors;
2266 $currenterrors = $self->{errors} if($self->{errors});
2267  
2268 if(@newerror)
2269 {
2270 my $error = join('',@newerror);
2271 debug(1,"ERROR: ",$error);
2272 push(@$currenterrors,$error);
2273 }
2274 $self->{errors} = $currenterrors;
2275 return 1;
2276 }
2277  
2278  
2279 =head2 C<add_identifier(%args)>
2280  
2281 Creates a new dc:identifier element containing the specified text, id,
2282 and scheme.
2283  
2284 If a <dc-metadata> element exists underneath <metadata>, the
2285 identifier element will be created underneath the <dc-metadata> in OEB
2286 1.2 format, otherwise the title element is created underneath
2287 <metadata> in OPF 2.0 format.
2288  
2289 Returns the twig element containing the new identifier.
2290  
2291 =head3 Arguments
2292  
2293 C<add_identifier()> takes three named arguments, one mandatory, two
2294 optional.
2295  
2296 =over
2297  
2298 =item * C<text> - the text of the identifier. This is mandatory, and
2299 the method croaks if it is not present.
2300  
2301 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute to be added (optional)
2302  
2303 =item * C<id> - 'id' attribute to be added. If this is specified, and
2304 the id is already in use, a warning will be added but the method will
2305 continue, removing the id attribute from the element that previously
2306 contained it.
2307  
2308 =back
2309  
2310 =cut
2311  
2312 sub add_identifier :method ## no critic (Always unpack @_ first)
2313 {
2314 my $self = shift;
2315 my (%args) = @_;
2316 my %valid_args = (
2317 'text' => 1,
2318 'id' => 1,
2319 'scheme' => 1,
2320 );
2321 my $subname = ( caller(0) )[3];
2322 croak($subname . "() called as a procedure") unless(ref $self);
2323 debug(2,"DEBUG[",$subname,"]");
2324 $self->twigcheck();
2325 foreach my $arg (keys %args)
2326 {
2327 croak($subname,"(): invalid argument '",$arg,"'")
2328 if(!$valid_args{$arg});
2329 }
2330 croak($subname,"(): identifier text not specified")
2331 unless($args{text});
2332  
2333 $self->fix_metastructure_basic();
2334 my $meta = $self->{twigroot}->first_child('metadata');
2335 my $dcmeta = $meta->first_child('dc-metadata');
2336 my $element;
2337 my $idelem;
2338 my $newid = $args{id};
2339 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
2340  
2341 if($dcmeta)
2342 {
2343 $element = $dcmeta->insert_new_elt('last_child','dc:Identifier');
2344 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
2345 }
2346 else
2347 {
2348 $element = $meta->insert_new_elt('last_child','dc:identifier');
2349 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
2350 }
2351 $element->set_text($args{text});
2352  
2353 if($idelem && $idelem->cmp($element) )
2354 {
2355 $self->add_warning(
2356 $subname,"(): reassigning id '",$newid,
2357 "' from a '",$idelem->gi,"' element!"
2358 );
2359 $idelem->del_att('id');
2360 }
2361 $element->set_att('id' => $newid) if($newid);
2362  
2363 return $element;
2364 }
2365  
2366  
2367 =head2 C<add_item($href,$id,$mediatype)>
2368  
2369 Adds a document to the OPF manifest (but not spine), creating
2370 <manifest> if necessary. To add an item only to both the OPF manifest
2371 and spine, see add_document().
2372  
2373 =head3 Arguments
2374  
2375 =over
2376  
2377 =item C<$href>
2378  
2379 The href to the document in question. Usually, this is just a
2380 filename (or relative path and filename) of a file in the current
2381 working directory. If you are planning to eventually generate a .epub
2382 book, all hrefs MUST be in or below the current working directory.
2383  
2384 =item C<$id>
2385  
2386 The XML ID to use. If not specified, defaults to the href with all
2387 nonword characters removed.
2388  
2389 This must be unique not only to the manifest list, but to every
2390 element in the OPF file. If a duplicate ID exists, the method sets an
2391 error and returns undef.
2392  
2393 =item C<$mediatype> (optional)
2394  
2395 The mime type of the document. If not specified, will attempt to
2396 autodetect the mime type, and if that fails, will set an error and
2397 return undef.
2398  
2399 =back
2400  
2401 =cut
2402  
2403 sub add_item :method ## no critic (Always unpack @_ first)
2404 {
2405 my $self = shift;
2406 my ($href,$id,$mediatype) = @_;
2407 my $subname = (caller(0))[3];
2408 croak($subname . "() called as a procedure") unless(ref $self);
2409 debug(2,"DEBUG[",$subname,"]");
2410 $self->twigcheck();
2411  
2412 $href = trim($href);
2413 return unless($href);
2414  
2415 my $twig = $self->{twig};
2416 my $topelement = $self->{twigroot};
2417 my $element;
2418  
2419 $id = $href unless($id);
2420 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
2421 $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars
2422  
2423 $element = $twig->first_elt("*[\@id='$id']");
2424 if($element)
2425 {
2426 $self->add_error(
2427 $subname . "(): ID '" . $id . "' already exists"
2428 . " (in a '" . $element->gi ."' tag)"
2429 );
2430 debug(2,"DEBUG[/",$subname,"]");
2431 return;
2432 }
2433  
2434 if(!$mediatype)
2435 {
2436 my $mimetype = mimetype($href);
2437 if($mimetype) { $mediatype = $mimetype; }
2438 else { $mediatype = "application/xhtml+xml"; }
2439 debug(2,"DEBUG: '",$href,"' has mimetype '",$mediatype,"'");
2440 }
2441  
2442 my $manifest = $self->{twigroot}->first_child('manifest');
2443 $manifest = $topelement->insert_new_elt('last_child','manifest')
2444 if(!$manifest);
2445  
2446 debug(2,"DEBUG: adding item '",$id,"': '",$href,"'");
2447 my $item = $manifest->insert_new_elt('last_child','item');
2448 $item->set_id($id);
2449 $item->set_att(
2450 'href' => $href,
2451 'media-type' => $mediatype
2452 );
2453  
2454 debug(2,"DEBUG[/",$subname,"]");
2455 return 1;
2456 }
2457  
2458  
2459 =head2 add_metadata(%args)
2460  
2461 Creates a metadata element with the specified text, attributes, and parent.
2462  
2463 If a <dc-metadata> element exists underneath <metadata>, the language
2464 element will be created underneath the <dc-metadata> and any standard
2465 attributes will be created in OEB 1.2 format, otherwise the element is
2466 created underneath <metadata> in OPF 2.0 format.
2467  
2468 Returns 1 on success, returns undef if no gi or if no text was specified.
2469  
2470 =cut
2471  
2472 =head3 Arguments
2473  
2474 =over
2475  
2476 =item C<gi>
2477  
2478 The generic identifier (tag) of the metadata element to alter or
2479 create. If not specified, the method sets an error and returns undef.
2480  
2481 =item C<parent>
2482  
2483 The generic identifier (tag) of the parent to use for any newly
2484 created element. If not specified, defaults to 'dc-metadata' if
2485 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
2486  
2487 A newly created element will be created under the first element found
2488 with this gi. A modified element will be moved under the first
2489 element found with this gi.
2490  
2491 Newly created elements will use OPF 2.0 attribute names if the parent
2492 is 'metadata' and OEB 1.2 attribute names otherwise.
2493  
2494 =item C<text>
2495  
2496 This specifies the element text to set. If not specified, the method
2497 sets an error and returns undef.
2498  
2499 =item C<id> (optional)
2500  
2501 This specifies the ID to set on the element. If set and the ID is
2502 already in use, a warning is logged and the ID is removed from the
2503 other location and assigned to the element.
2504  
2505 =item C<fileas> (optional)
2506  
2507 This specifies the file-as attribute to set on the element.
2508  
2509 =item C<role> (optional)
2510  
2511 This specifies the role attribute to set on the element.
2512  
2513 =item C<scheme> (optional)
2514  
2515 This specifies the scheme attribute to set on the element.
2516  
2517 =back
2518  
2519 =head3 Example
2520  
2521 $retval = $ebook->add_metadata(gi => 'AuthorNonstandard',
2522 text => 'Element Text',
2523 id => 'customid',
2524 fileas => 'Text, Element',
2525 role => 'xxx',
2526 scheme => 'code');
2527  
2528 =cut
2529  
2530 sub add_metadata :method ## no critic (Always unpack @_ first)
2531 {
2532 my $self = shift;
2533 my (%args) = @_;
2534 my $subname = ( caller(0) )[3];
2535 croak($subname . "() called as a procedure") unless(ref $self);
2536 debug(3,"DEBUG[",$subname,"]");
2537 my %valid_args = (
2538 'gi' => 1,
2539 'parent' => 1,
2540 'text' => 1,
2541 'id' => 1,
2542 'fileas' => 1,
2543 'role' => 1,
2544 'scheme' => 1,
2545 );
2546 foreach my $arg (keys %args)
2547 {
2548 croak($subname,"(): invalid argument '",$arg,"'")
2549 if(!$valid_args{$arg});
2550 }
2551  
2552 my $gi = $args{gi};
2553 unless($gi)
2554 {
2555 $self->add_error($subname,"(): no gi specified");
2556 return;
2557 }
2558  
2559 my $text = $args{text};
2560 unless($text)
2561 {
2562 $self->add_error($subname,"(): no text specified");
2563 return;
2564 }
2565  
2566 my $newid = $args{id};
2567 my $idelem;
2568 my $element;
2569 my $meta;
2570 my $dcmeta;
2571 my $parent;
2572 my %dcatts;
2573  
2574 $self->fix_metastructure_basic();
2575 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
2576 if($args{parent});
2577 $meta = $self->{twigroot}->first_child('metadata');
2578 $dcmeta = $meta->first_child('dc-metadata');
2579 $parent = $parent || $dcmeta || $meta;
2580 if($parent->gi eq 'metadata')
2581 {
2582 %dcatts = (
2583 'file-as' => 'opf:file-as',
2584 'role' => 'opf:role',
2585 'scheme' => 'opf:scheme',
2586 );
2587 }
2588 else
2589 {
2590 %dcatts = (
2591 'file-as' => 'file-as',
2592 'role' => 'role',
2593 'scheme' => 'scheme'
2594 );
2595 }
2596  
2597 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
2598 $element = $parent->insert_new_elt('last_child',$gi);
2599 $element->set_att($dcatts{'file-as'},$args{fileas})
2600 if($args{fileas});
2601 $element->set_att($dcatts{'role'},$args{role})
2602 if($args{role});
2603 $element->set_att($dcatts{'scheme'},$args{scheme})
2604 if($args{scheme});
2605 $element->set_text($text);
2606  
2607 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
2608 if($idelem && $idelem->cmp($element) )
2609 {
2610 $self->add_warning(
2611 $subname,"(): reassigning id '",$newid,
2612 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
2613 );
2614 $idelem->del_att('id');
2615 }
2616 $element->set_att('id' => $newid) if($newid);
2617 return 1;
2618 }
2619  
2620  
2621 =head2 C<add_subject(%args)>
2622  
2623 Creates a new dc:subject element containing the specified text, code,
2624 and id.
2625  
2626 If a <dc-metadata> element exists underneath <metadata>, the
2627 subject element will be created underneath the <dc-metadata> in OEB
2628 1.2 format, otherwise the title element is created underneath
2629 <metadata> in OPF 2.0 format.
2630  
2631 Returns the twig element containing the new subject.
2632  
2633 =head3 Arguments
2634  
2635 C<add_subject()> takes four named arguments, one mandatory, three
2636 optional.
2637  
2638 =over
2639  
2640 =item * C<text> - the text of the subject. This is mandatory, and
2641 the method croaks if it is not present.
2642  
2643 =item * C<scheme> (optional) - 'opf:scheme' or 'scheme' attribute to
2644 be added. Be warned that neither the OEB 1.2 nor the OPF 2.0
2645 specifications allow a scheme to be added to this element, so if this
2646 is specified, the resulting OPF file will fail to validate against
2647 either standard.
2648  
2649 =item * C<basiccode> (optional) - 'BASICCode' attribute to be added.
2650 Be warned that this is a Mobipocket-specific attribute that does not
2651 exist in either the OEB 1.2 nor the OPF 2.0 specifications, so if this
2652 is specified, the resulting OPF file will fail to validate against
2653 either standard.
2654  
2655 =item * C<id> (optional) - 'id' attribute to be added. If this is
2656 specified, and the id is already in use, a warning will be added but
2657 the method will continue, removing the id attribute from the element
2658 that previously contained it.
2659  
2660 =back
2661  
2662 =cut
2663  
2664 sub add_subject :method ## no critic (Always unpack @_ first)
2665 {
2666 my $self = shift;
2667 my (%args) = @_;
2668 my %valid_args = (
2669 'text' => 1,
2670 'id' => 1,
2671 'scheme' => 1,
2672 'basiccode' => 1,
2673 );
2674 my $subname = ( caller(0) )[3];
2675 croak($subname . "() called as a procedure") unless(ref $self);
2676 debug(2,"DEBUG[",$subname,"]");
2677 $self->twigcheck();
2678 foreach my $arg (keys %args)
2679 {
2680 croak($subname,"(): invalid argument '",$arg,"'")
2681 if(!$valid_args{$arg});
2682 }
2683 croak($subname,"(): subject text not specified")
2684 unless($args{text});
2685  
2686 $self->fix_metastructure_basic();
2687 my $meta = $self->{twigroot}->first_child('metadata');
2688 my $dcmeta = $meta->first_child('dc-metadata');
2689 my $element;
2690 my $idelem;
2691 my $newid = $args{id};
2692 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
2693  
2694 if($dcmeta)
2695 {
2696 $element = $dcmeta->insert_new_elt('last_child','dc:Subject');
2697 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
2698 }
2699 else
2700 {
2701 $element = $meta->insert_new_elt('last_child','dc:subject');
2702 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
2703 }
2704 $element->set_text($args{text});
2705 $element->set_att('BASICCode' => $args{basiccode}) if($args{basiccode});
2706  
2707 if($idelem && $idelem->cmp($element) )
2708 {
2709 $self->add_warning(
2710 $subname,"(): reassigning id '",$newid,
2711 "' from a '",$idelem->gi,"' element!"
2712 );
2713 $idelem->del_att('id');
2714 }
2715 $element->set_att('id' => $newid) if($newid);
2716  
2717 return $element;
2718 }
2719  
2720  
2721 =head2 C<add_warning(@newwarning)>
2722  
2723 Joins @newwarning to a single string and adds it to the list of object
2724 warnings. The warning should not end with a newline newline.
2725  
2726 SEE ALSO: L</add_error()>, L</clear_warnings()>, L</clear_warnerr()>
2727  
2728 =cut
2729  
2730 sub add_warning :method ## no critic (Always unpack @_ first)
2731 {
2732 my $self = shift;
2733 my (@newwarning) = @_;
2734 my $subname = (caller(0))[3];
2735 croak($subname . "() called as a procedure") unless(ref $self);
2736 debug(3,"DEBUG[",$subname,"]");
2737  
2738 my @currentwarnings;
2739 @currentwarnings = @{$self->{warnings}} if($self->{warnings});
2740  
2741 if(@newwarning)
2742 {
2743 my $warning = join('',@newwarning);
2744 debug(1,"WARNING: ",$warning);
2745 push(@currentwarnings,$warning);
2746 }
2747 $self->{warnings} = \@currentwarnings;
2748  
2749 debug(3,"DEBUG[/",$subname,"]");
2750 return 1;
2751 }
2752  
2753  
2754 =head2 C<clear_errors()>
2755  
2756 Clear the current list of errors
2757  
2758 =cut
2759  
2760 sub clear_errors :method
2761 {
2762 my $self = shift;
2763 my $subname = ( caller(0) )[3];
2764 croak($subname . "() called as a procedure") unless(ref $self);
2765 debug(2,"DEBUG[",$subname,"]");
2766  
2767 $self->{errors} = ();
2768 return 1;
2769 }
2770  
2771  
2772 =head2 C<clear_warnerr()>
2773  
2774 Clear both the error and warning lists
2775  
2776 =cut
2777  
2778 sub clear_warnerr :method
2779 {
2780 my $self = shift;
2781 my $subname = ( caller(0) )[3];
2782 croak($subname . "() called as a procedure") unless(ref $self);
2783 debug(2,"DEBUG[",$subname,"]");
2784  
2785 $self->{errors} = ();
2786 $self->{warnings} = ();
2787 return 1;
2788 }
2789  
2790  
2791 =head2 C<clear_warnings()>
2792  
2793 Clear the current list of warnings
2794  
2795 =cut
2796  
2797 sub clear_warnings :method
2798 {
2799 my $self = shift;
2800 my $subname = ( caller(0) )[3];
2801 croak($subname . "() called as a procedure") unless(ref $self);
2802 debug(2,"DEBUG[",$subname,"]");
2803  
2804 $self->{warnings} = ();
2805 return 1;
2806 }
2807  
2808  
2809 =head2 C<delete_meta_filepos()>
2810  
2811 Deletes metadata elements with the attribute 'filepos' underneath
2812 the given parent element
2813  
2814 These are secondary metadata elements included in the output from
2815 mobi2html may that are not used.
2816  
2817 =cut
2818  
2819 sub delete_meta_filepos :method
2820 {
2821 my $self = shift;
2822 my $subname = ( caller(0) )[3];
2823 croak($subname . "() called as a procedure") unless(ref $self);
2824 debug(2,"DEBUG[",$subname,"]");
2825 $self->twigcheck();
2826  
2827 my @elements = $self->{twigroot}->descendants('metadata[@filepos]');
2828 foreach my $el (@elements)
2829 {
2830 $el->delete;
2831 }
2832 return 1;
2833 }
2834  
2835  
2836 =head2 C<fix_dates()>
2837  
2838 Standardizes all <dc:date> elements via fix_datestring(). Adds a
2839 warning to the object for each date that could not be fixed.
2840  
2841 Called from L</fix_misc()>.
2842  
2843 =cut
2844  
2845 sub fix_dates :method
2846 {
2847 my $self = shift;
2848 my $subname = ( caller(0) )[3];
2849 croak($subname . "() called as a procedure") unless(ref $self);
2850 debug(2,"DEBUG[",$subname,"]");
2851 $self->twigcheck();
2852  
2853 my @dates;
2854 my $newdate;
2855  
2856 @dates = $self->{twigroot}->descendants('dc:date');
2857 push(@dates,$self->{twigroot}->descendants('dc:Date'));
2858  
2859 foreach my $dcdate (@dates)
2860 {
2861 if(!$dcdate->text)
2862 {
2863 $self->add_warning(
2864 "WARNING: found dc:date with no value -- skipping");
2865 }
2866 else
2867 {
2868 $newdate = fix_datestring($dcdate->text);
2869 if(!$newdate)
2870 {
2871 $self->add_warning(
2872 sprintf("fixmisc(): can't deal with date '%s' -- skipping",
2873 $dcdate->text)
2874 );
2875 }
2876 elsif($dcdate->text ne $newdate)
2877 {
2878 debug(2,"DEBUG: setting date from '",$dcdate->text,
2879 "' to '",$newdate,"'");
2880 $dcdate->set_text($newdate);
2881 }
2882 }
2883 }
2884 return 1;
2885 }
2886  
2887  
2888 =head2 C<fix_guide()>
2889  
2890 Fixes problems related to the OPF guide elements, specifically:
2891  
2892 =over
2893  
2894 =item * Deletes empty guide elements
2895  
2896 =item * Moves all reference elements directly underneath the guide element
2897  
2898 =item * Finds reference elements with a href with only an anchor
2899 portion and assigns them to the first spine href. This only works if
2900 the spine is in working condition, so it may be wise to run
2901 L</fix_spine()> before C<fix_guide()> if the input is expected to be
2902 very badly broken.
2903  
2904 =back
2905  
2906 Logs a warning if a reference href is found that does not appear in
2907 the manifest.
2908  
2909 =cut
2910  
2911 sub fix_guide :method
2912 {
2913 my $self = shift;
2914 my $subname = ( caller(0) )[3];
2915 croak($subname . "() called as a procedure") unless(ref $self);
2916 debug(2,"DEBUG[",$subname,"]");
2917 $self->twigcheck();
2918  
2919 my $twigroot = $self->{twigroot};
2920 my $guide = $twigroot->first_descendant('guide');
2921 my $parent;
2922 my $href;
2923 my @spine;
2924 my @elements = $twigroot->descendants(qr/^reference$/ix);
2925 if(@elements)
2926 {
2927 # If <guide> doesn't exist, create it
2928 unless($guide)
2929 {
2930 debug(1,"DEBUG: creating <guide>");
2931 $guide = $twigroot->insert_new_elt('last_child','guide');
2932 }
2933  
2934 # Make sure that the guide is a child of the twigroot,
2935 $parent = $guide->parent;
2936 if( $parent->cmp($twigroot) )
2937 {
2938 debug(1,"DEBUG: moving <guide>");
2939 $guide->move('last_child',$twigroot);
2940 }
2941  
2942 foreach my $el (@elements)
2943 {
2944 $href = $el->att('href');
2945 if(!$href)
2946 {
2947 # No href means it is broken.
2948 # Leave it alone, but log a warning
2949 $self->add_warning(
2950 "fix_guide(): <reference> with no href -- skipping");
2951 next;
2952 }
2953 if($href =~ /^#/)
2954 {
2955 # Anchor-only href. Attempt to fix from the first
2956 # spine entry
2957 @spine = $self->spine;
2958 if(!@spine)
2959 {
2960 $self->add_warning(
2961 "fix_guide(): Cannot correct reference href '",$href,
2962 "', spine is empty");
2963 }
2964 elsif(!$spine[0]->{href})
2965 {
2966 $self->add_warning(
2967 "fix_guide(): Cannot correct reference href '",$href,
2968 "', cannot find href for first spine entry");
2969 }
2970 else
2971 {
2972 debug(1,"DEBUG: correcting reference href from '",$href,
2973 "' to '",$spine[0]->{href} . $href,"'");
2974 $el->set_att('href',$spine[0]->{href} . $href);
2975 }
2976 }
2977 debug(3,"DEBUG: processing reference '",$href,"')");
2978 $el->move('last_child',$guide);
2979 } # foreach my $el (@elements)
2980 } # if(@elements)
2981 else # No elements, delete guide if it exists
2982 {
2983 $guide->delete if($guide);
2984 }
2985 return 1;
2986 }
2987  
2988  
2989 =head2 C<fix_languages(%args)>
2990  
2991 Checks through the <dc:language> elements (case-insensitive) and
2992 removes any duplicates. If no <dc:language> elements are found, one
2993 is created.
2994  
2995 TODO: Also convert language names to IANA language and region codes.
2996  
2997 =head3 Arguments
2998  
2999 =over
3000  
3001 =item * C<default>
3002  
3003 The default language string to use when creating a new language
3004 element. If not specified, defaults to 'en'.
3005  
3006 =back
3007  
3008 =cut
3009  
3010 sub fix_languages :method
3011 {
3012 my $self = shift;
3013 my %args = @_;
3014 my $subname = ( caller(0) )[3];
3015 croak($subname . "() called as a procedure") unless(ref $self);
3016 debug(2,"DEBUG[",$subname,"]");
3017 $self->twigcheck();
3018  
3019 my %valid_args = (
3020 'default' => 1,
3021 );
3022 foreach my $arg (keys %args)
3023 {
3024 croak($subname,"(): invalid argument '",$arg,"'")
3025 if(!$valid_args{$arg});
3026 }
3027  
3028 my $twigroot = $self->{twigroot};
3029 my $defaultlang = $args{default} || 'en';
3030 my $langel;
3031 my @elements = $twigroot->descendants(qr/dc:language/ix);
3032 while($langel = shift(@elements) )
3033 {
3034 foreach my $el (@elements)
3035 {
3036 $el->delete if(twigelt_detect_duplicate($el,$langel) );
3037 }
3038 }
3039  
3040 @elements = $self->languages;
3041 if(!@elements)
3042 {
3043 $self->set_language(text => $defaultlang);
3044 }
3045 return 1;
3046 }
3047  
3048  
3049 =head2 C<fix_links()>
3050  
3051 Checks through the links in the manifest and checks them for anything
3052 they might link to, adding anything missing to the manifest.
3053  
3054 A warning is added for every manifest item missing a href.
3055  
3056 If no <manifest> element exists directly underneath the <package>
3057 root, or <manifest> contains no items, the method logs a warning and
3058 returns undef. Otherwise, it returns 1.
3059  
3060 =cut
3061  
3062 sub fix_links :method
3063 {
3064 my $self = shift;
3065 my $subname = ( caller(0) )[3];
3066 croak($subname . "() called as a procedure") unless(ref $self);
3067 debug(2,"DEBUG[",$subname,"]");
3068 $self->twigcheck();
3069  
3070 my $twigroot = $self->{twigroot};
3071  
3072 my $manifest = $twigroot->first_child('manifest');
3073 my @unchecked;
3074  
3075 # The %links hash points a href to one of three values:
3076 # * undef : the link has not been checked at all
3077 # * 0 : the link has been checked and is not reachable
3078 # * 1 : the link has been checked and exists
3079 my %links;
3080 my @newlinks;
3081 my $href;
3082 my $mimetype;
3083  
3084 my %linking_mimetypes = (
3085 'text/html' => 1,
3086 'text/xhtml' => 1,
3087 'text/xml' => 1,
3088 'text/x-oeb1-document' => 1,
3089 'application/atom+xml' => 1,
3090 'application/xhtml+xml' => 1,
3091 'application/xml' => 1
3092 );
3093  
3094 if(!$manifest)
3095 {
3096 $self->add_warning(
3097 "fix_links(): no manifest found!"
3098 );
3099 return;
3100 }
3101 @unchecked = $self->manifest_hrefs;
3102 if(!@unchecked)
3103 {
3104 $self->add_warning(
3105 "fix_links(): empty manifest found!"
3106 );
3107 return;
3108 }
3109  
3110 # Initialize %links, so we don't try to add something already in
3111 # the manifest
3112 foreach my $mhref (@unchecked)
3113 {
3114 $links{$mhref} = undef unless(exists $links{$mhref});
3115 }
3116  
3117 while(@unchecked)
3118 {
3119 debug(3,"DEBUG: ",scalar(@unchecked),
3120 " items left to check at start of loop");
3121 $href = shift(@unchecked);
3122 $href = trim($href);
3123 debug(3,"DEBUG: checking '",$href,"'");
3124 next if(defined $links{$href});
3125  
3126 # Skip URIs for now
3127 if($href =~ m#^ \w+://#ix)
3128 {
3129 debug(1,"DEBUG: URI '",$href,"' skipped");
3130 $links{href} = 0;
3131 next;
3132 }
3133 if(! -f $href)
3134 {
3135 $self->add_warning(
3136 "fix_links(): '" . $href . "' not found"
3137 );
3138 $links{$href} = 0;
3139 next;
3140 }
3141  
3142 $mimetype = mimetype($href);
3143  
3144 if(!$linking_mimetypes{$mimetype})
3145 {
3146 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,
3147 "' -- not checking");
3148 $links{$href} = 1;
3149 next;
3150 }
3151  
3152 debug(1,"DEBUG: finding links in '",$href,"'");
3153 push(@newlinks,find_links($href));
3154 trim(@newlinks) if(@newlinks);
3155 $links{$href} = 1;
3156 foreach my $newlink (@newlinks)
3157 {
3158 # Skip URIs for now
3159 if($newlink =~ m#^ \w+://#ix)
3160 {
3161 debug(1,"DEBUG: URI '",$newlink,"' skipped");
3162 next;
3163 }
3164 elsif(!exists $links{$newlink})
3165 {
3166 debug(2,"DEBUG: adding '",$newlink,"' to the list");
3167 push(@unchecked,$newlink);
3168 $self->add_item($newlink);
3169 }
3170 }
3171 debug(2,"DEBUG: ",scalar(@unchecked),
3172 " items left to check at end of loop");
3173 } # while(@unchecked)
3174 debug(2,"DEBUG[/",$subname,"]");
3175 return 1;
3176 }
3177  
3178 =head2 C<fix_manifest()>
3179  
3180 Finds all <item> elements and moves them underneath <manifest>,
3181 creating <manifest> if necessary.
3182  
3183 Logs a warning but continues if it finds an <item> with a missing id
3184 or href attribute. If both id and href attributes are missing, logs a
3185 warning, skips moving the item entirely (unless it was already
3186 underneath <manifest>, in which case it is moved to preserve its sort
3187 order along all other items under <manifest>), but otherwise
3188 continues.
3189  
3190 =cut
3191  
3192 sub fix_manifest :method
3193 {
3194 my $self = shift;
3195 my $subname = ( caller(0) )[3];
3196 croak($subname . "() called as a procedure") unless(ref $self);
3197 debug(2,"DEBUG[",$subname,"]");
3198 $self->twigcheck();
3199  
3200 my $twigroot = $self->{twigroot};
3201  
3202 my $manifest = $twigroot->first_descendant('manifest');
3203 my @elements;
3204 my $parent;
3205  
3206 my $href;
3207 my $id;
3208  
3209 # If <manifest> doesn't exist, create it
3210 if(! $manifest)
3211 {
3212 debug(1,"DEBUG: creating <manifest>");
3213 $manifest = $twigroot->insert_new_elt('last_child','manifest');
3214 }
3215  
3216 # Make sure that the manifest is the first child of the twigroot,
3217 # which should be <package>
3218 $parent = $manifest->parent;
3219 if($parent != $twigroot)
3220 {
3221 debug(1,"DEBUG: moving <manifest>");
3222 $manifest->move('last_child',$twigroot);
3223 }
3224  
3225 @elements = $twigroot->descendants(qr/^item$/ix);
3226 foreach my $el (@elements)
3227 {
3228 $href = $el->att('href');
3229 $id = $el->id;
3230 if(!$id)
3231 {
3232 if(!$href)
3233 {
3234 # No ID, no href, there's something very fishy here,
3235 # so log a warning.
3236 # If it is already underneath <manifest>, move it to
3237 # preserve sort order, but otherwise leave it alone
3238 $self->add_warning(
3239 "fix_manifest(): found item with no id or href"
3240 );
3241 debug(1,"fix_manifest(): found item with no id or href");
3242 if($el->parent == $manifest)
3243 {
3244 $el->move('last_child',$manifest);
3245 }
3246 else
3247 {
3248 print "DEBUG: skipping item with no id or href\n"
3249 if($debug);
3250 }
3251 next;
3252 } # if(!$href)
3253 # We have a href, but no ID. Log a warning, but move it anyway.
3254 $self->add_warning(
3255 'fix_manifest(): handling item with no ID! '
3256 . sprintf "(href='%s')",$href
3257 );
3258 debug(1,"DEBUG: processing item with no id (href='",$href,"')");
3259 $el->move('last_child',$manifest);
3260 } # if(!$id)
3261 if(!$href)
3262 {
3263 # We have an ID, but no href. Log a warning, but move it anyway.
3264 $self->add_warning(
3265 "fix_manifest(): item with id '" . $id . "' has no href!"
3266 );
3267 debug(1,"fix_manifest(): item with id '",$id,"' has no href!");
3268 $el->move('last_child',$manifest);
3269 }
3270 else
3271 {
3272 # We have an ID and a href
3273 debug(3,"DEBUG: processing item '",$id,"' (href='",$href,"')");
3274 $el->move('last_child',$manifest);
3275 }
3276 }
3277 return 1;
3278 }
3279  
3280 =head2 C<fix_metastructure_basic()>
3281  
3282 Verifies that <metadata> exists (creating it if necessary), and moves
3283 it to be the first child of <package>.
3284  
3285 Used in L</fix_metastructure_oeb12()>, L</fix_packageid()>, and
3286 L</set_primary_author(%args)>.
3287  
3288 =cut
3289  
3290 sub fix_metastructure_basic :method
3291 {
3292 my $self = shift;
3293 my $subname = ( caller(0) )[3];
3294 croak($subname . "() called as a procedure") unless(ref $self);
3295 debug(3,"DEBUG[",$subname,"]");
3296 $self->twigcheck();
3297  
3298 my $twigroot = $self->{twigroot};
3299 my $metadata = $twigroot->first_descendant('metadata');
3300  
3301 if(! $metadata)
3302 {
3303 debug(1,"DEBUG: creating <metadata>");
3304 $metadata = $twigroot->insert_new_elt('first_child','metadata');
3305 }
3306 debug(3,"DEBUG: moving <metadata> to be the first child of <package>");
3307 $metadata->move('first_child',$twigroot);
3308 return 1;
3309 }
3310  
3311  
3312 =head2 C<fix_metastructure_oeb12()>
3313  
3314 Verifies the existence of <metadata>, <dc-metadata>, and <x-metadata>,
3315 creating them as needed, and making sure that <metadata> is a child of
3316 <package>, while <dc-metadata> and <x-metadata> are children of
3317 <metadata>.
3318  
3319 Used in L</fix_oeb12()> and L</fix_mobi()>.
3320  
3321 =cut
3322  
3323 sub fix_metastructure_oeb12 :method
3324 {
3325 my $self = shift;
3326 my $subname = ( caller(0) )[3];
3327 croak($subname . "() called as a procedure") unless(ref $self);
3328 debug(3,"DEBUG[",$subname,"]");
3329 $self->twigcheck();
3330  
3331 my $twigroot = $self->{twigroot};
3332  
3333 my $metadata;
3334 my $dcmeta;
3335 my $xmeta;
3336 my $parent;
3337  
3338 # Start by forcing the basic <package><metadata> structure
3339 $self->fix_metastructure_basic;
3340 $metadata = $twigroot->first_child('metadata');
3341  
3342 # If <dc-metadata> doesn't exist, we'll have to create it.
3343 $dcmeta = $twigroot->first_descendant('dc-metadata');
3344 if(! $dcmeta)
3345 {
3346 debug(2,"DEBUG: creating <dc-metadata>");
3347 $dcmeta = $metadata->insert_new_elt('first_child','dc-metadata');
3348 }
3349  
3350 # Make sure that $dcmeta is a child of $metadata
3351 $parent = $dcmeta->parent;
3352 if($parent != $metadata)
3353 {
3354 debug(2,"DEBUG: moving <dc-metadata>");
3355 $dcmeta->move('first_child',$metadata);
3356 }
3357  
3358 # If <x-metadata> doesn't exist, create it
3359 $xmeta = $metadata->first_descendant('x-metadata');
3360 if(! $xmeta)
3361 {
3362 debug(2,"DEBUG: creating <x-metadata>");
3363 $xmeta = $metadata->insert_new_elt('last_child','x-metadata');
3364 }
3365  
3366 # Make sure that x-metadata is a child of metadata
3367 $parent = $xmeta->parent;
3368 if($parent != $metadata)
3369 {
3370 debug(2,"DEBUG: moving <x-metadata>");
3371 $xmeta->move('after',$dcmeta);
3372 }
3373 return 1;
3374 }
3375  
3376  
3377 =head2 C<fix_misc()>
3378  
3379 Fixes miscellaneous potential problems in OPF data. Specifically,
3380 this is a shortcut to calling L</delete_meta_filepos()>,
3381 L</fix_packageid()>, L</fix_dates()>, L</fix_languages()>,
3382 L</fix_publisher()>, L</fix_manifest()>, L</fix_spine()>,
3383 L</fix_guide()>, and L</fix_links()>.
3384  
3385 The objective here is that you can run either C<fix_misc()> and either
3386 L</fix_oeb12()> or L</fix_opf20()> and a perfectly valid OPF file will
3387 result from only two calls.
3388  
3389 =cut
3390  
3391 sub fix_misc :method
3392 {
3393 my $self = shift;
3394 my $subname = ( caller(0) )[3];
3395 croak($subname . "() called as a procedure") unless(ref $self);
3396 debug(2,"DEBUG[",$subname,"]");
3397 $self->twigcheck();
3398  
3399 $self->delete_meta_filepos();
3400 $self->fix_packageid();
3401 $self->fix_dates();
3402 $self->fix_languages();
3403 $self->fix_publisher();
3404 $self->fix_manifest();
3405 $self->fix_spine();
3406 $self->fix_guide();
3407 $self->fix_links();
3408  
3409 debug(2,"DEBUG[/",$subname,"]");
3410 return 1;
3411 }
3412  
3413  
3414 =head2 C<fix_mobi()>
3415  
3416 Manipulates the twig to fix Mobipocket-specific issues
3417  
3418 =over
3419  
3420 =item * Force the OEB 1.2 structure (although not the namespace, DTD,
3421 or capitalization), so that <dc-metadata> and <x-metadata> are
3422 guaranteed to exist.
3423  
3424 =item * Find and move all Mobi-specific elements to <x-metadata>
3425  
3426 =item * If no <output> element exists, creates one for a utf-8 ebook
3427  
3428 =back
3429  
3430 Note that the forced creation of <output> will cause the OPF file to
3431 become noncompliant with IDPF specifications.
3432  
3433 =cut
3434  
3435 sub fix_mobi :method
3436 {
3437 my $self = shift;
3438 my $subname = ( caller(0) )[3];
3439 croak($subname . "() called as a procedure") unless(ref $self);
3440 debug(2,"DEBUG[",$subname,"]");
3441 $self->twigcheck();
3442  
3443 my $twigroot = $self->{twigroot};
3444  
3445 my %mobicontenttypes = (
3446 'text/x-oeb1-document' => 'text/x-oeb1-document',
3447 'application/x-mobipocket-subscription'
3448 => 'application/x-mobipocket-subscription',
3449 'application/x-mobipocket-subscription-feed'
3450 => 'application/x-mobipocket-subscription-feed',
3451 'application/x-mobipocket-subscription-magazine'
3452 => 'application/x-mobipocket-subscription-magazine',
3453 'image/gif' => 'image/gif',
3454 'application/msword' => 'application/msword',
3455 'application/vnd.ms-excel' => 'application/vnd.ms-excel',
3456 'application/vnd.ms-powerpoint' => 'application/vnd.ms-powerpoint',
3457 'text/plain' => 'text/plain',
3458 'text/html' => 'text/html',
3459 'application/vnd.mobipocket-game' => 'application/vnd.mobipocket-game',
3460 'application/vnd.mobipocket-franklin-ua-game'
3461 => 'application/vnd.mobipocket-franklin-ua-game'
3462 );
3463  
3464 my %mobiencodings = (
3465 'Windows-1252' => 'Windows-1252',
3466 'utf-8' => 'utf-8'
3467 );
3468  
3469 my @mobitags = (
3470 'output',
3471 'Adult',
3472 'Demo',
3473 'DefaultLookupIndex',
3474 'DictionaryInLanguage',
3475 'DictionaryOutLanguage',
3476 'DictionaryVeryShortName',
3477 'DatabaseName',
3478 'EmbeddedCover',
3479 'Review',
3480 'SRP',
3481 'Territory'
3482 );
3483  
3484 my $dcmeta;
3485 my $xmeta;
3486 my @elements;
3487 my $output;
3488  
3489  
3490 # Mobipocket currently requires that its custom elements be found
3491 # underneath <x-metadata>. Since the presence of <x-metadata>
3492 # requires that the Dublin Core tags be under <dc-metadata>, we
3493 # have to use at least the OEB1.2 structure (deprecated, but still
3494 # allowed in OPF2.0), though we don't have to convert everything.
3495 $self->fix_metastructure_oeb12();
3496 $dcmeta = $twigroot->first_descendant('dc-metadata');
3497 $xmeta = $twigroot->first_descendant('x-metadata');
3498  
3499 # If <x-metadata> doesn't exist, create it. Even if there are no
3500 # mobi-specific tags, this method will create at least one
3501 # (<output>) which will need it.
3502 if(!$xmeta)
3503 {
3504 debug(2,"DEBUG: creating <x-metadata>");
3505 $xmeta = $dcmeta->insert_new_elt('after','x-metadata')
3506 }
3507  
3508 foreach my $tag (@mobitags)
3509 {
3510 @elements = $twigroot->descendants($tag);
3511 next unless (@elements);
3512  
3513 # In theory, only one Mobipocket-specific element should ever
3514 # be present in a document. We'll deal with multiples anyway,
3515 # but send a warning.
3516 if(scalar(@elements) > 1)
3517 {
3518 $self->add_warning(
3519 'fix_mobi(): Found ' . scalar(@elements) . " '" . $tag .
3520 "' elements, but only one should exist."
3521 );
3522 }
3523  
3524 foreach my $el (@elements)
3525 {
3526 $el->move('last_child',$xmeta);
3527 }
3528 }
3529  
3530 $output = $xmeta->first_child('output');
3531 if($output)
3532 {
3533 my $encoding = $mobiencodings{$output->att('encoding')};
3534 my $contenttype = $mobicontenttypes{$output->att('content-type')};
3535  
3536 if($contenttype)
3537 {
3538 $output->set_att('encoding','utf-8') if(!$encoding);
3539 debug(2,"DEBUG: setting encoding only and returning");
3540 return 1;
3541 }
3542 }
3543 else
3544 {
3545 debug(1,"DEBUG: creating <output> under <x-metadata>");
3546 $output = $xmeta->insert_new_elt('last_child','output');
3547 }
3548  
3549  
3550 # At this stage, we definitely have <output> in the right place.
3551 # Set the attributes and return.
3552 $output->set_att('encoding' => 'utf-8',
3553 'content-type' => 'text/x-oeb1-document');
3554 debug(2,"DEBUG[/",$subname,"]");
3555 return 1;
3556 }
3557  
3558  
3559 =head2 C<fix_oeb12()>
3560  
3561 Modifies the OPF data to conform to the OEB 1.2 standard
3562  
3563 Specifically, this involves:
3564  
3565 =over
3566  
3567 =item * adding the OEB 1.2 doctype
3568  
3569 =item * removing OPF 2.0 version and namespace attributes
3570  
3571 =item * setting the OEB 1.2 namespace on <package>
3572  
3573 =item * moving all of the dc-metadata elements underneath an element
3574 with tag <dc-metadata>, which itself is forced to be underneath
3575 <metadata>, which is created if it doesn't exist.
3576  
3577 =item * moving any remaining tags underneath <x-metadata>, again
3578 forced to be under <metadata>
3579  
3580 =item * making the dc-metadata tags conform to the OEB v1.2 capitalization
3581  
3582 =back
3583  
3584 =cut
3585  
3586 sub fix_oeb12 :method
3587 {
3588 my $self = shift;
3589 my $subname = ( caller(0) )[3];
3590 croak($subname . "() called as a procedure") unless(ref $self);
3591 debug(2,"DEBUG[",$subname,"]");
3592 $self->twigcheck();
3593  
3594 my $twigroot = $self->{twigroot};
3595 my $metadata;
3596 my $dcmeta;
3597 my $xmeta;
3598 my @elements;
3599  
3600 # Verify and correct locations for <metadata>, <dc-metadata>, and
3601 # <x-metadata>, creating them as needed.
3602 $self->fix_metastructure_oeb12;
3603 $metadata = $twigroot->first_descendant('metadata');
3604 $dcmeta = $metadata->first_descendant('dc-metadata');
3605 $xmeta = $metadata->first_descendant('x-metadata');
3606  
3607 # Clobber metadata attributes 'xmlns:dc' and 'xmlns:opf'
3608 # used only in OPF2.0
3609 $metadata->del_atts('xmlns:dc','xmlns:opf');
3610  
3611 # Assign the DC namespace attribute to dc-metadata for OEB 1.2
3612 $dcmeta->set_att('xmlns:dc',"http://purl.org/dc/elements/1.1/");
3613  
3614 # Set the correct tag name and move it into <dc-metadata> in the
3615 # right order
3616 foreach my $dcel (keys %dcelements12)
3617 {
3618 @elements = $twigroot->descendants(qr/^$dcel$/ix);
3619 foreach my $el (@elements)
3620 {
3621 debug(3,"DEBUG: processing '",$el->gi,"'");
3622 croak("Found invalid DC element '",$el->gi,"'!")
3623 if(!$dcelements12{lc $el->gi});
3624 $el->set_gi($dcelements12{lc $el->gi});
3625 $el = twigelt_fix_oeb12_atts($el);
3626 $el->move('last_child',$dcmeta);
3627 }
3628 }
3629  
3630 # Handle non-DC metadata, deleting <x-metadata> if it isn't
3631 # needed.
3632 @elements = $metadata->children(qr/^(?!(?s:.*)-metadata)/x);
3633 if(@elements)
3634 {
3635 if($debug)
3636 {
3637 print {*STDERR} "DEBUG: extra metadata elements found: ";
3638 foreach my $el (@elements) { print {*STDERR} $el->gi," "; }
3639 print {*STDERR} "\n";
3640 }
3641 foreach my $el (@elements)
3642 {
3643 $el->move('last_child',$xmeta);
3644 }
3645 }
3646 @elements = $twigroot->children(qr/^meta$/ix);
3647 foreach my $el (@elements)
3648 {
3649 $el->set_gi(lc $el->gi);
3650 $el->move('last_child',$xmeta);
3651 }
3652 @elements = $xmeta->children;
3653 $xmeta->delete unless(@elements);
3654  
3655 # Fix <manifest> and <spine>
3656 $self->fix_manifest;
3657 $self->fix_spine;
3658  
3659 # Set the OEB 1.2 doctype
3660 $self->{twig}->set_doctype('package',
3661 "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd",
3662 "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN");
3663  
3664 # Clean up <package>
3665 $twigroot->del_att('version');
3666 $twigroot->set_att(
3667 'xmlns' => 'http://openebook.org/namespaces/oeb-package/1.0/');
3668 $self->fix_packageid;
3669  
3670 $self->{spec} = $validspecs{'OEB12'};
3671 debug(2,"DEBUG[/",$subname,"]");
3672 return 1;
3673 }
3674  
3675  
3676 =head2 C<fix_oeb12_dcmetatags()>
3677  
3678 Makes a case-insensitive search for tags matching a known list of DC
3679 metadata elements and corrects the capitalization to the OEB 1.2
3680 standard. Also corrects 'dc:Copyrights' to 'dc:Rights'. See global
3681 variable $dcelements12.
3682  
3683 The L</fix_oeb12()> method does this also, but fix_oeb12_dcmetatags()
3684 is usable separately for the case where you want DC metadata elements
3685 with consistent tag names, but don't want them moved from wherever
3686 they are.
3687  
3688 =cut
3689  
3690 sub fix_oeb12_dcmetatags :method
3691 {
3692 my $self = shift;
3693 my $subname = ( caller(0) )[3];
3694 croak($subname . "() called as a procedure") unless(ref $self);
3695 debug(2,"DEBUG[",$subname,"]");
3696 $self->twigcheck();
3697  
3698 my $topelement = $self->{twigroot};
3699  
3700 my @elements;
3701  
3702 foreach my $dcmetatag (keys %dcelements12)
3703 {
3704 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
3705 foreach my $el (@elements)
3706 {
3707 $el->set_tag($dcelements12{lc $el->tag})
3708 if($dcelements12{lc $el->tag});
3709 }
3710 }
3711 return 1;
3712 }
3713  
3714  
3715 =head2 C<fix_opf20()>
3716  
3717 Modifies the OPF data to conform to the OPF 2.0 standard
3718  
3719 Specifically, this involves:
3720  
3721 =over
3722  
3723 =item * moving all of the dc-metadata and x-metadata elements directly
3724 underneath <metadata>
3725  
3726 =item * removing the <dc-metadata> and <x-metadata> elements themselves
3727  
3728 =item * lowercasing the dc-metadata tags (and fixing dc:copyrights to
3729 dc:rights)
3730  
3731 =item * setting namespaces on dc-metata OPF attributes
3732  
3733 =item * setting version and xmlns attributes on <package>
3734  
3735 =item * setting xmlns:dc and xmlns:opf on <metadata>
3736  
3737 =back
3738  
3739 =cut
3740  
3741 sub fix_opf20 :method
3742 {
3743 my $self = shift;
3744 my $subname = ( caller(0) )[3];
3745 croak($subname . "() called as a procedure") unless(ref $self);
3746 debug(2,"DEBUG[",$subname,"]");
3747 $self->twigcheck();
3748  
3749 # Ensure a sane structure
3750 $self->fix_metastructure_basic();
3751  
3752 my $twigroot = $self->{twigroot};
3753 my $metadata = $twigroot->first_descendant('metadata');
3754 my @elements;
3755  
3756 # If <dc-metadata> exists, make sure that it is directly
3757 # underneath <metadata> so that its children will collapse to the
3758 # correct position, then erase it.
3759 @elements = $twigroot->descendants('dc-metadata');
3760 if(@elements)
3761 {
3762 foreach my $dcmeta (@elements)
3763 {
3764 debug(1,"DEBUG: moving <dc-metadata>");
3765 $dcmeta->move('first_child',$metadata);
3766 $dcmeta->erase;
3767 }
3768 }
3769  
3770 # If <x-metadata> exists, make sure that it is directly underneath
3771 # <metadata> so that its children will collapse to the correct
3772 # position, then erase it.
3773 @elements = $twigroot->descendants('x-metadata');
3774 if(@elements)
3775 {
3776 foreach my $xmeta (@elements)
3777 {
3778 debug(1,"DEBUG: moving <x-metadata>");
3779 $xmeta->move('last_child',$metadata);
3780 $xmeta->erase;
3781 }
3782 }
3783  
3784 # For all DC elements at any location, set the correct tag name
3785 # and attribute namespace and move it directly under <metadata>
3786 foreach my $dcmetatag (keys %dcelements20)
3787 {
3788 @elements = $twigroot->descendants(qr/$dcmetatag/ix);
3789 foreach my $el (@elements)
3790 {
3791 debug(1,"DEBUG: checking element '",$el->gi,"'");
3792 $el->set_gi($dcelements20{$dcmetatag});
3793 $el = twigelt_fix_opf20_atts($el);
3794 $el->move('last_child',$metadata);
3795 }
3796 }
3797  
3798 # Find any <meta> elements anywhere in the package and move them
3799 # under <x-metadata>. Force the tag to lowercase.
3800  
3801 @elements = $twigroot->children(qr/^meta$/ix);
3802 foreach my $el (@elements)
3803 {
3804 $el->set_gi(lc $el->gi);
3805 $el->move('last_child',$metadata);
3806 }
3807  
3808 # Fix the <package> attributes
3809 $twigroot->set_att('version' => '2.0',
3810 'xmlns' => 'http://www.idpf.org/2007/opf');
3811 $self->fix_packageid;
3812  
3813 # Fix the <metadata> attributes
3814 $metadata->set_att('xmlns:dc' => "http://purl.org/dc/elements/1.1/",
3815 'xmlns:opf' => "http://www.idpf.org/2007/opf");
3816  
3817 # Fix <manifest> and <spine>
3818 $self->fix_manifest;
3819 $self->fix_spine;
3820  
3821 # Clobber the doctype, if present
3822 $self->{twig}->set_doctype(0,0,0,0);
3823  
3824 # Set the specification
3825 $self->{spec} = $validspecs{'OPF20'};
3826  
3827 debug(2,"DEBUG[/",$subname,"]");
3828 return 1;
3829 }
3830  
3831  
3832 =head2 C<fix_opf20_dcmetatags()>
3833  
3834 Makes a case-insensitive search for tags matching a known list of DC
3835 metadata elements and corrects the capitalization to the OPF 2.0
3836 standard. Also corrects 'dc:copyrights' to 'dc:rights'. See package
3837 variable %dcelements20.
3838  
3839 The L</fix_opf20()> method does this also, but
3840 C<fix_opf20_dcmetatags()> is usable separately for the case where you
3841 want DC metadata elements with consistent tag names, but don't want
3842 them moved from wherever they are.
3843  
3844 =cut
3845  
3846 sub fix_opf20_dcmetatags :method
3847 {
3848 my $self = shift;
3849 my $subname = ( caller(0) )[3];
3850 croak($subname . "() called as a procedure") unless(ref $self);
3851 debug(2,"DEBUG[",$subname,"]");
3852 $self->twigcheck();
3853  
3854 my $topelement = $self->{twigroot};
3855 my @elements;
3856  
3857 foreach my $dcmetatag (keys %dcelements20)
3858 {
3859 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
3860 foreach my $el (@elements)
3861 {
3862 $el->set_tag($dcelements20{lc $el->tag})
3863 if($dcelements20{lc $el->tag});
3864 }
3865 }
3866 return;
3867 }
3868  
3869  
3870 =head2 C<fix_packageid()>
3871  
3872 Checks the <package> element for the attribute 'unique-identifier',
3873 makes sure that it is mapped to a valid dc:identifier subelement, and
3874 if not, searches those subelements for an identifier to assign, or
3875 creates one if nothing can be found.
3876  
3877 Requires that <metadata> exist. Croaks if it doesn't. Run
3878 L</fix_oeb12()> or L</fix_opf20()> before calling this if the input
3879 might be very broken.
3880  
3881 =cut
3882  
3883 sub fix_packageid :method
3884 {
3885 my $self = shift;
3886 my $subname = ( caller(0) )[3];
3887 croak($subname . "() called as a procedure") unless(ref $self);
3888 debug(2,"DEBUG[",$subname,"]");
3889 $self->twigcheck();
3890  
3891 # Start by enforcing the basic structure needed
3892 $self->fix_metastructure_basic();
3893 my $twigroot = $self->{twigroot};
3894 my $packageid = $twigroot->att('unique-identifier');
3895  
3896 my $meta = $twigroot->first_child('metadata')
3897 or croak($subname,"(): metadata not found");
3898 my $element;
3899  
3900 if($packageid)
3901 {
3902 # Check that the ID maps to a valid identifier
3903 # If not, undefine it
3904 debug(2,"DEBUG: checking existing packageid '",$packageid,"'");
3905  
3906 # The twig ID handling system is unreliable, especially when
3907 # multiple twigs may be existing simultaneously. Use
3908 # XML::Twig->first_elt instead of XML::Twig->elt_id, even
3909 # though it is slower.
3910 #
3911 # As of Twig 3.32, this will cause 'uninitialized value'
3912 # warnings to be spewed for each time no descendants are
3913 # found.
3914 #$element = $self->{twig}->elt_id($packageid);
3915 $element = $self->{twig}->first_elt("*[\@id='$packageid']");
3916  
3917 if($element)
3918 {
3919 if(lc($element->tag) ne 'dc:identifier')
3920 {
3921 debug(1,"DEBUG: packageid '",$packageid,
3922 "' points to a non-identifier element ('",
3923 $element->tag,"')");
3924 debug(1,"DEBUG: undefining existing packageid '",
3925 $packageid,"'");
3926 undef($packageid);
3927 }
3928 elsif(!$element->text)
3929 {
3930 debug(1,"DEBUG: packageid '",$packageid,
3931 "' points to an empty identifier.");
3932 debug(1,"DEBUG: undefining existing packageid '",
3933 $packageid,"'");
3934 undef($packageid);
3935 }
3936 }
3937 else { undef($packageid); };
3938 }
3939  
3940 if(!$packageid)
3941 {
3942 # Search known IDs for a unique Package ID
3943 $packageid = $self->search_knownuids;
3944 }
3945  
3946 # If no unique ID found so far, start searching known schemes
3947 if(!$packageid)
3948 {
3949 $packageid = $self->search_knownuidschemes;
3950 }
3951  
3952 # And if we still don't have anything, we have to make one from
3953 # scratch using Data::UUID
3954 if(!$packageid)
3955 {
3956 debug(1,"DEBUG: creating new UUID");
3957 $element = twigelt_create_uuid();
3958 $element->paste('first_child',$meta);
3959 $packageid = 'UUID';
3960 }
3961  
3962 # At this point, we have a unique ID. Assign it to package
3963 $twigroot->set_att('unique-identifier',$packageid);
3964 debug(2,"[/",$subname,"]");
3965 return 1;
3966 }
3967  
3968  
3969 =head2 C<fix_publisher()>
3970  
3971 Standardizes publisher names in all dc:publisher entities, mapping
3972 known variants of a publisher's name to a canonical form via package
3973 variable %publishermap.
3974  
3975 Publisher entries with no text are deleted.
3976  
3977 =cut
3978  
3979 sub fix_publisher :method
3980 {
3981 my $self = shift;
3982 my $subname = ( caller(0) )[3];
3983 croak($subname . "() called as a procedure") unless(ref $self);
3984 debug(2,"DEBUG[",$subname,"]");
3985 $self->twigcheck();
3986  
3987 my @publishers = $self->twigroot->descendants(qr/^dc:publisher$/ix);
3988 foreach my $pub (@publishers)
3989 {
3990 debug(3,"Examining publisher entry in element '",$pub->gi,"'");
3991 if(!$pub->text)
3992 {
3993 debug(1,'Deleting empty publisher entry');
3994 $pub->delete;
3995 next;
3996 }
3997 elsif( $publishermap{lc $pub->text} &&
3998 ($publishermap{lc $pub->text} ne $pub->text) )
3999 {
4000 debug(1,"DEBUG: Changing publisher from '",$pub->text,"' to '",
4001 $publishermap{lc $pub->text},"'");
4002 $pub->set_text($publishermap{lc $pub->text});
4003 }
4004 }
4005 return 1;
4006 }
4007  
4008  
4009 =head2 C<fix_spine()>
4010  
4011 Fixes problems with the OPF spine, specifically:
4012  
4013 =over
4014  
4015 =item Moves all <itemref> elements underneath <spine>, creating
4016 <spine> if necessary.
4017  
4018 =back
4019  
4020 =cut
4021  
4022 sub fix_spine :method
4023 {
4024 my $self = shift;
4025 my $subname = ( caller(0) )[3];
4026 croak($subname . "() called as a procedure") unless(ref $self);
4027 debug(2,"DEBUG[",$subname,"]");
4028 $self->twigcheck();
4029  
4030 my $twigroot = $self->{twigroot};
4031 my $spine = $twigroot->first_descendant('spine');
4032 my @elements;
4033 my $parent;
4034  
4035 @elements = $twigroot->descendants(qr/^itemref$/ix);
4036 if(@elements)
4037 {
4038 # If <spine> doesn't exist, create it
4039 if(! $spine)
4040 {
4041 debug(1,"DEBUG: creating <spine>");
4042 $spine = $twigroot->insert_new_elt('last_child','spine');
4043 }
4044  
4045 # Make sure that the spine is a child of the twigroot,
4046 $parent = $spine->parent;
4047 if($parent != $twigroot)
4048 {
4049 debug(1,"DEBUG: moving <spine>");
4050 $spine->move('last_child',$twigroot);
4051 }
4052  
4053 foreach my $el (@elements)
4054 {
4055 if(!$el->att('idref'))
4056 {
4057 # No idref means it is broken.
4058 # Leave it alone, but log a warning
4059 $self->add_warning(
4060 "fix_spine(): <itemref> with no idref -- skipping");
4061 next;
4062 }
4063 debug(3,"DEBUG: processing itemref '",$el->att('idref'),"')");
4064 $el->move('last_child',$spine);
4065 }
4066 }
4067 else # No elements, delete spine if it exists
4068 {
4069 $spine->delete if($spine);
4070 }
4071  
4072 return 1;
4073 }
4074  
4075  
4076 =head2 C<gen_epub(%args)>
4077  
4078 Creates a .epub format e-book. This will create (or overwrite) the
4079 files 'mimetype' and 'META-INF/container.xml' in the current
4080 directory, creating the subdirectory META-INF as needed.
4081  
4082 =head3 Arguments
4083  
4084 This method can take two optional named arguments.
4085  
4086 =over
4087  
4088 =item C<filename>
4089  
4090 The filename of the .epub output file. If not specified, takes the
4091 base name of the opf file and adds a .epub extension.
4092  
4093 =item C<dir>
4094  
4095 The directory to output the .epub file. If not specified, uses the
4096 current working directory. If a specified directory does not exist,
4097 it will be created, or the method will croak.
4098  
4099 =back
4100  
4101 =head3 Example
4102  
4103 gen_epub(filename => 'mybook.epub',
4104 dir => '../epub_books');
4105  
4106 =cut
4107  
4108 sub gen_epub :method ## no critic (Always unpack @_ first)
4109 {
4110 my $self = shift;
4111 my (%args) = @_;
4112 my $subname = ( caller(0) )[3];
4113 croak($subname . "() called as a procedure") unless(ref $self);
4114 debug(2,"DEBUG[",$subname,"]");
4115  
4116 my %valid_args = (
4117 'filename' => 1,
4118 'dir' => 1,
4119 );
4120 foreach my $arg (keys %args)
4121 {
4122 croak($subname,"(): invalid argument '",$arg,"'")
4123 if(!$valid_args{$arg});
4124 }
4125  
4126 my $filename = $args{filename};
4127 my $dir = $args{dir};
4128 my $zip = Archive::Zip->new();
4129 my $member;
4130  
4131 $self->gen_epub_files();
4132 if(! $self->{opffile} )
4133 {
4134 $self->add_error(
4135 "Cannot create epub without an OPF (did you forget to init?)");
4136 debug(1,"Cannot create epub without an OPF");
4137 return;
4138 }
4139 if(! -f $self->{opffile} )
4140 {
4141 $self->add_error(
4142 sprintf("OPF '%s' does not exist (did you forget to save?)",
4143 $self->{opffile})
4144 );
4145 debug(1,"OPF '",$self->{opffile},"' does not exist");
4146 return;
4147 }
4148  
4149 $member = $zip->addFile('mimetype');
4150 $member->desiredCompressionMethod(COMPRESSION_STORED);
4151  
4152 $member = $zip->addFile('META-INF/container.xml');
4153 $member->desiredCompressionLevel(9);
4154  
4155 $member = $zip->addFile($self->{opffile});
4156 $member->desiredCompressionLevel(9);
4157  
4158 foreach my $file ($self->manifest_hrefs())
4159 {
4160 if(! $file)
4161 {
4162 error("No items found in manifest!");
4163 debug(1,"No items found in manifest!");
4164 return;
4165 }
4166 if(-f $file)
4167 {
4168 $member = $zip->addFile($file);
4169 $member->desiredCompressionLevel(9);
4170 }
4171 else { print STDERR "WARNING: ",$file," not found, skipping.\n"; }
4172 }
4173  
4174 if(! $filename)
4175 {
4176 ($filename) = fileparse($self->{opffile},'\.\w+$');
4177 $filename .= ".epub";
4178 }
4179  
4180 if($dir)
4181 {
4182 unless(-d $dir)
4183 {
4184 mkpath($dir)
4185 or croak("Unable to create working directory '",$dir,"'!");
4186 }
4187 $filename = "$dir/$filename";
4188 }
4189  
4190 unless ( $zip->writeToFileNamed($filename) == AZ_OK )
4191 {
4192 $self->add_error(
4193 sprintf("Failed to create epub as '%s'",$filename));
4194 debug(1,"Failed to create epub as '",$filename,"'");
4195 return;
4196 }
4197 return 1;
4198 }
4199  
4200  
4201 =head2 C<gen_epub_files()>
4202  
4203 Generates the C<mimetype> and C<META-INF/container.xml> files expected
4204 by a .epub container, but does not actually generate the .epub file
4205 itself. This will be called automatically by C<gen_epub>.
4206  
4207 =cut
4208  
4209 sub gen_epub_files :method
4210 {
4211 my $self = shift;
4212 my $subname = ( caller(0) )[3];
4213 croak($subname . "() called as a procedure") unless(ref $self);
4214 debug(2,"DEBUG[",$subname,"]");
4215  
4216 create_epub_mimetype();
4217 create_epub_container($self->{opffile});
4218 return 1;
4219 }
4220  
4221  
4222 =head2 C<gen_ncx($filename)>
4223  
4224 Creates a NCX-format table of contents from the package
4225 unique-identifier, the dc:title, dc:creator, and spine elements, and
4226 then add the NCX entry to the manifest if it is not already
4227 referenced.
4228  
4229 Adds an error and fails if any of those cannot be found. The first
4230 available dc:title is taken, but will prioritize dc:creator elements
4231 with opf:role="aut" over those with no role attribute (see
4232 twigelt_is_author() for details).
4233  
4234 WARNING: This method REQUIRES that the e-book be in OPF 2.0 format to
4235 function correctly. Call fix_opf20() before calling gen_ncx().
4236 gen_ncx() will log an error and fail if $self{spec} is not set to
4237 OPF20.
4238  
4239 =head3 Arguments
4240  
4241 =over
4242  
4243 =item $filename : The filename to save to. If not specified, will use
4244 'toc.ncx'.
4245  
4246 =back
4247  
4248 This method will overwrite any existing file.
4249  
4250 Returns a twig containing the NCX XML, or undef on failure.
4251  
4252 =cut
4253  
4254 sub gen_ncx :method ## no critic (Always unpack @_ first)
4255 {
4256 my $self = shift;
4257 my ($filename) = @_;
4258 my $subname = ( caller(0) )[3];
4259 croak($subname . "() called as a procedure") unless(ref $self);
4260 debug(2,"DEBUG[",$subname,"]");
4261 $self->twigcheck;
4262  
4263 $filename = 'toc.ncx' if(!$filename);
4264  
4265 my $twigroot = $self->{twigroot};
4266 my $identifier = $self->identifier;
4267 my $element; # Generic element container
4268 my $parent; # Generic parent element container
4269 my $ncx; # NCX twig
4270 my $ncxroot; # NCX twig root <ncx>
4271 my $ncxitem; # manifest item pointing to the NCX document
4272 my $navmap; # NCX element <navMap>
4273 my $navpoint; # NCX element <navPoint>
4274 my %navpointorder; # Hash mapping playOrder to id
4275 my $navpointindex = 1; # playOrder number starting at 1
4276 my $title; # E-book title
4277 my $author; # E-book primary author
4278 my @spinelist; # List of hashrefs containing spine data
4279 my $manifest; # OPF manifest element
4280  
4281 if($self->{spec} ne 'OPF20')
4282 {
4283 $self->add_error(
4284 $subname . "(): specification is currently set to '"
4285 . $self->{spec} . "' -- need 'OPF20'"
4286 );
4287 debug(1,"DEBUG: gen_ncx() FAILED: wrong specification ('",
4288 $self->{spec},"')!");
4289 return;
4290 }
4291  
4292 if(!$identifier)
4293 {
4294 $self->add_error( $subname . "(): no unique-identifier found" );
4295 debug(1,"DEBUG: gen_ncx() FAILED: no unique-identifier!");
4296 return;
4297 }
4298  
4299 # Get the title
4300 $title = $self->title();
4301 if(!$title)
4302 {
4303 $self->add_error( $subname . "(): no title found" );
4304 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
4305 return;
4306 }
4307  
4308 # Get the author
4309 $author = $self->primary_author();
4310 if(!$author)
4311 {
4312 $self->add_error( $subname . "(): no title found" );
4313 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
4314 return;
4315 }
4316  
4317 # Get the spine list
4318 @spinelist = $self->spine();
4319 if(!@spinelist)
4320 {
4321 $self->add_error( $subname . "(): no spine found" );
4322 debug(1,"DEBUG: gen_ncx() FAILED: no spine!");
4323 return;
4324 }
4325  
4326 # Make sure the manifest element exists
4327 # (This should in theory never fail, since it is also checked by
4328 # spine() above)
4329 $manifest = $twigroot->first_descendant('manifest');
4330 if(!$manifest)
4331 {
4332 $self->add_error( $subname . "(): no manifest found" );
4333 debug(1,"DEBUG: gen_ncx() FAILED: no manifest!");
4334 return;
4335 }
4336  
4337 $ncx = XML::Twig->new(
4338 output_encoding => 'utf-8',
4339 pretty_print => 'record'
4340 );
4341  
4342 # <ncx>
4343 $element = XML::Twig::Elt->new('ncx');
4344 $element->set_att('xmlns' => 'http://www.daisy.org/z3986/2005/ncx/');
4345 $ncx->set_root($element);
4346 $ncxroot = $ncx->root;
4347  
4348 # <head>
4349 $parent = $ncxroot->insert_new_elt('first_child','head');
4350 $element = $parent->insert_new_elt('last_child','meta');
4351 $element->set_att(
4352 'name' => 'dtb:uid',
4353 'content' => $identifier
4354 );
4355  
4356 $element = $parent->insert_new_elt('last_child','meta');
4357 $element->set_att(
4358 'name' => 'dtb:depth',
4359 'content' => '1'
4360 );
4361 $element = $parent->insert_new_elt('last_child','meta');
4362 $element->set_att(
4363 'name' => 'dtb:totalPageCount',
4364 'content' => '0'
4365 );
4366  
4367 $element = $parent->insert_new_elt('last_child','meta');
4368 $element->set_att(
4369 'name' => 'dtb:maxPageNumber',
4370 'content' => '0'
4371 );
4372  
4373 # <docTitle>
4374 $parent = $parent->insert_new_elt('after','docTitle');
4375 $element = $parent->insert_new_elt('first_child','text');
4376 $element->set_text($title);
4377  
4378 # <navMap>
4379 $navmap = $parent->insert_new_elt('after','navMap');
4380  
4381 foreach my $spineitem (@spinelist)
4382 {
4383 # <navPoint>
4384 $navpoint = $navmap->insert_new_elt('last_child','navPoint');
4385 $navpoint->set_att('id' => $$spineitem{'id'},
4386 'playOrder' => $navpointindex);
4387 $navpointindex++;
4388  
4389 # <navLabel>
4390 $parent = $navpoint->insert_new_elt('last_child','navLabel');
4391 $element = $parent->insert_new_elt('last_child','text');
4392 $element->set_text($$spineitem{'id'});
4393  
4394 # <content>
4395 $element = $navpoint->insert_new_elt('last_child','content');
4396 $element->set_att('src' => $$spineitem{'href'});
4397 }
4398  
4399 # Backup existing file
4400 if(-e $filename)
4401 {
4402 rename($filename,"$filename.backup")
4403 or croak($subname,"(): could not backup ",$filename,"!");
4404 }
4405  
4406 # Twig handles utf-8 on its own. Setting binmode :utf8 here will
4407 # cause double-conversion.
4408 open(my $fh_ncx,'>',$filename)
4409 or croak($subname,"(): failed to open '",$filename,"' for writing!");
4410 $ncx->print(\*$fh_ncx);
4411 close($fh_ncx)
4412 or croak($subname,"(): failed to close '",$filename,"'!");
4413  
4414 # Search for existing NCX entries and modify the first one found,
4415 # creating a new one if there are no matches.
4416 $ncxitem = $manifest->first_child('item[@id="ncx"]');
4417 $ncxitem = $manifest->first_child("item[\@href='$filename']")
4418 if(!$ncxitem);
4419 $ncxitem = $manifest->first_child('item[@media-type="application/x-dtbncx+xml"]')
4420 if(!$ncxitem);
4421 $ncxitem = $manifest->insert_new_elt('first_child','item')
4422 if(!$ncxitem);
4423  
4424 $ncxitem->set_att(
4425 'id' => 'ncx',
4426 'href' => $filename,
4427 'media-type' => 'application/x-dtbncx+xml'
4428 );
4429  
4430 # Move the NCX item to the top of the manifest
4431 $ncxitem->move('first_child',$manifest);
4432  
4433 return $ncx;
4434 }
4435  
4436  
4437 =head2 C<save()>
4438  
4439 Saves the OPF file to disk. Existing files are backed up to
4440 filename.backup.
4441  
4442 =cut
4443  
4444 sub save :method
4445 {
4446 my $self = shift;
4447 my $subname = ( caller(0) )[3];
4448 croak($subname . "() called as a procedure") unless(ref $self);
4449 debug(2,"DEBUG[",$subname,"]");
4450  
4451 croak($subname,"(): no opffile specified (did you forget to init?)")
4452 if(!$self->{opffile});
4453  
4454 my $fh_opf;
4455 my $filename = $self->{opffile};
4456  
4457 # Backup existing file
4458 if(-e $filename)
4459 {
4460 rename($filename,"$filename.backup")
4461 or croak($subname,"(): could not backup ",$filename,"!");
4462 }
4463  
4464  
4465 # Twig handles utf8 on its own. If you open this file with
4466 # binmode :utf8, it will double-convert.
4467 if(!open($fh_opf,">",$self->{opffile}))
4468 {
4469 add_error(sprintf("Could not open '%s' to save to!",$self->{opffile}));
4470 return;
4471 }
4472 $self->{twig}->print(\*$fh_opf);
4473  
4474 if(!close($fh_opf))
4475 {
4476 add_error(sprintf("Failure while closing '%s'!",$self->{opffile}));
4477 return;
4478 }
4479 return 1;
4480 }
4481  
4482  
4483 =head2 C<set_adult($bool)>
4484  
4485 Sets the Mobipocket-specific <Adult> element, creating or deleting it
4486 as necessary. If C<$bool> is true, the text is set to 'yes'. If it
4487 is defined but false, any existing elements are deleted. If it is
4488 undefined, the method immediately returns.
4489  
4490 If a new element has to be created, L</fix_metastructure_oeb12> is
4491 called to ensure that <x-metadata> exists and the element is created
4492 under <x-metadata>, as Mobipocket elements are not recognized by
4493 Mobipocket's software when placed directly under <metadata>
4494  
4495 =cut
4496  
4497 sub set_adult :method
4498 {
4499 my $self = shift;
4500 my $adult = shift;
4501 my $subname = ( caller(0) )[3];
4502 croak($subname . "() called as a procedure") unless(ref $self);
4503 debug(2,"DEBUG[",$subname,"]");
4504 $self->twigcheck;
4505  
4506 return 1 unless(defined $adult);
4507  
4508 my $xmeta;
4509 my $element;
4510 my @elements;
4511  
4512 if($adult)
4513 {
4514 $element = $self->{twigroot}->first_descendant(qr/^adult$/ix);
4515 unless($element)
4516 {
4517 $self->fix_metastructure_oeb12();
4518 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
4519 $element = $xmeta->insert_new_elt('last_child','Adult');
4520 }
4521 $element->set_text('yes');
4522 }
4523 else
4524 {
4525 @elements = $self->{twigroot}->descendants(qr/^adult$/ix);
4526 foreach my $el (@elements)
4527 {
4528 debug(2,"DEBUG: deleting <Adult> flag");
4529 $el->delete;
4530 }
4531 }
4532 return 1;
4533 }
4534  
4535  
4536 =head2 C<set_date(%args)>
4537  
4538 Sets the date metadata for a given event. If more than one dc:date or
4539 dc:Date element is present with the specified event attribute, sets
4540 the first. If no dc:date element is present with the specified event
4541 attribute, a new element is created.
4542  
4543 If a <dc-metadata> element exists underneath <metadata>, the date
4544 element will be created underneath the <dc-metadata> in OEB 1.2
4545 format, otherwise the title element is created underneath <metadata>
4546 in OPF 2.0 format.
4547  
4548 Returns 1 on success, logs an error and returns undef if no text or
4549 event was specified.
4550  
4551 =head3 Arguments
4552  
4553 =over
4554  
4555 =item C<text>
4556  
4557 This specifies the description to use as the text of the element. If
4558 not specified, the method sets an error and returns undef.
4559  
4560 =item C<event>
4561  
4562 This specifies the event attribute for the date. If not specified,
4563 the method sets an error and returns undef.
4564  
4565 =item C<id> (optional)
4566  
4567 This specifies the ID to set on the element. If set and the ID is
4568 already in use, a warning is logged and the ID is removed from the
4569 other location and assigned to the element.
4570  
4571 =back
4572  
4573 =cut
4574  
4575 sub set_date :method ## no critic (Always unpack @_ first)
4576 {
4577 my $self = shift;
4578 my (%args) = @_;
4579 my $subname = ( caller(0) )[3];
4580 croak($subname . "() called as a procedure") unless(ref $self);
4581 debug(2,"DEBUG[",$subname,"]");
4582 my %valid_args = (
4583 'text' => 1,
4584 'event' => 1,
4585 'id' => 1,
4586 );
4587 foreach my $arg (keys %args)
4588 {
4589 croak($subname,"(): invalid argument '",$arg,"'")
4590 if(!$valid_args{$arg});
4591 }
4592  
4593 my $text = $args{text};
4594 my $event = $args{event};
4595 my $newid = $args{id};
4596 unless($text)
4597 {
4598 $self->add_error($subname,"(): no text specified");
4599 return;
4600 }
4601 unless($event)
4602 {
4603 $self->add_error($subname,"(): no event specified");
4604 return;
4605 }
4606  
4607 my $meta = $self->{twigroot}->first_child('metadata');
4608 my $dcmeta = $meta->first_child('dc-metadata');
4609 my $idelem;
4610 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
4611  
4612 $self->fix_metastructure_basic();
4613  
4614 my $element = $self->{twigroot}->first_descendant(
4615 "dc:date[\@opf:event=~/$event/ix or \@event=~/$event/ix]");
4616 $element = $self->{twigroot}->first_descendant(
4617 "dc:Date[\@opf:event=~/$event/ix or \@event=~/$event/ix]")
4618 unless($element);
4619  
4620 if($element)
4621 {
4622 $element->set_text($text);
4623 }
4624 elsif($dcmeta)
4625 {
4626 $element = $dcmeta->insert_new_elt('last_child','dc:Date');
4627 $element->set_att('event',$event);
4628 $element->set_text($text);
4629 }
4630 else
4631 {
4632 $element = $meta->insert_new_elt('last_child','dc:date');
4633 $element->set_att('opf:event',$event);
4634 $element->set_text($text);
4635 }
4636  
4637 if($idelem && $idelem->cmp($element) )
4638 {
4639 $self->add_warning(
4640 $subname,"(): reassigning id '",$newid,
4641 "' from a '",$idelem->gi,"' element!"
4642 );
4643 $idelem->del_att('id');
4644 }
4645 $element->set_att('id' => $newid) if($newid);
4646 return 1;
4647 }
4648  
4649  
4650 =head2 set_description(%args)
4651  
4652 Sets the text and optionally ID of the first dc:description element
4653 found (case-insensitive). Creates the element if one did not exist.
4654 If a <dc-metadata> element exists underneath <metadata>, the
4655 description element will be created underneath the <dc-metadata> in
4656 OEB 1.2 format, otherwise the title element is created underneath
4657 <metadata> in OPF 2.0 format.
4658  
4659 Returns 1 on success, returns undef if no publisher was specified.
4660  
4661 =head3 Arguments
4662  
4663 C<set_description()> takes one required and one optional named argument
4664  
4665 =over
4666  
4667 =item C<text>
4668  
4669 This specifies the description to use as the text of the element. If
4670 not specified, the method returns undef.
4671  
4672 =item C<id> (optional)
4673  
4674 This specifies the ID to set on the element. If set and the ID is
4675 already in use, a warning is logged and the ID is removed from the
4676 other location and assigned to the element.
4677  
4678 =back
4679  
4680 =head3 Example
4681  
4682 $retval = $ebook->set_description('text' => 'A really good book',
4683 'id' => 'mydescid');
4684  
4685 =cut
4686  
4687 sub set_description :method ## no critic (Always unpack @_ first)
4688 {
4689 my $self = shift;
4690 my (%args) = @_;
4691 my $subname = ( caller(0) )[3];
4692 croak($subname . "() called as a procedure") unless(ref $self);
4693 debug(2,"DEBUG[",$subname,"]");
4694 my %valid_args = (
4695 'text' => 1,
4696 'id' => 1,
4697 );
4698 foreach my $arg (keys %args)
4699 {
4700 croak($subname,"(): invalid argument '",$arg,"'")
4701 if(!$valid_args{$arg});
4702 }
4703  
4704 my $text = $args{text};
4705 unless($text)
4706 {
4707 $self->add_error($subname,"(): no text specified");
4708 return;
4709 }
4710  
4711 $self->fix_metastructure_basic();
4712 my $element = $self->{twigroot}->first_descendant(qr/^dc:description$/ix);
4713 my $meta = $self->{twigroot}->first_child('metadata');
4714 my $dcmeta = $meta->first_child('dc-metadata');
4715  
4716 my $gi = ($dcmeta) ? 'dc:Description' : 'dc:description';
4717 $self->set_metadata(gi => $gi,
4718 text => $text,
4719 id => $args{id});
4720  
4721 return 1;
4722 }
4723  
4724  
4725 =head2 C<set_language(%args)>
4726  
4727 Sets the text and optionally the ID of the first dc:language element
4728 found (case-insensitive). Creates the element if one did not exist.
4729 If a <dc-metadata> element exists underneath <metadata>, the language
4730 element will be created underneath the <dc-metadata> in OEB 1.2
4731 format, otherwise the title element is created underneath <metadata>
4732 in OPF 2.0 format.
4733  
4734 Returns 1 on success, returns undef if no text was specified.
4735  
4736 =head3 Arguments
4737  
4738 =over
4739  
4740 =item C<text>
4741  
4742 This specifies the language set as the text of the element. If not
4743 specified, the method sets an error and returns undef. This should be
4744 an IANA language code, and it will be lowercased before it is set.
4745  
4746 =item C<id> (optional)
4747  
4748 This specifies the ID to set on the element. If set and the ID is
4749 already in use, a warning is logged and the ID is removed from the
4750 other location and assigned to the element.
4751  
4752 =back
4753  
4754 =head3 Example
4755  
4756 $retval = $ebook->set_language('text' => 'en-us',
4757 'id' => 'langid');
4758  
4759 =cut
4760  
4761 sub set_language :method ## no critic (Always unpack @_ first)
4762 {
4763 my $self = shift;
4764 my (%args) = @_;
4765 my $subname = ( caller(0) )[3];
4766 croak($subname . "() called as a procedure") unless(ref $self);
4767 debug(2,"DEBUG[",$subname,"]");
4768 my %valid_args = (
4769 'text' => 1,
4770 'id' => 1,
4771 );
4772 foreach my $arg (keys %args)
4773 {
4774 croak($subname,"(): invalid argument '",$arg,"'")
4775 if(!$valid_args{$arg});
4776 }
4777  
4778 my $text = lc($args{text});
4779 unless($text)
4780 {
4781 $self->add_error($subname,"(): no text specified");
4782 return;
4783 }
4784  
4785 $self->fix_metastructure_basic();
4786 my $element = $self->{twigroot}->first_descendant(qr/^dc:language$/ix);
4787 my $meta = $self->{twigroot}->first_child('metadata');
4788 my $dcmeta = $meta->first_child('dc-metadata');
4789  
4790 my $gi = ($dcmeta) ? 'dc:Language' : 'dc:language';
4791 $self->set_metadata(gi => $gi,
4792 text => $text,
4793 id => $args{id});
4794 return 1;
4795 }
4796  
4797  
4798 =head2 set_metadata(%args)
4799  
4800 Sets the text and optionally the ID of the first specified element
4801 type found (case-insensitive). Creates the element if one did not
4802 exist (with the exact capitalization specified).
4803  
4804 If a <dc-metadata> element exists underneath <metadata>, the language
4805 element will be created underneath the <dc-metadata> and any standard
4806 attributes will be created in OEB 1.2 format, otherwise the element is
4807 created underneath <metadata> in OPF 2.0 format.
4808  
4809 Returns 1 on success, returns undef if no gi or if no text was specified.
4810  
4811 =cut
4812  
4813 =head3 Arguments
4814  
4815 =over
4816  
4817 =item C<gi>
4818  
4819 The generic identifier (tag) of the metadata element to alter or
4820 create. If not specified, the method sets an error and returns undef.
4821  
4822 =item C<parent>
4823  
4824 The generic identifier (tag) of the parent to use for any newly
4825 created element. If not specified, defaults to 'dc-metadata' if
4826 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
4827  
4828 A newly created element will be created under the first element found
4829 with this gi. A modified element will be moved under the first
4830 element found with this gi.
4831  
4832 Newly created elements will use OPF 2.0 attribute names if the parent
4833 is 'metadata' and OEB 1.2 attribute names otherwise.
4834  
4835 =item C<text>
4836  
4837 This specifies the element text to set. If not specified, the method
4838 sets an error and returns undef.
4839  
4840 =item C<id> (optional)
4841  
4842 This specifies the ID to set on the element. If set and the ID is
4843 already in use, a warning is logged and the ID is removed from the
4844 other location and assigned to the element.
4845  
4846 =item C<fileas> (optional)
4847  
4848 This specifies the file-as attribute to set on the element.
4849  
4850 =item C<role> (optional)
4851  
4852 This specifies the role attribute to set on the element.
4853  
4854 =item C<scheme> (optional)
4855  
4856 This specifies the scheme attribute to set on the element.
4857  
4858 =back
4859  
4860 =head3 Example
4861  
4862 $retval = $ebook->set_metadata(gi => 'AuthorNonstandard',
4863 text => 'Element Text',
4864 id => 'customid',
4865 fileas => 'Text, Element',
4866 role => 'xxx',
4867 scheme => 'code');
4868  
4869 =cut
4870  
4871 sub set_metadata :method ## no critic (Always unpack @_ first)
4872 {
4873 my $self = shift;
4874 my (%args) = @_;
4875 my $subname = ( caller(0) )[3];
4876 croak($subname . "() called as a procedure") unless(ref $self);
4877 debug(3,"DEBUG[",$subname,"]");
4878 my %valid_args = (
4879 'gi' => 1,
4880 'parent' => 1,
4881 'text' => 1,
4882 'id' => 1,
4883 'fileas' => 1,
4884 'role' => 1,
4885 'scheme' => 1,
4886 );
4887 foreach my $arg (keys %args)
4888 {
4889 croak($subname,"(): invalid argument '",$arg,"'")
4890 if(!$valid_args{$arg});
4891 }
4892  
4893 my $gi = $args{gi};
4894 unless($gi)
4895 {
4896 $self->add_error($subname,"(): no gi specified");
4897 return;
4898 }
4899  
4900 my $text = $args{text};
4901 unless($text)
4902 {
4903 $self->add_error($subname,"(): no text specified");
4904 return;
4905 }
4906  
4907 my $newid = $args{id};
4908 my $idelem;
4909 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
4910  
4911 my $element = $self->{twigroot}->first_descendant(qr/^ $gi $/ix);
4912 my $meta;
4913 my $dcmeta;
4914 my $parent;
4915 my %dcatts;
4916  
4917 $self->fix_metastructure_basic();
4918 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
4919 if($args{parent});
4920 $meta = $self->{twigroot}->first_child('metadata');
4921 $dcmeta = $meta->first_child('dc-metadata');
4922 $parent = $parent || $dcmeta || $meta;
4923 if($parent->gi eq 'metadata')
4924 {
4925 %dcatts = (
4926 'file-as' => 'opf:file-as',
4927 'role' => 'opf:role',
4928 'scheme' => 'opf:scheme',
4929 );
4930 }
4931 else
4932 {
4933 %dcatts = (
4934 'file-as' => 'file-as',
4935 'role' => 'role',
4936 'scheme' => 'scheme'
4937 );
4938 }
4939  
4940  
4941 if($element)
4942 {
4943 debug(2,"DEBUG: updating '",$gi,"'");
4944 if($element->att('opf:file-as') && $args{fileas})
4945 {
4946 debug(3,"DEBUG: setting opf:file-as '",$args{fileas},"'");
4947 $element->set_att('opf:file-as',$args{fileas});
4948 }
4949 elsif($args{fileas})
4950 {
4951 debug(3,"DEBUG: setting file-as '",$args{fileas},"'");
4952 $element->set_att('file-as',$args{fileas});
4953 }
4954 if($element->att('opf:role') && $args{role})
4955 {
4956 debug(3,"DEBUG: setting opf:role '",$args{role},"'");
4957 $element->set_att('opf:role',$args{role});
4958 }
4959 elsif($args{role})
4960 {
4961 debug(3,"DEBUG: setting role '",$args{role},"'");
4962 $element->set_att('role',$args{role});
4963 }
4964 if($element->att('opf:scheme') && $args{scheme})
4965 {
4966 debug(3,"DEBUG: setting opf:scheme '",$args{scheme},"'");
4967 $element->set_att('opf:scheme',$args{scheme});
4968 }
4969 elsif($args{scheme})
4970 {
4971 debug(3,"DEBUG: setting scheme '",$args{scheme},"'");
4972 $element->set_att('scheme',$args{scheme});
4973 }
4974 debug(3,"DEBUG: setting text");
4975 $element->set_text($text);
4976  
4977 unless($element->parent->gi eq $parent->gi)
4978 {
4979 debug(2,"DEBUG: moving <",$element->gi,"> under <",
4980 $parent->gi,">");
4981 $element->move('last_child',$parent);
4982 }
4983 }
4984 else
4985 {
4986 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
4987 $element = $parent->insert_new_elt('last_child',$gi);
4988 $element->set_att($dcatts{'file-as'},$args{fileas})
4989 if($args{fileas});
4990 $element->set_att($dcatts{'role'},$args{role})
4991 if($args{role});
4992 $element->set_att($dcatts{'scheme'},$args{scheme})
4993 if($args{scheme});
4994 $element->set_text($text);
4995 }
4996  
4997 if($idelem && $idelem->cmp($element) )
4998 {
4999 $self->add_warning(
5000 $subname,"(): reassigning id '",$newid,
5001 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
5002 );
5003 $idelem->del_att('id');
5004 }
5005 $element->set_att('id' => $newid) if($newid);
5006 return 1;
5007 }
5008  
5009  
5010 =head2 set_opffile($filename)
5011  
5012 Sets the filename used to store the OPF metadata.
5013  
5014 Returns 1 on success; sets an error message and returns undef if no
5015 filename was specified.
5016  
5017 =cut
5018  
5019 sub set_opffile :method ## no critic (Always unpack @_ first)
5020 {
5021 my $self = shift;
5022 my ($filename) = @_;
5023 my $subname = ( caller(0) )[3];
5024 croak($subname . "() called as a procedure") unless(ref $self);
5025 debug(2,"DEBUG[",$subname,"]");
5026  
5027 unless($filename)
5028 {
5029 debug(1,$subname,"(): no filename specified!");
5030 $self->add_warning($subname,"(): no filename specified!");
5031 return;
5032 }
5033 $self->{opffile} = $filename;
5034 return 1;
5035 }
5036  
5037  
5038 =head2 set_retailprice(%args)
5039  
5040 Sets the Mobipocket-specific <SRP> element (Suggested Retail Price),
5041 creating or deleting it as necessary.
5042  
5043 If a new element has to be created, L</fix_metastructure_oeb12> is
5044 called to ensure that <x-metadata> exists and the element is created
5045 under <x-metadata>, as Mobipocket elements are not recognized by
5046 Mobipocket's software when placed directly under <metadata>
5047  
5048 =head3 Arguments
5049  
5050 =over
5051  
5052 =item * C<text>
5053  
5054 The price to set as the text of the element. If this is undefined,
5055 the method sets an error and returns undef. If it is set but false,
5056 any existing <SRP> element is deleted.
5057  
5058 =item * C<currency> (optional)
5059  
5060 The value to set on the 'Currency' attribute. If not provided,
5061 defaults to 'USD' (US Dollars)
5062  
5063 =back
5064  
5065 =cut
5066  
5067 sub set_retailprice :method ## no critic (Always unpack @_ first)
5068 {
5069 my $self = shift;
5070 my %args = @_;
5071 my $subname = ( caller(0) )[3];
5072 croak($subname . "() called as a procedure") unless(ref $self);
5073 debug(2,"DEBUG[",$subname,"]");
5074 $self->twigcheck;
5075  
5076 my %valid_args = (
5077 'text' => 1,
5078 'currency' => 1,
5079 );
5080  
5081 foreach my $arg (keys %args)
5082 {
5083 croak($subname,"(): invalid argument '",$arg,"'")
5084 if(!$valid_args{$arg});
5085 }
5086 unless(defined $args{text})
5087 {
5088 $self->add_error($subname,"(): text not defined");
5089 return;
5090 }
5091  
5092 my $xmeta;
5093 my $element;
5094 my @elements;
5095  
5096 if($args{text})
5097 {
5098 $element = $self->{twigroot}->first_descendant(qr/^ SRP $/ix);
5099 unless($element)
5100 {
5101 $self->fix_metastructure_oeb12();
5102 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
5103 $element = $xmeta->insert_new_elt('last_child','SRP');
5104 }
5105 $element->set_text($args{text});
5106 $element->set_att('Currency',$args{currency}) if($args{currency});
5107 }
5108 else
5109 {
5110 @elements = $self->{twigroot}->descendants(qr/^ SRP $/ix);
5111 foreach my $el (@elements)
5112 {
5113 debug(2,"DEBUG: deleting <SRP>");
5114 $el->delete;
5115 }
5116 }
5117 return 1;
5118 }
5119  
5120  
5121 =head2 set_primary_author(%args)
5122  
5123 Sets the text, id, file-as, and role attributes of the primary author
5124 element (see L</primary_author()> for details on how this is found),
5125 or if no primary author exists, creates a new element containing the
5126 information.
5127  
5128 This method calls L</fix_metastructure_basic()> to enforce the
5129 presence of the <metadata> element. When creating a new element, the
5130 method will use the OEB 1.2 element name and create the element
5131 underneath <dc-metadata> if an existing <dc-metadata> element is found
5132 underneath <metadata>. If no existing <dc-metadata> element is found,
5133 the new element will be created with the OPF 2.0 element name directly
5134 underneath <metadata>. Regardless, it is probably a good idea to call
5135 L</fix_oeb12()> or L</fix_opf20()> after calling this method to ensure
5136 a consistent scheme.
5137  
5138 =head3 Arguments
5139  
5140 Three optional named arguments can be passed:
5141  
5142 =over
5143  
5144 =item * C<text>
5145  
5146 Specifies the author text to set. If omitted and a primary author
5147 element exists, the text will be left as is; if omitted and a primary
5148 author element cannot be found, an error message will be generated and
5149 the method will return undef.
5150  
5151 =item * C<fileas>
5152  
5153 Specifies the 'file-as' attribute to set. If omitted and a primary
5154 author element exists, any existing attribute will be left untouched;
5155 if omitted and a primary author element cannot be found, the newly
5156 created element will not have this attribute.
5157  
5158 =item * C<id>
5159  
5160 Specifies the 'id' attribute to set. If this is specified, and the id
5161 is already in use, a warning will be added but the method will
5162 continue, removing the id attribute from the element that previously
5163 contained it.
5164  
5165 If this is omitted and a primary author element exists, any existing
5166 id will be left untouched; if omitted and a primary author element
5167 cannot be found, the newly created element will not have an id set.
5168  
5169 =back
5170  
5171 If called with no arguments, the only effect this method has is to
5172 enforce that either an 'opf:role' or 'role' attribute is set to 'aut'
5173 on the primary author element.
5174  
5175 =head3 Return values
5176  
5177 Returns 1 if successful, returns undef and sets an error message if
5178 the author argument is missing and no primary author element was
5179 found.
5180  
5181 =cut
5182  
5183 sub set_primary_author :method ## no critic (Always unpack @_ first)
5184 {
5185 my $self = shift;
5186 my (%args) = @_;
5187 my $subname = ( caller(0) )[3];
5188 croak($subname . "() called as a procedure") unless(ref $self);
5189 debug(2,"DEBUG[",$subname,"]");
5190 my %valid_args = (
5191 'text' => 1,
5192 'fileas' => 1,
5193 'id' => 1,
5194 );
5195 foreach my $arg (keys %args)
5196 {
5197 croak($subname,"(): invalid argument '",$arg,"'")
5198 if(!$valid_args{$arg});
5199 }
5200  
5201 my $twigroot = $self->{twigroot};
5202 $self->fix_metastructure_basic();
5203 my $meta = $twigroot->first_child('metadata');
5204 my $dcmeta = $meta->first_child('dc-metadata');
5205 my $element;
5206 my $newauthor = $args{text};
5207 my $newfileas = $args{fileas};
5208 my $newid = $args{id};
5209 my $idelem;
5210 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
5211  
5212 $element = $twigroot->first_descendant(\&twigelt_is_author);
5213 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
5214  
5215 unless($element)
5216 {
5217 unless($newauthor)
5218 {
5219 add_error(
5220 $subname,
5221 "(): cannot create a new author element when the author is not specified");
5222 return;
5223 }
5224 if($dcmeta)
5225 {
5226 $element = $dcmeta->insert_new_elt('last_child','dc:Creator');
5227 $element->set_att('role' => 'aut');
5228 $element->set_att('file-as' => $newfileas) if($newfileas);
5229 }
5230 else
5231 {
5232 $element = $meta->insert_new_elt('last_child','dc:creator');
5233 $element->set_att('opf:role' => 'aut');
5234 $element->set_att('opf:file-as' => $newfileas) if($newfileas);
5235 }
5236 } # unless($element)
5237 $element->set_text($newauthor);
5238  
5239 if($idelem && $idelem->cmp($element) )
5240 {
5241 $self->add_warning(
5242 $subname,"(): reassigning id '",$newid,
5243 "' from a '",$idelem->gi,"' element!"
5244 );
5245 $idelem->del_att('id');
5246 }
5247 $element->set_att('id' => $newid) if($newid);
5248 return 1;
5249 }
5250  
5251  
5252 =head2 C<set_publisher(%args)>
5253  
5254 Sets the text and optionally the ID of the first dc:publisher element
5255 found (case-insensitive). Creates the element if one did not exist.
5256 If a <dc-metadata> element exists underneath <metadata>, the publisher
5257 element will be created underneath the <dc-metadata> in OEB 1.2
5258 format, otherwise the title element is created underneath <metadata>
5259 in OPF 2.0 format.
5260  
5261 Returns 1 on success, returns undef if no publisher was specified.
5262  
5263 =head3 Arguments
5264  
5265 C<set_publisher()> takes one required and one optional named argument
5266  
5267 =over
5268  
5269 =item C<text>
5270  
5271 This specifies the publisher name to set as the text of the element.
5272 If not specified, the method returns undef.
5273  
5274 =item C<id> (optional)
5275  
5276 This specifies the ID to set on the element. If set and the ID is
5277 already in use, a warning is logged and the ID is removed from the
5278 other location and assigned to the element.
5279  
5280 =back
5281  
5282 =head3 Example
5283  
5284 $retval = $ebook->set_publisher('text' => 'My Publishing House',
5285 'id' => 'mypubid');
5286  
5287 =cut
5288  
5289 sub set_publisher :method ## no critic (Always unpack @_ first)
5290 {
5291 my $self = shift;
5292 my (%args) = @_;
5293 my $subname = ( caller(0) )[3];
5294 croak($subname . "() called as a procedure") unless(ref $self);
5295 debug(2,"DEBUG[",$subname,"]");
5296 my %valid_args = (
5297 'text' => 1,
5298 'id' => 1,
5299 );
5300 foreach my $arg (keys %args)
5301 {
5302 croak($subname,"(): invalid argument '",$arg,"'")
5303 if(!$valid_args{$arg});
5304 }
5305  
5306 my $publisher = $args{text};
5307 return unless($publisher);
5308  
5309 my $newid = $args{id};
5310 my $idelem;
5311 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
5312  
5313 $self->fix_metastructure_basic();
5314 my $element = $self->{twigroot}->first_descendant(qr/^dc:publisher$/ix);
5315 my $meta = $self->{twigroot}->first_child('metadata');
5316 my $dcmeta = $meta->first_child('dc-metadata');
5317  
5318 if(!$element && $dcmeta)
5319 {
5320 $element = $dcmeta->insert_new_elt('last_child','dc:Publisher');
5321 }
5322 elsif(!$element)
5323 {
5324 $element = $meta->insert_new_elt('last_child','dc:publisher');
5325 }
5326 $element->set_text($publisher);
5327 if($idelem && $idelem->cmp($element) )
5328 {
5329 $self->add_warning(
5330 $subname,"(): reassigning id '",$newid,
5331 "' from a '",$idelem->gi,"' element!"
5332 );
5333 $idelem->del_att('id');
5334 }
5335 $element->set_att('id' => $newid) if($newid);
5336 return 1;
5337 }
5338  
5339  
5340 =head2 set_review(%args)
5341  
5342 Sets the text and optionally ID of the first <Review> element found
5343 (case-insensitive), creating the element if one did not exist.
5344  
5345 This is a Mobipocket-specific element and if it needs to be created it
5346 will always be created under <x-metadata> with
5347 L</fix_metastructure_oeb12()> called to ensure that <x-metadata>
5348 exists.
5349  
5350 Returns 1 on success, returns undef if no review text was specified
5351  
5352 =head3 Arguments
5353  
5354 =over
5355  
5356 =item C<text>
5357  
5358 This specifies the description to use as the text of the element. If
5359 not specified, the method returns undef.
5360  
5361 =item C<id> (optional)
5362  
5363 This specifies the ID to set on the element. If set and the ID is
5364 already in use, a warning is logged and the ID is removed from the
5365 other location and assigned to the element.
5366  
5367 =back
5368  
5369 =head3 Example
5370  
5371 $retval = $ebook->set_review('text' => 'This book is perfect!',
5372 'id' => 'revid');
5373  
5374 =cut
5375  
5376 sub set_review :method ## no critic (Always unpack @_ first)
5377 {
5378 my $self = shift;
5379 my (%args) = @_;
5380 my $subname = ( caller(0) )[3];
5381 croak($subname . "() called as a procedure") unless(ref $self);
5382 debug(2,"DEBUG[",$subname,"]");
5383 my %valid_args = (
5384 'text' => 1,
5385 'id' => 1,
5386 );
5387 foreach my $arg (keys %args)
5388 {
5389 croak($subname,"(): invalid argument '",$arg,"'")
5390 if(!$valid_args{$arg});
5391 }
5392  
5393 my $text = $args{text};
5394 unless($text)
5395 {
5396 $self->add_error($subname,"(): no text specified");
5397 return;
5398 }
5399  
5400 $self->fix_metastructure_oeb12();
5401 $self->set_metadata(gi => 'Review',
5402 parent => 'x-metadata',
5403 text => $args{text},
5404 id => $args{id});
5405  
5406 return 1;
5407 }
5408  
5409  
5410 =head2 C<set_rights(%args)>
5411  
5412 Sets the text of the first dc:rights or dc:copyrights element found
5413 (case-insensitive). If the element found has the gi of dc:copyrights,
5414 it will be changed to dc:rights. This is to correct certain
5415 noncompliant Mobipocket files.
5416  
5417 Creates the element if one did not exist. If a <dc-metadata> element
5418 exists underneath <metadata>, the title element will be created
5419 underneath the <dc-metadata> in OEB 1.2 format, otherwise the title
5420 element is created underneath <metadata> in OPF 2.0 format.
5421  
5422 Returns 1 on success, returns undef if no rights string was specified.
5423  
5424 =head3 Arguments
5425  
5426 =over
5427  
5428 =item * C<text>
5429  
5430 This specifies the text of the element. If not specified, the method
5431 returns undef.
5432  
5433 =item * C<id> (optional)
5434  
5435 This specifies the ID to set on the element. If set and the ID is
5436 already in use, a warning is logged but the method continues anyway.
5437  
5438 =back
5439  
5440 =cut
5441  
5442 sub set_rights :method ## no critic (Always unpack @_ first)
5443 {
5444 my $self = shift;
5445 my (%args) = @_;
5446 my $subname = ( caller(0) )[3];
5447 croak($subname . "() called as a procedure") unless(ref $self);
5448 debug(2,"DEBUG[",$subname,"]");
5449 my %valid_args = (
5450 'text' => 1,
5451 'id' => 1,
5452 );
5453 foreach my $arg (keys %args)
5454 {
5455 croak($subname,"(): invalid argument '",$arg,"'")
5456 if(!$valid_args{$arg});
5457 }
5458 my $rights = $args{text};
5459 return unless($rights);
5460 my $newid = $args{id};
5461 my $idelem;
5462 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
5463  
5464 $self->fix_metastructure_basic();
5465 my $element = $self->{twigroot}->first_descendant(qr/^dc:(copy)?rights$/ix);
5466 my $meta = $self->{twigroot}->first_child('metadata');
5467 my $dcmeta = $meta->first_child('dc-metadata');
5468 my $parent = $dcmeta || $meta;
5469  
5470 $element ||= $parent->insert_new_elt('last_child','dc:rights');
5471 $element->set_text($rights);
5472 $element->set_gi('dc:Rights') if($element->gi eq 'dc:Copyrights');
5473 $element->set_gi('dc:rights') if($element->gi eq 'dc:copyrights');
5474 if($idelem && $idelem->cmp($element) )
5475 {
5476 $self->add_warning(
5477 $subname,"(): reassigning id '",$newid,
5478 "' from a '",$idelem->gi,"' element!"
5479 );
5480 $idelem->del_att('id');
5481 }
5482 $element->set_att('id' => $newid) if($newid);
5483 return 1;
5484 }
5485  
5486  
5487 =head2 C<set_spec($spec)>
5488  
5489 Sets the OEB specification to match when modifying OPF data.
5490 Allowable values are 'OEB12', 'OPF20', and 'MOBI12'.
5491  
5492 Returns 1 if successful; returns undef and sets an error message if an
5493 unknown specification was set.
5494  
5495 =cut
5496  
5497 sub set_spec :method ## no critic (Always unpack @_ first)
5498 {
5499 my $self = shift;
5500 my ($spec) = @_;
5501 my $subname = ( caller(0) )[3];
5502 croak($subname . "() called as a procedure") unless(ref $self);
5503 debug(2,"DEBUG[",$subname,"]");
5504  
5505 unless($validspecs{$spec})
5506 {
5507 $self->add_error($subname,"(): invalid specification '",$spec,"'");
5508 return;
5509 }
5510 $self->{spec} = $validspecs{$spec};
5511 return 1;
5512 }
5513  
5514  
5515 =head2 C<set_title(%args)>
5516  
5517 Sets the text or id of the first dc:title element found
5518 (case-insensitive). Creates the element if one did not exist. If a
5519 <dc-metadata> element exists underneath <metadata>, the title element
5520 will be created underneath the <dc-metadata> in OEB 1.2 format,
5521 otherwise the title element is created underneath <metadata> in OPF
5522 2.0 format.
5523  
5524 =head3 Arguments
5525  
5526 set_title() takes two optional named arguments. If neither is
5527 specified, the method will do nothing.
5528  
5529 =over
5530  
5531 =item * C<text>
5532  
5533 This specifies the text of the element. If not specified, and no
5534 title element is found, an error will be set and the method will
5535 return undef -- set_title() will refuse to create a dc:title element
5536 with no text.
5537  
5538 =item * C<id>
5539  
5540 This specifies the ID to set on the element. If set and the ID is
5541 already in use, a warning is logged but the method continues anyway.
5542  
5543 =back
5544  
5545 =cut
5546  
5547 sub set_title :method ## no critic (Always unpack @_ first)
5548 {
5549 my $self = shift;
5550 my (%args) = @_;
5551 my $subname = ( caller(0) )[3];
5552 croak($subname . "() called as a procedure") unless(ref $self);
5553 debug(2,"DEBUG[",$subname,"]");
5554  
5555 my %valid_args = (
5556 'text' => 1,
5557 'id' => 1,
5558 );
5559 foreach my $arg (keys %args)
5560 {
5561 croak($subname,"(): invalid argument '",$arg,"'")
5562 if(!$valid_args{$arg});
5563 }
5564 my $title = $args{text};
5565 my $newid = $args{id};
5566 my $idelem;
5567 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
5568  
5569 $self->fix_metastructure_basic();
5570 my $element = $self->{twigroot}->first_descendant(qr/^dc:title$/ix);
5571 my $meta = $self->{twigroot}->first_child('metadata');
5572 my $dcmeta = $meta->first_child('dc-metadata');
5573 my $parent = $dcmeta || $meta;
5574 unless($element)
5575 {
5576 unless($title)
5577 {
5578 add_error($subname,
5579 "(): no title specified, but no existing title found");
5580 return;
5581 }
5582 $element = $parent->insert_new_elt('last_child','dc:title');
5583 }
5584 $element->set_text($title) if($title);
5585  
5586 if($idelem && $idelem->cmp($element) )
5587 {
5588 $self->add_warning(
5589 $subname,"(): reassigning id '",$newid,
5590 "' from a '",$idelem->gi,"' element!"
5591 );
5592 $idelem->del_att('id');
5593 }
5594 $element->set_att('id' => $newid) if($newid);
5595 return 1;
5596 }
5597  
5598  
5599 =head2 C<set_type(%args)>
5600  
5601 Sets the text and optionally the ID of the first dc:type element
5602 found (case-insensitive). Creates the element if one did not exist.
5603 If a <dc-metadata> element exists underneath <metadata>, the publisher
5604 element will be created underneath the <dc-metadata> in OEB 1.2
5605 format, otherwise the title element is created underneath <metadata>
5606 in OPF 2.0 format.
5607  
5608 Returns 1 on success, returns undef if no publisher was specified.
5609  
5610 =head3 Arguments
5611  
5612 C<set_type()> takes one required and one optional named argument
5613  
5614 =over
5615  
5616 =item C<text>
5617  
5618 This specifies the publisher name to set as the text of the element.
5619 If not specified, the method returns undef.
5620  
5621 =item C<id> (optional)
5622  
5623 This specifies the ID to set on the element. If set and the ID is
5624 already in use, a warning is logged and the ID is removed from the
5625 other location and assigned to the element.
5626  
5627 =back
5628  
5629 =head3 Example
5630  
5631 $retval = $ebook->set_type('text' => 'Short Story',
5632 'id' => 'mytypeid');
5633  
5634 =cut
5635  
5636 sub set_type :method ## no critic (Always unpack @_ first)
5637 {
5638 my $self = shift;
5639 my (%args) = @_;
5640 my $subname = ( caller(0) )[3];
5641 croak($subname . "() called as a procedure") unless(ref $self);
5642 debug(2,"DEBUG[",$subname,"]");
5643 my %valid_args = (
5644 'text' => 1,
5645 'id' => 1,
5646 );
5647 foreach my $arg (keys %args)
5648 {
5649 croak($subname,"(): invalid argument '",$arg,"'")
5650 if(!$valid_args{$arg});
5651 }
5652  
5653 my $text = $args{text};
5654 return unless($text);
5655  
5656 my $newid = $args{id};
5657 my $idelem;
5658 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
5659  
5660 $self->fix_metastructure_basic();
5661 my $element = $self->{twigroot}->first_descendant(qr/^dc:type$/ix);
5662 my $meta = $self->{twigroot}->first_child('metadata');
5663 my $dcmeta = $meta->first_child('dc-metadata');
5664  
5665 if(!$element && $dcmeta)
5666 {
5667 $element = $dcmeta->insert_new_elt('last_child','dc:Type');
5668 }
5669 elsif(!$element)
5670 {
5671 $element = $meta->insert_new_elt('last_child','dc:type');
5672 }
5673 $element->set_text($text);
5674 if($idelem && $idelem->cmp($element) )
5675 {
5676 $self->add_warning(
5677 $subname,"(): reassigning id '",$newid,
5678 "' from a '",$idelem->gi,"' element!"
5679 );
5680 $idelem->del_att('id');
5681 }
5682 $element->set_att('id' => $newid) if($newid);
5683 return 1;
5684 }
5685  
5686  
5687 ################################
5688 ########## PROCEDURES ##########
5689 ################################
5690  
5691 =head1 PROCEDURES
5692  
5693 All procedures are exportable, but none are exported by default. All
5694 procedures can be exported by using the ":all" tag.
5695  
5696  
5697 =head2 C<create_epub_container($opffile)>
5698  
5699 Creates the XML file META-INF/container.xml pointing to the
5700 specified OPF file.
5701  
5702 Creates the META-INF directory if necessary. Will destroy any
5703 non-directory file named 'META-INF' in the current directory. If
5704 META-INF/container.xml already exists, it will rename that file to
5705 META-INF/container.xml.backup.
5706  
5707 =head3 Arguments
5708  
5709 =over
5710  
5711 =item $opffile
5712  
5713 The OPF filename (and path, if necessary) to use in the container. If
5714 not specified, looks for a sole OPF file in the current working
5715 directory. Fails if more than one is found.
5716  
5717 =back
5718  
5719 =head3 Return values
5720  
5721 =over
5722  
5723 =item Returns a twig representing the container data if successful, undef
5724 otherwise
5725  
5726 =back
5727  
5728 =cut
5729  
5730 sub create_epub_container
5731 {
5732 my ($opffile) = @_;
5733 my $subname = ( caller(0) )[3];
5734 debug(2,"DEBUG[",$subname,"]");
5735  
5736 my $twig;
5737 my $twigroot;
5738 my $rootfiles;
5739 my $element;
5740 my $fh_container;
5741  
5742 if($opffile eq '') { return; }
5743  
5744 if(-e 'META-INF')
5745 {
5746 if(! -d 'META-INF')
5747 {
5748 unlink('META-INF') or return;
5749 mkdir('META-INF') or return;
5750 }
5751 }
5752 else { mkdir('META-INF') or return; }
5753  
5754 $twig = XML::Twig->new(
5755 output_encoding => 'utf-8',
5756 pretty_print => 'record'
5757 );
5758  
5759 $element = XML::Twig::Elt->new('container');
5760 $element->set_att('version' => '1.0',
5761 'xmlns' => 'urn:oasis:names:tc:opendocument:xmlns:container');
5762 $twig->set_root($element);
5763 $twigroot = $twig->root;
5764  
5765 $rootfiles = $twigroot->insert_new_elt('first_child','rootfiles');
5766 $element = $rootfiles->insert_new_elt('first_child','rootfile');
5767 $element->set_att('full-path',$opffile);
5768 $element->set_att('media-type','application/oebps-package+xml');
5769  
5770  
5771 # Backup existing file
5772 if(-e 'META-INF/container.xml')
5773 {
5774 rename('META-INF/container.xml','META-INF/container.xml.backup')
5775 or croak($subname,"(): could not backup container.xml!");
5776 }
5777  
5778 # Twig handles utf-8 on its own. Setting binmode :utf8 here will
5779 # cause a double-conversion.
5780 open($fh_container,'>','META-INF/container.xml')
5781 or croak($subname,"(): could not write to 'META-INF/container.xml'\n");
5782 $twig->print(\*$fh_container);
5783 close($fh_container)
5784 or croak($subname,"(): could not close 'META-INF/container.xml'\n");
5785 return $twig;
5786 }
5787  
5788  
5789 =head2 C<create_epub_mimetype()>
5790  
5791 Creates a file named 'mimetype' in the current working directory
5792 containing 'application/epub+zip' (no trailing newline)
5793  
5794 Destroys and overwrites that file if it exists.
5795  
5796 Returns the mimetype string if successful, undef otherwise.
5797  
5798 =cut
5799  
5800 sub create_epub_mimetype
5801 {
5802 my $subname = ( caller(0) )[3];
5803 debug(2,"DEBUG[",$subname,"]");
5804  
5805 my $mimetype = "application/epub+zip";
5806 my $fh_mimetype;
5807  
5808 open($fh_mimetype,">",'mimetype') or return;
5809 print {*$fh_mimetype} $mimetype;
5810 close($fh_mimetype) or croak($subname,"(): failed to close filehandle [$!]");
5811  
5812 return $mimetype;
5813 }
5814  
5815  
5816 =head2 C<debug($level,@message)>
5817  
5818 Prints a debugging message to C<STDERR> if package variable C<$debug>
5819 is greater than or equal to C<$level>. A trailing newline is
5820 appended, and should not be part of @message.
5821  
5822 Returns true or dies.
5823  
5824 =cut
5825  
5826 sub debug
5827 {
5828 my ($level,@message) = @_;
5829 my $subname = ( caller(0) )[3];
5830 croak($subname,"(): no debugging level specified") unless($level);
5831 croak($subname,"(): invalid debugging level '",$level,"'")
5832 unless( $level =~ /^\d$/ );
5833 croak($subname,"(): no message specified") unless(@message);
5834 print {*STDERR} @message,"\n" if($debug >= $level);
5835 return 1;
5836 }
5837  
5838  
5839 =head2 C<excerpt_line($text)>
5840  
5841 Takes as an argument a list of text pieces that will be joined. If
5842 the joined length is less than 70, all of the joined text is returned.
5843  
5844 If the joined length is greater than 70, the return string is the
5845 first 30 characters followed by C<' [...] '> followed by the last 30
5846 characters.
5847  
5848 =cut
5849  
5850 sub excerpt_line
5851 {
5852 my @parts = @_;
5853 my $subname = ( caller(0) )[3];
5854 my $text = join('',@parts);
5855 if(length($text) > 70)
5856 {
5857 $text =~ /^ (.{30}) .*? (.{30}) $/sx;
5858 return ($1 . ' [...] ' . $2);
5859 }
5860 else { return $text; }
5861 }
5862  
5863  
5864 =head2 C<find_in_path($pattern,@extradirs)>
5865  
5866 Searches through C<$ENV{PATH}> (and optionally any additional
5867 directories specified in C<@extradirs>) for the first regular file
5868 matching C<$pattern>. C<$pattern> itself can take two forms: if
5869 passed a C<qr//> regular expression, that expression is used directly.
5870 If passed any other string, that string will be used for a
5871 case-insensitive exact match where the extension '.bat', '.com', or
5872 '.exe' is optional (i.e. the final pattern will be
5873 C<qr/^ $pattern (\.bat|\.com|\.exe)? $/ix>).
5874  
5875 Returns the first match found, or undef if there were no matches or if
5876 no pattern was specified.
5877  
5878 =cut
5879  
5880 sub find_in_path
5881 {
5882 my ($pattern,@extradirs) = @_;
5883 return unless($pattern);
5884 my $subname = ( caller(0) )[3];
5885 debug(3,"DEBUG[",$subname,"]");
5886  
5887 my $regexp;
5888 my @dirs;
5889 my $fh_dir;
5890 my @filelist;
5891 my $envsep = ':';
5892 my $filesep = '/';
5893 if($OSNAME eq 'MSWin32')
5894 {
5895 $envsep = ';';
5896 $filesep = "\\";
5897 }
5898  
5899 if(ref($pattern) eq 'Regexp') { $regexp = $pattern; }
5900 else { $regexp = qr/^ $pattern (\.bat|\.com|\.exe)? $/ix; }
5901  
5902 @dirs = split(/$envsep/,$ENV{PATH});
5903 unshift(@dirs,@extradirs) if(@extradirs);
5904 foreach my $dir (@dirs)
5905 {
5906 if(-d $dir)
5907 {
5908 if(opendir($fh_dir,$dir))
5909 {
5910 @filelist = grep { /$regexp/ } readdir($fh_dir);
5911 @filelist = grep { -f "$dir/$_" } @filelist;
5912 closedir($fh_dir);
5913  
5914 if(@filelist) { return $dir . $filesep . $filelist[0]; }
5915 }
5916 }
5917 }
5918 return;
5919 }
5920  
5921 =head2 C<find_links($filename)>
5922  
5923 Searches through a file for href and src attributes, and returns a
5924 list of unique links with any named anchors removed
5925 (e.g. 'myfile.html#part7' returns as just 'myfile.html'). If no links
5926 are found, or the file does not exist, returns undef.
5927  
5928 Does not check to see if the links are local. Requires that links be
5929 surrounded by double quotes, not single or left bare. Assumes that
5930 any link will not be broken across multiple lines, so it will (for
5931 example) fail to find:
5932  
5933 <img src=
5934 "myfile.jpg">
5935  
5936 though it can find:
5937  
5938 <img
5939 src="myfile.jpg">
5940  
5941 This also does not distinguish between local files and remote links.
5942  
5943 =cut
5944  
5945 sub find_links
5946 {
5947 my ($filename) = @_;
5948 return unless(-f $filename);
5949 my $subname = ( caller(0) )[3];
5950 debug(3,"DEBUG[",$subname,"]");
5951  
5952 my $fh;
5953 my %linkhash;
5954 my @links;
5955  
5956 open($fh,'<:raw',$filename)
5957 or croak($subname,"(): unable to open '",$filename,"'\n");
5958  
5959 while(<$fh>)
5960 {
5961 @links = /(?:href|src) \s* = \s* "
5962 ([^">]+)/gix;
5963 foreach my $link (@links)
5964 {
5965 # Strip off any named anchors
5966 $link =~ s/#.*$//;
5967 next unless($link);
5968 debug(2, "DEBUG: found link '",$link,"'");
5969 $linkhash{$link}++;
5970 }
5971 }
5972 if(%linkhash) { return keys(%linkhash); }
5973 else { return; }
5974 }
5975  
5976  
5977 =head2 C<find_opffile()>
5978  
5979 Attempts to locate an OPF file, first by calling
5980 L</get_container_rootfile()> to check the contents of
5981 C<META-INF/container.xml>, and then by looking for a single file with
5982 the extension C<.opf> in the current working directory.
5983  
5984 Returns the filename of the OPF file, or undef if nothing was found.
5985  
5986 =cut
5987  
5988 sub find_opffile
5989 {
5990 my $subname = ( caller(0) )[3];
5991 my $opffile = get_container_rootfile();
5992  
5993 if(!$opffile)
5994 {
5995 my @candidates = glob("*.opf");
5996 if(scalar(@candidates) > 1)
5997 {
5998 debug(1,"DEBUG: Multiple OPF files found, but no container",
5999 " to specify which one to choose!");
6000 return;
6001 }
6002 if(scalar(@candidates) < 1)
6003 {
6004 debug(1,"DEBUG: No OPF files found!");
6005 return;
6006 }
6007 $opffile = $candidates[0];
6008 }
6009 return $opffile;
6010 }
6011  
6012  
6013 =head2 C<fix_datestring($datestring)>
6014  
6015 Takes a date string and attempts to convert it to the limited subset
6016 of ISO8601 allowed by the OPF standard (YYYY, YYYY-MM, or YYYY-MM-DD).
6017  
6018 In the special case of finding MM/DD/YYYY, it assumes that it was a
6019 Mobipocket-mangled date, and not only converts it, but will strip the
6020 day information if the day is '01', and both the month and day
6021 information if both month and day are '01'. This is because
6022 Mobipocket Creator enforces a complete MM/DD/YYYY even if the month
6023 and day aren't known, and it is common practice to use 01 for an
6024 unknown value.
6025  
6026 =head3 Arguments
6027  
6028 =over
6029  
6030 =item $datestring
6031  
6032 A date string in a format recognizable by Date::Manip
6033  
6034 =back
6035  
6036 =head3 Returns $fixeddate
6037  
6038 =over
6039  
6040 =item $fixeddate : the corrected string, or undef on failure
6041  
6042 =back
6043  
6044 =cut
6045  
6046 sub fix_datestring
6047 {
6048 my ($datestring) = @_;
6049 return unless($datestring);
6050 my $subname = ( caller(0) )[3];
6051 debug(2,"DEBUG[",$subname,"]");
6052  
6053 my $date;
6054 my ($year,$month,$day);
6055 my $fixeddate;
6056  
6057 $_ = $datestring;
6058  
6059 debug(3,"DEBUG: checking M(M)/D(D)/YYYY");
6060 if(( ($month,$day,$year) = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/x ) == 3)
6061 {
6062 # We have a XX/XX/XXXX datestring
6063 debug(3,"DEBUG: found '",$month,"/",$day,"/",$year,"'");
6064 ($year,$month,$day) = ymd_validate($year,$month,$day);
6065 if($year)
6066 {
6067 $fixeddate = $year;
6068 $fixeddate .= sprintf("-%02u",$month)
6069 unless( ($month == 1) && ($day == 1) );
6070 $fixeddate .= sprintf("-%02u",$day) unless($day == 1);
6071 debug(3,"DEBUG: returning '",$fixeddate,"'");
6072 return $fixeddate;
6073 }
6074 }
6075  
6076 debug(3,"DEBUG: checking M(M)/YYYY");
6077 if(( ($month,$year) = /^(\d{1,2})\/(\d{4})$/x ) == 2)
6078 {
6079 # We have a XX/XXXX datestring
6080 debug(3,"DEBUG: found '",$month,"/",$year,"'");
6081 if($month <= 12)
6082 {
6083 # We probably have MM/YYYY
6084 $fixeddate = sprintf("%04u-%02u",$year,$month);
6085 debug(3,"DEBUG: returning '",$fixeddate,"'");
6086 return $fixeddate;
6087 }
6088 }
6089  
6090 # These regexps will reduce '2009-xx-01' to just 2009
6091 # We don't want this, so don't use them.
6092 # ($year,$month,$day) = /(\d{4})-?(\d{2})?-?(\d{2})?/;
6093 # ($year,$month,$day) = /(\d{4})(?:-?(\d{2})-?(\d{2}))?/;
6094  
6095 # Force exact match)
6096 debug(3,"DEBUG: checking YYYY-MM-DD");
6097 ($year,$month,$day) = /^(\d{4})-(\d{2})-(\d{2})$/x;
6098 ($year,$month,$day) = ymd_validate($year,$month,$day);
6099  
6100 if(!$year)
6101 {
6102 debug(3,"DEBUG: checking YYYYMMDD");
6103 ($year,$month,$day) = /^(\d{4})(\d{2})(\d{2})$/x;
6104 ($year,$month,$day) = ymd_validate($year,$month,$day);
6105 }
6106  
6107 if(!$year)
6108 {
6109 debug(3,"DEBUG: checking YYYY-M(M)");
6110 ($year,$month) = /^(\d{4})-(\d{1,2})$/x;
6111 ($year,$month) = ymd_validate($year,$month,undef);
6112 }
6113  
6114 if(!$year)
6115 {
6116 debug(3,"DEBUG: checking YYYY");
6117 ($year) = /^(\d{4})$/x;
6118 }
6119  
6120 # At this point, we've exhausted all of the common cases. We use
6121 # Date::Manip to hit all of the unlikely ones as well. This comes
6122 # with a drawback: Date::Manip doesn't distinguish between 2008
6123 # and 2008-01-01, but we should have covered that above.
6124 #
6125 # Note that Date::Manip will die on MS Windows system unless the
6126 # TZ environment variable is set in a specific manner.
6127 # See:
6128 # http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES
6129  
6130 if(!$year)
6131 {
6132 $date = ParseDate($datestring);
6133 $year = UnixDate($date,"%Y");
6134 $month = UnixDate($date,"%m");
6135 $day = UnixDate($date,"%d");
6136 debug(2,"DEBUG: Date::Manip found '",UnixDate($date,"%Y-%m-%d"),"'");
6137 }
6138  
6139 if($year)
6140 {
6141 # If we still have a $year, $month and $day either don't exist
6142 # or are plausibly valid.
6143 print {*STDERR} "DEBUG: found year=",$year," " if($debug >= 2);
6144 $fixeddate = sprintf("%04u",$year);
6145 if($month)
6146 {
6147 print {*STDERR} "month=",$month," " if($debug >= 2);
6148 $fixeddate .= sprintf("-%02u",$month);
6149 if($day)
6150 {
6151 print {*STDERR} "day=",$day if($debug >= 2);
6152 $fixeddate .= sprintf("-%02u",$day);
6153 }
6154 }
6155 print {*STDERR} "\n" if($debug >= 2);
6156 debug(2,"DEBUG: returning '",$fixeddate,"'");
6157 return $fixeddate if($fixeddate);
6158 }
6159  
6160 if(!$year)
6161 {
6162 debug(3,"fix_date: didn't find a valid date in '",$datestring,"'!");
6163 return;
6164 }
6165 elsif($debug)
6166 {
6167 print {*STDERR} "DEBUG: found ",sprintf("04u",$year);
6168 print {*STDERR} sprintf("-02u",$month) if($month);
6169 print {*STDERR} sprintf("-02u",$day),"\n" if($day);
6170 }
6171  
6172 $fixeddate = sprintf("%04u",$year);
6173 $fixeddate .= sprintf("-%02u-%02u",$month,$day);
6174 return $fixeddate;
6175 }
6176  
6177  
6178 =head2 C<get_container_rootfile($container)>
6179  
6180 Opens and parses an OPS/epub container, extracting the 'full-path'
6181 attribute of element 'rootfile'
6182  
6183 =head3 Arguments
6184  
6185 =over
6186  
6187 =item $container
6188  
6189 The OPS container to parse. Defaults to 'META-INF/container.xml'
6190  
6191 =back
6192  
6193 =head3 Return values
6194  
6195 =over
6196  
6197 =item Returns a string containing the rootfile on success, undef on failure.
6198  
6199 =back
6200  
6201 =cut
6202  
6203 sub get_container_rootfile
6204 {
6205 my ($container) = @_;
6206 my $subname = ( caller(0) )[3];
6207 debug(2,"DEBUG[",$subname,"]");
6208  
6209 my $twig = XML::Twig->new();
6210 my $rootfile;
6211 my $retval = undef;
6212  
6213 $container = 'META-INF/container.xml' if(! $container);
6214  
6215 if(-f $container)
6216 {
6217 $twig->parsefile($container) or return;
6218 $rootfile = $twig->root->first_descendant('rootfile');
6219 return unless($rootfile);
6220 $retval = $rootfile->att('full-path');
6221 }
6222 return $retval;
6223 }
6224  
6225  
6226 =head2 C<hexstring($bindata)>
6227  
6228 Takes as an argument a scalar containing a sequence of binary bytes.
6229 Returns a string converting each octet of the data to its two-digit
6230 hexadecimal equivalent. There is no leading "0x" on the string.
6231  
6232 =cut
6233  
6234 sub hexstring
6235 {
6236 my $data = shift;
6237 my $subname = ( caller(0) )[3];
6238 debug(4,"DEBUG[",$subname,"]");
6239  
6240 croak($subname,"(): no data provided")
6241 unless($data);
6242  
6243 my $byte;
6244 my $retval = '';
6245 my $pos = 0;
6246  
6247 while($pos < length($data))
6248 {
6249 $byte = unpack("C",substr($data,$pos,1));
6250 $retval .= sprintf("%02x",$byte);
6251 $pos++;
6252 }
6253 return $retval;
6254 }
6255  
6256  
6257 =head2 C<print_memory($label)>
6258  
6259 Checks /proc/$PID/statm and prints out a line to STDERR showing the
6260 current memory usage. This is a debugging tool that will likely fail
6261 to do anything useful on a system without a /proc system compatible
6262 with Linux.
6263  
6264 =head3 Arguments
6265  
6266 =over
6267  
6268 =item $label
6269  
6270 If defined, will be output along with the memory usage.
6271  
6272 =back
6273  
6274 Returns 1 on success, undef otherwise.
6275  
6276 =cut
6277  
6278 sub print_memory
6279 {
6280 my ($label) = @_;
6281 my $subname = ( caller(0) )[3];
6282 debug(2,"DEBUG[",$subname,"]");
6283  
6284 my @mem;
6285 my $fh_procstatm;
6286  
6287 if(!open($fh_procstatm,"<","/proc/$$/statm"))
6288 {
6289 print "[",$label,"]: " if(defined $label);
6290 print "Couldn't open /proc/$$/statm [$!]\n";
6291 return;
6292 }
6293  
6294 @mem = split(/\s+/,<$fh_procstatm>);
6295 close($fh_procstatm);
6296  
6297 # @mem[0]*4 = size (kb)
6298 # @mem[1]*4 = resident (kb)
6299 # @mem[2]*4 = shared (kb)
6300 # @mem[3] = trs
6301 # @mem[4] = lrs
6302 # @mem[5] = drs
6303 # @mem[6] = dt
6304  
6305 print "Current memory usage";
6306 print " [".$label."]" if(defined $label);
6307 print ": size=",$mem[0]*4,"k";
6308 print " resident=",$mem[1]*4,"k";
6309 print " shared=",$mem[2]*4,"k\n";
6310 return 1;
6311 }
6312  
6313  
6314  
6315 =head2 C<split_metadata($metahtmlfile, $metafile)>
6316  
6317 Takes a psuedo-HTML containing one or more <metadata>...</metadata>
6318 blocks and splits out the metadata blocks into an XML file ready to be
6319 used as an OPF document. The input HTML file is rewritten without the
6320 metadata.
6321  
6322 If $metafile (or the temporary HTML-only file created during the
6323 split) already exists, it will be moved to filename.backup.
6324  
6325 =head3 Arguments
6326  
6327 =over
6328  
6329 =item C<$metahtmlfile>
6330  
6331 The filename of the pseudo-HTML file
6332  
6333 =item C<$metafile> (optional)
6334  
6335 The filename to write out any extracted metadata. If not specified,
6336 will default to the basename of $metahtmlfile with '.opf' appended.
6337  
6338 =back
6339  
6340 Returns the filename the metadata was written to, or undef if no
6341 metadata was found.
6342  
6343 =cut
6344  
6345 sub split_metadata
6346 {
6347 my ($metahtmlfile,$metafile) = @_;
6348 my $subname = ( caller(0) )[3];
6349 debug(2,"DEBUG[",$subname,"]");
6350  
6351 croak($subname,"(): no input file specified")
6352 if(!$metahtmlfile);
6353  
6354 croak($subname,"(): input file has zero size")
6355 if(-z $metahtmlfile);
6356  
6357 my @metablocks;
6358 my @guideblocks;
6359 my $htmlfile;
6360  
6361 my ($filebase,$filedir,$fileext);
6362 my ($fh_metahtml,$fh_meta,$fh_html);
6363  
6364 ($filebase,$filedir,$fileext) = fileparse($metahtmlfile,'\.\w+$');
6365 $metafile = $filedir . $filebase . ".opf" if(!$metafile);
6366 $htmlfile = $filedir . $filebase . "-html.html";
6367  
6368 debug(2,"DEBUG: metahtml='",$metahtmlfile,"' meta='",$metafile,
6369 " html='",$htmlfile,"'");
6370  
6371 # Move existing output files to avoid overwriting them
6372 if(-f $metafile)
6373 {
6374 debug(3, "DEBUG: moving metafile '",$metafile,"'");
6375 croak ($subname,"(): output file '",$metafile,
6376 "' exists and could not be moved!")
6377 if(! rename($metafile,"$metafile.backup") );
6378 }
6379 if(-f $htmlfile)
6380 {
6381 debug(3, "DEBUG: moving htmlfile '",$htmlfile,"'");
6382 croak ($subname,"(): output file '",$htmlfile,
6383 "' exists and could not be moved!")
6384 if(! rename($htmlfile,"$metafile.backup") );
6385 }
6386  
6387 debug(2," splitting '",$metahtmlfile,"'");
6388 open($fh_metahtml,"<:raw",$metahtmlfile)
6389 or croak($subname,"(): Failed to open '",$metahtmlfile,"' for reading!");
6390 open($fh_meta,">:raw",$metafile)
6391 or croak($subname,"(): Failed to open '",$metafile,"' for writing!");
6392 open($fh_html,">:raw",$htmlfile)
6393 or croak($subname,"(): Failed to open '",$htmlfile,"' for writing!");
6394  
6395  
6396 # Preload the return value with the OPF headers
6397 print $fh_meta $utf8xmldec,$oeb12doctype,"<package>\n";
6398 #print $fh_meta $utf8xmldec,$opf20package;
6399  
6400 # Finding and removing all of the metadata requires that the
6401 # entire thing be handled as one slurped string, so temporarily
6402 # undefine the perl delimiter
6403 #
6404 # Since multiple <metadata> sections may be present, cannot use
6405 # </metadata> as a delimiter.
6406 local $/;
6407 while(<$fh_metahtml>)
6408 {
6409 s/\sfilepos=\d+//gix;
6410 (@metablocks) = m#(<metadata>.*</metadata>)#gisx;
6411 (@guideblocks) = m#(<guide>.*</guide>)#gisx;
6412 last unless(@metablocks || @guideblocks);
6413 print {*$fh_meta} @metablocks,"\n" if(@metablocks);
6414 print {*$fh_meta} @guideblocks,"\n" if(@guideblocks);
6415 s#<metadata>.*</metadata>##gisx;
6416 s#<guide>.*</guide>##gisx;
6417 print {*$fh_html} $_,"\n";
6418 }
6419 print $fh_meta "</package>\n";
6420  
6421 close($fh_html)
6422 or croak($subname,"(): Failed to close '",$htmlfile,"'!");
6423 close($fh_meta)
6424 or croak($subname,"(): Failed to close '",$metafile,"'!");
6425 close($fh_metahtml)
6426 or croak($subname,"(): Failed to close '",$metahtmlfile,"'!");
6427  
6428 if( (-z $htmlfile) && (-z $metafile) )
6429 {
6430 croak($subname,"(): ended up with no text in any output file",
6431 " -- bailing out!");
6432 }
6433  
6434 # It is very unlikely that split_metadata will be called twice
6435 # from the same program, so undef all capture variables reclaim
6436 # the memory. Just going out of scope will not necessarily do
6437 # this.
6438 undef(@metablocks);
6439 undef(@guideblocks);
6440 undef($_);
6441  
6442 if(-z $htmlfile)
6443 {
6444 debug(1,"split_metadata(): HTML has zero size.",
6445 " Not replacing original.");
6446 unlink($htmlfile);
6447 }
6448 else
6449 {
6450 rename($htmlfile,$metahtmlfile)
6451 or croak("split_metadata(): Failed to rename ",$htmlfile,
6452 " to ",$metahtmlfile,"!\n");
6453 }
6454  
6455 if(-z $metafile)
6456 {
6457 croak($subname,
6458 "(): unable to remove empty output file '",$metafile,"'!")
6459 if(! unlink($metafile) );
6460 return;
6461 }
6462 return $metafile;
6463 }
6464  
6465  
6466 =head2 C<split_pre($htmlfile,$outfilebase)>
6467  
6468 Splits <pre>...</pre> blocks out of a source HTML file into their own
6469 separate HTML files including required headers. Each block will be
6470 written to its own file following the naming format
6471 C<$outfilebase-###.html>, where ### is a three-digit number beginning
6472 at 001 and incrementing for each block found. If C<$outfilebase> is
6473 not specified, it defaults to the basename of C<$htmlfile> with
6474 "-pre-###.html" appended. The
6475  
6476 Returns a list containing all filenames created.
6477  
6478 =cut
6479  
6480 sub split_pre
6481 {
6482 my ($htmlfile,$outfilebase) = @_;
6483 my $subname = ( caller(0) )[3];
6484 debug(2,"DEBUG[",$subname,"]");
6485  
6486 croak($subname,"(): no input file specified")
6487 if(!$htmlfile);
6488  
6489 my ($filebase,$filedir,$fileext);
6490 my ($fh_html,$fh_htmlout,$fh_pre);
6491 my $htmloutfile;
6492 my @preblocks;
6493 my @prefiles = ();
6494 my $prefile;
6495 my $count = 0;
6496  
6497 my $htmlheader = <<'END';
6498 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
6499 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6500 <html>
6501 <head>
6502 <title></title>
6503 </head>
6504 <body>
6505 END
6506  
6507 ($filebase,$filedir,$fileext) = fileparse($htmlfile,'\.\w+$');
6508 $outfilebase = "$filebase-pre" if(!$outfilebase);
6509 $htmloutfile = "$filebase-nopre.html";
6510  
6511 open($fh_html,"<:raw",$htmlfile)
6512 or croak($subname,"(): Failed to open '",$htmlfile,"' for reading!");
6513 open($fh_htmlout,">:raw",$htmloutfile)
6514 or croak($subname,"(): Failed to open '",$htmloutfile,"' for writing!");
6515  
6516 local $/;
6517 while(<$fh_html>)
6518 {
6519 (@preblocks) = /(<pre>.*?<\/pre>)/gisx;
6520 last unless(@preblocks);
6521  
6522 foreach my $pre (@preblocks)
6523 {
6524 $count++;
6525 debug(1,"DEBUG: split_pre() splitting block ",
6526 sprintf("%03d",$count));
6527 $prefile = sprintf("%s-%03d.html",$outfilebase,$count);
6528 if(-f $prefile)
6529 {
6530 rename($prefile,"$prefile.backup")
6531 or croak("Unable to rename '",$prefile,
6532 "' to '",$prefile,".backup'");
6533 }
6534 open($fh_pre,">:raw",$prefile)
6535 or croak("Unable to open '",$prefile,"' for writing!");
6536 print {*$fh_pre} $utf8xmldec;
6537 print {*$fh_pre} $htmlheader,"\n";
6538 print {*$fh_pre} $pre,"\n";
6539 print {*$fh_pre} "</body>\n</html>\n";
6540 close($fh_pre) or croak("Unable to close '",$prefile,"'!");
6541 push @prefiles,$prefile;
6542 }
6543 s/(<pre>.*?<\/pre>)//gisx;
6544 print {*$fh_htmlout} $_,"\n";
6545 close($fh_htmlout)
6546 or croak($subname,"(): Failed to close '",$htmloutfile,"'!");
6547 rename($htmloutfile,$htmlfile)
6548 or croak($subname,"(): Failed to rename '",$htmloutfile,"' to '",
6549 $htmlfile,"'!");
6550 }
6551 return @prefiles;
6552 }
6553  
6554  
6555 =head2 C<strip_script(%args)>
6556  
6557 Strips any <script>...</script> blocks out of a HTML file.
6558  
6559 =head3 Arguments
6560  
6561 =over
6562  
6563 =item C<infile>
6564  
6565 Specifies the input file. If not specified, the sub croaks.
6566  
6567 =item C<outfile>
6568  
6569 Specifies the output file. If not specified, it defaults to C<infile>
6570 (i.e. the input file is overwritten).
6571  
6572 =item C<noscript>
6573  
6574 If set to true, the sub will strip <noscript>...</noscript> blocks as
6575 well.
6576  
6577 =back
6578  
6579 =cut
6580  
6581 sub strip_script
6582 {
6583 my %args = @_;
6584 my $subname = ( caller(0) )[3];
6585 debug(2,"DEBUG[",$subname,"]");
6586  
6587 croak($subname,"(): no input file specified")
6588 if(!$args{infile});
6589  
6590 my %valid_args = (
6591 'infile' => 1,
6592 'outfile' => 1,
6593 'noscript' => 1,
6594 );
6595 foreach my $arg (keys %args)
6596 {
6597 croak($subname,"(): invalid argument '",$arg,"'")
6598 if(!$valid_args{$arg});
6599 }
6600  
6601 my $infile = $args{infile};
6602 my $outfile = $args{outfile};
6603 $outfile = $infile unless($outfile);
6604  
6605 my ($fh_in,$fh_out);
6606 my $html;
6607 local $/;
6608  
6609 open($fh_in,"<:raw",$infile)
6610 or croak($subname,"(): Failed to open '",$infile,"' for reading!\n");
6611 $html = <$fh_in>;
6612 close($fh_in)
6613 or croak($subname,"(): Failed to close '",$infile,"'!\n");
6614  
6615 $html =~ s#<script>.*?</script>\n?##gix;
6616 $html =~ s#<noscript>.*?</noscript>\n?##gix
6617 if($args{noscript});
6618  
6619 open($fh_out,">:raw",$outfile)
6620 or croak($subname,"(): Failed to open '",$outfile,"' for writing!\n");
6621 print {*$fh_out} $html;
6622 close($fh_out)
6623 or croak($subname,"(): Failed to close '",$outfile,"'!\n");
6624  
6625 return 1;
6626 }
6627  
6628  
6629 =head2 C<system_tidy_xhtml($infile,$outfile)>
6630  
6631 Runs tidy on a XHTML file semi-safely (using a secondary file)
6632  
6633 Converts HTML to XHTML if necessary
6634  
6635 =head3 Arguments
6636  
6637 =over
6638  
6639 =item $infile
6640  
6641 The filename to tidy
6642  
6643 =item $outfile
6644  
6645 The filename to use for tidy output if the safety condition to
6646 overwrite the input file isn't met.
6647  
6648 Defaults to C<infile-tidy.ext> if not specified.
6649  
6650 =back
6651  
6652 =head3 Global variables used
6653  
6654 =over
6655  
6656 =item $tidycmd
6657  
6658 the location of the tidy executable
6659  
6660 =item $tidyxhtmlerrors
6661  
6662 the filename to use to output errors
6663  
6664 =item $tidysafety
6665  
6666 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
6667  
6668 =back
6669  
6670 =head3 Return Values
6671  
6672 Returns the return value from tidy
6673  
6674 =over
6675  
6676 =item 0 - no errors
6677  
6678 =item 1 - warnings only
6679  
6680 =item 2 - errors
6681  
6682 =item Dies horribly if the return value is unexpected
6683  
6684 =back
6685  
6686 =cut
6687  
6688 sub system_tidy_xhtml
6689 {
6690 my ($infile,$outfile) = @_;
6691 my $retval;
6692  
6693 croak("system_tidy_xhtml called with no input file") if(!$infile);
6694 if(!$outfile)
6695 {
6696 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
6697 $outfile = $filebase . "-tidy" . $fileext;
6698 }
6699 croak("system_tidy_xhtml called with no output file") if(!$outfile);
6700  
6701 $retval = system($tidycmd,
6702 '-q','-utf8','--tidy-mark','no',
6703 '--wrap','0',
6704 '--clean','yes',
6705 '-asxhtml',
6706 '--output-xhtml','yes',
6707 '--add-xml-decl','yes',
6708 '--doctype','transitional',
6709 '-f',$tidyxhtmlerrors,
6710 '-o',$outfile,
6711 $infile);
6712  
6713 # Some systems may return a two-byte code, so deal with that first
6714 if($retval >= 256) { $retval = $retval >> 8 };
6715 if($retval == 0)
6716 {
6717 rename($outfile,$infile) if($tidysafety < 4);
6718 unlink($tidyxhtmlerrors);
6719 }
6720 elsif($retval == 1)
6721 {
6722 rename($outfile,$infile) if($tidysafety < 3);
6723 unlink($tidyxhtmlerrors) if($tidysafety < 2);
6724 }
6725 elsif($retval == 2)
6726 {
6727 print {*STDERR} "WARNING: Tidy errors encountered. Check ",$tidyxhtmlerrors,"\n"
6728 if($tidysafety > 0);
6729 unlink($tidyxhtmlerrors) if($tidysafety < 1);
6730 }
6731 else
6732 {
6733 # Something unexpected happened (program crash, sigint, other)
6734 croak("Tidy did something unexpected (return value=",$retval,
6735 "). Check all output.");
6736 }
6737 return $retval;
6738 }
6739  
6740  
6741 =head2 C<system_tidy_xml($infile,$outfile)>
6742  
6743 Runs tidy on an XML file semi-safely (using a secondary file)
6744  
6745 =head3 Arguments
6746  
6747 =over
6748  
6749 =item C<$infile>
6750  
6751 The filename to tidy
6752  
6753 =item C<$outfile> (optional)
6754  
6755 The filename to use for tidy output if the safety condition to
6756 overwrite the input file isn't met.
6757  
6758 Defaults to C<infile-tidy.ext> if not specified.
6759  
6760 =back
6761  
6762 =head3 Global variables used
6763  
6764 =over
6765  
6766 =item C<$tidycmd>
6767  
6768 the name of the tidy executable
6769  
6770 =item C<$tidyxmlerrors>
6771  
6772 the filename to use to output errors
6773  
6774 =item C<$tidysafety>
6775  
6776 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
6777  
6778 =back
6779  
6780 =head3 Return values
6781  
6782 Returns the return value from tidy
6783  
6784 =over
6785  
6786 =item 0 - no errors
6787  
6788 =item 1 - warnings only
6789  
6790 =item 2 - errors
6791  
6792 =item Dies horribly if the return value is unexpected
6793  
6794 =back
6795  
6796 =cut
6797  
6798 sub system_tidy_xml
6799 {
6800 my ($infile,$outfile) = @_;
6801 my $retval;
6802  
6803 croak("system_tidy_xml called with no input file") if(!$infile);
6804  
6805 if(!$outfile)
6806 {
6807 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
6808 $outfile = $filebase . "-tidy" . $fileext;
6809 }
6810 croak("system_tidy_xml called with no output file") if(!$outfile);
6811  
6812 $retval = system($tidycmd,
6813 '-q','-utf8','--tidy-mark','no',
6814 '--wrap','0',
6815 '-xml',
6816 '--add-xml-decl','yes',
6817 '-f',$tidyxmlerrors,
6818 '-o',$outfile,
6819 $infile);
6820  
6821 # Some systems may return a two-byte code, so deal with that first
6822 if($retval >= 256) { $retval = $retval >> 8 };
6823 if($retval == 0)
6824 {
6825 rename($outfile,$infile) if($tidysafety < 4);
6826 unlink($tidyxmlerrors);
6827 }
6828 elsif($retval == 1)
6829 {
6830 rename($outfile,$infile) if($tidysafety < 3);
6831 unlink($tidyxmlerrors) if($tidysafety < 2);
6832 }
6833 elsif($retval == 2)
6834 {
6835 print STDERR "WARNING: Tidy errors encountered. Check ",$tidyxmlerrors,"\n"
6836 if($tidysafety > 0);
6837 unlink($tidyxmlerrors) if($tidysafety < 1);
6838 }
6839 else
6840 {
6841 # Something unexpected happened (program crash, sigint, other)
6842 croak("Tidy did something unexpected (return value=",$retval,
6843 "). Check all output.");
6844 }
6845 return $retval;
6846 }
6847  
6848  
6849 =head2 C<trim>
6850  
6851 Removes any whitespace characters from the beginning or end of every
6852 string in @list (also works on scalars).
6853  
6854 trim; # trims $_ inplace
6855 $new = trim; # trims (and returns) a copy of $_
6856 trim $str; # trims $str inplace
6857 $new = trim $str; # trims (and returns) a copy of $str
6858 trim @list; # trims @list inplace
6859 @new = trim @list; # trims (and returns) a copy of @list
6860  
6861 This was shamelessly copied from japhy's example at perlmonks.org:
6862  
6863 http://www.perlmonks.org/?node_id=36684
6864  
6865 If needed for large lists, it would probably be better to use
6866 String::Strip.
6867  
6868 =cut
6869  
6870 sub trim ## no critic (Always unpack @_ first)
6871 {
6872 ## no critic (Comma used to separate statements)
6873 @_ = $_ if not @_ and defined wantarray;
6874 @_ = @_ if defined wantarray;
6875 for ( @_ ? @_ : $_ ) { s/^\s+//, s/\s+$// }
6876 return wantarray ? @_ : $_[ 0 ] if defined wantarray;
6877 }
6878  
6879  
6880 =head2 C<twigelt_create_uuid($gi)>
6881  
6882 Creates an unlinked element with the specified gi (tag), and then
6883 assigns it the id and scheme attributes 'UUID'.
6884  
6885 =head3 Arguments
6886  
6887 =over
6888  
6889 =item $gi : The gi (tag) to use for the element
6890  
6891 Default: 'dc:identifier'
6892  
6893 =back
6894  
6895 Returns the element.
6896  
6897 =cut
6898  
6899 sub twigelt_create_uuid
6900 {
6901 my ($gi) = @_;
6902 my $subname = ( caller(0) )[3];
6903 debug(2,"DEBUG[",$subname,"]");
6904 my $element;
6905  
6906 if(!$gi) { $gi = 'dc:identifier'; }
6907  
6908 my $uuidgen = Data::UUID->new();
6909 $element = XML::Twig::Elt->new($gi);
6910 $element->set_id('UUID');
6911 $element->set_att('scheme' => 'UUID');
6912 $element->set_text($uuidgen->create_str());
6913 return $element;
6914 }
6915  
6916  
6917 =head2 C<twigelt_detect_duplicate($element1, $element2)>
6918  
6919 Takes two twig elements and returns 1 if they have the same GI (tag),
6920 text, and attributes, but are not actually the same element. The GI
6921 comparison is case-insensitive. The others are case-sensitive.
6922  
6923 Returns 0 otherwise.
6924  
6925 Croaks if passed anything but twig elements.
6926  
6927 =cut
6928  
6929 sub twigelt_detect_duplicate
6930 {
6931 my ($element1,$element2) = @_;
6932 my $subname = ( caller(0) )[3];
6933 debug(3,"DEBUG[",$subname,"]");
6934  
6935 croak($subname,"(): arguments must be XML::Twig::Elt objects")
6936 unless( $element1->isa('XML::Twig::Elt')
6937 && $element2->isa('XML::Twig::Elt') );
6938  
6939 my (%atts1, %atts2);
6940  
6941 unless($element1->cmp($element2))
6942 {
6943 debug(3," both elements have the same position");
6944 return 0;
6945 }
6946  
6947 unless( lc($element1->gi) eq lc($element2->gi) )
6948 {
6949 debug(3," elements have different GIs");
6950 return 0;
6951 }
6952  
6953 unless($element1->text eq $element2->text)
6954 {
6955 debug(3," elements have different text");
6956 return 0;
6957 }
6958  
6959 %atts1 = %{$element1->atts};
6960 %atts2 = %{$element2->atts};
6961  
6962 my $attkeys1 = join('',sort keys %atts1);
6963 my $attkeys2 = join('',sort keys %atts2);
6964  
6965 # This is much simpler with the ~~ operator, but Perl 5.10
6966 # features are being avoided until 5.10 is standard both on MacOSX
6967 # and Debian
6968 # Note that the ~~ operator only checks keys of hashes, not values
6969 # unless(%atts1 ~~ %atts2)
6970 unless($attkeys1 eq $attkeys2)
6971 {
6972 debug(3," elements have different attributes");
6973 return 0;
6974 }
6975  
6976 foreach my $att (keys %atts1)
6977 {
6978 unless($element1->att($att) eq $element2->att($att))
6979 {
6980 debug(3," elements have different values for attribute '",
6981 $att,"'");
6982 return 0;
6983 }
6984 }
6985 debug(3," elements are duplicates of each other!");
6986 return 1;
6987 }
6988  
6989 =head2 C<twigelt_fix_oeb12_atts($element)>
6990  
6991 Checks the attributes in a twig element to see if they match OPF names
6992 with an opf: namespace, and if so, removes the namespace. Used by the
6993 fix_oeb12() method.
6994  
6995 Takes as a sole argument a twig element.
6996  
6997 Returns that element with the modified attributes, or undef if the
6998 element didn't exist. Returns an unmodified element if both att and
6999 opf:att exist.
7000  
7001 =cut
7002  
7003 sub twigelt_fix_oeb12_atts
7004 {
7005 my ($element) = @_;
7006 return unless($element);
7007 my $subname = ( caller(0) )[3];
7008 debug(3,"DEBUG[",$subname,"]");
7009  
7010 my %opfatts_no_ns = (
7011 "opf:role" => "role",
7012 "opf:file-as" => "file-as",
7013 "opf:scheme" => "scheme",
7014 "opf:event" => "event"
7015 );
7016  
7017 foreach my $att ($element->att_names)
7018 {
7019 debug(3,"DEBUG: checking attribute '",$att,"'");
7020 if($opfatts_no_ns{$att})
7021 {
7022 # If the opf:att attribute properly exists already, do nothing.
7023 if($element->att($opfatts_no_ns{$att}))
7024 {
7025 debug(1,"DEBUG: found both '",$att,"' and '",
7026 $opfatts_no_ns{$att},"' -- skipping.");
7027 next;
7028 }
7029 debug(1,"DEBUG: changing attribute '",$att,"' => '",
7030 $opfatts_no_ns{$att},"'");
7031 $element->change_att_name($att,$opfatts_no_ns{$att});
7032 }
7033 }
7034 return $element;
7035 }
7036  
7037  
7038 =head2 C<twigelt_fix_opf20_atts($element)>
7039  
7040 Checks the attributes in a twig element to see if they match OPF
7041 names, and if so, prepends the OPF namespace. Used by the fix_opf20()
7042 method.
7043  
7044 Takes as a sole argument a twig element.
7045  
7046 Returns that element with the modified attributes, or undef if the
7047 element didn't exist.
7048  
7049 =cut
7050  
7051 sub twigelt_fix_opf20_atts
7052 {
7053 my ($element) = @_;
7054 return unless($element);
7055 my $subname = ( caller(0) )[3];
7056 debug(2,"DEBUG[",$subname,"]");
7057  
7058 my %opfatts_ns = (
7059 "role" => "opf:role",
7060 "file-as" => "opf:file-as",
7061 "scheme" => "opf:scheme",
7062 "event" => "opf:event"
7063 );
7064  
7065 foreach my $att ($element->att_names)
7066 {
7067 debug(2,"DEBUG: checking attribute '",$att,"'");
7068 if($opfatts_ns{$att})
7069 {
7070 # If the opf:att attribute properly exists already, do nothing.
7071 if($element->att($opfatts_ns{$att}))
7072 {
7073 debug(1,"DEBUG: found both '",$att,"' and '",
7074 $opfatts_ns{$att},"' -- skipping.");
7075 next;
7076 }
7077 debug(1,"DEBUG: changing attribute '",$att,"' => '",
7078 $opfatts_ns{$att},"'");
7079 $element->change_att_name($att,$opfatts_ns{$att});
7080 }
7081 }
7082 return $element;
7083 }
7084  
7085  
7086 =head2 C<twigelt_is_author($element)>
7087  
7088 Takes as an argument a twig element. Returns true if the element is a
7089 dc:creator (case-insensitive) with either a opf:role="aut" or
7090 role="aut" attribute defined. Returns undef otherwise, and also if
7091 the element has no text.
7092  
7093 Croaks if fed no argument, or fed an argument that isn't a twig
7094 element.
7095  
7096 Intended to be used as a twig search condition.
7097  
7098 =head3 Example
7099  
7100 my @elements = $ebook->twigroot->descendants(\&twigelt_is_author);
7101  
7102 =cut
7103  
7104 sub twigelt_is_author
7105 {
7106 my ($element) = @_;
7107 my $subname = ( caller(0) )[3];
7108 debug(3,"DEBUG[",$subname,"]");
7109  
7110 croak($subname,"(): no element provided") unless($element);
7111  
7112 my $ref = ref($element) || '';
7113  
7114 croak($subname,"(): argument was of type '",$ref,
7115 "', needs to be 'XML::Twig::Elt' or a subclass")
7116 unless($element->isa('XML::Twig::Elt'));
7117  
7118 return if( (lc $element->gi) ne 'dc:creator');
7119 return unless($element->text);
7120  
7121 my $role = $element->att('opf:role') || $element->att('role');
7122 return unless($role);
7123  
7124 return 1 if($role eq 'aut');
7125 return;
7126 }
7127  
7128  
7129 =head2 C<twigelt_is_isbn($element)>
7130  
7131 Takes as an argument a twig element. Returns true if the element is a
7132 dc:identifier (case-insensitive) where any of the id, opf:scheme, or
7133 scheme attributes start with 'isbn', '-isbn', 'eisbn', or 'e-isbn'
7134 (again case-insensitive).
7135  
7136 Returns undef otherwise, and also if the element has no text.
7137  
7138 Croaks if fed no argument, or fed an argument that isn't a twig
7139 element.
7140  
7141 Intended to be used as a twig search condition.
7142  
7143 =head3 Example
7144  
7145 my @elements = $ebook->twigroot->descendants(\&twigelt_is_isbn);
7146  
7147 =cut
7148  
7149 sub twigelt_is_isbn
7150 {
7151 my ($element) = @_;
7152 my $subname = ( caller(0) )[3];
7153 debug(3,"DEBUG[",$subname,"]");
7154  
7155 croak($subname,"(): no element provided") unless($element);
7156  
7157 my $ref = ref($element) || '';
7158 my $id;
7159 my $scheme;
7160  
7161 croak($subname,"(): argument was of type '",$ref,
7162 "', needs to be 'XML::Twig::Elt' or a subclass")
7163 unless($element->isa('XML::Twig::Elt'));
7164  
7165 return if( (lc $element->gi) ne 'dc:identifier');
7166 return unless($element->text);
7167  
7168 $id = $element->id || '';
7169 return 1 if($id =~ /^e?-?isbn/ix);
7170  
7171 $scheme = $element->att('opf:scheme') || '';
7172 return 1 if($scheme =~ /^e?-?isbn/ix);
7173 $scheme = $element->att('scheme') || '';
7174 return 1 if($scheme =~ /^e?-?isbn/ix);
7175 return;
7176 }
7177  
7178  
7179 =head2 C<twigelt_is_knownuid($element)>
7180  
7181 Takes as an argument a twig element. Returns true if the element is a
7182 dc:identifier (case-insensitive) element with an C<id> attribute
7183 matching the known IDs of proper unique identifiers suitable for a
7184 package-id (also case-insensitive). Returns undef otherwise.
7185  
7186 Croaks if fed no argument, or fed an argument that isn't a twig element.
7187  
7188 Intended to be used as a twig search condition.
7189  
7190 =head3 Example
7191  
7192 my @elements = $ebook->twigroot->descendants(\&twigelt_is_knownuid);
7193  
7194 =cut
7195  
7196 sub twigelt_is_knownuid
7197 {
7198 my ($element) = @_;
7199 my $subname = ( caller(0) )[3];
7200 debug(3,"DEBUG[",$subname,"]");
7201  
7202 croak($subname,"(): no element provided") unless($element);
7203  
7204 my $ref = ref($element) || '';
7205  
7206 croak($subname,"(): argument was of type '",$ref,
7207 "', needs to be 'XML::Twig::Elt' or a subclass")
7208 unless($element->isa('XML::Twig::Elt'));
7209  
7210 return if( (lc $element->gi) ne 'dc:identifier');
7211 my $id = $element->id;
7212 return unless($id);
7213  
7214 my %knownuids = (
7215 'package-id' => 56,
7216 'overdriveguid' => 48,
7217 'guid' => 40,
7218 'uuid' => 32,
7219 'uid' => 24,
7220 'calibre_id' => 16,
7221 'fwid' => 8,
7222 );
7223  
7224 if($knownuids{lc $id})
7225 {
7226 # debug(2,"DEBUG: '",$element->gi,"' has known UID '",$id,"'");
7227 return 1;
7228 }
7229 return;
7230 }
7231  
7232  
7233 =head2 C<usedir($dir)>
7234  
7235 Changes the current working directory to the one specified, creating
7236 it if necessary.
7237  
7238 Returns the current working directory before the change. If no
7239 directory is specified, returns the current working directory without
7240 changing anything.
7241  
7242 Croaks on any failure.
7243  
7244 =cut
7245  
7246 sub usedir
7247 {
7248 my ($dir) = @_;
7249 my $subname = ( caller(0) )[3];
7250 debug(2,"DEBUG[",$subname,"]");
7251  
7252 my $cwd = getcwd();
7253 return $cwd unless($dir);
7254  
7255 unless(-d $dir)
7256 {
7257 debug(2," Creating directory '",$dir,"'");
7258 mkpath($dir)
7259 or croak("Unable to create output directory '",$dir,"'!\n");
7260 }
7261 chdir($dir)
7262 or croak("Unable to change working directory to '",$dir,"'!\n");
7263 return $cwd;
7264 }
7265  
7266  
7267 =head2 C<userconfigdir()>
7268  
7269 Returns the directory in which user configuration files and helper
7270 programs are expected to be found, creating that directory if it does
7271 not exist. Typically, this directory is C<"$ENV{HOME}/.ebooktools">,
7272 but on MSWin32 systems if that directory does not already exist,
7273 C<"$ENV{USERPROFILE}/ApplicationData/EBook-Tools"> is returned (and
7274 potentially created) instead.
7275  
7276 If C<$ENV{HOME}> (and C<$ENV{USERPROFILE}> on MSWin32) are not set, the
7277 sub returns undef.
7278  
7279 =cut
7280  
7281 sub userconfigdir
7282 {
7283 my $subname = ( caller(0) )[3];
7284 debug(3,"DEBUG[",$subname,"]");
7285  
7286 my $dir;
7287 $dir = $ENV{HOME} . '/.ebooktools' if($ENV{HOME});
7288 if($OSNAME eq 'MSWin32')
7289 {
7290 if(! -d $dir)
7291 {
7292 $dir = $ENV{USERPROFILE} . '\Application Data\EBook-Tools'
7293 if($ENV{USERPROFILE});
7294 }
7295 }
7296 if($dir)
7297 {
7298 if(! -d $dir)
7299 {
7300 mkpath($dir)
7301 or croak($subname,
7302 "(): unable to create configuration directory '",
7303 $dir,"'!\n");
7304 }
7305 return $dir;
7306 }
7307 else { return; }
7308 }
7309  
7310  
7311 =head2 C<ymd_validate($year,$month,$day)>
7312  
7313 Make sure month and day have valid values. Return the passed values
7314 if they are, return 3 undefs if not. Testing of month or day can be
7315 skipped by passing undef in that spot.
7316  
7317 =cut
7318  
7319 sub ymd_validate
7320 {
7321 my ($year,$month,$day) = @_;
7322  
7323 return (undef,undef,undef) unless($year);
7324  
7325 if($month)
7326 {
7327 return (undef,undef,undef) if($month > 12);
7328 if($day)
7329 {
7330 if(!eval { timelocal(0,0,0,$day,$month-1,$year); })
7331 {
7332 debug(1,"DEBUG: timelocal validation failed for year=",
7333 $year," month=",$month," day=",$day);
7334 return (undef,undef,undef);
7335 }
7336 }
7337 return ($year,$month,$day);
7338 }
7339  
7340 # We don't have a month. If we *do* have a day, the result is
7341 # broken, so send back the undefs.
7342 return (undef,undef,undef) if($day);
7343 return ($year,undef,undef);
7344 }
7345  
7346  
7347 ########## END CODE ##########
7348  
7349 =head1 BUGS AND LIMITATIONS
7350  
7351 =over
7352  
7353 =item * need to implement fix_primary_author() to convert names to
7354 standard 'last, first' naming format
7355  
7356 =item * fix_links() could be improved to download remote URIs instead
7357 of ignoring them.
7358  
7359 =item * fix_links() needs to check the <reference> links under <guide>
7360  
7361 =item * fix_links() needs to be redone with HTML::TreeBuilder to avoid
7362 the weakness with newlines between attribute names and values
7363  
7364 =item * Need to implement fix_tours() that should collect the related
7365 elements and delete the parent if none are found. Empty <tours>
7366 elements aren't allowed.
7367  
7368 =item * fix_languages() needs to convert language names into IANA
7369 language codes.
7370  
7371 =item * set_language() should add a warning if the text isn't a valid
7372 IANA language code.
7373  
7374 =item * NCX generation only generates from the spine. It should be
7375 possible to use a TOC html file for generation instead. In the long
7376 term, it should be possible to generate one from the headers and
7377 anchors in arbitrary HTML files.
7378  
7379 =item * It might be better to use sysread / index / substr / syswrite in
7380 &split_metadata to handle the split in 10k chunks, to avoid massive
7381 memory usage on large files.
7382  
7383 This may not be worth the effort, since the average size for most
7384 books is less than 500k, and the largest books are rarely over 10M.
7385  
7386 =item * The only generator is currently for .epub books. PDF,
7387 PalmDoc, Mobipocket, Plucker, and iSiloX are eventually planned.
7388  
7389 =item * Although I like keeping warnings associated with the ebook
7390 object, it may be better to throw exceptions on errors and catch them
7391 later. This probably won't be implemented until it bites someone who
7392 complains, though.
7393  
7394 =item * Unit tests are incomplete
7395  
7396 =back
7397  
7398 =head1 AUTHOR
7399  
7400 Zed Pobre <zed@debian.org>
7401  
7402 =head1 LICENSE AND COPYRIGHT
7403  
7404 Copyright 2008 Zed Pobre
7405  
7406 Licensed to the public under the terms of the GNU GPL, version 2
7407  
7408 =cut
7409  
7410 1;
« blib/lib/EBook/Tools/Unpack.pm ↑ Summary