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