| 1 | package FB3::Convert; | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use Data::Dumper; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use Term::ANSIColor; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 1 | ▶ | use File::Temp; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 1 | ▶ | use XML::LibXSLT; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 9 | use XML::LibXML; | ||
| 10 | use File::Basename; | ||
| 11 | use Hash::Merge; | ||
| 12 | use Cwd qw(cwd abs_path getcwd realpath); | ||
| 13 | use UUID::Tiny ':std'; | ||
| 14 | use File::Copy qw(copy); | ||
| 15 | use File::Temp qw/ tempfile tempdir /; | ||
| 16 | use FB3::Validator; | ||
| 17 | use utf8; | ||
| 18 | use URI::Escape; | ||
| 19 | use Encode qw(encode_utf8 decode_utf8); | ||
| 20 | use XML::Entities; | ||
| 21 | use XML::Entities::Data; | ||
| 22 | use Time::HiRes qw(gettimeofday sleep); | ||
| 23 | use Lingua::Identify qw(langof); | ||
| 24 | use Image::Magick; | ||
| 25 | use File::ShareDir qw/dist_dir/; | ||
| 26 | binmode(STDOUT,':utf8'); | ||
| 27 | |||
| 28 | our $VERSION = 0.32; | ||
| 29 | |||
| 30 | =head1 NAME | ||
| 31 | |||
| 32 | FB3::Convert - scripts and API for converting FB3 from and to different formats | ||
| 33 | |||
| 34 | =cut | ||
| 35 | |||
| 36 | my $Dist = dist_dir('FB3-Convert'); | ||
| 37 | my $ProfilesDir = $Dist."/profiles"; | ||
| 38 | my $CMYKProfile = $ProfilesDir.'/CoatedFOGRA27.icc'; | ||
| 39 | my $sRGBProfile = $ProfilesDir.'/sRGB_Color_Space.icc'; | ||
| 40 | |||
| 41 | my %MODULES; | ||
| 42 | # каким плагином работать - определяется тупо по расширению файла (см. ключ в хэше) | ||
| 43 | %MODULES = ( | ||
| 44 | 'epub' => { | ||
| 45 | 'class' => 'FB3::Convert::Epub', | ||
| 46 | 'unpack' => 1, | ||
| 47 | }, | ||
| 48 | 'fb2' => { | ||
| 49 | 'class' => 'FB3::Convert::FB2', | ||
| 50 | 'unpack' => 0, | ||
| 51 | }, | ||
| 52 | ); | ||
| 53 | |||
| 54 | my @BlockLevel = | ||
| 55 | ('address','article','aside','blockquote','canvas','dd','div','dl','dt','fieldset','figcaption','figure','footer','form', | ||
| 56 | 'h1','h2','h3','h4','h5','h6', | ||
| 57 | 'header','hr','li','main','nav','noscript','ol','output','p','pre','section','table','tfoot','ul','video', | ||
| 58 | #формально не блок-левел, но нам их тоже приводить к нормальному виду | ||
| 59 | 'th','tr','td' | ||
| 60 | ); | ||
| 61 | |||
| 62 | my $AllEntities = XML::Entities::Data::all; | ||
| 63 | delete $AllEntities->{'lt'}; | ||
| 64 | delete $AllEntities->{'gt'}; | ||
| 65 | delete $AllEntities->{'quot'}; | ||
| 66 | delete $AllEntities->{'apos'}; | ||
| 67 | delete $AllEntities->{'amp'}; | ||
| 68 | |||
| 69 | my %escapes = ( | ||
| 70 | '&' => '&', | ||
| 71 | '<' => '<', | ||
| 72 | '>' => '>', | ||
| 73 | '"' => '"', | ||
| 74 | '\'' => ''', | ||
| 75 | ); | ||
| 76 | my $xmlesc_rgx = join('|', keys %escapes); | ||
| 77 | |||
| 78 | sub xmlescape { | ||
| 79 | |||
| 80 | my $Esc = shift; | ||
| 81 | return unless defined $Esc; | ||
| 82 | |||
| 83 | $Esc =~ s/($xmlesc_rgx)/$escapes{$1}/gso; | ||
| 84 | return $Esc; | ||
| 85 | } | ||
| 86 | |||
| 87 | #Элементы, которые парсим в контенте и сохраняем в структуру | ||
| 88 | our $ElsMainList = { | ||
| 89 | 'span'=>undef, | ||
| 90 | 'a'=>undef, | ||
| 91 | 'em'=>undef, | ||
| 92 | 'sub'=>undef, | ||
| 93 | 'sup'=>undef, | ||
| 94 | 'code'=>undef, | ||
| 95 | 'img'=>undef, | ||
| 96 | 'i'=>undef, | ||
| 97 | 'u'=>undef, | ||
| 98 | 'underline'=>undef, | ||
| 99 | 'b'=>undef, | ||
| 100 | 'strong'=>undef, | ||
| 101 | 'br'=>undef, | ||
| 102 | }; | ||
| 103 | |||
| 104 | our $ElsMainList2={}; | ||
| 105 | map {$ElsMainList2->{$_}=undef;} keys %$ElsMainList; | ||
| 106 | $ElsMainList2->{p}=undef; | ||
| 107 | |||
| 108 | my @AccessImgFormat = ('png','gif','jpg','jpeg','svg','bmp','tiff','tif', | ||
| 109 | 'cur','tga','vda','icb','vst'#<-targa | ||
| 110 | ); | ||
| 111 | my @ConvertImgFormat = ('bmp','tiff','tif', | ||
| 112 | 'cur','tga','vda','icb','vst' | ||
| 113 | ); | ||
| 114 | my %UseImgProfile = ('tiff'=>1,'tif'=>1); | ||
| 115 | |||
| 116 | my %AllowElementsMain = ( | ||
| 117 | 'table' => { | ||
| 118 | 'allow_attributes' => ['id'], | ||
| 119 | 'allow_elements_inside' => {'tr'=>undef}, | ||
| 120 | }, | ||
| 121 | 'tr' => { | ||
| 122 | 'allow_attributes' => ['id','align'], | ||
| 123 | 'allow_elements_inside' => {'th'=>undef,'td'=>undef}, | ||
| 124 | }, | ||
| 125 | 'th' => { | ||
| 126 | 'allow_attributes' => ['colspan','rowspan','align','valign'], | ||
| 127 | 'allow_elements_inside' => $ElsMainList2, | ||
| 128 | }, | ||
| 129 | 'td' => { | ||
| 130 | 'allow_attributes' => ['colspan','rowspan','align','valign'], | ||
| 131 | 'allow_elements_inside' => $ElsMainList2, | ||
| 132 | }, | ||
| 133 | 'i' => { | ||
| 134 | 'allow_attributes' => [], | ||
| 135 | 'allow_elements_inside' => $ElsMainList, | ||
| 136 | }, | ||
| 137 | 'strong' => { | ||
| 138 | 'allow_attributes' => ['id'], | ||
| 139 | 'allow_elements_inside' => $ElsMainList, | ||
| 140 | }, | ||
| 141 | 'underline' => { | ||
| 142 | 'allow_attributes' => ['id'], | ||
| 143 | 'allow_elements_inside' => $ElsMainList, | ||
| 144 | }, | ||
| 145 | 'em' => { | ||
| 146 | 'allow_attributes' => ['id'], | ||
| 147 | 'allow_elements_inside' => $ElsMainList, | ||
| 148 | }, | ||
| 149 | 'u' => { | ||
| 150 | 'allow_attributes' => ['id'] | ||
| 151 | }, | ||
| 152 | 'sup' => { | ||
| 153 | 'allow_attributes' => ['id'] | ||
| 154 | }, | ||
| 155 | 'sub' => { | ||
| 156 | 'allow_attributes' => ['id'] | ||
| 157 | }, | ||
| 158 | 'p' => { | ||
| 159 | 'allow_attributes' => ['id'], | ||
| 160 | 'allow_elements_inside' => $ElsMainList, | ||
| 161 | 'exclude_if_inside' => ['ul','ol','table'], #с этими вариантами лучше схлопнуться родительскому 'p' | ||
| 162 | }, | ||
| 163 | 'span' => { | ||
| 164 | 'allow_attributes' => ['id'], | ||
| 165 | 'allow_elements_inside' => $ElsMainList, | ||
| 166 | }, | ||
| 167 | 'title' => { | ||
| 168 | 'processor' => \&Transform2Valid, | ||
| 169 | 'allow_attributes' => ['id'], | ||
| 170 | 'allow_elements_inside' => {'p'=>undef}, | ||
| 171 | }, | ||
| 172 | 'subtitle' => { | ||
| 173 | 'allow_attributes' => ['id'], | ||
| 174 | 'allow_elements_inside' => $ElsMainList, | ||
| 175 | }, | ||
| 176 | 'ul' => { | ||
| 177 | 'allow_attributes' => ['id'], | ||
| 178 | 'allow_elements_inside' => {'li'=>undef, 'title'=>undef, 'epigraph'=>undef}, | ||
| 179 | }, | ||
| 180 | 'ol' => { | ||
| 181 | 'allow_attributes' => ['id'], | ||
| 182 | 'allow_elements_inside' => {'li'=>undef, 'title'=>undef, 'epigraph'=>undef}, | ||
| 183 | }, | ||
| 184 | 'li' => { | ||
| 185 | 'allow_attributes' => [], | ||
| 186 | 'allow_elements_inside' => {'em'=>undef,a=>undef}, | ||
| 187 | }, | ||
| 188 | 'root_fb3_container' => { | ||
| 189 | 'allow_elements_inside' => { | ||
| 190 | 'underline'=>undef, | ||
| 191 | 'b'=>undef, | ||
| 192 | 'strong'=>undef, | ||
| 193 | 'span'=>undef, | ||
| 194 | 'div'=>undef, | ||
| 195 | 'b'=>undef, | ||
| 196 | 'h1'=>undef, | ||
| 197 | 'h2'=>undef, | ||
| 198 | 'h3'=>undef, | ||
| 199 | 'h4'=>undef, | ||
| 200 | 'h5'=>undef, | ||
| 201 | 'h6'=>undef, | ||
| 202 | 'table'=>undef, | ||
| 203 | 'ul'=>undef, | ||
| 204 | 'ol'=>undef, #полноправные элементы корня | ||
| 205 | 'p'=>undef, # см. ^^^ | ||
| 206 | 'title'=>undef, #разрешен, так как нужен в заголовочном section, но в body его необходимо удалять | ||
| 207 | 'subtitle'=>undef, | ||
| 208 | 'img' => undef, #некоторые элементы попадаются в корне, их так же нужно разрешить. Transform2Valid() их обрамит в <p> | ||
| 209 | 'a' => undef # см. ^^^ | ||
| 210 | } | ||
| 211 | }, | ||
| 212 | |||
| 213 | ); | ||
| 214 | |||
| 215 | my $XSLT = XML::LibXSLT->new; | ||
| 216 | my $XC = XML::LibXML::XPathContext->new(); | ||
| 217 | my $Parser = XML::LibXML->new(); | ||
| 218 | |||
| 219 | use constant { | ||
| 220 | NS_FB3_DESCRIPTION => 'http://www.fictionbook.org/FictionBook3/description' | ||
| 221 | }; | ||
| 222 | |||
| 223 | sub new { | ||
| 224 | my $class = shift; | ||
| 225 | my $X = {}; | ||
| 226 | my %Args = @_; | ||
| 227 | |||
| 228 | if ($Args{'empty'}) { | ||
| 229 | bless $X, $class; | ||
| 230 | return $X; | ||
| 231 | } | ||
| 232 | |||
| 233 | my $SourcePath = $Args{'source'}; | ||
| 234 | my $SourceFileName = $SourcePath; | ||
| 235 | $SourceFileName =~ s/.*?([^\/]+)$/$1/g; | ||
| 236 | |||
| 237 | my $DestinationDir = $Args{'destination_dir'} || tempdir(); | ||
| 238 | my $DestinationFile = $Args{'destination_file'}; | ||
| 239 | |||
| 240 | if ($DestinationFile) { | ||
| 241 | if ($DestinationFile =~ /^[^\/]/) { | ||
| 242 | $DestinationFile = cwd()."/".$DestinationFile; | ||
| 243 | } | ||
| 244 | my $DstFileDir = dirname($DestinationFile); | ||
| 245 | Error($X,"Directory for destination file not found! : ".$DstFileDir) unless -d $DstFileDir; | ||
| 246 | $DestinationFile = Cwd::realpath($DestinationFile); | ||
| 247 | } | ||
| 248 | |||
| 249 | Error($X,"source file not defined") unless $SourcePath; | ||
| 250 | Error($X,"source file '".$SourcePath."' not exists") unless -f $SourcePath; | ||
| 251 | |||
| 252 | my $FileType; | ||
| 253 | if ($Args{'src_type'}) { | ||
| 254 | $FileType = $Args{'src_type'}; | ||
| 255 | } else { | ||
| 256 | $SourcePath =~ /\.([^\.]+)$/; | ||
| 257 | $FileType = $1; | ||
| 258 | } | ||
| 259 | |||
| 260 | Error($X, "File '".$SourcePath."' format '".$FileType."' not detected") unless $MODULES{$FileType}; | ||
| 261 | |||
| 262 | my $Sub = $FileType; | ||
| 263 | |||
| 264 | my $Module = $MODULES{$Sub}->{class}; | ||
| 265 | #подгружаем нужный модуль | ||
| 266 | eval { | ||
| 267 | (my $MFile = $Module) =~ s|::|/|g; | ||
| 268 | require $MFile . '.pm'; | ||
| 269 | 1; | ||
| 270 | } or do { | ||
| 271 | Error($X, "Can't load module ".$Module." ".$@); | ||
| 272 | }; | ||
| 273 | |||
| 274 | $X->{'ClassName'} = $Sub; | ||
| 275 | $X->{'Source'} = $SourcePath; | ||
| 276 | $X->{'SourceFileName'} = $SourceFileName; | ||
| 277 | $X->{'SourceDir'} = undef; | ||
| 278 | $X->{'DestinationDir'} = $DestinationDir; | ||
| 279 | $X->{'DestinationFile'} = $DestinationFile; | ||
| 280 | $X->{'Module'} = $Module; | ||
| 281 | $X->{'verbose'} = $Args{'verbose'} ? $Args{'verbose'} : 0; | ||
| 282 | $X->{'euristic'} = $Args{'euristic'} || undef; | ||
| 283 | $X->{'euristic_debug'} = $Args{'euristic_debug'} || undef; | ||
| 284 | $X->{'phantom_js_path'} = $Args{'phantom_js_path'} || undef; | ||
| 285 | $X->{'showname'} = $Args{'showname'} ? 1 : 0; | ||
| 286 | $X->{'allow_elements'} = \%AllowElementsMain; | ||
| 287 | $X->{'href_list'} = {}; #собираем ссылки в документе | ||
| 288 | $X->{'id_list'} = {}; #собираем ссылки в документе | ||
| 289 | $X->{'bench'} = $Args{'bench'} ? 1 : 0; #бенчмарк режим в stdout | ||
| 290 | $X->{'bench2file'} = $Args{'bench2file'} ? $Args{'bench2file'} : 0; #бенчмарк режим в файл | ||
| 291 | $X->{'bench_list'} = {}; #бенчмарк режим | ||
| 292 | $X->{'simple'} = $Args{'simple'} ? 1 : 0; #Преобразование без создания структуры | ||
| 293 | $X->{'xsl_path'} = $Args{'xsl_path'}; | ||
| 294 | $X->{'src_type'} = $Args{'src_type'} if exists $MODULES{$Args{'src_type'}}; | ||
| 295 | |||
| 296 | unless ($Args{'simple'}) { | ||
| 297 | #Наша внутренняя структура данных конвертора. шаг влево - расстрел | ||
| 298 | $X->{'STRUCTURE'} = { | ||
| 299 | |||
| 300 | 'DESCRIPTION' => { | ||
| 301 | 'TITLE-INFO' => { | ||
| 302 | 'COVER_DESC' => undef, | ||
| 303 | 'AUTHORS' => undef, #[ | ||
| 304 | #{ | ||
| 305 | # 'first-name' => "Иван", | ||
| 306 | # 'id' => 'bcf95bde-eedc-49ef-926c-588bd4cfd9cd', | ||
| 307 | # 'middle-name' => undef, | ||
| 308 | # 'last-name' => "Растеряйло" | ||
| 309 | #}, | ||
| 310 | #], | ||
| 311 | 'PUBLISHER' => undef, | ||
| 312 | 'ANNOTATION' => undef, | ||
| 313 | 'BOOK-TITLE' => undef, | ||
| 314 | 'GENRES' => undef, #[ | ||
| 315 | # 'humor_prose', | ||
| 316 | # 'prose_su_classics' | ||
| 317 | #], | ||
| 318 | }, | ||
| 319 | 'DOCUMENT-INFO' => { | ||
| 320 | 'DATE' => undef, #{ | ||
| 321 | #'attributes' => { | ||
| 322 | # 'value' => undef | ||
| 323 | #} | ||
| 324 | #}, | ||
| 325 | 'TIME' => { | ||
| 326 | 'attributes' => { | ||
| 327 | 'value' => "00:00:00", | ||
| 328 | } | ||
| 329 | }, | ||
| 330 | 'LANGUAGE' => undef, | ||
| 331 | 'ID' => undef | ||
| 332 | } | ||
| 333 | }, | ||
| 334 | 'IMG_LIST' => [ # сюда складывает все встреченные картинки. Их ведь нужно копировать в новую папку, и rels строить | ||
| 335 | # { | ||
| 336 | # 'src_path' => 'images/_1000516292.jpg', | ||
| 337 | # 'id' => 'img1', | ||
| 338 | # 'new_path' => 'img/794__1000516292.jpg' | ||
| 339 | # } | ||
| 340 | ], | ||
| 341 | 'CSS_LIST' => [ # так же со стилями | ||
| 342 | #{ | ||
| 343 | # 'id' => 'mainCSS', | ||
| 344 | # 'new_path' => undef, | ||
| 345 | # 'src_path' => 'css/main.css' | ||
| 346 | #}, | ||
| 347 | ], | ||
| 348 | 'PAGES' => { # контент для body | ||
| 349 | 'attributes' => { | ||
| 350 | 'CP_compact' => 1 # узлы без контейнеров | ||
| 351 | }, | ||
| 352 | 'value' => [ | ||
| 353 | {} # дерево любой вложенности. см sub Obj2DOM | ||
| 354 | ] | ||
| 355 | } | ||
| 356 | }; | ||
| 357 | } | ||
| 358 | |||
| 359 | bless $X, $class; | ||
| 360 | Init($X); | ||
| 361 | |||
| 362 | #мета из файла (->fb3/description.xml) | ||
| 363 | if ($Args{'metadata'}) { | ||
| 364 | $X->Error("Meta file ".$Args{'metadata'}." not exists\n") unless -f $Args{'metadata'}; | ||
| 365 | $X->{'metadata'} = $Args{'metadata'}; | ||
| 366 | $X->ParseMetaFile() unless $Args{'simple'}; | ||
| 367 | File::Copy::copy($X->{'metadata'}, $X->{'DestinationDir'}."/fb3/description.xml"); | ||
| 368 | } elsif ($Args{'meta'}) { | ||
| 369 | #или мета из параметров | ||
| 370 | $X->BuildOuterMeta(meta => $Args{'meta'}); | ||
| 371 | } | ||
| 372 | |||
| 373 | return $X; | ||
| 374 | } | ||
| 375 | |||
| 376 | sub Init { | ||
| 377 | my $X = shift; | ||
| 378 | Msg($X,"Init\n"); | ||
| 379 | my $FB3Path = $X->{'DestinationDir'}; | ||
| 380 | |||
| 381 | if (-d $FB3Path) { | ||
| 382 | $X->Msg("Remove old destination dir: ".$FB3Path."\n","w"); | ||
| 383 | ForceRmDir($X, $FB3Path); | ||
| 384 | } | ||
| 385 | |||
| 386 | Msg($X,"Create FB3 directory: ".$FB3Path."\n"); | ||
| 387 | mkdir "$FB3Path" or $X->Error("$FB3Path : $!"); | ||
| 388 | |||
| 389 | for my $Dir ("/fb3", "/fb3/img", "/fb3/style", "/fb3/meta", "/fb3/_rels", "/_rels") { | ||
| 390 | mkdir "$FB3Path$Dir" or $X->Error("$FB3Path$Dir : $!"); | ||
| 391 | } | ||
| 392 | Msg($X,"FB3: Directory structure is created successfully.\n"); | ||
| 393 | |||
| 394 | } | ||
| 395 | |||
| 396 | sub Reap { | ||
| 397 | my $X = shift; | ||
| 398 | my $Processor = $MODULES{$X->{'ClassName'}}; | ||
| 399 | my $File = $X->{'Source'}; | ||
| 400 | |||
| 401 | $X->Msg("working with file ".$File."\n",'w',1) if $X->{'showname'} || $X->{'verbose'}; | ||
| 402 | |||
| 403 | $X->_bs('unpack','Распаковка файла'); | ||
| 404 | $File = $Processor->{class}->_Unpacker($X,$File) if $Processor->{'unpack'}; | ||
| 405 | $X->_be('unpack'); | ||
| 406 | |||
| 407 | $X->_bs('reap','Потрошение исходного файла, cборка данных'); | ||
| 408 | $Processor->{'class'}->Reaper($X, source => ($File || $X->{'Source'}), src_type=>$X->{'src_type'}); | ||
| 409 | $X->_be('reap'); | ||
| 410 | |||
| 411 | return $X->{'STRUCTURE'}; | ||
| 412 | } | ||
| 413 | |||
| 414 | # -- методы могут быть переопределены в дочернем классе -- | ||
| 415 | |||
| 416 | #Распаковывает файл как zip, на выходе отдает директорию | ||
| 417 | sub _Unpacker { | ||
| 418 | my $self = shift; | ||
| 419 | my $X = shift; | ||
| 420 | my $Source = shift; | ||
| 421 | |||
| 422 | my $TMPPath = tempdir(CLEANUP=>1); | ||
| 423 | |||
| 424 | $X->{'SourceDir'} = $TMPPath; | ||
| 425 | $X->{'unzipped'} = 1; | ||
| 426 | |||
| 427 | my $Zip = Archive::Zip->new(); | ||
| 428 | |||
| 429 | unless ($Zip->read($Source) == Archive::Zip::AZ_OK ) { | ||
| 430 | Error($X,"Error reading file '".$Source."' as zip"); | ||
| 431 | } | ||
| 432 | |||
| 433 | my @FilesInZip = $Zip->members(); | ||
| 434 | |||
| 435 | Msg($X,"Unzip source file to directory: ".$TMPPath."\n"); | ||
| 436 | foreach (@FilesInZip) { | ||
| 437 | my $Fname = $_->fileName; | ||
| 438 | Error($X,"Error reading file '".$Source."' as zip. So file '".substr($Fname,-100,100)."' have strange structure. [may be exploit?]") if $Fname =~ m#\.\./# || $Fname =~ m#^\W*/#; | ||
| 439 | my $ExtFile = $TMPPath.'/'.$Fname; | ||
| 440 | |||
| 441 | my $Code; | ||
| 442 | eval{$Code = $Zip->extractMember($_, $ExtFile);}; | ||
| 443 | if ($@) { | ||
| 444 | my $Ext; | ||
| 445 | $Ext = "[dublicate names of dir and file?] " if $@ =~ /mkdir\s(.+?):/; | ||
| 446 | Error($X,"can't unpuck ".$Fname." from ".$Source." archive: $Ext".EncodeUtf8($X,$@)); | ||
| 447 | } | ||
| 448 | $X->Error($X,"can't unpuck ".$Fname." from ".$Source." archive. Code #".$Code) unless $Code == AZ_OK; | ||
| 449 | } | ||
| 450 | |||
| 451 | return $TMPPath; | ||
| 452 | } | ||
| 453 | |||
| 454 | sub FB3Create { | ||
| 455 | my $X = shift; | ||
| 456 | my $Processor = $MODULES{$X->{'ClassName'}}; | ||
| 457 | |||
| 458 | my $FB3Path = $Processor->{'class'}->FB3Creator($X); | ||
| 459 | |||
| 460 | return $FB3Path; | ||
| 461 | } | ||
| 462 | |||
| 463 | sub FB3_2_Zip { | ||
| 464 | my $X = shift; | ||
| 465 | my %Args = @_; | ||
| 466 | |||
| 467 | Msg($X,"Create Zip from FB3: ".$X->{'DestinationFile'}."\n"); | ||
| 468 | |||
| 469 | my $old_dir = cwd(); | ||
| 470 | chdir("$X->{'DestinationDir'}"); | ||
| 471 | system("/usr/bin/zip -rq9 '".$X->{'DestinationFile'}."' ./*"); | ||
| 472 | chdir $old_dir if $old_dir; | ||
| 473 | Msg($X,"Delete dir after zip: $X->{'DestinationDir'}\n"); | ||
| 474 | ForceRmDir($X,$X->{'DestinationDir'}); | ||
| 475 | Msg($X,"OK\n"); | ||
| 476 | } | ||
| 477 | |||
| 478 | sub InNode { | ||
| 479 | my $X = shift; | ||
| 480 | my $Node = shift; | ||
| 481 | join "",map {$_->toString} $Node->childNodes; | ||
| 482 | } | ||
| 483 | |||
| 484 | # function Obj2DOM() | ||
| 485 | # | ||
| 486 | # example: | ||
| 487 | # my $Doc = Obj2DOM($X, | ||
| 488 | # obj => { | ||
| 489 | # attributes => {attr1 => 1, attr2 => 2}, | ||
| 490 | # title0 => 'TITLE0', | ||
| 491 | # title1 => { | ||
| 492 | # attributes => {attr3 => 3, attr4 => 4}, | ||
| 493 | # value => 'TITLE1', | ||
| 494 | # }, | ||
| 495 | # title2 => { | ||
| 496 | # attributes => {attr5 => 5, attr6 => 6}, | ||
| 497 | # value => [7,8,{item9=>[10,12,{item12=>12}]}], | ||
| 498 | # }, | ||
| 499 | # title3 => [ | ||
| 500 | # {'item13' => 13}, | ||
| 501 | # {'item14' => 14}, | ||
| 502 | # 15,16, | ||
| 503 | # '_17','_18', | ||
| 504 | # ], | ||
| 505 | # 'title4' => { | ||
| 506 | # attributes => {CP_compact => 1}, | ||
| 507 | # value => [123,{span=>'spanvalue'}] | ||
| 508 | # } | ||
| 509 | # } | ||
| 510 | # ); | ||
| 511 | # print $Doc->toString( | ||
| 512 | # 1 #pretty | ||
| 513 | # ); | ||
| 514 | # | ||
| 515 | # (hashes sorted by keys) => | ||
| 516 | # <?xml version="1.0" encoding="utf-8"?> | ||
| 517 | # <root attr1="1" attr2="2"> | ||
| 518 | # <title0>TITLE0</title0> | ||
| 519 | # <title1 attr4="4" attr3="3">TITLE1</title1> | ||
| 520 | # <title2 attr6="6" attr5="5"> | ||
| 521 | # <item>7</item> | ||
| 522 | # <item>8</item> | ||
| 523 | # <item> | ||
| 524 | # <item>10</item> | ||
| 525 | # <item>12</item> | ||
| 526 | # <item12>12</item12> | ||
| 527 | # </item9> | ||
| 528 | # </title2> | ||
| 529 | # <title3> | ||
| 530 | # <item13>13</item13> | ||
| 531 | # <item14>14</item14> | ||
| 532 | # <item>15</item> | ||
| 533 | # <item>16</item> | ||
| 534 | # <item>_17</item> | ||
| 535 | # <item>_18</item> | ||
| 536 | # </title3> | ||
| 537 | # <title4> | ||
| 538 | # 123<span>spanvalue</span> | ||
| 539 | # </title4> | ||
| 540 | # </root> | ||
| 541 | |||
| 542 | my $Doc; | ||
| 543 | sub Obj2DOM { | ||
| 544 | my $X = shift; | ||
| 545 | my %Args = @_; | ||
| 546 | |||
| 547 | my $Obj = $Args{'obj'}; | ||
| 548 | my $Parent = $Args{'parent'} || undef; | ||
| 549 | my $Sub = $Args{'sub'} || 0; | ||
| 550 | my $Root = $Args{'root'} || {name=>'root'}; | ||
| 551 | |||
| 552 | #параметры, влияющие на поведение отрисовки DOM | ||
| 553 | my $ArrayNodeNameLikeParent = $Args{'like_parent'} || 0; # title1 =>[{},{}] ==> <title1><title1/><title1/></title1> | ||
| 554 | my $Compact = $Args{'compact'} || 0; # like_parent не актуально. элементы не обрамляются в item-контейнеры | ||
| 555 | |||
| 556 | undef $Doc unless $Sub; #первый заход парсинга. $Doc fresh and virginity | ||
| 557 | |||
| 558 | unless ($Doc) { | ||
| 559 | $Doc = XML::LibXML::Document->new('1.0', 'utf-8'); | ||
| 560 | } | ||
| 561 | |||
| 562 | my $First=0; | ||
| 563 | if (!$Parent) { | ||
| 564 | $First=1; | ||
| 565 | $Parent = $Doc->createElement($Root->{'name'}); | ||
| 566 | if ($Root->{'attributes'}) { | ||
| 567 | foreach my $RAttr ( keys %{$Root->{'attributes'}}) { | ||
| 568 | $Parent->addChild($Doc->createAttribute( $RAttr => $Root->{'attributes'}->{$RAttr} )); | ||
| 569 | } | ||
| 570 | } | ||
| 571 | } | ||
| 572 | |||
| 573 | if (ref $Obj eq 'HASH') { | ||
| 574 | |||
| 575 | foreach my $Key (sort keys %$Obj) { | ||
| 576 | my $Value = $Obj->{$Key}; | ||
| 577 | |||
| 578 | if ($Key eq 'attributes') { | ||
| 579 | foreach (sort keys %{$Obj->{'attributes'}}) { | ||
| 580 | $Compact = 1 if $_ eq 'CP_compact' && $Obj->{'attributes'}->{$_}; #все следующие вложенные ноды - в формате compact | ||
| 581 | $Parent->addChild($Doc->createAttribute( $_ => $Obj->{'attributes'}->{$_} )) unless $First; | ||
| 582 | } | ||
| 583 | } elsif ($Key eq 'value') { | ||
| 584 | Obj2DOM($X, sub=>1, obj => $Obj->{$Key}, parent => $Parent, like_parent => $ArrayNodeNameLikeParent, compact => $Compact); | ||
| 585 | } else { | ||
| 586 | my $Child = $Doc->createElement($Key); | ||
| 587 | Obj2DOM($X, sub=>1, obj => $Obj->{$Key}, parent => $Child, like_parent => $ArrayNodeNameLikeParent, compact => $Compact); | ||
| 588 | $Parent->addChild($Child); | ||
| 589 | } | ||
| 590 | |||
| 591 | } | ||
| 592 | |||
| 593 | } elsif (ref $Obj eq 'ARRAY') { | ||
| 594 | foreach my $Item (@$Obj) { | ||
| 595 | if (ref $Item eq '' | ||
| 596 | || (!$Compact && ref $Item eq 'HASH') | ||
| 597 | ) { | ||
| 598 | my $Child; | ||
| 599 | $Child = $Doc->createElement($ArrayNodeNameLikeParent?$Parent->nodeName:'item') unless $Compact; | ||
| 600 | Obj2DOM($X, sub=>1, obj => $Item, parent => ($Compact ? $Parent : $Child), like_parent => $ArrayNodeNameLikeParent, compact => $Compact); | ||
| 601 | $Parent->addChild($Child) unless $Compact; | ||
| 602 | } else { | ||
| 603 | Obj2DOM($X, sub=>1, obj => $Item, parent => $Parent, like_parent => $ArrayNodeNameLikeParent, compact => $Compact); | ||
| 604 | } | ||
| 605 | } | ||
| 606 | } elsif (ref $Obj eq '') { | ||
| 607 | $Parent->appendTextNode($Obj); | ||
| 608 | } | ||
| 609 | |||
| 610 | $Doc->setDocumentElement($Parent) unless $Sub; | ||
| 611 | return $Doc; | ||
| 612 | } | ||
| 613 | |||
| 614 | sub Content2Tree { | ||
| 615 | my $X = shift; | ||
| 616 | my $Obj = shift; | ||
| 617 | my $Content = $Obj->{'content'}; | ||
| 618 | my $File = uri_unescape($Obj->{'file'}); | ||
| 619 | |||
| 620 | $Content = $X->trim($Content); | ||
| 621 | |||
| 622 | #ровняем пробелы у block-level | ||
| 623 | my $BlockRegExp = '('.(join "|", @BlockLevel).')'; | ||
| 624 | $Content =~ s#\s*(</?$BlockRegExp[^>]*>)\s*#$1#gi; | ||
| 625 | |||
| 626 | my $XMLDoc = XML::LibXML->new( | ||
| 627 | expand_entities => 0, # не считать & за entity | ||
| 628 | no_network => 1, # не будем тянуть внешние вложения | ||
| 629 | recover => ($X->{'verbose'} && $X->{'verbose'} > 1 ? 1 : 2), # не падать при кривой структуре. например, не закрыт тег. entity и пр | => 1 - вопить, 2 - совсем молчать | ||
| 630 | load_ext_dtd => 0, # полный молчок про dtd | ||
| 631 | ); | ||
| 632 | |||
| 633 | my $NodeDoc = $XMLDoc->parse_string('<root_fb3_container>'.$Content.'</root_fb3_container>') || $X->Error("Can't parse! ".$!); | ||
| 634 | |||
| 635 | my $RootEl = $NodeDoc->getDocumentElement; | ||
| 636 | my $Result = &ProcNode($X,$RootEl,$File,'root_fb3_container'); | ||
| 637 | |||
| 638 | $X->_bs('TRPost','Постпроцессинг трансфомированных'); | ||
| 639 | $Result = $X->TransformedPostprocess($Result); | ||
| 640 | $X->_be('TRPost'); | ||
| 641 | |||
| 642 | |||
| 643 | return { | ||
| 644 | content => $X->NormalizeTree($Result), | ||
| 645 | ID => $X->Path2ID(uri_unescape($File),undef,'main_section'), #main-sectioon | ||
| 646 | ID_SUB => $X->UUID(), #sub-section | ||
| 647 | }; | ||
| 648 | } | ||
| 649 | |||
| 650 | #после трансформации нод (Epub::TransformTo и т.д), общая картина может стать невалидной | ||
| 651 | #еще раз обработаем дерево с учетом текущих реалий | ||
| 652 | sub TransformedPostprocess { | ||
| 653 | my $X = shift; | ||
| 654 | my $Data = shift; | ||
| 655 | |||
| 656 | my %AllowElements = %{$X->{'allow_elements'}}; | ||
| 657 | |||
| 658 | return unless ref $Data eq 'ARRAY'; | ||
| 659 | |||
| 660 | foreach my $Item (@$Data) { | ||
| 661 | if (ref $Item eq 'HASH') { | ||
| 662 | foreach my $NodeName (sort keys %$Item) { | ||
| 663 | my $NodeValue = $Item->{$NodeName}; | ||
| 664 | if (ref $NodeValue eq 'HASH' && exists $NodeValue->{'was'} && $NodeValue->{'was'} ne $NodeName) { #была трансформация. кандидат на рассмотрение | ||
| 665 | my $Exclude = 0; | ||
| 666 | if ($AllowElements{$NodeValue->{'was'}}->{'exclude_if_inside'}) { #проверка на вшивость | ||
| 667 | $Exclude = 1 if $X->StructHaveInside($NodeValue->{'value'}, $AllowElements{$NodeValue->{'was'}}->{'exclude_if_inside'}); | ||
| 668 | } | ||
| 669 | if ($Exclude) { | ||
| 670 | $Item = $NodeValue->{'value'}; | ||
| 671 | } | ||
| 672 | } | ||
| 673 | if (ref $NodeValue eq 'HASH') { | ||
| 674 | delete $NodeValue->{'was'} if exists $NodeValue->{'was'}; | ||
| 675 | TransformedPostprocess($X,$NodeValue->{'value'}) if exists $NodeValue->{'value'}; | ||
| 676 | } | ||
| 677 | } | ||
| 678 | } elsif (ref $Item eq 'ARRAY') { | ||
| 679 | TransformedPostprocess($X,$Item); | ||
| 680 | } | ||
| 681 | } | ||
| 682 | |||
| 683 | return $Data; | ||
| 684 | } | ||
| 685 | |||
| 686 | sub StructHaveInside { | ||
| 687 | my $X = shift; | ||
| 688 | my $Node = shift; | ||
| 689 | my $ExcludeList = shift; | ||
| 690 | return unless ref $Node eq 'ARRAY'; | ||
| 691 | |||
| 692 | my $Finded = 0; | ||
| 693 | foreach my $Item (@$Node) { | ||
| 694 | last if $Finded; | ||
| 695 | if (ref $Item eq 'ARRAY') { | ||
| 696 | return 1 if $X->StructHaveInside($Item,$ExcludeList); | ||
| 697 | } elsif (ref $Item eq 'HASH') { #рассматриваем только первый уровень, глубже - не наше поле ответственности | ||
| 698 | foreach my $NodeNameInside (sort keys %$Item) { | ||
| 699 | return 1 if grep {$NodeNameInside eq $_} @$ExcludeList; | ||
| 700 | } | ||
| 701 | } | ||
| 702 | } | ||
| 703 | return $Finded; | ||
| 704 | } | ||
| 705 | |||
| 706 | sub NormalizeTree { | ||
| 707 | my $X = shift; | ||
| 708 | my $Data = shift; | ||
| 709 | |||
| 710 | return unless ref $Data eq 'ARRAY'; | ||
| 711 | |||
| 712 | my @Ar; | ||
| 713 | foreach my $Item (@$Data) { | ||
| 714 | |||
| 715 | if (ref $Item eq 'HASH') { | ||
| 716 | foreach (keys %$Item) { | ||
| 717 | $Item->{$_}->{'value'} = NormalizeTree($X,$Item->{$_}->{'value'}) | ||
| 718 | if ref $Item->{$_} eq 'HASH' && exists $Item->{$_}->{'value'}; | ||
| 719 | } | ||
| 720 | } | ||
| 721 | |||
| 722 | if (ref $Item eq 'ARRAY') { | ||
| 723 | $Item = NormalizeTree($X,$Item); | ||
| 724 | push @Ar, @$Item; | ||
| 725 | next; | ||
| 726 | } | ||
| 727 | |||
| 728 | if (!ref $Item) { | ||
| 729 | my $Str; | ||
| 730 | unless ($Item =~ /^\s+$/) { | ||
| 731 | $Str = $X->trim($Item); | ||
| 732 | } else { | ||
| 733 | $Str = $Item; | ||
| 734 | } | ||
| 735 | $Str =~ s/[\n\r]//g; | ||
| 736 | next if $Str eq ''; | ||
| 737 | } | ||
| 738 | |||
| 739 | push @Ar, $Item; | ||
| 740 | } | ||
| 741 | |||
| 742 | @$Data = @Ar; | ||
| 743 | return \@Ar; | ||
| 744 | } | ||
| 745 | |||
| 746 | sub ProcNode { | ||
| 747 | my $X = shift; | ||
| 748 | my $Node = shift; | ||
| 749 | my $RelPath = shift; | ||
| 750 | my $LastGoodParent = lc(shift); | ||
| 751 | my @Dist; | ||
| 752 | |||
| 753 | my %AllowElements = %{$X->{'allow_elements'}}; | ||
| 754 | |||
| 755 | foreach my $Child ( $Node->getChildnodes ) { | ||
| 756 | |||
| 757 | my $ChildNodeName = lc($Child->nodeName); | ||
| 758 | |||
| 759 | my $Allow = 1; | ||
| 760 | |||
| 761 | if ($AllowElements{$ChildNodeName}->{'exclude_if_inside'}) { #проверка на вшивость 1 | ||
| 762 | $Allow = 0 if $X->NodeHaveInside($Child, $AllowElements{$ChildNodeName}->{'exclude_if_inside'}); | ||
| 763 | } | ||
| 764 | |||
| 765 | if ($Allow) { #проверка на вшивость 2 | ||
| 766 | $Allow = | ||
| 767 | ($Child->nodeName !~ /#text/i | ||
| 768 | && exists $AllowElements{$LastGoodParent} | ||
| 769 | && ( | ||
| 770 | # !$AllowElements{$LastGoodParent}->{'allow_elements_inside'} || | ||
| 771 | exists $AllowElements{$LastGoodParent}->{'allow_elements_inside'}->{$ChildNodeName}) ) | ||
| 772 | ? 1 : 0; | ||
| 773 | } | ||
| 774 | |||
| 775 | #если ноду прибиваем, нужно чтобы дочерние работали по правилам пэрент-ноды (она ведь теперь и есть пэрент для последующих вложенных) | ||
| 776 | my $GoodParent = $Allow ? $ChildNodeName : $LastGoodParent; #если нода прошла разрешение, то теперь она становится последней parent в ветке и далее равняемся на ее правила | ||
| 777 | |||
| 778 | my $OldNodeName = $Child->nodeName; | ||
| 779 | |||
| 780 | #разрешенные атрибуты текущей ноды | ||
| 781 | my $AllowAttributes = | ||
| 782 | $Allow | ||
| 783 | && exists $AllowElements{$ChildNodeName}->{'allow_attributes'} | ||
| 784 | && $AllowElements{$ChildNodeName}->{'allow_attributes'} | ||
| 785 | ? $X->NodeGetAllowAttributes($Child) | ||
| 786 | : 0; | ||
| 787 | |||
| 788 | if ($Allow && $AllowElements{$ChildNodeName}->{'processor'}) { | ||
| 789 | $Child = $AllowElements{$ChildNodeName}->{'processor'}->($X,'node'=>$Child, 'relpath'=>$RelPath, params=>$AllowElements{$ChildNodeName}->{'processor_params'}); | ||
| 790 | } | ||
| 791 | |||
| 792 | my $NodeName = $Child->nodeName; #имя могло измениться процессором | ||
| 793 | |||
| 794 | push @Dist, $NodeName =~ /#text/i | ||
| 795 | ? unquot($X,$Child->toString) #текстовая нода | ||
| 796 | : | ||
| 797 | $Allow | ||
| 798 | ? { #тэг в ноде выводим | ||
| 799 | $NodeName => $AllowAttributes | ||
| 800 | ? {attributes => ConvertIds($X,$X->NodeGetAllowAttributes($Child),$RelPath), 'value' => &ProcNode($X,$Child,$RelPath,$GoodParent), 'was'=>$OldNodeName} # надо с атрибутами выводить | ||
| 801 | : &ProcNode($X,$Child,$RelPath,$GoodParent), # дочку строим по упрощенной схеме ('value' не обязателен) | ||
| 802 | } | ||
| 803 | : &ProcNode($X,$Child,$RelPath,$GoodParent) # не выводим тэг, шагаем дальше строить дерево | ||
| 804 | ; | ||
| 805 | } | ||
| 806 | |||
| 807 | return \@Dist; | ||
| 808 | } | ||
| 809 | |||
| 810 | sub NodeHaveInside { | ||
| 811 | my $X = shift; | ||
| 812 | my $Node = shift; | ||
| 813 | my $Elements = shift; | ||
| 814 | |||
| 815 | my %H = map {lc($_)=>1} @$Elements; | ||
| 816 | |||
| 817 | foreach my $Child ( $Node->getChildnodes ) { | ||
| 818 | if (exists $H{lc($Child->nodeName())}) { | ||
| 819 | undef %H; | ||
| 820 | return 1; | ||
| 821 | } | ||
| 822 | } | ||
| 823 | |||
| 824 | undef %H; | ||
| 825 | return 0; | ||
| 826 | } | ||
| 827 | |||
| 828 | sub ConvertIds { | ||
| 829 | my $X = shift; | ||
| 830 | my $Attributes = shift; | ||
| 831 | my $RelPath = shift; | ||
| 832 | |||
| 833 | #если есть рутовое имя, соорудим новый id-атрибут | ||
| 834 | if ($RelPath && exists $Attributes->{'id'}) { | ||
| 835 | my $Href = $RelPath."#".$Attributes->{'id'}; | ||
| 836 | #так же должны быть преобразованы <a href !!! | ||
| 837 | my $Id = $X->Path2ID(uri_unescape($Href),undef,'convert_id'); | ||
| 838 | $Attributes->{'id'} = 'link_'.$Id; | ||
| 839 | $X->{'id_list'}->{$Attributes->{'id'}} = $Href; | ||
| 840 | } | ||
| 841 | |||
| 842 | return $Attributes; | ||
| 843 | } | ||
| 844 | |||
| 845 | sub Path2ID { | ||
| 846 | my $X = shift; | ||
| 847 | my $DestPath = shift || return undef; #Искомый путь | ||
| 848 | my $LocalPath = shift || undef; #путь, относительно которого вычисляем Искомый | ||
| 849 | my $Debug = shift; | ||
| 850 | my $Skip = shift; | ||
| 851 | |||
| 852 | unless ($LocalPath) { | ||
| 853 | $LocalPath = $X->{'ContentDir'}; #Если не указан, работаем от корневой папки с контентом | ||
| 854 | } else { | ||
| 855 | $LocalPath = dirname($X->RealPath($X->{'ContentDir'}.'/'.$LocalPath)); | ||
| 856 | } | ||
| 857 | |||
| 858 | my $Link = $X->RealPath($LocalPath.'/'.$DestPath, $Debug, $Skip); | ||
| 859 | |||
| 860 | my $Path = defined $Link && $Link ne '' ? $X->UUID($Link) : undef; | ||
| 861 | |||
| 862 | return $Path; | ||
| 863 | } | ||
| 864 | |||
| 865 | sub RealPath { | ||
| 866 | my $X = shift; | ||
| 867 | my $Path = shift; | ||
| 868 | my $Debug = shift; | ||
| 869 | my $Skip = shift; | ||
| 870 | |||
| 871 | my $RealPath = undef; | ||
| 872 | |||
| 873 | if ($RealPath = Cwd::realpath($Path)) { | ||
| 874 | $RealPath =~ s/%20/ /g; | ||
| 875 | my $RealPath2 = $RealPath; | ||
| 876 | $RealPath2 =~ s/#.*$//g; | ||
| 877 | $RealPath = undef if !-f $RealPath2 && !-d $RealPath2; | ||
| 878 | } | ||
| 879 | |||
| 880 | $X->Error("Wrong path!\n$! $Path".($Debug?' ('.$Debug.')':'')) if !$RealPath && !$Skip; | ||
| 881 | return $RealPath; | ||
| 882 | } | ||
| 883 | |||
| 884 | sub NodeGetAllowAttributes { | ||
| 885 | my $X = shift; | ||
| 886 | my $Node = shift; | ||
| 887 | |||
| 888 | my %AllowElements = %{$X->{'allow_elements'}}; | ||
| 889 | |||
| 890 | my %Attrs; | ||
| 891 | my @Attrs = $Node->findnodes( "./@*"); | ||
| 892 | foreach my $Attr (@Attrs) { | ||
| 893 | $Attrs{$Attr->nodeName} = $Attr->value | ||
| 894 | if | ||
| 895 | (ref $AllowElements{$Node->nodeName}->{'allow_attributes'} eq 'ARRAY' | ||
| 896 | && grep {$Attr->nodeName eq $_} @{$AllowElements{$Node->nodeName}->{'allow_attributes'}} | ||
| 897 | ); | ||
| 898 | } | ||
| 899 | |||
| 900 | return \%Attrs; | ||
| 901 | } | ||
| 902 | |||
| 903 | sub UUID { | ||
| 904 | my $X = shift; | ||
| 905 | my $Str = shift || ''; | ||
| 906 | return $Str ? lc(uuid_to_string(create_uuid(UUID_V5,$Str))) : lc(create_uuid_as_string(UUID_V4)); | ||
| 907 | } | ||
| 908 | |||
| 909 | sub trim { | ||
| 910 | my $X = shift; | ||
| 911 | my $str = shift; | ||
| 912 | $str =~ s/\t/ /g; | ||
| 913 | $str =~ s/\s+/ /g; | ||
| 914 | $str =~ s/^\s*//; | ||
| 915 | $str =~ s/\s*$//; | ||
| 916 | $str =~ s/^\t*//; | ||
| 917 | $str =~ s/\t*$//; | ||
| 918 | return $str; | ||
| 919 | } | ||
| 920 | |||
| 921 | sub trim_soft { | ||
| 922 | my $X = shift; | ||
| 923 | my $str = shift; | ||
| 924 | $str =~ s/^\s*//; | ||
| 925 | $str =~ s/\s*$//; | ||
| 926 | $str =~ s/^\t*//; | ||
| 927 | $str =~ s/\t*$//; | ||
| 928 | return $str; | ||
| 929 | } | ||
| 930 | |||
| 931 | sub unquot { | ||
| 932 | my $X = shift; | ||
| 933 | my $str = shift; | ||
| 934 | |||
| 935 | $str =~ s/&/&/g; | ||
| 936 | $str =~ s/</</g; | ||
| 937 | $str =~ s/>/>/g; | ||
| 938 | $str =~ s/&guot;/"/g; | ||
| 939 | $str =~ s/'/'/g; | ||
| 940 | |||
| 941 | return $str; | ||
| 942 | } | ||
| 943 | |||
| 944 | sub quot { | ||
| 945 | my $X = shift; | ||
| 946 | my $str = shift; | ||
| 947 | |||
| 948 | $str =~ s/&/&/g; | ||
| 949 | $str =~ s/&/&/g; | ||
| 950 | $str =~ s/ / /g; | ||
| 951 | $str =~ s/</</g; | ||
| 952 | $str =~ s/>/>/g; | ||
| 953 | $str =~ s/"/"/g; | ||
| 954 | $str =~ s/"/'/g; | ||
| 955 | |||
| 956 | return $str; | ||
| 957 | } | ||
| 958 | |||
| 959 | sub qent { | ||
| 960 | my $X = shift; | ||
| 961 | my $Str = shift; | ||
| 962 | |||
| 963 | $Str =~ s/&#(0+)?60;/</g; | ||
| 964 | $Str =~ s/&#(0+)?62;/>/g; | ||
| 965 | $Str =~ s/&#x(0+)?3e;/>/gi; | ||
| 966 | $Str =~ s/&#x(0+)?3c;/</gi; | ||
| 967 | |||
| 968 | $Str =~ s/&#(0+)?38;/&/g; | ||
| 969 | $Str =~ s/&#x(0+)?26;/&/g; | ||
| 970 | |||
| 971 | $Str =~ s/&#(0+)?34;/"/g; | ||
| 972 | $Str =~ s/&#x(0+)?22;/"/g; | ||
| 973 | |||
| 974 | $Str =~ s/&#(0+)?39;/'/g; | ||
| 975 | $Str =~ s/&#x(0+)?27;/'/g; | ||
| 976 | |||
| 977 | XML::Entities::_decode_entities($Str, $AllEntities, 0); | ||
| 978 | $Str =~ s/&(?!amp;|quot;|apos;|lt;|gt;)/&/gi; | ||
| 979 | return $Str; | ||
| 980 | } | ||
| 981 | |||
| 982 | sub html_trim { | ||
| 983 | my $X = shift; | ||
| 984 | my $str = shift; | ||
| 985 | |||
| 986 | $str = quot($X,trim($X,$str)); | ||
| 987 | |||
| 988 | return $str; | ||
| 989 | } | ||
| 990 | |||
| 991 | sub EraseTags { | ||
| 992 | my $X = shift; | ||
| 993 | my $str = shift; | ||
| 994 | $str =~ s/<.*?>//g; | ||
| 995 | return $str; | ||
| 996 | } | ||
| 997 | |||
| 998 | # <= string, [type (i|w|e) ] | ||
| 999 | sub Msg { | ||
| 1000 | my $X = shift; | ||
| 1001 | my $Str = shift; | ||
| 1002 | my $Type = shift || 'i'; | ||
| 1003 | my $Force = shift; | ||
| 1004 | |||
| 1005 | return if !$X->{'verbose'} && $Type ne 'e' && !$Force; | ||
| 1006 | |||
| 1007 | #my $Color; | ||
| 1008 | #if ($Type eq 'w') { | ||
| 1009 | # $Color = "bold green"; | ||
| 1010 | #} elsif ($Type eq 'e') { | ||
| 1011 | # $Color = "bold red"; | ||
| 1012 | #} | ||
| 1013 | |||
| 1014 | #print color($Color) if $Color; | ||
| 1015 | print $Str; | ||
| 1016 | #print color('reset') if $Color; | ||
| 1017 | } | ||
| 1018 | |||
| 1019 | sub Error { | ||
| 1020 | my $X = shift; | ||
| 1021 | my $ErrStr = shift; | ||
| 1022 | Msg($X,$ErrStr."\n",'e'); | ||
| 1023 | Cleanup($X,1); | ||
| 1024 | exit; | ||
| 1025 | } | ||
| 1026 | |||
| 1027 | #проверка валидности полученного FB3 | ||
| 1028 | sub Validate { | ||
| 1029 | my $X = shift; | ||
| 1030 | my %Args = @_; | ||
| 1031 | my $ValidateDir = $Args{'path'}; | ||
| 1032 | my $XsdPath = $Args{'xsd'}; | ||
| 1033 | |||
| 1034 | $X->Msg("Validate result\n"); | ||
| 1035 | my $Valid = FB3::Validator->new( $XsdPath ); | ||
| 1036 | return $Valid->Validate($ValidateDir||$X->{'DestinationDir'}); | ||
| 1037 | } | ||
| 1038 | |||
| 1039 | sub Cleanup { | ||
| 1040 | my $X = shift; | ||
| 1041 | my $CleanDest = shift; | ||
| 1042 | |||
| 1043 | if ($X->{'unzipped'} && $X->{'SourceDir'}) { #если наследили распаковкой в tmp | ||
| 1044 | ForceRmDir($X,$X->{'SourceDir'}); | ||
| 1045 | Msg($X,"Clean tmp directory ".$X->{'SourceDir'}."\n"); | ||
| 1046 | } | ||
| 1047 | |||
| 1048 | #просят почистить результат | ||
| 1049 | if ($CleanDest) { | ||
| 1050 | ForceRmDir($X,$X->{'DestinationDir'}) if $X->{'DestinationDir'}; | ||
| 1051 | } | ||
| 1052 | |||
| 1053 | } | ||
| 1054 | |||
| 1055 | sub ForceRmDir{ | ||
| 1056 | my $X = shift; | ||
| 1057 | my $DirToClean=shift; | ||
| 1058 | return unless -e $DirToClean; | ||
| 1059 | my @FilesToKill; | ||
| 1060 | opendir(INPUT_FOLDER, $DirToClean); | ||
| 1061 | for (readdir(INPUT_FOLDER)){ | ||
| 1062 | next if /\A\.\Z|(\A\.\.\Z)/; | ||
| 1063 | if (-d "$DirToClean/$_"){ | ||
| 1064 | ForceRmDir($X,"$DirToClean/$_") | ||
| 1065 | } else { | ||
| 1066 | push (@FilesToKill, $_) | ||
| 1067 | } | ||
| 1068 | } | ||
| 1069 | closedir(INPUT_FOLDER); | ||
| 1070 | for (@FilesToKill){ | ||
| 1071 | unlink "$DirToClean/$_" or warn "error '$!' deleting file '$DirToClean/$_'" | ||
| 1072 | } | ||
| 1073 | rmdir($DirToClean) or $X->Error("Error removing dir $DirToClean!\n$!"); | ||
| 1074 | } | ||
| 1075 | |||
| 1076 | sub Reaper { | ||
| 1077 | print "This method in package " . __PACKAGE__ . " and not defined in Processor class\n"; | ||
| 1078 | } | ||
| 1079 | |||
| 1080 | sub FB3Creator { | ||
| 1081 | print "This method in package " . __PACKAGE__ . " and not defined in Processor class\n"; | ||
| 1082 | } | ||
| 1083 | |||
| 1084 | sub TransformTable2Valid { | ||
| 1085 | my $X = shift; | ||
| 1086 | my %Args = @_; | ||
| 1087 | my $Node = $Args{'node'}; | ||
| 1088 | |||
| 1089 | foreach my $TH ($Node->findnodes('./tr/th')) { | ||
| 1090 | $TH->addChild(XML::LibXML::Text->new('')) unless $TH->getChildnodes; | ||
| 1091 | $X->Transform2Valid(node=>$TH); | ||
| 1092 | } | ||
| 1093 | foreach my $TD ($Node->findnodes('./tr/td')) { | ||
| 1094 | $TD->addChild(XML::LibXML::Text->new('')) unless $TD->getChildnodes; | ||
| 1095 | $X->Transform2Valid(node=>$TD); | ||
| 1096 | } | ||
| 1097 | |||
| 1098 | return $Node; | ||
| 1099 | } | ||
| 1100 | |||
| 1101 | sub Transform2Valid { | ||
| 1102 | my $X = shift; | ||
| 1103 | my %Args = @_; | ||
| 1104 | my $Node = $Args{'node'}; | ||
| 1105 | |||
| 1106 | my $NewNode = XML::LibXML::Element->new($Node->nodeName); #будем собирать новую ноду | ||
| 1107 | foreach ($Node->getAttributes) { #скопируем атрибуты | ||
| 1108 | $NewNode->setAttribute($_->name => $_->value); | ||
| 1109 | } | ||
| 1110 | |||
| 1111 | my $Wrap = XML::LibXML::Element->new("p"); | ||
| 1112 | |||
| 1113 | foreach my $Child ($Node->getChildnodes) { | ||
| 1114 | if ($Child->nodeName =~ /^(p|table|ul|ol|title|subtitle|section)$/) { | ||
| 1115 | if ($Wrap->hasChildNodes) { | ||
| 1116 | #закроем текуший враппер и создадим новый | ||
| 1117 | $NewNode->addChild($Wrap->cloneNode(1)); | ||
| 1118 | $Wrap = XML::LibXML::Element->new("p") if $Wrap->hasChildNodes; | ||
| 1119 | } | ||
| 1120 | #на текущие ноды не применяем враппер | ||
| 1121 | $NewNode->addChild($Child->cloneNode(1)); | ||
| 1122 | next; | ||
| 1123 | } | ||
| 1124 | |||
| 1125 | # остальные в <p>node</p> | ||
| 1126 | $Wrap->addChild($Child->cloneNode(1)); | ||
| 1127 | |||
| 1128 | } | ||
| 1129 | |||
| 1130 | #закрываем остатки враппера | ||
| 1131 | $NewNode->addChild($Wrap->cloneNode(1)) if $Wrap->hasChildNodes; | ||
| 1132 | |||
| 1133 | $Node->replaceNode($NewNode); | ||
| 1134 | return $Node; | ||
| 1135 | } | ||
| 1136 | |||
| 1137 | sub BuildOuterMeta { | ||
| 1138 | my $X = shift; | ||
| 1139 | my %Args = @_; | ||
| 1140 | |||
| 1141 | my $Meta = $Args{'meta'}; | ||
| 1142 | |||
| 1143 | my $ID = $Meta->{'id'}; | ||
| 1144 | my $LANGUAGE = $Meta->{'language'}; | ||
| 1145 | my $TITLE = $Meta->{'title'}; | ||
| 1146 | my $ANNOTATION = $Meta->{'annotation'}; | ||
| 1147 | my $GENRES = $Meta->{'genres'}; | ||
| 1148 | my $AUTHORS = $Meta->{'authors'}; | ||
| 1149 | my $DATE = $Meta->{'date'}; | ||
| 1150 | |||
| 1151 | my $MetaFile = $X->{'metadata'} if -s $X->{'metadata'}; | ||
| 1152 | if (-s $MetaFile) { | ||
| 1153 | my $xpc = XML::LibXML::XPathContext->new($Parser->load_xml( | ||
| 1154 | location => $MetaFile, | ||
| 1155 | expand_entities => 0, | ||
| 1156 | no_network => 1, | ||
| 1157 | load_ext_dtd => 0 | ||
| 1158 | )); | ||
| 1159 | $xpc->registerNs('fbd', &NS_FB3_DESCRIPTION); | ||
| 1160 | $ID = ($xpc->findnodes('/fbd:fb3-description')->[0])->getAttribute('id'); | ||
| 1161 | }; | ||
| 1162 | |||
| 1163 | my $DESCRIPTION = $X->{'STRUCTURE'}->{'DESCRIPTION'}; | ||
| 1164 | |||
| 1165 | $DESCRIPTION->{'DOCUMENT-INFO'}->{'ID'} = $ID if defined $ID; | ||
| 1166 | $DESCRIPTION->{'DOCUMENT-INFO'}->{'LANGUAGE'} = $LANGUAGE if defined $LANGUAGE; | ||
| 1167 | $DESCRIPTION->{'DOCUMENT-INFO'}->{'DATE'} = {'attributes'=>{'value'=>$DATE}} if defined $DATE; | ||
| 1168 | $DESCRIPTION->{'TITLE-INFO'}->{'BOOK-TITLE'} = $TITLE if defined $TITLE; | ||
| 1169 | $DESCRIPTION->{'TITLE-INFO'}->{'ANNOTATION'} = $ANNOTATION if defined $ANNOTATION; | ||
| 1170 | |||
| 1171 | $DESCRIPTION->{'TITLE-INFO'}->{'GENRES'} = [ map { trim($X,$_) } split /,/,$GENRES ] if defined $GENRES; | ||
| 1172 | $DESCRIPTION->{'TITLE-INFO'}->{'AUTHORS'} = [ map { BuildAuthorName($X,$_) } split /,/,$AUTHORS ] if defined $AUTHORS; | ||
| 1173 | |||
| 1174 | } | ||
| 1175 | |||
| 1176 | sub BuildAuthorName { | ||
| 1177 | my $X = shift; | ||
| 1178 | my ($FirstName, $MiddleName, $LastName) = split /\s/,shift,3; | ||
| 1179 | unless ($LastName) { | ||
| 1180 | $LastName = $MiddleName; | ||
| 1181 | $MiddleName = undef; | ||
| 1182 | } | ||
| 1183 | |||
| 1184 | return { | ||
| 1185 | 'id' => UUID(), | ||
| 1186 | 'first-name' => $FirstName, | ||
| 1187 | 'middle-name' => $MiddleName, | ||
| 1188 | 'last-name' => $LastName, | ||
| 1189 | }; | ||
| 1190 | } | ||
| 1191 | |||
| 1192 | sub EncodeUtf8 { | ||
| 1193 | my $X = shift; | ||
| 1194 | my $Out = shift; | ||
| 1195 | $Out = Encode::encode_utf8($Out) if $Out; | ||
| 1196 | return $Out; | ||
| 1197 | } | ||
| 1198 | |||
| 1199 | sub IsEmptyLineValue { | ||
| 1200 | my $X = shift; | ||
| 1201 | my $Item = shift; | ||
| 1202 | return 0 unless ref $Item eq 'ARRAY'; | ||
| 1203 | |||
| 1204 | return 1 if (!scalar @$Item || (scalar @$Item == 1 && $Item->[0] =~ /^[\s\t\n\r]+$/) ); | ||
| 1205 | return 0; | ||
| 1206 | } | ||
| 1207 | |||
| 1208 | sub CutLinkDiez { | ||
| 1209 | my $X = shift; | ||
| 1210 | my $Str = shift; | ||
| 1211 | $Str =~ s/^#//; | ||
| 1212 | return $Str; | ||
| 1213 | } | ||
| 1214 | |||
| 1215 | sub CorrectOuterLink{ | ||
| 1216 | my $X = shift; | ||
| 1217 | my $Str = shift; | ||
| 1218 | |||
| 1219 | unless ($Str =~ /^(http|https|mailto|ftp)\:(.+)/i) { | ||
| 1220 | $X->Msg("Find not valid Link and delete [$Str]\n"); | ||
| 1221 | return ""; | ||
| 1222 | } | ||
| 1223 | |||
| 1224 | my $Protocol = $1; | ||
| 1225 | my $Link = $2; | ||
| 1226 | $Link = $X->trim_soft($Link); | ||
| 1227 | |||
| 1228 | if ($Protocol eq 'mailto') { | ||
| 1229 | unless (ValidEMAIL($Link)) { | ||
| 1230 | $X->Msg("Find not valid Email and delete [".$Protocol.":".$Link."]\n"); | ||
| 1231 | return ""; | ||
| 1232 | } | ||
| 1233 | } else { | ||
| 1234 | unless (ValidURL($Protocol.':'.$Link)) { | ||
| 1235 | $X->Msg("Find not valid URL and delete [".$Protocol.":".$Link."]\n"); | ||
| 1236 | return ""; | ||
| 1237 | } | ||
| 1238 | } | ||
| 1239 | |||
| 1240 | return $Protocol.':'.$Link; | ||
| 1241 | } | ||
| 1242 | |||
| 1243 | sub ValidURL{ | ||
| 1244 | my $Url=shift; | ||
| 1245 | return 0 unless $Url; | ||
| 1246 | return 0 if length($Url)>300; | ||
| 1247 | |||
| 1248 | my $RegExp = | ||
| 1249 | '^(https|http|ftp):\/\/'. # protocol | ||
| 1250 | '(([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+'. # username | ||
| 1251 | '(:([a-z0-9$_\.\+!\*\'\(\),;\?&=-]|%[0-9a-f]{2})+)?'. # password | ||
| 1252 | '@)?(?#'. # auth requires @ | ||
| 1253 | ')((([a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*'. # domain segments AND | ||
| 1254 | '[a-z][a-z0-9-]*[a-z0-9]'. # top level domain OR | ||
| 1255 | '|((\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\.){3}'. | ||
| 1256 | '(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])'. # IP address | ||
| 1257 | ')(:\d{1,5})?'. # port | ||
| 1258 | ')(((\/+([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)*'. # path | ||
| 1259 | '(\?([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)'. # query string | ||
| 1260 | '?)?)?'. # path and query string optional | ||
| 1261 | '(#([a-z0-9$_\.\+!\*\'\(\),;:@&=-]|%[0-9a-f]{2})*)?'. # fragment | ||
| 1262 | '$'; | ||
| 1263 | |||
| 1264 | return $Url=~/$RegExp/i; | ||
| 1265 | } | ||
| 1266 | |||
| 1267 | sub ValidEMAIL{ | ||
| 1268 | my $Email=shift; | ||
| 1269 | return 0 unless $Email; | ||
| 1270 | return 0 if length($Email)>50; | ||
| 1271 | return $Email=~ /^[-+a-z0-9_]+(\.[-+a-z0-9_]+)*\@([-a-z0-9_]+\.)+[a-z]{2,10}$/i; | ||
| 1272 | } | ||
| 1273 | |||
| 1274 | sub ShitFixFile { | ||
| 1275 | my $X = shift; | ||
| 1276 | my $Fname = uri_unescape(shift); | ||
| 1277 | |||
| 1278 | my $Content; | ||
| 1279 | open my $Fo,"<".$Fname or $X->Error("Can't open file $Fname: $!"); | ||
| 1280 | map {$Content.=$_;} <$Fo>; | ||
| 1281 | close $Fo; | ||
| 1282 | |||
| 1283 | $Content = $X->ShitFix($Content); | ||
| 1284 | |||
| 1285 | open my $Fs,">".$Fname or $X->Error("Can't open file $Fname: $!"); | ||
| 1286 | print $Fs $Content; | ||
| 1287 | close $Fs; | ||
| 1288 | } | ||
| 1289 | |||
| 1290 | sub MetaFix { | ||
| 1291 | my $X = shift; | ||
| 1292 | my $Str = shift; | ||
| 1293 | # закрываем то, что в html не обязано | ||
| 1294 | $Str =~ s/<\s*\/\s*(meta|link)\s*>//gi; | ||
| 1295 | $Str =~ s/(<(meta|link|img)[^>]+?)\s*?(\/?\s*?)>/$1\/>/g; | ||
| 1296 | |||
| 1297 | return $Str; | ||
| 1298 | } | ||
| 1299 | |||
| 1300 | #phantomjs любит превращать кое-что в нечитаемое для Libxml | ||
| 1301 | sub SomeFix { | ||
| 1302 | my $X = shift; | ||
| 1303 | my $Str = shift; | ||
| 1304 | |||
| 1305 | $Str =~ s#<([bB][rR])>\s*</\1>#<br/>#g; # <br> </br> => <br/> | ||
| 1306 | $Str =~ s/<\s*[bB][rR]\s*>/<br\/>/g; # <br> => <br/> | ||
| 1307 | |||
| 1308 | return $Str; | ||
| 1309 | } | ||
| 1310 | |||
| 1311 | |||
| 1312 | sub ShitFix { | ||
| 1313 | my $X = shift; | ||
| 1314 | my $Str = shift; | ||
| 1315 | # /i здесь вызывает невероятные тормоза к сожалению | ||
| 1316 | $Str =~ s#<([iI][mM][gG]) ([^>]+?/?)>\s*</\1>#<img $2>#g; # <img> </img> => <img/> | ||
| 1317 | |||
| 1318 | #DOM такое не любит | ||
| 1319 | $Str =~ s/<([aA])([^>]*?)\/\s*>/<$1$2><\/$1>/g; # <a/> => <a></a> | ||
| 1320 | $Str =~ s/<([dD][iI][vV])([^>]*?)\/\s*>/<$1$2><\/$1>/g; # <div/> => <div></div> | ||
| 1321 | |||
| 1322 | $Str = $X->SomeFix($Str); | ||
| 1323 | $Str = $X->MetaFix($Str); | ||
| 1324 | |||
| 1325 | return $Str; | ||
| 1326 | } | ||
| 1327 | |||
| 1328 | sub ParseMetaFile { | ||
| 1329 | my $X = shift; | ||
| 1330 | |||
| 1331 | my $MetaFile = $X->{'metadata'} if -f $X->{'metadata'}; | ||
| 1332 | |||
| 1333 | if ($MetaFile) { | ||
| 1334 | |||
| 1335 | my $DESCRIPTION = $X->{'STRUCTURE'}->{'DESCRIPTION'}; | ||
| 1336 | |||
| 1337 | Msg($X,"Parse metafile ".$MetaFile."\n"); | ||
| 1338 | my $xpc = XML::LibXML::XPathContext->new($Parser->load_xml( | ||
| 1339 | location => $MetaFile, | ||
| 1340 | expand_entities => 0, | ||
| 1341 | no_network => 1, | ||
| 1342 | load_ext_dtd => 0 | ||
| 1343 | )); | ||
| 1344 | $xpc->registerNs('fbd', &NS_FB3_DESCRIPTION); | ||
| 1345 | |||
| 1346 | my $ID = ($xpc->findnodes('/fbd:fb3-description')->[0])->getAttribute('id'); | ||
| 1347 | $DESCRIPTION->{'DOCUMENT-INFO'}->{'ID'} = $ID if defined $ID; | ||
| 1348 | |||
| 1349 | my $TITLE = $xpc->findnodes('/fbd:fb3-description/fbd:title/fbd:main')->[0]; | ||
| 1350 | $DESCRIPTION->{'TITLE-INFO'}->{'BOOK-TITLE'} = EncodeUtf8($X,$TITLE->string_value) if defined $TITLE; | ||
| 1351 | |||
| 1352 | my $ANNOTATION = $xpc->findnodes('/fbd:fb3-description/fbd:annotation/fbd:p')->[0]; | ||
| 1353 | $DESCRIPTION->{'TITLE-INFO'}->{'ANNOTATION'} = EncodeUtf8($X,$ANNOTATION->string_value) if defined $ANNOTATION; | ||
| 1354 | |||
| 1355 | my $LANGUAGE = $xpc->findnodes('/fbd:fb3-description/fbd:lang')->[0]; | ||
| 1356 | $DESCRIPTION->{'DOCUMENT-INFO'}->{'LANGUAGE'} = $LANGUAGE->string_value if defined $LANGUAGE; | ||
| 1357 | |||
| 1358 | my @GENRES = map { EncodeUtf8($X,$_->string_value) } ($xpc->findnodes('/fbd:fb3-description/fbd:fb3-classification/fbd:subject')); | ||
| 1359 | $DESCRIPTION->{'TITLE-INFO'}->{'GENRES'} = [ @GENRES ]; | ||
| 1360 | |||
| 1361 | my @AUTHORS; | ||
| 1362 | foreach my $Subject ($xpc->findnodes('/fbd:fb3-description/fbd:fb3-relations/fbd:subject')) { | ||
| 1363 | my $SubjID = $Subject->getAttribute("id") ; | ||
| 1364 | my $SubjLink = $Subject->getAttribute("link") ; | ||
| 1365 | my $SubjPercent = $Subject->getAttribute("percent") ; | ||
| 1366 | my $SubjNAME = $Subject->getElementsByTagName("main"); | ||
| 1367 | |||
| 1368 | my ($FirstName, $MiddleName, $LastName) = split /\s+/, $SubjNAME, 3; | ||
| 1369 | |||
| 1370 | unless ($LastName) { | ||
| 1371 | $LastName = $MiddleName; | ||
| 1372 | $MiddleName = undef; | ||
| 1373 | } | ||
| 1374 | |||
| 1375 | push @AUTHORS, { | ||
| 1376 | 'id' => $SubjID, | ||
| 1377 | 'link' => $SubjLink, | ||
| 1378 | 'percent' => $SubjPercent, | ||
| 1379 | 'first-name' => EncodeUtf8($X,$FirstName), | ||
| 1380 | 'middle-name' => EncodeUtf8($X,$MiddleName), | ||
| 1381 | 'last-name' => EncodeUtf8($X,$LastName), | ||
| 1382 | }; | ||
| 1383 | } | ||
| 1384 | $DESCRIPTION->{'TITLE-INFO'}->{'AUTHORS'} = [ @AUTHORS ]; | ||
| 1385 | |||
| 1386 | } | ||
| 1387 | |||
| 1388 | } | ||
| 1389 | |||
| 1390 | ### BENCHMARK | ||
| 1391 | |||
| 1392 | #Точка старта | ||
| 1393 | sub _bs { | ||
| 1394 | my $X = shift; | ||
| 1395 | my $Key = shift; | ||
| 1396 | my $Desc = shift || undef; | ||
| 1397 | return if ( !(exists $X->{'bench'} && $X->{'bench'}) && !(exists $X->{'bench2file'} && $X->{'bench2file'}) ); | ||
| 1398 | |||
| 1399 | $X->Error("Bench: _bs(); key not defined in string format") unless $Key; | ||
| 1400 | $X->Error("Bench: _bs(): Key is not a string") if ref $Key; | ||
| 1401 | |||
| 1402 | $X->{'bench_list'}->{$Key} = { | ||
| 1403 | 'desc' => $Desc, | ||
| 1404 | 'timers' => [] | ||
| 1405 | } unless exists $X->{'bench_list'}->{$Key}; | ||
| 1406 | |||
| 1407 | my $Timers = $X->{'bench_list'}->{$Key}->{'timers'}; | ||
| 1408 | |||
| 1409 | if (@$Timers) { | ||
| 1410 | $X->Error("Bench: last timer don't closed with X->_be('$Key') function") | ||
| 1411 | if exists $Timers->[scalar @$Timers - 1]->{'start'} && !exists $Timers->[scalar @$Timers - 1]->{'end'}; | ||
| 1412 | } | ||
| 1413 | |||
| 1414 | my $ts = gettimeofday(); | ||
| 1415 | push @$Timers, { | ||
| 1416 | 'start' => $ts, | ||
| 1417 | }; | ||
| 1418 | } | ||
| 1419 | |||
| 1420 | #Точка окончания | ||
| 1421 | sub _be { | ||
| 1422 | my $X = shift; | ||
| 1423 | my $Key = shift; | ||
| 1424 | return if ( !(exists $X->{'bench'} && $X->{'bench'}) && !(exists $X->{'bench2file'} && $X->{'bench2file'}) ); | ||
| 1425 | |||
| 1426 | $X->Error("Bench: _be(); key not defined in string format") unless $Key; | ||
| 1427 | $X->Error("Bench: _be(): Key is not a string") if ref $Key; | ||
| 1428 | |||
| 1429 | $X->Error("Bench: _be(); Key '$Key' not exists. Do you make X->_bs($Key)??") unless exists $X->{'bench_list'}->{$Key}; | ||
| 1430 | |||
| 1431 | my $Timers = $X->{'bench_list'}->{$Key}->{'timers'}; | ||
| 1432 | $X->Error("Bench: _be(): Can't close timer. Two o more calls of _be($Key)??") | ||
| 1433 | if exists $Timers->[scalar @$Timers - 1]->{'end'}; | ||
| 1434 | my $te = gettimeofday(); | ||
| 1435 | $Timers->[scalar @$Timers - 1]->{'end'} = $te; | ||
| 1436 | } | ||
| 1437 | |||
| 1438 | #Сброс статистики | ||
| 1439 | sub _bf { | ||
| 1440 | my $X = shift; | ||
| 1441 | return if ( !(exists $X->{'bench'} && $X->{'bench'}) && !(exists $X->{'bench2file'} && $X->{'bench2file'}) ); | ||
| 1442 | |||
| 1443 | my $Out = "BENCHMARK ".localtime().":\n\n"; | ||
| 1444 | |||
| 1445 | foreach my $Key (sort keys %{$X->{'bench_list'}}) { | ||
| 1446 | my $Item = $X->{'bench_list'}->{$Key}; | ||
| 1447 | my $Cnt = scalar @{$Item->{'timers'}}; | ||
| 1448 | my $Summ=0; | ||
| 1449 | $Out .= "[key: '$Key'] "; | ||
| 1450 | $Out .= "[cnt: $Cnt] "; | ||
| 1451 | foreach my $t ( @{$Item->{'timers'}} ) { | ||
| 1452 | $Summ += ($t->{'end'} - $t->{'start'}); | ||
| 1453 | } | ||
| 1454 | $Out .= "[time: ".sprintf('%.4f',$Summ)." sec] "; | ||
| 1455 | $Out .= "[avg: ".sprintf('%.4f',$Summ/$Cnt)." sec]\n"; | ||
| 1456 | $Out .= "desc: ".$Item->{'desc'}."\n\n" if $Item->{'desc'}; | ||
| 1457 | } | ||
| 1458 | |||
| 1459 | $X->{'bench_list'} = {}; | ||
| 1460 | |||
| 1461 | $X->Msg("\n".$Out,'w',1) if $X->{'bench'}; | ||
| 1462 | |||
| 1463 | if ($X->{'bench2file'}) { | ||
| 1464 | open my $F,">>:utf8",$X->{'bench2file'} or $X->Error($!); | ||
| 1465 | print $F $Out; | ||
| 1466 | close $F; | ||
| 1467 | } | ||
| 1468 | |||
| 1469 | } | ||
| 1470 | |||
| 1471 | sub isUseImageProfile { | ||
| 1472 | my $X = shift; | ||
| 1473 | my $ImgType = lc(shift) || return; | ||
| 1474 | return 1 if exists $UseImgProfile{$ImgType} && $UseImgProfile{$ImgType}; | ||
| 1475 | } | ||
| 1476 | |||
| 1477 | sub isConvertImageType { | ||
| 1478 | my $X = shift; | ||
| 1479 | my $ImgType = shift || return; | ||
| 1480 | return grep {lc($ImgType) eq $_} @ConvertImgFormat; | ||
| 1481 | } | ||
| 1482 | |||
| 1483 | sub isAllowedImageType { | ||
| 1484 | my $X = shift; | ||
| 1485 | my $ImgType = shift || return; | ||
| 1486 | return grep {lc($ImgType) eq $_} @AccessImgFormat; | ||
| 1487 | } | ||
| 1488 | |||
| 1489 | sub GuessLang { | ||
| 1490 | my $X = shift; | ||
| 1491 | my $Text = shift; | ||
| 1492 | return if length($Text) < 150; | ||
| 1493 | $Text = substr($Text,0,2000); | ||
| 1494 | my %LangsHashLocal = Lingua::Identify::langof($Text); | ||
| 1495 | my @SortedProbability = sort {$b <=> $a} values(%LangsHashLocal); | ||
| 1496 | foreach my $Lang (keys %LangsHashLocal) { | ||
| 1497 | return lc($Lang) if $LangsHashLocal{$Lang} == $SortedProbability[0]; | ||
| 1498 | } | ||
| 1499 | } | ||
| 1500 | |||
| 1501 | sub Img2JPG { | ||
| 1502 | my $X = shift; | ||
| 1503 | my $ImgFile = shift; | ||
| 1504 | my $UseProfile = shift || undef; | ||
| 1505 | my $To = $ImgFile.".jpg"; | ||
| 1506 | my $Image = new Image::Magick; | ||
| 1507 | |||
| 1508 | $Image->Read($ImgFile); #почему-то у IM "or die" всегда срабатывает...; | ||
| 1509 | |||
| 1510 | if ($UseProfile) { | ||
| 1511 | if (!-s $sRGBProfile) { | ||
| 1512 | $X->Msg("Can't find sRGB ICC profile $sRGBProfile. Try convert to RGB colorspace without profile. May wrong colors for CMYK->RGB\n"); | ||
| 1513 | $Image->Quantize(colorspace=>'sRGB'); | ||
| 1514 | } elsif (!-s $CMYKProfile) { | ||
| 1515 | $X->Msg("Can't find CMYK ICC profile $CMYKProfile. Try convert to RGB colorspace without profile. May wrong colors for CMYK->RGB\n"); | ||
| 1516 | $Image->Quantize(colorspace=>'sRGB'); | ||
| 1517 | } else { | ||
| 1518 | |||
| 1519 | #вытираем профили | ||
| 1520 | $Image->Profile(name => 'ICC', profile => ''); | ||
| 1521 | $Image->Profile(name => 'IPTC', profile => ''); | ||
| 1522 | |||
| 1523 | open my $PHRGB,"<".$sRGBProfile or die $!; | ||
| 1524 | binmode($PHRGB); | ||
| 1525 | my $ProfRGBBLOB = join("", <$PHRGB>); | ||
| 1526 | close $PHRGB; | ||
| 1527 | |||
| 1528 | open my $PHCMYK,"<".$CMYKProfile or die $!; | ||
| 1529 | binmode($PHCMYK); | ||
| 1530 | my $ProfCMYKBLOB = join("", <$PHCMYK>); | ||
| 1531 | close $PHCMYK; | ||
| 1532 | |||
| 1533 | $Image->Profile(name => 'ICC', profile => $ProfCMYKBLOB); | ||
| 1534 | $Image->Profile(name => 'ICC', profile => $ProfRGBBLOB); | ||
| 1535 | |||
| 1536 | } | ||
| 1537 | } | ||
| 1538 | |||
| 1539 | $Image->[0]->Write($To); | ||
| 1540 | |||
| 1541 | unless (-s $To) { | ||
| 1542 | $X->Error("Cant't convert $ImgFile to JPG"); | ||
| 1543 | } else { | ||
| 1544 | unlink($ImgFile); | ||
| 1545 | return $To; | ||
| 1546 | } | ||
| 1547 | } | ||
| 1548 | |||
| 1549 | =head1 LICENSE AND COPYRIGHT | ||
| 1550 | |||
| 1551 | Copyright (C) 2018 Litres.ru | ||
| 1552 | |||
| 1553 | The GNU Lesser General Public License version 3.0 | ||
| 1554 | |||
| 1555 | FB3::Convert is free software: you can redistribute it and/or modify it | ||
| 1556 | under the terms of the GNU Lesser General Public License as published by | ||
| 1557 | the Free Software Foundation, either version 3.0 of the License. | ||
| 1558 | |||
| 1559 | FB3::Convert is distributed in the hope that it will be useful, but | ||
| 1560 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | ||
| 1561 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public | ||
| 1562 | License for more details. | ||
| 1563 | |||
| 1564 | Full text of License L<http://www.gnu.org/licenses/lgpl-3.0.en.html>. | ||
| 1565 | |||
| 1566 | =cut | ||
| 1567 | |||
| 1568 | |||
| 1569 | 1; | ||