blib/lib/FB3/Convert/Epub.pm

filter: Statementstmt 100% 6 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 8 / 8 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/FB3/Convert.pm ↑ Summary
1 package FB3::Convert::Epub;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use base 'FB3::Convert';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 use XML::LibXML;
6 use File::Basename;
7 use Image::ExifTool qw(:Public);
8 use Image::Size;
9 use Clone qw(clone);
10 use FB3::Euristica;
11 use URI::Escape;
12 use utf8;
13  
14 my %NS = (
15 'container' => 'urn:oasis:names:tc:opendocument:xmlns:container',
16 'root' => 'http://www.idpf.org/2007/opf',
17 'xhtml' => 'http://www.w3.org/1999/xhtml',
18 'dc' => 'http://purl.org/dc/elements/1.1/',
19 );
20  
21 my $XC = XML::LibXML::XPathContext->new();
22  
23 my %GenreTranslate = (
24 'accounting'=>'Бухучет, налогообложение, аудит',
25 'adventure'=>'Приключения',
26 'adv_animal'=>'Природа и животные',
27 'adv_geo'=>'Книги о Путешествиях',
28 'adv_history'=>'Исторические приключения',
29 'adv_maritime'=>'Морские приключения',
30 'adv_western'=>'Вестерны',
31 'antique'=>'Старинная литература',
32 'antique_ant'=>'Античная литература',
33 'antique_east'=>'Древневосточная литература',
34 'antique_european'=>'Европейская старинная литература',
35 'antique_myths'=>'Мифы. Легенды. Эпос',
36 'antique_russian'=>'Древнерусская литература',
37 'aphorism_quote'=>'Афоризмы и цитаты',
38 'architecture_book'=>'Архитектура',
39 'auto_regulations'=>'Автомобили и ПДД',
40 'banking'=>'Банковское дело',
41 'beginning_authors'=>'Начинающие авторы',
42 'samizdat'=>'Самиздат',
43 'children'=>'Книги для детей',
44 'child_adv'=>'Детские приключения',
45 'child_det'=>'Детские детективы',
46 'child_education'=>'Учебная литература',
47 'child_prose'=>'Детская проза',
48 'child_sf'=>'Детская фантастика',
49 'child_tale'=>'Сказки',
50 'child_verse'=>'Детские стихи',
51 'cinema_theatre'=>'Кинематограф, театр',
52 'city_fantasy'=>'Городское фэнтези',
53 'computers'=>'Компьютеры',
54 'comp_db'=>'Базы данных',
55 'comp_hard'=>'Компьютерное Железо',
56 'comp_osnet'=>'ОС и Сети',
57 'comp_programming'=>'Программирование',
58 'comp_soft'=>'Программы',
59 'comp_www'=>'Интернет',
60 'detective'=>'Современные детективы',
61 'det_action'=>'Боевики',
62 'det_classic'=>'Классические детективы',
63 'det_crime'=>'Криминальные боевики',
64 'det_espionage'=>'Шпионские детективы',
65 'det_hard'=>'Крутой детектив',
66 'det_history'=>'Исторические детективы',
67 'det_irony'=>'Иронические детективы',
68 'det_police'=>'Полицейские детективы',
69 'det_political'=>'Политические детективы',
70 'dragon_fantasy'=>'Фэнтези про драконов',
71 'dramaturgy'=>'Драматургия',
72 'economics'=>'Экономика',
73 'essays'=>'Эссе',
74 'fantasy_fight'=>'Боевое фэнтези',
75 'foreign_action'=>'Зарубежные боевики',
76 'foreign_adventure'=>'Зарубежные приключения',
77 'foreign_antique'=>'Зарубежная старинная литература',
78 'foreign_business'=>'Зарубежная деловая литература',
79 'foreign_children'=>'Зарубежные детские книги',
80 'foreign_comp'=>'Зарубежная компьютерная литература',
81 'foreign_contemporary'=>'Современная зарубежная литература',
82 'foreign_desc'=>'Зарубежная справочная литература',
83 'foreign_detective'=>'Зарубежные детективы',
84 'foreign_dramaturgy'=>'Зарубежная драматургия',
85 'foreign_edu'=>'Зарубежная образовательная литература',
86 'foreign_fantasy'=>'Зарубежное фэнтези',
87 'foreign_home'=>'Зарубежная прикладная и научно-популярная литература',
88 'foreign_humor'=>'Зарубежный юмор',
89 'foreign_language'=>'Иностранные языки',
90 'foreign_love'=>'Зарубежные любовные романы',
91 'foreign_other'=>'Зарубежное',
92 'foreign_poetry'=>'Зарубежные стихи',
93 'foreign_prose'=>'Зарубежная классика',
94 'foreign_psychology'=>'Зарубежная психология',
95 'foreign_publicism'=>'Зарубежная публицистика',
96 'foreign_religion'=>'Зарубежная эзотерическая и религиозная литература',
97 'foreign_sf'=>'Зарубежная фантастика',
98 'geography_book'=>'География',
99 'geo_guides'=>'Путеводители',
100 'global_economy'=>'ВЭД',
101 'historical_fantasy'=>'Историческое фэнтези',
102 'home'=>'Дом и Семья',
103 'home_cooking'=>'Кулинария',
104 'home_crafts'=>'Хобби, Ремесла',
105 'home_diy'=>'Сделай Сам',
106 'home_entertain'=>'Развлечения',
107 'home_garden'=>'Сад и Огород',
108 'home_health'=>'Здоровье',
109 'home_pets'=>'Домашние Животные',
110 'home_sex'=>'Эротика, Секс',
111 'home_sport'=>'Спорт, фитнес',
112 'humor'=>'Юмор',
113 'humor_anecdote'=>'Анекдоты',
114 'humor_fantasy'=>'Юмористическое фэнтези',
115 'humor_prose'=>'Юмористическая проза',
116 'humor_verse'=>'Юмористические стихи',
117 'industries'=>'Отраслевые издания',
118 'job_hunting'=>'Поиск работы, карьера',
119 'literature_18'=>'Литература 18 века',
120 'literature_19'=>'Литература 19 века',
121 'literature_20'=>'Литература 20 века',
122 'love_contemporary'=>'Современные любовные романы',
123 'love_detective'=>'Остросюжетные любовные романы',
124 'love_erotica'=>'Эротическая литература',
125 'love_fantasy'=>'Любовное фэнтези',
126 'love_history'=>'Исторические любовные романы',
127 'love_sf'=>'Любовно-фантастические романы',
128 'love_short'=>'Короткие любовные романы',
129 'magician_book'=>'Книги про волшебников',
130 'management'=>'Управление, подбор персонала',
131 'marketing'=>'Маркетинг, PR, реклама',
132 'military_special'=>'Военное дело, спецслужбы',
133 'music_dancing'=>'Музыка, балет',
134 'narrative'=>'Повести',
135 'newspapers'=>'Газеты',
136 'nonfiction'=>'Документальная литература',
137 'nonf_biography'=>'Биографии и Мемуары',
138 'nonf_criticism'=>'Критика',
139 'nonf_publicism'=>'Публицистика',
140 'org_behavior'=>'Корпоративная культура',
141 'paper_work'=>'Делопроизводство',
142 'pedagogy_book'=>'Педагогика',
143 'periodic'=>'Журналы',
144 'personal_finance'=>'Личные финансы',
145 'poetry'=>'Поэзия',
146 'popadanec'=>'Попаданцы',
147 'popular_business'=>'О бизнесе популярно',
148 'prose_classic'=>'Классическая проза',
149 'prose_counter'=>'Контркультура',
150 'prose_history'=>'Историческая литература',
151 'prose_military'=>'Книги о войне',
152 'prose_rus_classic'=>'Русская классика',
153 'prose_su_classics'=>'Советская литература',
154 'psy_alassic'=>'Классики психологии',
155 'psy_childs'=>'Детская психология',
156 'psy_generic'=>'Общая психология',
157 'psy_personal'=>'Личностный рост',
158 'psy_sex_and_family'=>'Секс и семейная психология',
159 'psy_social'=>'Социальная психология',
160 'psy_theraphy'=>'Психотерапия и консультирование',
161 'real_estate'=>'Недвижимость',
162 'reference'=>'Справочная литература',
163 'ref_dict'=>'Словари',
164 'ref_encyc'=>'Энциклопедии',
165 'ref_guide'=>'Руководства',
166 'ref_ref'=>'Справочники',
167 'religion'=>'Религия',
168 'religion_esoterics'=>'Эзотерика',
169 'religion_rel'=>'Религиозные тексты',
170 'religion_self'=>'Самосовершенствование',
171 'russian_contemporary'=>'Современная русская литература',
172 'russian_fantasy'=>'Русское фэнтези',
173 'science'=>'Прочая образовательная литература',
174 'sci_biology'=>'Биология',
175 'sci_chem'=>'Химия',
176 'sci_culture'=>'Культурология',
177 'sci_history'=>'История',
178 'sci_juris'=>'Юриспруденция, право',
179 'sci_linguistic'=>'Языкознание',
180 'sci_math'=>'Математика',
181 'sci_medicine'=>'Медицина',
182 'sci_philosophy'=>'Философия',
183 'sci_phys'=>'Физика',
184 'sci_politics'=>'Политика, политология',
185 'sci_religion'=>'Религиоведение',
186 'sci_tech'=>'Техническая литература',
187 'sf'=>'Научная фантастика',
188 'sf_action'=>'Боевая фантастика',
189 'sf_cyberpunk'=>'Киберпанк',
190 'sf_detective'=>'Детективная фантастика',
191 'sf_heroic'=>'Героическая фантастика',
192 'sf_history'=>'Историческая фантастика',
193 'sf_horror'=>'Ужасы и Мистика',
194 'sf_humor'=>'Юмористическая фантастика',
195 'sf_social'=>'Социальная фантастика',
196 'sf_space'=>'Космическая фантастика',
197 'short_story'=>'Рассказы',
198 'sketch'=>'Очерки',
199 'small_business'=>'Малый бизнес',
200 'sociology_book'=>'Социология',
201 'stock'=>'Ценные бумаги, инвестиции',
202 'thriller'=>'Триллеры',
203 'upbringing_book'=>'Воспитание детей',
204 'vampire_book'=>'Книги про вампиров',
205 'visual_arts'=>'Изобразительное искусство, фотография',
206 );
207  
208 sub FindFile {
209 my $FileName = shift;
210 my $Dirs = shift;
211  
212 foreach (@$Dirs) {
213 my $Path = $_.'/'.$FileName;
214 return $Path if -f $Path;
215 }
216 return undef;
217 }
218  
219 sub Reaper {
220 my $self = shift;
221 my $X = shift;
222  
223 my %Args = @_;
224 my $Source = $Args{'source'} || $X->Error("Source path not defined");
225 my $XC = XML::LibXML::XPathContext->new();
226  
227 $XC->registerNs('container', $NS{'container'});
228 $XC->registerNs('root', $NS{'root'});
229 $XC->registerNs('dc', $NS{'dc'});
230  
231 my $AllowElements = $X->{'allow_elements'};
232 ### Обработчики нод для epub
233 $AllowElements->{'img'} = {
234 'allow_attributes' => ['src','id','alt'
235 #,'width',#пока не подготовлен
236 ],
237 'processor' => \&ProcessImg,
238 };
239 $AllowElements->{'a'} = {
240 'allow_attributes' => ['src','id','xlink:href'],
241 'processor' => \&ProcessHref,
242 'allow_elements_inside' => $FB3::Convert::ElsMainList,
243 };
244 $AllowElements->{'b'} = {
245 'allow_attributes' => ['id'],
246 processor => \&TransformTo,
247 processor_params => ['strong']
248 };
249 $AllowElements->{'i'} = {
250 'allow_attributes' => ['id'],
251 processor => \&TransformTo,
252 processor_params => ['em']
253 };
254 $AllowElements->{'br'} = { #мы его потом превратим в параграф
255 };
256 $AllowElements->{'u'} = {
257 'allow_attributes' => [],
258 processor => \&TransformTo,
259 processor_params => ['underline']
260 };
261 $AllowElements->{'div'} = {
262 'exclude_if_inside' => ['div','p','ul','ol','h1','h2','h3','h4','h5','h6','li','pre','table','section'], #Если div содежрит block-level элементы, мы его чикаем
263 'allow_attributes' => [],
264 processor => \&TransformTo,
265 processor_params => ['p'],
266 'allow_elements_inside' => $FB3::Convert::ElsMainList2,
267 };
268 $AllowElements->{'h1'} = {
269 'allow_attributes' => ['id'],
270 processor => \&TransformH2Title,
271 'allow_elements_inside' => {'p'=>undef},
272 };
273 $AllowElements->{'h2'} = $AllowElements->{'h1'};
274 $AllowElements->{'h3'} = $AllowElements->{'h1'};
275 $AllowElements->{'h4'} = $AllowElements->{'h1'};
276 $AllowElements->{'h5'} = $AllowElements->{'h1'};
277 $AllowElements->{'h6'} = $AllowElements->{'h1'};
278  
279 my $Structure = $X->{'STRUCTURE'};
280 my $Description = $Structure->{'DESCRIPTION'};
281
282 ###### счетчики, настройки, аккмуляторы и пр.
283 $X->{'MaxMoveCount'} = 100; # максимальное кол-во символов принятия решения пустых <a id="good_link" href="bad_link"> на перенос
284 $X->{'EmptyLinksList'} = {}; # список пустых <a id="good_link" href=""> на перенос или превращение
285
286 ##### где хранится содержимое книги
287 my $ContainerFile = $Source."/META-INF/container.xml";
288 $X->Error($self." ".$ContainerFile." not found!") unless -f $ContainerFile;
289  
290 $X->Msg("Parse container ".$ContainerFile."\n");
291 my $CtDoc = XML::LibXML->load_xml(
292 location=>$ContainerFile,
293 expand_entities => 0,
294 no_network => 1,
295 load_ext_dtd => 0
296 ) || $X->Error("Can't parse file ".$ContainerFile);
297
298 my $RootFile = $XC->findnodes('/container:container/container:rootfiles/container:rootfile',$CtDoc)->[0]->getAttribute('full-path');
299 $X->Error("Can't find full-path attribute in Container [".$NS{'container'}." space]") unless $RootFile;
300  
301 #### root-файл с описанием контента
302 $RootFile = $Source."/".$RootFile;
303 $X->Error("Can't find root (full-path attribute) file ".$RootFile) unless -f $RootFile;
304  
305 #Директория, относительно которой лежит контент. Нам с ней еще работать
306 $X->{'ContentDir'} = $RootFile;
307 $X->{'ContentDir'} =~ s/\/?[^\/]+$//;
308  
309 if ($X->{'euristic'}) {
310 $X->Msg("Euristica enabled\n",'w');
311  
312 my $PhantomJS = $X->{'phantom_js_path'} || FindFile('phantomjs', [split /:/,$ENV{'PATH'}]);
313  
314 if (-e $PhantomJS) {
315 my $EuristicaObj = new FB3::Euristica(
316 'verbose' => $X->{verbose},
317 'phjs' => $PhantomJS,
318 'ContentDir' => $X->{'ContentDir'},
319 'SourceDir' => $X->{'SourceDir'},
320 'DestinationDir' => $X->{'DestinationDir'},
321 'DebugPath' => $X->{'euristic_debug'},
322 'DebugPrefix' => $X->{'SourceFileName'},
323 'unzipped' => $X->{'unzipped'},
324 );
325 $X->{'EuristicaObj'} = $EuristicaObj;
326 } else {
327 $X->Msg("[SKIP EURISTIC] PhantomJS binary not found. Try --phantomjs=PATH-TO-FILE, --euristic_skip options.\nPhantomJS mus be installed for euristic analize of titles <http://phantomjs.org/>\n",'e');
328 }
329
330 }
331  
332 $X->Msg("Parse rootfile ".$RootFile."\n");
333
334 my $RootDoc = XML::LibXML->load_xml(
335 location => $RootFile,
336 expand_entities => 0,
337 no_network => 1,
338 load_ext_dtd => 0
339 ) || $X->Error("Can't parse file ".$RootFile);
340 $RootDoc->setEncoding('utf-8');
341  
342 #ИЩЕМ Cover
343 my $CoverImg;
344 my $CheckIsCover=0;
345  
346 #согласно epub.3 может быть в <item properties="cover-image"
347 if (my $CoverNode = $XC->findnodes('/root:package/root:manifest/root:item[@properties="cover-image"]',$RootDoc)->[0]) {
348 if ($CoverNode->getAttribute('media-type') =~ /^image\/(jpeg|png|gif)$/) {
349 if ($CoverNode->getAttribute('href')) {
350 $CoverImg = $CoverNode->getAttribute('href');
351 }
352 }
353 }
354  
355 #согласно epub.2 может быть в <meta name="cover"
356 if ( !$CoverImg && (my $CoverNode = $XC->findnodes('/root:package/root:metadata/root:meta[@name="cover"]',$RootDoc)->[0]) ) {
357 my $CoverID = $CoverNode->getAttribute('content');
358 if (my $CoverItem = $XC->findnodes('/root:package/root:manifest/root:item[@id="'.$CoverID.'"]',$RootDoc)->[0]) {
359 if ($CoverItem->getAttribute('media-type') =~ /^image\/(jpeg|png|gif)$/) {
360 if ($CoverItem->getAttribute('href')) {
361 $CoverImg = $CoverItem->getAttribute('href');
362 }
363 }
364 }
365 }
366  
367 # список файлов с контентом
368 my @Manifest;
369 for my $MItem ($XC->findnodes('/root:package/root:manifest/root:item',$RootDoc)) {
370 my $ItemHref = $MItem->getAttribute('href');
371 my $ItemType = $MItem->getAttribute('media-type');
372 push @Manifest, {
373 'id' => $MItem->getAttribute('id'),
374 'href' => $ItemHref,
375 'type' => $ItemType,
376 };
377  
378 if ( # обложка не найдена? попробуем сами поискать
379 !$CoverImg
380 && $ItemHref =~ /cover/i
381 && $ItemType =~ /^image\/(jpeg|png|gif)$/
382 ) {
383 $CheckIsCover = 1; #способ хулиганский, поэтому будем проверять картинку
384 $CoverImg = $ItemHref;
385 }
386  
387 }
388 my @Spine;
389 for my $MItem ($XC->findnodes('/root:package/root:spine/root:itemref',$RootDoc)) {
390 my $IdRef = $MItem->getAttribute('idref');
391 push @Spine, $IdRef;
392 }
393  
394 if ($CoverImg) {
395 $X->Msg("Try process cover image '$CoverImg'\n");
396
397 my $SkipExists = 1;
398 my $CoverSrcFile = $X->RealPath(
399 FB3::Convert::dirname(
400 $X->{'ContentDir'}.'/'.$CoverImg
401 ).'/'.FB3::Convert::basename($CoverImg),
402 undef, $SkipExists);
403  
404 $CoverSrcFile = CheckIsCover($X,$CoverSrcFile) if $CheckIsCover;
405  
406 if (-f $CoverSrcFile) {
407 my $ImgList = $X->{'STRUCTURE'}->{'IMG_LIST'};
408 my $CoverDestPath = $X->{'DestinationDir'}."/fb3/img";
409  
410 $CoverImg =~ /.([^\/\.]+)$/;
411 my $ImgType = $1;
412  
413 my $ImgID = 'img_'.$X->UUID($CoverSrcFile);
414 my $NewFileName = $ImgID.'.'.$ImgType;
415 my $CoverDestFile = $CoverDestPath.'/'.$NewFileName;
416  
417 my $CoverDesc = {
418 'src_path' => $CoverSrcFile,
419 'new_path' => "img/".$NewFileName, #заменим на новое имя
420 'id' => $ImgID,
421 };
422  
423 push @$ImgList, $CoverDesc unless grep {$_->{id} eq $ImgID} @$ImgList;
424 $Structure->{'DESCRIPTION'}->{'TITLE-INFO'}->{'COVER_DESC'} = $CoverDesc;
425  
426 #Копируем исходник на новое место с новым уникальным именем
427 unless (-f $CoverDestFile) {
428 $X->Msg("copy $CoverSrcFile -> $CoverDestFile\n");
429 FB3::Convert::copy($CoverSrcFile, $CoverDestFile) or $X->Error($!." [copy $CoverSrcFile -> $CoverDestFile]");
430 }
431 $X->Msg("Cover '$CoverImg' is OK\n");
432 }
433  
434 }
435 #/cover
436  
437 $X->Msg("Assemble content\n");
438 my $AC = AssembleContent($X, 'manifest' => \@Manifest, 'spine' => \@Spine);
439 # Отдаем контент на обработку
440  
441 #Заполняем внутренний формат
442  
443 #МЕТА
444 my $GlobalID;
445 unless (defined $Description->{'DOCUMENT-INFO'}->{'ID'}) {
446 $Description->{'DOCUMENT-INFO'}->{'ID'} = $GlobalID = $X->UUID();
447 }
448  
449 unless (defined $Description->{'DOCUMENT-INFO'}->{'LANGUAGE'}) {
450 my $Lang = $XC->findnodes('/root:package/root:metadata/dc:language',$RootDoc)->[0];
451 $Description->{'DOCUMENT-INFO'}->{'LANGUAGE'} = $self->html_trim($Lang->to_literal) if $Lang;
452  
453 unless ($Description->{'DOCUMENT-INFO'}->{'LANGUAGE'}) {
454 my $TextForIdent = FetchText4Ident($AC,500);
455 $Description->{'DOCUMENT-INFO'}->{'LANGUAGE'} = $X->GuessLang($TextForIdent);
456 $Description->{'DOCUMENT-INFO'}->{'LANGUAGE'} ||= 'en';
457 }
458 }
459  
460 unless (defined $Description->{'TITLE-INFO'}->{'BOOK-TITLE'}) {
461 my $Title = $XC->findnodes('/root:package/root:metadata/dc:title',$RootDoc)->[0];
462 $Description->{'TITLE-INFO'}->{'BOOK-TITLE'} = $self->EncodeUtf8($self->html_trim($Title->to_literal)) if $Title;
463 }
464  
465 unless (defined $Description->{'TITLE-INFO'}->{'ANNOTATION'}) {
466 my $Annotation = $XC->findnodes('/root:package/root:metadata/dc:description',$RootDoc)->[0];
467 $Description->{'TITLE-INFO'}->{'ANNOTATION'} = $self->EncodeUtf8($self->EraseTags($self->html_trim($Annotation->to_literal))) if $Annotation;
468 }
469  
470 unless (defined $Description->{'TITLE-INFO'}->{'PUBLISHER'}) {
471 my $Publisher = $XC->findnodes('/root:package/root:metadata/dc:publisher',$RootDoc)->[0];
472 $Description->{'TITLE-INFO'}->{'PUBLISHER'} = $self->EncodeUtf8($self->html_trim($Publisher->to_literal)) if $Publisher;
473 }
474
475 unless (defined $Description->{'TITLE-INFO'}->{'GENRES'}) {
476 my @Genres;
477 for my $Genre ($XC->findnodes('/root:package/root:metadata/dc:subject',$RootDoc)) {
478 next unless $Genre->to_literal;
479 push @Genres, $self->EncodeUtf8($self->html_trim($Genre->to_literal)),
480 }
481 push @Genres, 'Unknown' unless @Genres;
482
483 $Description->{'TITLE-INFO'}->{'GENRES'} = \@Genres;
484 }
485  
486 unless (defined $Description->{'DOCUMENT-INFO'}->{'DATE'}) {
487 my($day, $month, $year, $hour, $min, $sec)=(localtime)[3,4,5,2,1,0];
488 $Description->{'DOCUMENT-INFO'}->{'DATE'} = {
489 'attributes' => {
490 'value' => ($year+1900).'-'.sprintf("%02d",($month+1)).'-'.sprintf("%02d",$day),
491 }
492 };
493 $Description->{'DOCUMENT-INFO'}->{'TIME'} = {
494 'attributes' => {
495 'value' => sprintf("%02d",$hour).':'.sprintf("%02d",$min).':'.sprintf("%02d",$sec),
496 }
497 };
498 }
499  
500 unless (defined $Description->{'TITLE-INFO'}->{'AUTHORS'}) {
501 my @Authors;
502 for my $Author ($XC->findnodes('/root:package/root:metadata/dc:creator',$RootDoc)) {
503 my $Author = $self->BuildAuthorName($self->EncodeUtf8($self->html_trim($Author->to_literal)));
504 push @Authors, $Author;
505 }
506 push @Authors, $self->BuildAuthorName('Unknown') unless scalar @Authors;
507 $Description->{'TITLE-INFO'}->{'AUTHORS'} = \@Authors;
508 }
509  
510 ##print Data::Dumper::Dumper($AC);
511  
512 #КОНТЕНТ
513  
514 my @Pages;
515 foreach (@$AC) {
516 $X->Msg("Processing in structure: ".$_->{'file'}."\n",'i');
517 $X->_bs('c2tree','Контент в дерево согласно схеме');
518 push @Pages, $X->Content2Tree($_);
519 $X->_be('c2tree');
520 }
521  
522 # [#01]
523 my @PagesComplete;
524  
525 #Клеим смежные title
526 #Отрезаем ненужное
527
528 foreach my $Page (@Pages) {
529  
530 $Page->{'content'} = CleanNodeEmptyId($X,$Page->{'content'});
531 $Page->{'content'} = CleanEmptyP($X,$Page->{'content'});
532  
533 my $c=-1;
534 my $EmptyLineDetect=undef;
535 my $LastSpace=0;
536 foreach my $Item (@{$Page->{'content'}}) {
537 $c++;
538 next unless defined $Item;
539 if (ref $Item eq '' && $Item eq '') {
540 $Item=undef;
541 next;
542 }
543  
544 if (ref $Item eq '' && $Item =~ /^[\s\n\r\t]+$/) {
545 if ($LastSpace) {
546 $Item=undef;
547 } else {
548 $Item=" ";
549 }
550 $LastSpace=1;
551 next;
552 }
553 $LastSpace=0;
554  
555 #клеим смежные emptyline
556 if (ref $Item eq 'HASH'
557 && exists $Item->{'p'}
558 && $X->IsEmptyLineValue($Item->{'p'}->{'value'})
559 ) {
560  
561 if (defined $EmptyLineDetect) {
562 push @{$Page->{'content'}->[$EmptyLineDetect]->{p}->{'value'}}, @{$Item->{'p'}->{'value'}};
563 $Item = undef;
564 next;
565 }
566 $EmptyLineDetect = $c;
567 } else {
568 $EmptyLineDetect = undef;
569 }
570  
571 #<title/> иногда попадаются - режем
572 if (
573 ref $Item eq 'HASH'
574 && exists $Item->{'title'}
575 ) {
576 $Item->{'title'}->{'value'} = CleanTitle($X,$Item->{'title'}->{'value'});
577 $Item = undef unless @{$Item->{'title'}->{'value'}};
578 }
579  
580 }
581  
582 for (my $c = scalar @{$Page->{'content'}}; $c>=0; $c--) {
583 my $Item = $Page->{'content'}->[$c];
584 my $LastTitleOK = -1;
585  
586 next if (ref $Item ne 'HASH' || !exists $Item->{'title'});
587  
588 for (my $i=$c-1;$i>=0;$i--) { #бежим назад и ищем, нет ли перед нами title?
589 my $Last = $Page->{'content'}->[$i];
590 next if !ref($Last) && $X->trim($Last) eq ''; #если перед нами перенос строки, игнорим, ищем title дальше
591 if (ref $Last eq 'HASH' && exists $Last->{'title'}) { #перед нами title, будем клеить текущий title с ним
592 $LastTitleOK = $i;
593 last;
594 } else {
595 last; #наткнулись на НЕ-title, хватит перебирать
596 }
597  
598 }
599  
600 if ($LastTitleOK > -1) {
601 my $TitleMove = clone($Item->{'title'}->{'value'});
602 push @{$Page->{'content'}->[$LastTitleOK]->{'title'}->{'value'}}, @$TitleMove; #переносим title в предыдущий
603 delete $Page->{'content'}->[$c];
604 delete $Page->{'content'}->[$c-1] #перенос строки тоже грохнем
605 if (
606 !ref $Page->{'content'}->[$c-1]
607 && $X->trim($Page->{'content'}->[$c-1]) eq ''
608 );
609 }
610  
611 }
612  
613 #MOVE EMPTY LINKS to title
614 for (my $c = scalar @{$Page->{'content'}}; $c>=0; $c--) {
615 my $Item = $Page->{'content'}->[$c];
616
617 next if (ref $Item ne 'HASH' || !exists $Item->{'title'});
618  
619 my @LinksMove2Title;
620 for (my $i=$c-1;$i>=0;$i--) { #бежим назад и ищем, нет ли перед нами <a id="some"/>?
621 my $Last = $Page->{'content'}->[$i];
622 next if !ref($Last) && $X->trim($Last) eq ''; #если перед нами перенос строки, игнорим, ищем <a> дальше
623 if (
624 ref $Last eq 'HASH'
625 && IsEmptyA($Last)
626 ) {
627 my $Move = delete $Page->{'content'}->[$i];
628 my $key = each %$Move;
629 push @LinksMove2Title, $key ne 'a' ? @{$Move->{$key}->{'value'}} : $Move;
630 } else {
631 last; #наткнулись на НЕ-<a>, хватит перебирать
632 }
633 }
634  
635 if (@LinksMove2Title && ref $Item eq 'HASH' && exists $Item->{'title'}) {
636 foreach my $Link (@LinksMove2Title) {
637 #занято
638 if (exists $Item->{'title'}->{'attributes'}->{'id'} && $Item->{'title'}->{'attributes'}->{'id'}) {
639 #тогда будем менять линк на текущий
640 $X->{'EmptyLinksList'}->{$Link->{'a'}->{'attributes'}->{'id'}} = $Item->{'title'}->{'attributes'}->{'id'};
641 } else {
642 #пусто, займем это место!
643 $Item->{'title'}->{'attributes'}->{'id'} = $Link->{'a'}->{'attributes'}->{'id'};
644 }
645  
646 }
647 }
648 CleanTitle($X,$Item->{'title'}->{'value'});
649 }
650  
651 #Clean undef
652 my @Push;
653 foreach (@{$Page->{'content'}}) {
654 next unless defined $_;
655 push @Push, $_;
656 }
657 $Page->{'content'} = \@Push;
658
659 #РИсуем section's
660 my @P;
661 my $Sec = SectionBody($X);
662  
663 $c=0;
664 my $TitleOK = 0;
665 push @{$Page->{'content'}},''; #пустышка-закрывашка (так легче обработать массив)
666 foreach my $Item (@{$Page->{'content'}}) {
667  
668 $c++;
669 if (ref $Item eq 'HASH') {
670 my ($Key) = each %$Item;
671 if ($Key =~ /^title$/) {
672 $TitleOK = 1;
673 } else {
674 $TitleOK = 0;
675 }
676 } else {
677 $TitleOK = 0;
678 }
679  
680 if ($TitleOK) { #встретили title
681 if (@{$Sec->{'section'}->{'value'}}) {
682 my $CloneSec = clone($Sec);
683 $CloneSec->{'section'}->{'attributes'}->{'id'} = $X->UUID();
684 push @P, clone($CloneSec);
685 }
686 $Sec->{'section'}->{'value'} = []; #надо закрыть section
687 push @{$Sec->{'section'}->{'value'}}, $Item; #и продолжить пушить в новый
688 next;
689 }
690  
691 push @{$Sec->{'section'}->{'value'}}, $Item if $Item;
692  
693 if ( #страница закрывается, пушим section что там в нем осталось
694 $c >= scalar @{$Page->{'content'}}
695 ) {
696 my $CloneSec = clone($Sec);
697 $CloneSec->{'section'}->{'attributes'}->{'id'} = $X->UUID();
698 push @P, $CloneSec;
699 $Sec->{'section'}->{'value'} = [];
700 }
701  
702 }
703 pop @{$Page->{'content'}}; #закрывашка
704  
705 #одиночки title нам в section не нужны - не валидно
706 #таких разжалуем в subtitle
707 foreach my $Sec (@P) {
708 my $Last = pop @{$Sec->{'section'}->{'value'}};
709 push @{$Sec->{'section'}->{'value'}}, $Last unless (ref $Last eq '' && $X->trim($Last) eq '') ;
710  
711 if (
712 scalar @{$Sec->{'section'}->{'value'}} == 1
713 && ref $Sec->{'section'}->{'value'}->[0] eq 'HASH'
714 && exists $Sec->{'section'}->{'value'}->[0]->{'title'}
715 ) {
716  
717 my $ValNode = $Sec->{'section'}->{'value'}->[0]->{'title'}->{'value'}->[0];
718 $Sec->{'section'}->{'value'} =
719 [
720 {
721 'subtitle' => {
722 'value' => (ref $ValNode eq 'HASH' ? $ValNode->{'p'}->{'value'} : $ValNode),
723 }
724 }
725 ];
726  
727 }
728  
729 }
730  
731 my $Content;
732 my @PN; #финальная подчистка
733 foreach my $Item (@P) {
734 next unless defined $Item;
735 my $NotEmpty = 0;
736 foreach my $String (@{$Item->{'section'}->{'value'}}) {
737 $NotEmpty = 1 if defined $String && (ref $String eq 'HASH' || (ref $String eq '' && $X->trim($String) ne ''));
738 }
739 push @PN, $Item if $NotEmpty;
740 }
741  
742 if (scalar @PN > 1) {
743 $Content = \@PN;
744 } elsif (scalar @PN) {
745 $Content = $PN[0]->{'section'}->{'value'}; #если section один, то берем только его внутренности, контейнер section лишний
746 }
747  
748 if ($Content && @$Content) {
749 push @PagesComplete, {ID=>$Page->{'ID'},'content'=>$Content};
750 } else {
751 $X->Msg("Find empty page. Skip [id: $Page->{'ID'}]\n");
752 }
753
754 }
755 @Pages = ();
756  
757 my @Body;
758 foreach my $PC (@PagesComplete) {
759 push @Body, {
760 'section' => {
761 attributes=>{
762 'id' => $PC->{'ID'}
763 },
764 'value' => $PC->{'content'},
765 }
766 };
767 }
768  
769 #анализируем и переносим пустые <a> и элементы с несушествующими id
770 foreach my $Page (@Body) {
771 AnaliseIdEmptyHref($X,$Page->{'section'});
772 }
773 MoveIdEmptyHref($X,\@Body);
774
775 #финальная подчистка
776 foreach my $Page (@Body) {
777 CleanEmptyP($X,$Page->{'section'}->{'value'});
778 }
779  
780 $Structure->{'PAGES'} = {
781 value => \@Body
782 };
783  
784 }
785  
786 sub FetchText4Ident {
787 my $Data = shift;
788 my $MinLen = shift || 200;
789 my $Text;
790  
791 foreach (@$Data) {
792 my $Content = $_->{'content'};
793 $Content =~ s/<.*>//g;
794 $Content =~ s/[\n\r]/ /g;
795 $Content =~ s/^\s*//;
796 $Content =~ s/\s*$//;
797 $Content =~ s/\s+/ /g;
798 $Content =~ s/[\{\}\\\(\)\/0-9\[\]]+//g;
799 $Content =~ s/\s+\././g;
800 $Content =~ s/,\./,/g;
801 $Content =~ s/\.+/./g;
802  
803 $Text .= (length($Text)?' ':'').$Content;
804 return $Text if length($Text) >= $MinLen;
805 }
806  
807 return $Text;
808 }
809  
810 sub CleanEmptyP {
811 my $X = shift;
812 my $Data = shift;
813 return $Data unless ref $Data eq 'ARRAY';
814  
815 #^<p/> и emptyline режем в начале
816 foreach my $Item (@$Data) {
817 next unless defined $Item;
818 if (
819 (ref $Item eq 'HASH'
820 && exists $Item->{'p'}
821 && ( $X->IsEmptyLineValue($Item->{'p'}->{'value'}))
822 || !defined $Item || (ref $Item eq '' && $Item =~ /^[\s\t]$/))
823 ) {
824 $Item=undef;
825 } else {
826 last;
827 }
828 }
829  
830 #^<p/> и emptyline режем в конце
831 foreach my $Item (reverse @$Data) {
832 if (
833 (ref $Item eq 'HASH'
834 && exists $Item->{'p'}
835 && ( $X->IsEmptyLineValue($Item->{'p'}->{'value'}))
836 || (!defined $Item || (ref $Item eq '' && $Item =~ /^[\s\t]+$/))
837 )
838 ) {
839 $Item = undef;
840 } else {
841 last;
842 }
843 }
844  
845 #^<p/> и emptyline режем после title
846 my $LastTitleOK=0;
847 foreach my $Item (@$Data) {
848  
849 next unless defined $Item;
850
851 if (ref $Item eq 'HASH'
852 && exists $Item->{'title'}
853 ) {
854 $LastTitleOK=1;
855 next;
856 }
857  
858 if ( $LastTitleOK &&
859 (ref $Item eq 'HASH'
860 && exists $Item->{'p'}
861 && ( $X->IsEmptyLineValue($Item->{'p'}->{'value'}))
862 || !defined $Item || (ref $Item eq '' && $Item =~ /^[\s\t]$/))
863 ) {
864 $Item=undef;
865 } else {
866 $LastTitleOK=0;
867 #next;
868 }
869  
870 if (ref $Item eq 'HASH'
871 && exists $Item->{'section'}) {
872 $Item->{'section'}->{'value'} = CleanEmptyP($X,$Item->{'section'}->{'value'});
873 }
874  
875 }
876
877 return $Data;
878 }
879  
880 sub IsEmptyA {
881 my $Data = shift;
882 return 0 unless ref $Data eq 'HASH';
883
884 return 1 if (
885 (
886 exists $Data->{'p'}
887 && @{$Data->{'p'}->{'value'}} == 1
888 && IsEmptyA($Data->{'p'}->{'value'}->[0])
889 )
890 ||
891 (
892 exists $Data->{'span'}
893 && @{$Data->{'span'}->{'value'}} == 1
894 && IsEmptyA($Data->{'span'}->{'value'}->[0])
895 )
896 ||
897 (exists $Data->{'a'}
898 && $Data->{'a'}->{'attributes'}->{'xlink:href'} eq ''
899 && !@{$Data->{'a'}->{'value'}}
900 )
901 ); #в <a> ничего нет. Иначе это уже полезный контент, и нечего его в title переносить
902 return 0;
903 }
904  
905 sub SectionBody {
906 my $X=shift;
907 my $Sec = { #заготовка section
908 'section' => {
909 'value' => [],
910 'attributes' => {
911 'id' => $X->UUID(),
912 }
913 }
914 };
915 }
916
917 # заполняет $X->{'EmptyLinksList'}
918 # <a id="ID" href=""> ID => newID
919 sub AnaliseIdEmptyHref {
920 my $X = shift;
921 my $Data = shift;
922 my $Hash4Move = shift;
923  
924 return if (ref $Data ne 'HASH' || !exists $Data->{'value'});
925  
926 my $First = 0;
927 unless ($Hash4Move) {
928 $Hash4Move = {
929 'count_abs' => 0, #счетчик от начала секции
930 'neighbour' => {}, #счетчик от начала секции - кандидатов, куда можно переносить
931 'candidates' => {} #счетчик от начала секции кандидатов на перенос
932 };
933 $First = 1;
934 }
935  
936 $Data->{'value'} = [$Data->{'value'}] unless ref $Data->{'value'} eq 'ARRAY';
937  
938 foreach my $Item (@{$Data->{'value'}}) {
939  
940 if (ref $Item eq '') { # это голый текст
941 $Hash4Move->{'count_abs'} += length($Item);
942 } elsif (ref $Item eq 'HASH') { # это нода
943  
944 foreach my $El (keys %$Item) {
945 if ($El eq 'section') {
946 AnaliseIdEmptyHref($X,$Item->{$El}); #вложенную секцию обрабатывает как отдельную
947 } else {
948 if (ref $Item->{$El} eq 'HASH' && exists $Item->{$El}->{'attributes'}->{'id'} && $Item->{$El}->{'attributes'}->{'id'} ne '') {
949 if ($El eq 'a' && exists $Item->{$El}->{'attributes'}->{'xlink:href'}
950 && ( #пустая или кривая ссылка - кандидат на переезд
951 $Item->{$El}->{'attributes'}->{'xlink:href'} eq ''
952 || ( $Item->{$El}->{'attributes'}->{'xlink:href'} =~ /^#/ && !exists $X->{'id_list'}->{ $X->CutLinkDiez($Item->{$El}->{'attributes'}->{'xlink:href'}) } )
953 )
954 ) {
955 #ссылка - кандидат на перенос
956 $Hash4Move->{'candidates'}->{$Item->{$El}->{'attributes'}->{'id'}} = $Hash4Move->{'count_abs'};
957 } else {
958 #кандидат, куда можно перенести ссылку
959 $Hash4Move->{'neighbour'}->{$Item->{$El}->{'attributes'}->{'id'}} = $Hash4Move->{'count_abs'};
960 }
961 }
962 AnaliseIdEmptyHref($X,$Item->{$El},$Hash4Move);
963 }
964 }
965
966 }
967  
968 }
969
970 if ($First) {
971 #анализируем и собираем элементы для переноса или превращения
972 foreach my $Cand (keys %{$Hash4Move->{'candidates'}}) {
973
974 if ( $Hash4Move->{'candidates'}->{$Cand} <= $X->{'MaxMoveCount'} ) {
975 #переносим в id секции
976 $X->{'EmptyLinksList'}->{$Cand} = $Data->{'attributes'}->{'id'};
977 } else {
978 #вычислим ближайшего соседа для переноса
979 my %Sort = ();
980 foreach (keys %{$Hash4Move->{'neighbour'}}) {
981 $Sort{$_} = abs($Hash4Move->{'candidates'}->{$Cand} - $Hash4Move->{'neighbour'}->{$_});
982 }
983 my $MinNeigh = [sort {$Sort{$a} <=> $Sort{$b}} keys %Sort]->[0];
984 $X->{'EmptyLinksList'}->{$Cand} = $MinNeigh if (%Sort && $Sort{$MinNeigh} <= $X->{'MaxMoveCount'});
985 }
986 #иначе отдаем на превращение
987 $X->{'EmptyLinksList'}->{$Cand} = 'rename' if !exists $X->{'EmptyLinksList'}->{$Cand} || !defined $X->{'EmptyLinksList'}->{$Cand};
988 }
989 }
990
991 }
992  
993 sub MoveIdEmptyHref {
994 my $X = shift;
995 my $Data = shift;
996 return unless ref $Data eq 'ARRAY';
997  
998 foreach my $Item (@$Data) {
999 next unless ref $Item eq 'HASH';
1000 foreach my $ElName (keys %$Item) {
1001 my $El = $Item->{$ElName};
1002 next unless ref $El eq 'HASH';
1003 #меняем ссылку
1004 if (
1005 $X->{'EmptyLinksList'}->{ $X->CutLinkDiez($El->{'attributes'}->{'xlink:href'}) } ne 'rename'
1006 && exists $El->{'attributes'}
1007 && exists $El->{'attributes'}->{'xlink:href'}
1008 && exists $X->{'EmptyLinksList'}->{ $X->CutLinkDiez($El->{'attributes'}->{'xlink:href'}) }
1009 ) {
1010 $El->{'attributes'}->{'xlink:href'} = "#".$X->{'EmptyLinksList'}->{ $X->CutLinkDiez($El->{'attributes'}->{'xlink:href'}) };
1011 $X->Msg("Empty link move to neighbour id $El->{'attributes'}->{'xlink:href'} [".($X->{'id_list'}->{$X->CutLinkDiez($El->{'attributes'}->{'xlink:href'})}||'section')."]\n","w");
1012 }
1013 #удаляем элемент со старым id либо превращаем в span, если нет кандидатов на перенос
1014 if (
1015 exists $El->{'attributes'}
1016 && exists $El->{'attributes'}->{'id'}
1017 && exists $X->{'EmptyLinksList'}->{ $El->{'attributes'}->{'id'} }
1018 ) {
1019 if ($X->{'EmptyLinksList'}->{ $El->{'attributes'}->{'id'} } eq 'rename') {
1020 $Item = $El->{'value'} = {'span'=>{'value'=>$El->{'value'},'attributes'=>{'id'=>$El->{'attributes'}->{'id'}}}}; #-> span
1021 $X->Msg("Empty link rename to <span> [".$X->{'id_list'}->{$El->{'attributes'}->{'id'}}."]\n","w");
1022 } else {
1023 $Item = $El->{'value'}; #удаляем
1024 }
1025 }
1026 MoveIdEmptyHref($X,$El->{'value'});
1027 }
1028 }
1029  
1030 }
1031  
1032 sub AssembleContent {
1033 my $X = shift;
1034 my %Args = @_;
1035 my $Manifest = $Args{'manifest'} || [];
1036 my $Spine = $Args{'spine'} || [];
1037  
1038 my @Pages;
1039 my $XC = XML::LibXML::XPathContext->new();
1040 $XC->registerNs('xhtml', $NS{'xhtml'});
1041  
1042 $X->Error('Spin list is empty or not defined!') unless scalar @$Spine;
1043  
1044 my %ReverseManifest; #так проще грепать
1045 my $Ind=0;
1046 foreach my $Item (@$Manifest) {
1047 $Ind++;
1048 $ReverseManifest{$Item->{'id'}} = $Item;
1049 # !! Стили пока не трогаем !!
1050 #if ($Item->{'type'} =~ /^text\/css$/) { # В манифесте css
1051 # push @{$X->{'STRUCTURE'}->{'CSS_LIST'}}, {
1052 # 'src_path' => $Item->{'href'},
1053 # 'new_path' => undef,
1054 # 'id' => $Item->{'id'},
1055 # };
1056 #}
1057 }
1058  
1059 my @Files4Eur;
1060 if ($X->{'EuristicaObj'}) { #придется собрать файлы для эвристики отдельно. нужно будет объединить с обработкой
1061 for my $ItemID (@$Spine) {
1062 my $Item = $ReverseManifest{$ItemID};
1063 if ($Item->{'type'} =~ /^application\/xhtml/) {
1064 my $ContentFile = $X->{'ContentDir'}.'/'.$Item->{'href'};
1065 $ContentFile =~ s/%20/ /g;
1066 push @Files4Eur, $ContentFile;
1067 }
1068 }
1069 $X->Msg("Calculate all links for euristica\n");
1070 $X->_bs('EuristicLinks','Калькуляция всех локальных ссылок для эвристики');
1071 $X->{'EuristicaObj'}->CalculateLinks('files'=>\@Files4Eur);
1072 $X->_be('EuristicLinks');
1073 }
1074  
1075 #бежим по списку, составляем скелет контекстной части
1076 for my $ItemID (@$Spine) {
1077 my $Item = $ReverseManifest{$ItemID};
1078  
1079 if (!exists $ReverseManifest{$ItemID}) {
1080 $X->Msg("id ".$ItemID." not exists in Manifest list\n",'i');
1081 next;
1082 }
1083  
1084 if ($Item->{'type'} =~ /^application\/xhtml/) { # Видимо, текст
1085  
1086 my $ContentFile = $X->{'ContentDir'}.'/'.$Item->{'href'};
1087 $ContentFile = uri_unescape($ContentFile);
1088  
1089 $X->Msg("Fix strange text\n");
1090 $X->_bs('Strange', 'Зачистка странностей');
1091 $X->ShitFixFile($ContentFile);
1092 $X->_be('Strange');
1093  
1094 if ($X->{'EuristicaObj'}) {
1095 $X->Msg("Euristic analize ".$ContentFile."\n");
1096 $X->_bs('euristic','Эвристический анализ заголовка');
1097 my $Euristica = $X->{'EuristicaObj'}->ParseFile('file'=>$ContentFile);
1098 #print Data::Dumper::Dumper($Euristica);
1099
1100 #пишем контент из эвристики на место
1101 ##if ($Euristica->{'CHANGED'}
1102 ##) {
1103 open my $FS,">:utf8",$ContentFile;
1104 print $FS $Euristica->{'CONTENT'};
1105 close $FS;
1106 ##}
1107 $X->_be('euristic');
1108  
1109 }
1110  
1111 $X->Msg("Parse content file ".$ContentFile."\n");
1112  
1113 $X->_bs('parse_epub_xhtml', 'xml-парсинг файлов epub [Открытие, первичные преобразования, парсинг]');
1114 my $Content;
1115 open my $FO,"<".$ContentFile or $X->Error("can't open file $ContentFile $!");
1116 map {$Content.=$_} <$FO>;
1117 close $FO;
1118  
1119 $X->_bs('Entities', 'Преобразование Entities');
1120 $Content = $X->qent(Encode::decode_utf8($Content));
1121 $X->_be('Entities');
1122  
1123 #phantomjs нам снова наследил
1124 if ($X->{'EuristicaObj'}) {
1125 $Content = $X->MetaFix($Content);
1126 $Content = $X->SomeFix($Content);
1127 }
1128  
1129 $X->Msg("Parse XML\n");
1130 my $ContentDoc = XML::LibXML->load_xml(
1131 string => $Content,
1132 expand_entities => 0, # не считать & за entity
1133 no_network => 1, # не будем тянуть внешние вложения
1134 recover => 2, # => 0 - падать при кривой структуре. например, не закрыт тег. entity и пр | => 1 - вопить, 2 - совсем молчать
1135 load_ext_dtd => 0 # полный молчок про dtd
1136 );
1137 $ContentDoc->setEncoding('utf-8');
1138  
1139 my $Body = $XC->findnodes('/xhtml:html/xhtml:body',$ContentDoc)->[0];
1140 $X->Error("Can't find /html/body node in file $ContentFile. This is true XML?") unless $Body;
1141  
1142 #перерисуем все ns-подобные атрибуты. мешают при дальнейшем парсинге
1143 foreach my $NodeAttr ( $XC->findnodes('//*[@*]', $Body) ) {
1144 my @Attrs = $NodeAttr->findnodes( "./@*");
1145 foreach my $Attr (@Attrs) {
1146 if ($Attr->nodeName =~ /^.+:(.+)/) { #если атриббут похож на ns
1147  
1148 my $AttrName = $1;
1149 my $AttrValue = $NodeAttr->getAttribute($Attr->nodeName);
1150  
1151 $NodeAttr->setAttribute($AttrName => $AttrValue) unless $NodeAttr->getAttribute($AttrName); #переименуем ns-Образный в обычный, если такового нет
1152 $NodeAttr->removeAttribute( $Attr->nodeName ); #удалим ns-образный
1153 }
1154 }
1155 }
1156  
1157 #при сборе fb3 тэг title разрешен, но в body ему появляться нельзя.
1158 #резанем костылем по шее
1159 for my $node ($XC->findnodes('//xhtml:title',$Body)) {
1160 $node->parentNode()->removeChild($node);
1161 }
1162  
1163 $Content = $X->InNode($Body);
1164 $Content =~ s/^\s*//;
1165 $Content =~ s/\s*$//;
1166 push @Pages, {
1167 content=>$Content,
1168 file=>$Item->{'href'}
1169 };
1170  
1171 $X->_be('parse_epub_xhtml');
1172  
1173 } else {
1174 $X->Msg("ID ".$Item->{'id'}.": I not understood what is it '".$Item->{'type'}."[".$Item->{'href'}."]'\n",'w');
1175 }
1176  
1177 }
1178  
1179 return (
1180 pages => \@Pages,
1181 );
1182  
1183 }
1184  
1185 sub CheckIsCover {
1186 my $X = shift;
1187 my $ImgSrcFile = shift;
1188  
1189 my $ImgInfo = [Image::Size::imgsize($ImgSrcFile)];
1190 my $W = $ImgInfo->[0] || return;
1191 my $H = $ImgInfo->[1] || return;
1192  
1193 my $Prop = $H/$W;
1194 #img должен быть 1:1 - 1:5 и ширина 200+
1195 return unless ($W>=200 && $Prop >=1 && $Prop <=5);
1196 return $ImgSrcFile;
1197 }
1198  
1199 sub CleanTitle {
1200 my $X = shift;
1201 my $Node = shift;
1202  
1203 return $Node unless ref $Node eq 'ARRAY';
1204  
1205 foreach my $Item (@$Node) {
1206 $Item = undef
1207 if ref $Item eq 'HASH' && exists $Item->{'p'} &&
1208 (
1209 (
1210 ref $Item->{'p'}->{'value'} eq 'ARRAY' && !scalar @{$Item->{'p'}->{'value'}}
1211 || !grep {$_ =~ /[^\s\t]+/} @{$Item->{'p'}->{'value'}}
1212 )
1213 || $Item->{'p'}->{'value'} =~ /^[\s\t]*$/
1214 );
1215  
1216 }
1217  
1218 my @Ret;
1219 foreach (@$Node) {
1220 push @Ret, $_ if defined $_;
1221 }
1222
1223 return \@Ret;
1224 }
1225  
1226 sub CleanNodeEmptyId {
1227 my $X = shift;
1228 my $Node = shift;
1229 my $IdsCollect = shift || {};
1230  
1231 return $Node unless ref $Node eq 'ARRAY';
1232  
1233 my $Ret = [];
1234  
1235 foreach my $Item (@$Node) {
1236 push @$Ret, $Item;
1237 next unless ref $Item eq 'HASH';
1238 foreach my $El (keys %$Item) {
1239 next if ref $Item->{$El} ne 'HASH' || !exists $Item->{$El}->{'value'};
1240 $Item->{$El}->{'value'} = CleanNodeEmptyId($X,$Item->{$El}->{'value'},$IdsCollect);
1241 if (exists $Item->{$El}->{'attributes'}->{'id'} || $El =~ /^(a|span)$/) {
1242 my $Id = exists $Item->{$El}->{'attributes'}->{'id'} ? $Item->{$El}->{'attributes'}->{'id'} : '';
1243  
1244 if (!$Id || !exists $X->{'href_list'}->{"#".$Id} || exists $IdsCollect->{$Id}) { #элементы с несуществующими id
1245 my $Link;
1246 $Link = $X->trim($Item->{$El}->{'attributes'}->{'xlink:href'}) if exists $Item->{$El}->{'attributes'}->{'xlink:href'};
1247
1248 if ($Id) {
1249 if (exists $IdsCollect->{$Id}) {
1250 $X->Msg("Find double ID and delete '$Id' in node '$El'\n","w");
1251 } else {
1252 $X->Msg("Find non exists ID and delete '$Id' in node '$El' [".$X->{'id_list'}->{$Id}."]\n","w");
1253 }
1254 delete $Item->{$El}->{'attributes'}->{'id'}; #удалим id
1255 } elsif ($Link eq '') {
1256 $X->Msg("Find node '$El' without id\n","w");
1257 }
1258  
1259 next unless $El =~ /^(a|span)$/;
1260 #<a> c действующими линками оставим
1261 if ($El eq 'a' && $Link ne ''
1262 && (
1263 $Link !~ /^#link_/ #только ссылки внутри section нам интересны
1264 || exists $X->{'id_list'}->{$X->CutLinkDiez($Link)} #ссылка живая
1265 )
1266 ) {
1267 $X->Msg("Find link [$Link]. Skip\n","w");
1268 next;
1269 }
1270 pop @$Ret;
1271 push @$Ret, @{$Item->{$El}->{'value'}} if scalar @{$Item->{$El}->{'value'}}; #переносим на место ноды ее внутренности
1272 $X->Msg("Delete node '$El'\n");
1273 }
1274 $IdsCollect->{$Id}++;
1275 }
1276 }
1277 }
1278  
1279 return $Ret;
1280 }
1281  
1282 #Процессоры обработки нод
1283  
1284 # Копируем картинки, перерисовывает атрибуты картинок на новые
1285 my %ImgChecked;
1286 sub ProcessImg {
1287 my $X = shift;
1288 my %Args = @_;
1289 my $Node = $Args{'node'};
1290 my $RelPath = $Args{'relpath'};
1291  
1292 my $ImgList = $X->{'STRUCTURE'}->{'IMG_LIST'};
1293 my $Src = $Node->getAttribute('src');
1294  
1295 unless ($Src) {
1296 $X->Msg("Can't find img src. Remove img\n","w");
1297 my $Doc = XML::LibXML::Document->new('1.0', 'utf-8');
1298 my $Text = $Doc->createTextNode('');
1299 return $Text;
1300 }
1301  
1302 #честный абсолютный путь к картинке
1303 my $SkipExists = 1; #не падать, если файл отсутствует
1304 my $ImgSrcFile = $X->RealPath(
1305 FB3::Convert::dirname($X->RealPath( $RelPath ? $X->{'ContentDir'}.'/'.$RelPath : $X->{'ContentDir'}, undef, $SkipExists)).'/'.$Src,
1306 undef,$SkipExists);
1307  
1308 my $CoverIxists = $X->{'STRUCTURE'}->{'DESCRIPTION'}->{'TITLE-INFO'}->{'COVER_DESC'};
1309  
1310 my $ImgID;
1311  
1312 if (exists $CoverIxists->{'src_path'} && $CoverIxists->{'src_path'} eq $ImgSrcFile ) {
1313 $ImgID = $CoverIxists->{'id'}; #уже отрабатывали картинку как cover, просто заменим src на готовый
1314 } else {
1315  
1316 unless (-f $ImgSrcFile) { #не нашли картинку
1317 $X->Msg("Can't find img".$ImgSrcFile." Replace to text [no image in epub file]\n","w");
1318 my $Doc = XML::LibXML::Document->new('1.0', 'utf-8');
1319 my $Text = $Doc->createTextNode('[no image in epub file]');
1320 return $Text;
1321 }
1322  
1323 unless (exists $ImgChecked{$ImgSrcFile}) {
1324 $X->_bs('img_info','Тип IMG');
1325 my $ImgInfo;
1326 my $ImgType;
1327 if ($ImgSrcFile =~ /.svg$/) {
1328 $ImgInfo = Image::ExifTool::ImageInfo($ImgSrcFile);
1329 $ImgType = ref $ImgInfo eq 'HASH' ? $ImgInfo->{'FileType'} : undef;
1330 } else {
1331 $ImgInfo = [Image::Size::imgsize($ImgSrcFile)];
1332 $ImgType = $ImgInfo->[2];
1333 }
1334 $X->_be('img_info');
1335  
1336 if ( !$ImgType || !$X->isAllowedImageType($ImgType) ) { #неизвестный формат
1337 $X->Msg("Can't detect img".$ImgSrcFile." Replace to text [bad img format]\n","w");
1338 my $Doc = XML::LibXML::Document->new('1.0', 'utf-8');
1339 my $Text = $Doc->createTextNode('[bad img format]');
1340 return $Text;
1341 }
1342  
1343 $X->_bs('img2jpg','IMG -> JPG');
1344 if ($X->isConvertImageType($ImgType)) { #некоторые попытаемся сконвертировать в jpg
1345 $ImgSrcFile = $X->Img2JPG($ImgSrcFile,$X->isUseImageProfile($ImgType));
1346 $Src .= ".jpg";
1347 }
1348 $X->_be('img2jpg');
1349  
1350 }
1351 $ImgChecked{$ImgSrcFile} = 1;
1352  
1353 $X->Msg("Find img, try transform: ".$Src."\n","w");
1354  
1355 my $ImgDestPath = $X->{'DestinationDir'}."/fb3/img";
1356  
1357 $Src =~ /.([^\/\.]+)$/;
1358 my $ImgType = $1;
1359  
1360 $ImgID = 'img_'.$X->UUID($ImgSrcFile);
1361  
1362 my $NewFileName = $ImgID.'.'.$ImgType;
1363 my $ImgDestFile = $ImgDestPath.'/'.$NewFileName;
1364  
1365 push @$ImgList, {
1366 'src_path' => $ImgSrcFile,
1367 'new_path' => "img/".$NewFileName, #заменим на новое имя
1368 'id' => $ImgID,
1369 } unless grep {$_->{id} eq $ImgID} @$ImgList;
1370  
1371 #Копируем исходник на новое место с новым уникальным именем
1372 unless (-f $ImgDestFile) {
1373 $X->Msg("copy $ImgSrcFile -> $ImgDestFile\n");
1374 $X->_bs('img_copy','Копирование IMG');
1375 FB3::Convert::copy($ImgSrcFile, $ImgDestFile) or $X->Error($!." [copy $ImgSrcFile -> $ImgDestFile]");
1376 $X->_be('img_copy');
1377 }
1378  
1379 }
1380  
1381 $Node->setAttribute('src' => $ImgID);
1382  
1383 return $Node;
1384 }
1385  
1386 # Перерисовываем href
1387 sub ProcessHref {
1388 my $X = shift;
1389 my %Args = @_;
1390 my $Node = $Args{'node'};
1391 my $RelPath = $Args{'relpath'};
1392  
1393 my $Href = $Node->getAttribute('href') || "";
1394  
1395 $Href = $X->trim_soft($Href);
1396 my ($Link, $Anchor) = split(/\#/, $Href, 2);
1397  
1398 my $NewHref =
1399 $Href ?
1400 $Href =~ /^[a-z]+\:/i
1401 ? $X->CorrectOuterLink($Href)
1402 : '#'.($Anchor ? 'link_' : '').$X->Path2ID( ($Link
1403 ?$Href: #внешний section
1404 basename($RelPath)."#".$Anchor #текущий section
1405 ), $RelPath , 'process_href',
1406 'skip' #не падать, если внешняя ссыль кривая
1407 )
1408 : '';
1409 $NewHref = undef if $NewHref =~ /^\#$/ || $NewHref =~ /^\#link_$/;
1410  
1411 if (defined($NewHref)) {
1412 $X->{'href_list'}->{$NewHref} = $Href if $X->trim($NewHref) ne '';
1413 $Node->setAttribute('xlink:href' => $NewHref);
1414 } else {
1415 $Node->parentNode->removeChild( $Node );
1416 }
1417  
1418 return $Node;
1419 }
1420  
1421 sub TransformTo {
1422 my $X = shift;
1423 my %Args = @_;
1424 my $Node = $Args{'node'};
1425 my $To = $Args{'params'}->[0];
1426  
1427 $Node->setNodeName($To);
1428 return $Node;
1429 }
1430  
1431 sub TransformH2Title {
1432 my $X = shift;
1433 my %Args = @_;
1434 my $Node = $Args{'node'};
1435  
1436 my $NewNode = XML::LibXML::Element->new('title');
1437 foreach ($Node->getAttributes) { #скопируем атрибуты
1438 $NewNode->setAttribute($_->name => $_->value);
1439 }
1440  
1441 my $Wrap = XML::LibXML::Element->new("p"); #wrapper
1442 foreach my $Child ($Node->getChildnodes) {
1443 my $Excl = $X->{'allow_elements'}->{'p'}->{'exclude_if_inside'};
1444 if ( grep {$Child->nodeName eq $_} @$Excl ) {
1445 foreach my $ChildIns ($Child->getChildnodes) {
1446 $Wrap->addChild($ChildIns->cloneNode(1));
1447 }
1448 } else {
1449 $Wrap->addChild($Child->cloneNode(1));
1450 }
1451 }
1452
1453 $NewNode->addChild($Wrap);
1454  
1455 return $NewNode;
1456 }
1457  
1458 sub FB3Creator {
1459 my $self = shift;
1460 my $X = shift;
1461 $X->Msg("Create FB3\n","w");
1462  
1463 my $Structure = shift || $X->{'STRUCTURE'} || $X->Error("Structure is empty");
1464 my $FB3Path = $X->{'DestinationDir'};
1465  
1466 #compile required files
1467 my $CoverSrc = $Structure->{'DESCRIPTION'}->{'TITLE-INFO'}->{'COVER_DESC'}->{'new_path'};
1468  
1469 $X->Msg("FB3: Create /_rels/.rels\n","w");
1470 my $FNrels="$FB3Path/_rels/.rels";
1471 open FHrels, ">$FNrels" or $X->Error("$FNrels: $!");
1472 print FHrels qq{<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1473 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">}.
1474 ( $CoverSrc ? qq{
1475 <Relationship Id="rId0" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail" Target="fb3/$CoverSrc"/>} : '' ).qq{
1476 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="fb3/meta/core.xml"/>
1477 <Relationship Id="rId2" Type="http://www.fictionbook.org/FictionBook3/relationships/Book" Target="fb3/description.xml"/>
1478 </Relationships>};
1479 close FHrels;
1480  
1481 $X->Msg("FB3: Create [Content_Types].xml\n","w");
1482 my $FNct="$FB3Path/[Content_Types].xml";
1483 open FHct, ">$FNct" or $X->Error("$FNct: $!");
1484 print FHct qq{<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1485 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
1486 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
1487 <Default Extension="png" ContentType="image/png"/>
1488 <Default Extension="jpg" ContentType="image/jpeg"/>
1489 <Default Extension="jpeg" ContentType="image/jpeg"/>
1490 <Default Extension="gif" ContentType="image/gif"/>
1491 <Default Extension="svg" ContentType="image/svg+xml"/>
1492 <Default Extension="xml" ContentType="application/xml"/>
1493 <Default Extension="css" ContentType="text/css"/>
1494 <Override PartName="/fb3/meta/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
1495 <Override PartName="/fb3/description.xml" ContentType="application/fb3-description+xml"/>
1496 <Override PartName="/fb3/body.xml" ContentType="application/fb3-body+xml"/>
1497 </Types>};
1498 close FHct;
1499  
1500 $X->Msg("FB3: Create /fb3/_rels/description.xml.rels\n","w");
1501 my $FNdrels="$FB3Path/fb3/_rels/description.xml.rels";
1502 open FHdrels, ">$FNdrels" or $X->Error("$FNdrels: $!");
1503 print FHdrels qq{<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1504 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1505 <Relationship Id="rId0"
1506 Target="body.xml"
1507 Type="http://www.fictionbook.org/FictionBook3/relationships/body" />
1508 </Relationships>};
1509 close FHdrels;
1510  
1511 # !! Стили пока не трогаем !!
1512 #Скопируем стили
1513 # foreach my $css (@{$Structure->{'CSS_LIST'}}) {
1514 # my $SrcPath = $X->{'ContentDir'}."/".$css->{'src_path'};
1515 # my $CssDestPath = $X->{'DestinationDir'}."/fb3/style";
1516 # my $CssFile = $css->{'src_path'};
1517 # $CssFile =~ s/.*\/([^\/]+)/$1/g;
1518 # my $DstPath = $CssDestPath."/".$CssFile;
1519 # $X->Msg("copy $SrcPath -> $DstPath\n","w");
1520 # copy($SrcPath, $DstPath) or $X->Error($!);
1521 # $css->{'new_path'} = "style/".$CssFile;
1522 # }
1523  
1524 #ДО ЭТОГО МОМЕНТА МЫ МОЖЕМ ИЗМЕНЯТЬ $Structure, ТО ЕСТЬ ВМЕШИВАТЬСЯ В КОНЕЧНЫЙ РЕЗУЛЬТАТ ОТРИСОВКИ FB3
1525 # print Data::Dumper::Dumper($Structure);
1526 # exit;
1527
1528 my $GlobalID = $Structure->{'DESCRIPTION'}->{'DOCUMENT-INFO'}->{'ID'};
1529 my $TitleInfo = $Structure->{'DESCRIPTION'}->{'TITLE-INFO'};
1530 my $DocInfo = $Structure->{'DESCRIPTION'}->{'DOCUMENT-INFO'};
1531
1532 #Пишем body
1533 $X->Msg("FB3: Create /fb3/body.xml\n","w");
1534 my $FNbody="$FB3Path/fb3/body.xml";
1535 my $BodyAttr = {
1536 'xmlns'=>"http://www.fictionbook.org/FictionBook3/body",
1537 'xmlns:xlink'=>"http://www.w3.org/1999/xlink",
1538 'id'=>$GlobalID,
1539 };
1540  
1541 $X->_bs('Obj2DOM_body','PAGES => DOM');
1542 my $Body = $X->Obj2DOM(
1543 obj=>{
1544 attributes=>{CP_compact=>1},
1545 value=>$Structure->{'PAGES'}->{'value'}
1546 },
1547 root=>{name=>'fb3-body', attributes=>$BodyAttr}
1548 );
1549 $X->_be('Obj2DOM_body');
1550
1551 #финальное приведение section к валидному виду
1552 foreach my $Section ($XC->findnodes( "/fb3-body/section/section", $Body), $XC->findnodes( "/fb3-body/section", $Body)) {
1553 $Section = $X->Transform2Valid(node=>$Section);
1554 }
1555  
1556 #финальное приведение table к валидному виду
1557 foreach my $Table ($XC->findnodes( "/fb3-body//table", $Body)) {
1558 $Table = $X->TransformTable2Valid(node=>$Table);
1559 }
1560  
1561 open FHbody, ">$FNbody" or $X->Error("$FNbody: $!");
1562 my $BodyString = $Body->toString(1);
1563 $BodyString =~ s/(<p>[^<>]*)<br\/>/$1<\/p><p>/g; #здесь уже правильный fb3, чистый и с параграфами, вот только <br/> нужно превратить в </p><p>
1564 $BodyString =~ s/<br\/>/ /g;
1565 print FHbody $BodyString;
1566 close FHbody;
1567  
1568 #Пишем мету
1569 #Превращаем перл-структуру в DOM
1570 delete $Structure->{'PAGES'};
1571 $X->_bs('Obj2DOM_meta','META => DOM');
1572 my $Doc = $X->Obj2DOM(obj=>$Structure, like_parent=>0, compact=>0 );
1573 $X->_be('Obj2DOM_meta');
1574  
1575 #Пишем rels
1576 $X->Msg("FB3: Create /fb3/_rels/body.xml.rels\n","w");
1577 my $FNbodyrels="$FB3Path/fb3/_rels/body.xml.rels";
1578 open FHbodyrels, ">$FNbodyrels" or $X->Error("$FNbodyrels: $!");
1579 print FHbodyrels qq{<?xml version="1.0" encoding="UTF-8"?>
1580 <Relationships xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:xlink="http://www.w3.org/1999/xlink">
1581 };
1582 foreach (@{$Structure->{'IMG_LIST'}}) {
1583 print FHbodyrels qq{ <Relationship Id="$_->{'id'}" Type="http://www.fictionbook.org/FictionBook3/relationships/image" Target="$_->{'new_path'}"/>
1584 };
1585 }
1586 print FHbodyrels qq{</Relationships>};
1587 close FHbodyrels;
1588
1589 #Пишем core
1590 $X->Msg("FB3: Create /fb3/meta/core.xml\n","w");
1591 my $FNcore="$FB3Path/fb3/meta/core.xml";
1592 open FHcore, ">$FNcore" or $X->Error("$FNcore: $!");
1593 print FHcore qq{<?xml version="1.0" encoding="UTF-8"?>
1594 <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.fictionbook.org/FictionBook3/description" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/">
1595 <dc:title>} . FB3::Convert::xmlescape($TitleInfo->{'BOOK-TITLE'}) . qq{</dc:title>
1596 <dc:subject>} . FB3::Convert::xmlescape($TitleInfo->{'ANNOTATION'}) . qq{</dc:subject>
1597 <dc:creator>};
1598
1599 my $c=1;
1600 foreach (@{$TitleInfo->{'AUTHORS'}}) {
1601 print FHcore FB3::Convert::xmlescape($_->{'first-name'}." ".$_->{'last-name'});
1602 print FHcore ", " if $c < scalar @{$TitleInfo->{'AUTHORS'}};
1603 $c++;
1604 }
1605
1606 print FHcore qq{</dc:creator>
1607 <dc:description>}.FB3::Convert::xmlescape($TitleInfo->{'ANNOTATION'}).qq{</dc:description>
1608 <cp:keywords>XML, FictionBook, eBook, OPC</cp:keywords>
1609 <cp:revision>1.00</cp:revision>
1610 }.
1611 ($DocInfo->{'DATE'}->{'attributes'}->{'value'}?qq{<dcterms:created xsi:type="dcterms:W3CDTF">}.$DocInfo->{'DATE'}->{'attributes'}->{'value'}.qq{</dcterms:created>
1612 }:'')
1613 .qq{<cp:contentStatus>Draft</cp:contentStatus>
1614 <cp:category>};
1615
1616 $c=1;
1617 foreach (@{$TitleInfo->{'GENRES'}}) {
1618 print FHcore FB3::Convert::xmlescape($_);
1619 print FHcore ", " if $c < scalar @{$TitleInfo->{'GENRES'}};
1620 $c++;
1621 }
1622  
1623 print FHcore qq{</cp:category>
1624 </cp:coreProperties>};
1625 close FHcore;
1626 #Пишем description
1627 $X->Msg("FB3: Create /fb3/description.xml\n","w");
1628 my $FNdesc="$FB3Path/fb3/description.xml";
1629 open FHdesc, ">$FNdesc" or $X->Error("$FNdesc: $!");
1630 print FHdesc qq{<?xml version="1.0" encoding="UTF-8"?>
1631 <fb3-description xmlns="http://www.fictionbook.org/FictionBook3/description" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" id="}.FB3::Convert::xmlescape($GlobalID).qq{" version="1.0">
1632 };
1633  
1634 print FHdesc qq{<title>
1635 <main>} . FB3::Convert::xmlescape($TitleInfo->{'BOOK-TITLE'}) . qq{</main>
1636 </title>
1637 };
1638
1639 print FHdesc qq{<fb3-relations>
1640 };
1641  
1642 foreach (@{$TitleInfo->{'AUTHORS'}}) {
1643  
1644 my $First = FB3::Convert::xmlescape($_->{'first-name'} );
1645 my $Middle = FB3::Convert::xmlescape($_->{'middle-name'});
1646 my $Last = FB3::Convert::xmlescape($_->{'last-name'} ) || "Unknown";
1647 my $Link = FB3::Convert::xmlescape($_->{'link'}) || "author";
1648  
1649 print FHdesc qq{<subject link="$Link" id="}.($_->{'id'}||'00000000-0000-0000-0000-000000000000').qq{">
1650 <title>
1651 <main>
1652 }.
1653 ($First?$First.' '.$Last:$Last).qq{
1654 </main>
1655 </title>}
1656 .($First?qq{
1657 <first-name>}.$First.'</first-name>':'')
1658 .($Middle?qq{
1659 <middle-name>}.$Middle.qq{</middle-name>}:'')
1660 .qq{
1661 <last-name>}.$Last.qq{</last-name>
1662 </subject>
1663 };
1664 }
1665  
1666 print FHdesc qq{</fb3-relations>
1667 };
1668  
1669 print FHdesc qq{<fb3-classification>
1670 };
1671 foreach (@{$TitleInfo->{'GENRES'}}) {
1672 print FHdesc qq{<subject>} . ( exists $GenreTranslate{$_} ? $GenreTranslate{$_} : FB3::Convert::xmlescape($_) ) . qq{</subject>
1673 };
1674 }
1675 print FHdesc qq{</fb3-classification>
1676 };
1677
1678 print FHdesc qq{<lang>}.$DocInfo->{'LANGUAGE'}.qq{</lang>
1679 <written>
1680 <lang>} . FB3::Convert::xmlescape($DocInfo->{'LANGUAGE'}) . qq{</lang>
1681 </written>
1682 };
1683  
1684 my $DCDate = $DocInfo->{'DATE'}->{'attributes'}->{'value'}."T".$DocInfo->{'TIME'}->{'attributes'}->{'value'};
1685 print FHdesc qq{<document-info created="}.$DCDate.qq{" updated="}.$DCDate.qq{"/>
1686 };
1687  
1688 print FHdesc qq{ <annotation>
1689 <p>} . FB3::Convert::xmlescape($TitleInfo->{'ANNOTATION'}) . qq{</p>
1690 </annotation>
1691 } if $TitleInfo->{'ANNOTATION'};
1692  
1693 print FHdesc qq{</fb3-description>};
1694 close FHdesc;
1695
1696 return $FB3Path;
1697 }
1698  
1699 1;
« blib/lib/FB3/Convert.pm ↑ Summary