forked from Vaporbook/BookGluttonEpub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBookGluttonEpub.php
executable file
·3937 lines (3238 loc) · 125 KB
/
BookGluttonEpub.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//error_reporting(E_ALL | E_STRICT);
define('JAVA_LOC', '/usr/bin/java');
define('TIDY_LOC', '/usr/bin/tidy');
define('EPUBCHECK', '/usr/local/epubcheck-1.1/epubcheck-1.1.jar');
define('UPLOAD_DIR', '/tmp');
define('ZIP_LOC','/usr/bin/zip');
class BookGluttonEpub
{
public function BookGluttonEpub()
{
$this->logverbose = true;
$this->loglevel = 0;
$this->m = null;
$this->dcdata = array();
$this->ncxXP = null;
$this->opfXP = null;
$this->prettyPrint = true;
$this->readonly = false;
$this->maxblocks = 3000;
$this->tidyloc = TIDY_LOC;
$this->java = JAVA_LOC;
$this->epubcheck = $this->java . ' -jar '.EPUBCHECK;
$this->epubcheck_ckstring = 'Epubcheck Version 1.0.3 No errors or warnings';
$this->opf = null;
$this->opfNS = "http://www.idpf.org/2007/opf"; // NO trailing slash
$this->dcNS = "http://purl.org/dc/elements/1.1/"; // NEEDS trailing slash to validate
$this->doctypeNISO = "-//NISO//DTD ncx 2005-1//EN";
$this->ncxNS = "http://www.daisy.org/z3986/2005/ncx/";
$this->opsmime = "application/oebps-package+xml";
$this->daisydtd = "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd";
$this->ncxmime = "application/x-dtbncx+xml";
$this->packageVersion = "2.0";
$this->xmllang = "en-US";
$this->title = '';
$this->author = '';
$this->zipQ = array();
$this->_za = null;
$this->ocf_filename = null; // temporary epub filename
$this->useNavDivs = false;
$this->useNavDocs = true;
$this->includecover = false;
$this->workpath = DiskUtil::getTempDir(); // this will be the path to write the epub to
$this->opsname = uniqid(); // unique name for ops container directory
$this->packagepath = $this->workpath . '/' .$this->opsname; // this will be the working package dir (ops)
$this->ncxpath = "index.ncx";
$this->opfpath = "index.opf";
$this->mimetypepath = $this->packagepath . '/mimetype'; // filename of mimetype file
$this->metapath = $this->packagepath . '/META-INF';
$this->opspath = $this->packagepath;
$this->navmaplabel = 'Table of Contents';
$this->uniqIDscheme = "PrimaryID";
$this->uniqIDval = 'not set';
$this->opsrel = ''; // this is the rel path within the package structure where content is found.
$this->ziphandle_limit = 100; // system-dependent
$this->suppress_purify = true;
$this->conversionIndexParsed = false;
$this->conversionMetasParsed = false;
$this->hasPrimaryIdSet = false;
$this->ncxCurPlayOrder = 0;
$this->ncxGeneratedDepth = 0;
$this->ncxGeneratedLength = 0;
$this->ncxGeneratedNavMapCurPoint = null;
$this->ncxLastDepth = 0;
$this->preflight = array();
$this->tmpdump = null;
$this->ncxSpineadd = array();
$this->zipstem = '';
$this->unsavedchanges = false;
$this->deferredSpine = false;
$this->xhtml11doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
$this->htmltag = '<html xmlns="http://www.w3.org/1999/xhtml">';
// A default XHTML 1.1 template for importing new content
$this->doctmpl =<<<END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
</html>
END
;
$this->logerr('BookGluttonEpub instantiated', 1);
}
public function setReadonly($bool)
{
$this->readonly = $bool;
}
public function create($meta=array('title'=>null,
'author'=>null,
'language'=>null,
'desc'=>null,
'rights'=>null))
{
}
public function createFromAssets($root=null, $files)
{
/**
Expects a path to an empty directory in which to create the OPS,
and an array of assets, each of which is a hash of path, content
keyvalues. content should be base64 encoded and will be decoded and
written to path relative to root.
*/
if(!$root) {
$root = $this->packagepath; // defaults to uniqid in temp dir
}
if(!file_exists($root)) {
DiskUtil::makeDir($root);
}
$this->ocf_filename = $this->_makeEpubTargetFromAssets($root, $files);
/*
foreach($files as $file) {
$file['content'] = base64_decode($file['content']);
$this->writeFile($file);
}
*/
//$this->loadOPS($root);
$this->open($this->ocf_filename);
$this->_saveMeta();
}
private function _makeEpubTargetFromAssets($packagedir, $files)
{
// expects base64 encoded content!!!!
// see the other function using ZipArchive for
// notes on why we do it this way
$this->mimetypepath = $packagedir . '/mimetype';
$this->_writeFile($this->mimetypepath, $this->getMimetypeString());
if(file_exists($this->mimetypepath)) {
$this->logerr('success!');
} else {
throw new Exception('could not create a mimetype file for this ops structure');
}
$arcname = $packagedir.'.epub';
//error_log('created archive file:'.$arcname);
$zipcmd = ZIP_LOC; // path to zip command
$zipflags = '-0 -j -X';
$zipcmdfull = "$zipcmd $zipflags $arcname $this->mimetypepath";
exec(escapeshellcmd($zipcmdfull), $output);
$this->logerr('output was:'.print_r($output, true));
$zip = new ZipArchive();
if($zip->open($arcname)!==TRUE) {
$this->logerr("cannot open <$arcname>");
}
$zipq = array();
// asm: the following line causes problems reading these on stanza, so leave commented
$zip->addEmptyDir('META-INF');
$dirnames = array();
foreach($files as $file) {
$pi = pathinfo($file['path']);
if($pi['dirname']!="." && $pi['dirname'] != "..") {
$dirnames[$pi['dirname']] = $pi['dirname'];
}
}
$fullpath = "";
// make sure dirs exist
foreach($dirnames as $dirpath=>$bool) {
$dirs = explode('/', $dirpath);
$fullpath = "";
foreach($dirs as $step) {
if($fullpath=="") {
$fullpath = $step;
} else {
$fullpath = $fullpath . '/'.$step;
}
$zip->addEmptyDir($fullpath);
}
}
$filenum = 1;
foreach($files as $file) {
if($file['path']=='mimetype') continue;
$filenum++;
// SEE NOTE ABOUT FILE HANDLE LIMITS
if($filenum > $this->ziphandle_limit) {
$zip->close();
$zip->open($arcname);
$filenum = 1;
}
$zip->addFromString($file['path'], base64_decode($file['content']));
}
$zip->close();
$arctmp = UPLOAD_DIR.'/'.uniqid().'.epub';
copy($arcname, $arctmp);
$zipflags = "-F $arctmp";
$zipcmdfull = "$zipcmd $zipflags";
if(!exec(escapeshellcmd($zipcmdfull), $output)) {
throw new Exception('could not fix zip file');
}
//error_log('zip -F output:'.print_r($output, true));
unlink($arcname);
DiskUtil::xRename($arctmp, $arcname);
return $arcname;
}
public function open($epub)
{
$this->_za = new ZipArchive();
if ($this->_za->open($epub) === TRUE) {
$this->numFiles = $this->_za->numFiles;
//$this->logerr('files found in archive are:');
$this->packagepath = $this->workpath . '/' .$this->opsname; // this will be the working package dir (ops)
$this->_za->extractTo($this->packagepath);
$this->mimetypepath = $this->packagepath . '/mimetype'; // filename of mimetype file
$this->metapath = $this->packagepath . '/META-INF';
$this->opspath = $this->packagepath;
$this->loadOPS($this->packagepath);
} else {
throw (new Exception('cannot open zipfile:'.$epub));
}
}
//_makeEpubTmp()
public function openRemote($href)
{
$tmpfile = DiskUtil::getTempDir().'/epubimport'.time().'.epub';
if(file_put_contents($tmpfile, file_get_contents($href))) {
$this->open($tmpfile);
return $tmpfile;
} else {
throw new Exception('EPUB file could not be stored locally for import');
}
}
public function ingestRaw($data)
{
$tmpfile = DiskUtil::getTempDir().'/epubimport'.time().'.epub';
if(file_put_contents($tmpfile, $data)) {
$this->open($tmpfile);
// return tmpfile location so it can be cleaned up
return $tmpfile;
} else {
throw new Exception('EPUB file could not be stored locally for import');
}
}
public function isWritable()
{
$path = $this->packagepath;
$mimetype = $path . '/mimetype';
$opf = $path . '/'. $this->opfpath;
$ncx = $path . '/'. $this->ncxpath;
$metafile = $this->metapath.'/container.xml';
@$res = is_writable($path) &&
is_writable($mimetype) &&
is_writable($opf) &&
is_writable($ncx) &&
is_writable($metafile);
return $res;
}
public function opfWritable()
{
return is_writable($this->packagepath . '/'. $this->opfpath);
}
public function ncxWritable()
{
return is_writable($this->packagepath . '/'. $this->opfpath);
}
public function mimeWritable()
{
return is_writable($this->packagepath . '/mimetype');
}
public function pathWritable()
{
return is_writable($this->packagepath);
}
public function metapathWritable()
{
return is_writable($this->metapath);
}
public function enableWrite()
{
$path = $this->packagepath;
$mimetype = $path . '/mimetype';
$opf = $path . '/'. $this->opfpath;
$ncx = $path . '/'. $this->ncxpath;
$metafile = $this->metapath.'/container.xml';
$changes = array($path, $mimetype, $opf, $ncx, $metafile);
$success = 0;
foreach($changes as $f) {
if(chmod($f, 0777)) {
$success++;
}
}
return ($success===count($changes));
}
public function disableWrite($mode = 0644)
{
$path = $this->packagepath;
$mimetype = $path . '/mimetype';
$opf = $path . '/'. $this->opfpath;
$ncx = $path . '/'. $this->ncxpath;
$metafile = $this->metapath.'/container.xml';
$changes = array($path, $mimetype, $opf, $ncx, $metafile);
$success = 0;
foreach($changes as $f) {
if(is_dir($f)) {
if(chmod($f, 0755)) {
$success++;
}
} else {
if(chmod($f, $mode)) {
$success++;
}
}
}
return ($success===count($changes));
}
public function upgradeMetadata()
{
$pack = $this->getPackageEl();
if($pack->getElementsByTagName('dc-metadata')->length > 0) {
$dcmetadata = $pack->getElementsByTagName('dc-metadata')->item(0);
if(!($metadata = $pack->getElementsByTagName('metadata')->item(0))) {
$metadata = $pack->appendChild($this->getOpfDoc()->createElement('metadata'));
}
$children = $dcmetadata->childNodes;
for($i = 0; $i < $children->length; $i++) {
$meta = $children->item($i);
$metadata->appendChild($meta->cloneNode(true));
}
$metadata->removeChild($dcmetadata);
}
}
public function regeneratePrimaryId()
{
$uuid = uuidGen::generateUuid();
$content = 'urn:uuid:'.$uuid;
$this->replacePrimaryIdValue($content);
return $content;
}
public function getPackageEl()
{
return $this->getOpfDoc()->getElementsByTagName('package')->item(0);
}
public function loadOPS($path)
{
// loads a local OPS file structure into xml containers
if(!$this->_za && class_exists('ZipArchive')) {
$this->_za = new ZipArchive();
} else {
$this->_za = null;
}
$this->packagepath = $path; // this will be the working package dir (ops)
$this->opspath = $this->packagepath; // alias
$this->mimetypepath = $this->packagepath . '/mimetype'; // filename of mimetype file
$this->metapath = $this->packagepath . '/META-INF';
// CONTENT.XML
$this->contdoc = $this->_makeContDoc($this->getContainerXMLRaw());
$this->rootfile = $this->_getRootFileName();
// get the relative path to it, trimming dots and slashes
$this->opsrel = trim(pathinfo($this->rootfile, PATHINFO_DIRNAME),'/.');
// opffile, oppath and rootfile are all the same!!!
$this->opfpath = $this->rootfile; // the relative path to the opf file
$this->opffile = $this->opfpath;
// .OPF
if(!$this->opfpath || !file_exists($path . '/'. $this->opfpath)) {
throw new Exception('not a valid path for opf file');
}
$opf = file_get_contents($path . '/'. $this->opfpath);
if(!$opf) {
throw new Exception("something is wrong there is no opf file at $path/".$this->opfpath);
}
$this->opf = $this->_makeOpfDoc($opf);
$this->ncx = $this->_makeNcxDoc($this->getNcxXMLRaw());
// add manifest files to zipQ
//error_log('adding these to a zip listing');
$this->_addToZipQ();
// .NCX
// do a lil check on things
$this->opf_metadataNode->setAttribute('xmlns:dc', "http://purl.org/dc/elements/1.1/");
$this->opf_metadataNode->setAttribute('xmlns:opf',"http://www.idpf.org/2007/opf");
// check for lang
if(!$this->hasLang()) {
$this->addMeta('language', $this->xmllang);
}
// numerical ids not allowed
foreach($this->opf_manifestNode->getElementsByTagName('item') as $item) {
$id = $item->getAttribute('id');
if(preg_match('/^\d/',$id)) {
$item->setAttribute('id', 'id'.$id);
}
}
foreach($this->opf_spineNode->getElementsByTagName('itemref') as $itemref) {
$id = $itemref->getAttribute('idref');
if(preg_match('/^\d/',$id)) {
$itemref->setAttribute('idref', 'id'.$id);
}
}
}
public function fileExists($href)
{
return file_exists($this->getAbs($href));
}
public function getAbs($href)
{
/**
Get full disk path to href of opf item
*/
$rel = (strlen($this->opsrel)>0) ? $this->opsrel . '/' : '';
return $this->opspath . '/' . $rel . $href;
}
private function _addToZipQ()
{
/**
Add all manifest files to zip archive object.
Called during LoadOPS as part of the init
for a package. If a file is not found,
throws Exception.
*/
if($this->opf_manifestNode) {
foreach($this->opf_manifestNode->getElementsByTagName('item') as $item) {
$href = $item->getAttribute('href');
if(!$this->fileExists($href)) {
$dump = $this->opf->saveXML();
//error_log('epub:file at '.$href.' does not exist'."\n$dump");
}
$abs = $this->getAbs($href);
$rel = $this->getRel($href);
if($href && file_exists($abs)) { // only add if it's a valid key and the file exists
// array_key_exists is failing in this, dont know why
// not even sure why we needed it here
// if(array_key_exists($rel, $this->zipQ)===FALSE) { // preserve existing (primacy rule)
$this->zipQ[$rel]=$abs;
//} else { // this is a duplicate id and should be removed
// if($this->opf_manifestNode->removeChild($item)) {
// error_log('epub:removed item with duplicate id:'.$rel);
// }
}
}
} else {
throw new Exception('manifest is not defined yet');
}
}
private function _getRootFileName()
{
return $this->contdoc->getElementsByTagName('rootfiles')->item(0)->getElementsByTagName('rootfile')->item(0)->getAttribute('full-path');
}
public function getContainerXMLRaw()
{
if(@!($container = file_get_contents($this->metapath.'/container.xml'))) {
$msg = "";
if(is_dir($this->metapath)) { $msg = ' and it is not even an existent directory!!'; }
//$result = DiskUtil::findFile($path, '*.opf'); // like find $path -name $regex
$result = false;
//TODO
if($result) {
$this->opffile = $result;
$this->opfpath = $this->opffile;
$container = null;
} else {
throw new Exception('container file not found in '.$this->metapath.$msg.' plus could not create');
}
} else {
return $container;
}
}
public function getNcxXMLRaw()
{
if(!$this->opf_spineNode||!$this->opfXP) throw new Exception('must define an xpath parser and a spine node representation before calling this');
$tocatt = $this->opf_spineNode->getAttribute('toc');
$path = $this->packagepath;
// error_log('//*[@id="'.$tocatt.'"]');
$tocitem = $this->opfXP->evaluate('//*[@id="'.$tocatt.'"]');
if($tocitem->length > 0) {
//error_log('found an item in manifest matching id '.$tocatt.' specified by spines toc attribute');
if($tocitem->item(0)->getAttribute('media-type')=='text/xml') {
// fix ncx for stanza - eliminate incorrect media-type value
$tocitem->item(0)->setAttribute('media-type', 'application/x-dtbncx+xml');
}
if($tocitem->item(0)->getAttribute('href')) {
$this->ncxpath = $this->getNcxPath($tocitem->item(0)->getAttribute('href'));
} else {
// error_log('found an item for the ncx but the href is not set. going to try to find the right file to attribute to this...');
$ncxfound = $this->_seekNcxFile($tocitem->item(0));
}
} else {
// an item with the specified id for the ncx item is not found:
// this should be fatal, but some software like Calibre does
// not put a toc attribute on the spine, even though there's
// an ncx in the manifest. no point in failing here without
// double-checking the manifest, even though against the spec
$ncxfound = false;
error_log('no ncx designation in spine attribute, seeking...');
foreach($this->opf_manifestNode->getElementsByTagName('item') as $item) {
$type = $item->getAttribute("media-type");
if($type=="application/x-dtbncx+xml") {
$this->ncxpath = $this->getNcxPath($item->getAttribute("href"));
if(!file_exists($path . '/' . $this->ncxpath)) {
error_log('ncx file not found at '.$path . '/' . $this->ncxpath);
}
$ncxfound = true;
break;
}
}
if(!$ncxfound) { // if still not found, seek
$ncxfound = $this->_seekNcxFile();
if(!$ncxfound) { // still no? fucked
throw new Exception('ncx not found, even after searching recursively');
}
}
}
if(!$this->ncxpath) {
if($this->_seekNcxFile()) {
//error_log('found ncx by searching filesystem');
} else {
//error_log('cannot locate ncx');
}
}
//error_log('checking for file at '.$path . '/'. $this->ncxpath);
if(!file_exists($path . '/'. $this->ncxpath) || !$this->ncxpath) { // make sure file there
//error_log('throwing Exception: ncx file not found');
throw new Exception('ncx file not found at '.$this->ncxpath);
}
//error_log('ncxpath set to '.$this->ncxpath);
return file_get_contents($path .'/'. $this->ncxpath);
}
private function _seekNcxFile($tocitem=null)
{
$tocatt = $this->opf_spineNode->getAttribute('toc');
if(!$tocatt) $tocatt = 'toc';
$ncxfound = false;
// be smart, just search the ops for files matching /\.ncx$/i
$files = array();
exec("find ".$this->packagepath." -type f -name '*'", $files);
//error_log(print_r($files, true));
foreach($files as $candidate) {
if(preg_match('/\.ncx$/i', trim($candidate))) {
// add the item to the manifest, with id=$tocatt
if(!$tocitem) { // if the item is not already defined
// error_log('creating a new manifest item for the ncx');
$item = $this->opf_manifestNode->appendChild($this->opf->createElement('item'));
$item->setAttribute('id', $tocatt);
} else {
$item = $tocitem;
}
$newhref = trim(str_replace($this->packagepath, '', $candidate), './ ');
// error_log('**find command found ncx href: '.$newhref);
$item->setAttribute('href', $newhref);
$item->setAttribute('media-type', 'application/x-dtbncx+xml');
$this->ncxpath = $this->getNcxPath($newhref);
//$this->_saveMeta();
$ncxfound = true;
}
}
return $ncxfound;
}
public function getNcxPath($href)
{
// conditionally appends a relative path to the ncx manifest href
// passed in, based on whether opsrel is rootlever or not
//error_log('opsrel is '.$this->opsrel);
return (strlen($this->opsrel)>0) ? $this->opsrel . '/' . $href : $href;
}
/* Conversion methods */
public function includeCover($cover)
{
//$this->logerr('setting cover HTML:'.$cover);
$this->includecover = $cover;
}
public function setPretty($bool)
{
//$this->logerr('setPretty called');
$this->prettyPrint = $bool;
}
public function loadSource($filename)
{
// detect zip or epub and forwards to either
// open method or loadSourceFromZip
if(!$filename) throw new Exception ('loadSource requires a non-null and non-empty filename');
$this->logerr('loadSource:'.$filename, 4);
//asm: this was causing the title to be 'Untitled'
/*
if(!@$this->opf) { // if create has not been called yet
//error_log('create has not been called, calling it now');
$this->create(array('title'=>$this->getTitle(), 'author'=>$this->getAuthor()));
}
*/
if(!@$this->opf) {
$this->_makeDirs();
$this->opf = $this->_makeOpfDoc();
$this->ncx = $this->_makeNcxDoc();
$this->contdoc = $this->_makeContDoc();
}
$base_href = '';
$docroot = '';
if(preg_match('/^(http:\/\/.+?)([^\/]*?)$/', $filename, $urlmatches)) { // pre-fetch remote files
// store url for later processing - add trailing slash if needed
$hostpath = $urlmatches[1];
$urlinfo = parse_url($filename);
$docroot = ($urlinfo['host']) ? 'http://' . $urlinfo['host'] : '';
$base_href = (preg_match('/\/$/', $hostpath)) ? $hostpath : $hostpath . '/';
//$this->logerr('trying to cache url:'.$filename);
$tmpwork = DiskUtil::getTempDir() . '/' . uniqid();
if(!($remote = file_get_contents($filename))) {
throw new Exception('cannot cache remote url');
}
if(!file_put_contents($tmpwork, $remote)) {
throw new Exception('cannot cache remote url');
} else {
$filename = $tmpwork;
}
}
$snip = file_get_contents($filename,null,null,0,2);
if(!$snip) { throw new Exception('file '.$filename.' does not exist'); }
if ($snip=='PK') { // .zip or epub
$this->loadSourceFromZip($filename);
$this->_saveMeta();
$this->loadOPS($this->packagepath);
} else {
throw new Exception("This method only accepts zipped HTML (web) archives conforming to the UBO spec");
/*
$pi = pathinfo($filename);
$basename = $pi['basename'];
$id = $this->_validID('source');
$doc = $this->_domFromDoc($filename);
$xp = new DOMXPath($doc);
$xp->registerNamespace("ht", "http://www.w3.org/1999/xhtml");
// build package elements
$this->_setIdentifier();
$this->setPublisher('BookGlutton API (www.BookGlutton.com)');
$this->_guessMetas($doc, $xp);
// add a cover
if($this->includecover!=false) {
//$this->logerr('adding cover item:'.print_r($this->includecover, true));
$this->_addCoverItem();
}
//$oochaps = $xp->query('//ht:p[@class="ChapterTitle"]', $bodynode);
$heads = $xp->query('//ht:h1|//ht:h2|//ht:h3', $doc);
$images = $doc->getElementsByTagname('img');
$this->logerr('found '.$heads->length.' headings here');
// save the document back out and add the items from the headings
if($this->useNavDivs==true) {
$doc = $this->_headsToNavDivs($doc, $heads, $basename);
} else {
if($this->useNavDocs==true) {
$this->logerr('calling headsToNavDocs');
try {
$this->_headsToNavDocs($doc, $heads, $basename);
} catch (Exception $e) {
error_log('ignoring caught Exception in _headsToNavDocs:'.$e->getMessage());
}
return; // skip adding the original source
} else {
$this->_headsToNavItems($doc, $heads, $basename);
}
}
foreach($images as $image) { // images must not be in spine!
$src = $image->getAttribute('src');
if(!preg_match('/^http:\/\//i', $src)) { // if img is not remote
$mime = $this->_getMimeFromExt($src);
$this->addItem($this->_validID('image'), $src, $mime, null, null);
}
}
$this->logerr('loadSource:adding source item now', 2);
$this->addItem($id, $basename, 'application/xhtml+xml', $doc->saveXML(), 'yes');
*/
}
}
public function getPackagePath()
{
return $this->packagepath;
}
public function setPackagePath($p)
{
$this->packagepath = $p;
$this->metapath = $this->packagepath . '/META-INF';
$this->opspath = $this->packagepath;
}
public function loadSourceFromZip($zipfile)
{
//error_log('loading:'.$zipfile);
$za = new ZipArchive();
if ($za->open($zipfile) === TRUE) { // valid zip
// check if its epub
$checkit = $za->statIndex(0);
if($checkit['name']=='mimetype') {
if($fp = $za->getStream('mimetype')) { // is a valid file
$contents = '';
while (!feof($fp)) { // suck contents in
$contents .= fread($fp, 2);
}
fclose($fp);
$this->logerr($contents, 3);
if(preg_match('/application\/epub\+zip/',$contents)) {
$this->logerr('this is an epub file!', 1);
$za->close();
$this->open($zipfile); // open as epub
return;
}
}
} else {
$this->logerr('No mimetype file found in archive, probably not epub', 2);
}
$numFiles = $za->numFiles;
// error_log($numFiles . " found in archive...");
$acceptlist = array();
$firstdoc = null;
$order=0;
for ($i=0; $i<$numFiles;$i++) {
$stats = ($za->statIndex($i));
// do some filtering by file extension first, only acceptable types
if(preg_match('/(xml|x?html?|gif|jpe?g|svg|png|swf|css)$/i',$stats['name'])) {
if(preg_match('/^[^\._]/', $stats['name'])) { // won't process hidden or system files
$mime = $this->_getMimeFromExt($stats['name']); // all html and xml types return '...+xml' for this
$isimg = preg_match('/(jpe?g|gif|png|swf|css|svg)$/i', $mime);
$prefix = ($isimg) ? 'image' : 'item';
$itemid = $this->_validID($prefix);
$addtospine = ($isimg) ? null : 'yes';
$fp = $za->getStream($stats['name']);
if($fp) { // is a valid file
$contents = '';
while (!feof($fp)) { $contents .= fread($fp, 2);}
fclose($fp);
// XML and HTML files - content docs
if (preg_match('/xml$/i', $mime)) {
$this->preflightReport('INFO: '.$mime.' "'.$stats['name'].'" ('.strlen($contents).' bytes)');
$this->_loadXMLContent($itemid, $stats['name'], $mime, $contents);
} else { // not xml or html, add to manifest
$this->logerr('Not a content document type, adding to manifest only.',2);
$this->preflightReport('INFO: '.$mime.' "'.$stats['name'].'" ('.strlen($contents).' bytes)');
$this->addItem($itemid, $stats['name'], $mime, $contents, false);
$contents = null; // free mem
}
} else {
//error_log("INFO: invalid file pointer from zip/EPUB");
} // fail silently if not a valid file
} else {
//error_log("Epub: not an allowed file");
$this->preflightReport("WARN: ".$stats['name']." skipped, not an allowed file");
}
} else {
// error_log("Epub: not an allowed file extension");
}
}
if($this->includecover!=false) {
$this->logerr('Adding a cover',2);
$this->_addCoverItem();
}
if(!$this->hasPrimaryIdSet) {
$this->_setIdentifier();
}
//$this->setPublisher('BookGlutton API (www.BookGlutton.com)');
if($this->deferredSpine===true) {
//error_log(print_r($this->ncxSpineadd),true);
foreach($this->ncxSpineadd as $key=>$path) {
foreach($this->opf_manifestNode->getElementsByTagName('item') as $item) {
//error_log($path.'=='.$item->getAttribute('href'));
if($item->getAttribute('href')==$path) {
//error_log('adding to spine');
$this->addSpineRef($item->getAttribute('id'), 'yes');
$this->preflightReport("INFO: added $path to spine");
break;
}
}
}
} else {
throw new Exception('no UBO index file found to build EPUB structure');
}
} else { // complain if this isnt even a valid zip
throw (new Exception('cannot open zipfile:'.$zipfile));
}
}
private function _loadXMLContent ($itemid, $name, $mime, $contents)
{
$this->logerr('This is to be an xml based content doc, judging from the extension:'.$name,2);
if(preg_match('/index\.html?$/i', $name)) {
$isindex = true;
$this->preflightReport("INFO: Found UBO index file");
} else {
$isindex = false;
}
$tmp = $this->opspath . '/' . $this->opsrel . '/' . $name; // path to new file (return from addItem?)
DiskUtil::assertPath(pathinfo($tmp, PATHINFO_DIRNAME));
$doc = new DomDocument();
if(preg_match('/<!DOCTYPE[^>]+?xhtml 1.1[^>]+?>/im', $contents)) {
$contents = preg_replace('/<!DOCTYPE[^>]+?>/m', $this->xhtml11doctype, $contents);
}
$contents = preg_replace('/<html[^>]+?>/m', $this->htmltag, $contents);
if(@!$doc->loadXML($contents)) {
$this->preflightReport("ERROR: Could not parse the file ".$name.". It may interfere with validation.",1);
}
$contents = null; // free mem
if($doc->getElementsByTagName('title')->length > 0) {
$title = $doc->getElementsByTagName('title')->item(0)->textContent;
}
if($isindex) {
// set metas from index file
$this->_parseMetasFromDoc($doc);
// build navigation doc
$this->ncxCurPlayOrder = 0;
$this->ncxGeneratedDepth = 0;
$this->ncxGeneratedLength = 0;
$this->ncxGeneratedNavMapCurPoint = null;
$this->ncxLastDepth = 0;
$this->ncxSpineadd = array();
$this->zipstem = pathinfo($name, PATHINFO_DIRNAME);
$this->_recurseList($doc->getElementsByTagName('ol')->item(0));
// defer building spine until after all docs accounted for
$this->deferredSpine = true;
}
$this->addItem($itemid, $name, $mime, $doc->saveXML());
$this->preflightReport("INFO: file ".$name." added");
$doc = null; // free mem
//$this->addNavItem($itemid, $title, $name, 'document');
}
private function _recurseList($olel, $depth=0)
{
if(!$olel) {
$this->preflightReport("ERROR: Could not find the toc list element. Be sure to use an ORDERED LIST element in your index.html file, with class attribute set to 'toc.' This will cause invalid results.",1);
return;
}
if($children = $olel->childNodes) {
foreach($children as $ol) {
if($child = $ol->firstChild) {
$this->_processHtml($child, $depth);
} else if($child = $ol->nextSibling) {
$this->_processHtml($child, $depth);
}
}
}
}
private function _processHtml($child,$depth)
{
if($child->nodeType==1) {
if($child->nodeName=='li') {
//error_log('li found');
$this->preflightReport("INFO: toc list item found - ".$child->nodeValue);
foreach($child->childNodes as $ch) {
if($ch->nodeName=='a') {