-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathebooks.php
1443 lines (1165 loc) · 66.4 KB
/
ebooks.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
namespace Plugins\Ebooks;
include 'vendor/autoload.php';
use Typemill\Plugin;
use Typemill\Models\WriteYaml;
use Typemill\Models\WriteCache;
use Typemill\Models\Validation;
use Typemill\Controllers\MetaApiController;
use Typemill\Extensions\ParsedownExtension;
use Valitron\Validator;
use PHPePub\Core\EPub;
use PHPePub\Core\Logger;
use PHPePub\Core\Structure\OPF\DublinCore;
use PHPePub\Helpers\CalibreHelper;
use PHPePub\Helpers\IBooksHelper;
use PHPePub\Helpers\Rendition\RenditionHelper;
use PHPePub\Helpers\URLHelper;
use PHPZip\Zip\File\Zip;
class Ebooks extends Plugin
{
public static function getSubscribedEvents()
{
return [
'onTwigLoaded' => ['onTwigLoaded',0],
'onMetaDefinitionsLoaded' => ['onMetaDefinitionsLoaded',0],
'onSystemnaviLoaded' => ['onSystemnaviLoaded',0],
'onPageReady' => ['onPageReady',0],
];
}
public static function addNewRoutes()
{
return [
['httpMethod' => 'get', 'route' => '/tm/ebooks', 'name' => 'ebooks.show', 'class' => 'Typemill\Controllers\ControllerSettings:showBlank', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'get', 'route' => '/api/v1/ebooklayouts', 'name' => 'ebooklayouts.get', 'class' => 'Plugins\Ebooks\Ebooks:getEbookLayouts', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'post', 'route' => '/api/v1/ebooklayoutcss', 'name' => 'ebooklayoutcss.store', 'class' => 'Plugins\Ebooks\Ebooks:storeEbookLayoutCSS', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'get', 'route' => '/api/v1/ebooktabdata', 'name' => 'ebooktabdata.get', 'class' => 'Plugins\Ebooks\Ebooks:getEbookTabData', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'post', 'route' => '/api/v1/ebooktabdata', 'name' => 'ebooktabdata.store', 'class' => 'Plugins\Ebooks\Ebooks:storeEbookTabData', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'post', 'route' => '/api/v1/ebooktabitem', 'name' => 'ebooktabitem.store', 'class' => 'Plugins\Ebooks\Ebooks:storeEbookTabItem', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'get', 'route' => '/api/v1/ebookprojects', 'name' => 'ebookprojects.get', 'class' => 'Plugins\Ebooks\Ebooks:getEbookProjects', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'get', 'route' => '/api/v1/ebookdata', 'name' => 'ebookdata.get', 'class' => 'Plugins\Ebooks\Ebooks:getEbookData', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'post', 'route' => '/api/v1/ebookdata', 'name' => 'ebookdata.store', 'class' => 'Plugins\Ebooks\Ebooks:storeEbookData', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'delete', 'route' => '/api/v1/ebookdata', 'name' => 'ebookdata.delete', 'class' => 'Plugins\Ebooks\Ebooks:deleteEbookData', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'get', 'route' => '/api/v1/ebooknavi', 'name' => 'ebooknavi.get', 'class' => 'Plugins\Ebooks\Ebooks:getEbookNavi', 'resource' => 'system', 'privilege' => 'view'],
['httpMethod' => 'post', 'route' => '/api/v1/headlinepreview', 'name' => 'headline.preview', 'class' => 'Plugins\Ebooks\Ebooks:generateHeadlinePreview', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'get', 'route' => '/api/v1/epubuuid', 'name' => 'epub.uuid', 'class' => 'Plugins\Ebooks\Ebooks:generateUuidV4', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'get', 'route' => '/tm/ebooks/preview', 'name' => 'ebook.preview', 'class' => 'Plugins\Ebooks\Ebooks:ebookPreview', 'resource' => 'content', 'privilege' => 'create'],
['httpMethod' => 'get', 'route' => '/tm/ebooks/epub', 'name' => 'ebook.epub', 'class' => 'Plugins\Ebooks\Ebooks:createEpub', 'resource' => 'content', 'privilege' => 'create'],
];
}
# ebooks in pages
public function onTwigLoaded($metadata)
{
$this->config = $this->getPluginSettings('ebooks');
if($this->adminpath)
{
if( isset($this->config['ebooksinpages']) && (strpos($this->path, 'tm/content') !== false) )
{
$this->addEditorCSS('/ebooks/public/ebooks.css?20220215');
$this->addEditorJS('/ebooks/public/ebookcomponents.js?20220215');
$this->addEditorJS('/ebooks/public/ebookinpages.js?20220215');
# inject thumbindex.js into pages if activated
if(isset($this->config['thumbindex']))
{
$this->addEditorJS('/ebooks/public/thumbindex.js?20220215');
}
}
}
}
public function onMetaDefinitionsLoaded($metadata)
{
$meta = $metadata->getData();
$thumbindex = false;
if(isset($this->config['ebooksinpages']))
{
# add a tab called "ebook" into pages with no fields, because we will use the fields of the ebook plugin.
$meta['ebooks'] = ['fields'=> []];
if(isset($this->config['thumbindex']))
{
$thumbindex = true;
$languageString = $this->config['languages'];
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $languageString);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# set initial value that will clear the values
$languages = ['clear' => ''];
# add values from textarea-field in the settings
foreach($lines as $line)
{
$keyvalue = explode(':', $line);
if(isset($keyvalue[0]) && isset($keyvalue[1]))
{
$languages[trim($keyvalue[0])] = trim($keyvalue[1]);
}
}
$meta['thumbindex']['fields']['language']['options'] = $languages;
}
}
if(!$thumbindex)
{
unset($meta['thumbindex']);
}
$metadata->setData($meta);
}
public function onSystemnaviLoaded($navidata)
{
if(isset($this->config['ebooksinsettings']))
{
$this->addSvgSymbol('<symbol id="icon-book" viewBox="0 0 32 32">
<path d="M28 4v26h-21c-1.657 0-3-1.343-3-3s1.343-3 3-3h19v-24h-20c-2.2 0-4 1.8-4 4v24c0 2.2 1.8 4 4 4h24v-28h-2z"></path>
<path d="M7.002 26v0c-0.001 0-0.001 0-0.002 0-0.552 0-1 0.448-1 1s0.448 1 1 1c0.001 0 0.001-0 0.002-0v0h18.997v-2h-18.997z"></path>
</symbol>');
$navi = $navidata->getData();
$navi['Ebooks'] = ['routename' => 'ebooks.show', 'icon' => 'icon-book', 'aclresource' => 'system', 'aclprivilege' => 'view'];
if($this->getPath() == 'tm/ebooks')
{
$navi['Ebooks']['active'] = true;
}
$navidata->setData($navi);
}
}
# ebooks in settings
public function onPageReady($data)
{
if($this->adminpath)
{
# inject ebook template into the settings page
if( isset($this->config['ebooksinsettings']) && (strpos($this->getPath(), 'tm/ebooks') !== false) )
{
# add the css and vue application
$this->addCSS('/ebooks/public/ebooks.css');
$this->addJS('/ebooks/public/ebookcomponents.js');
$this->addJS('/ebooks/public/ebookinsettings.js');
$pagedata = $data->getData();
$twig = $this->getTwig();
$loader = $twig->getLoader();
$loader->addPath(__DIR__ . '/templates');
# fetch the template and render it with twig
$content = $twig->fetch('/ebooks.twig', []);
$pagedata['content'] = $content;
$data->setData($pagedata);
}
}
}
public function getEbookProjects($request, $response, $args)
{
$settings = $this->getSettings();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
if(!$this->checkEbookFolder($folder))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'Please make sure that the folder data/ebooks exists and is writable.']), 500);
}
$folderContent = array_diff(scandir($folder), array('..', '.'));
$ebookprojects = [];
foreach($folderContent as $file)
{
if(substr($file,0,9) == 'ebookdata')
{
$ebookprojects[] = $file;
}
}
return $response->withJson(array('ebookprojects' => $ebookprojects, 'errors' => false), 200);
}
# single endpoint to get only the layouts. Not in use right now
public function getEbookLayouts($request, $response, $args)
{
$booklayouts = $this->scanEbookLayouts();
return $response->withJson(array('layoutdata' => $booklayouts, 'errors' => false), 200);
}
# gets the centrally stored ebook-data for ebook-plugin in settings-area
public function getEbookData($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
if(!$this->checkEbookFolder($folder))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'Please make sure that the folder data/ebooks exists and is writable.']), 500);
}
if(!isset($params['projectname']) OR $params['projectname'] == '' OR !preg_match("/^[a-z\-]*\.yaml$/", $params['projectname']))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'The projectname is not valid.']), 500);
}
# write params
$writeYaml = new WriteYaml();
# get the stored ebook-data
$formdata = $writeYaml->getYaml($folderName, $params['projectname']);
return $response->withJson(array('formdata' => $formdata, 'errors' => false), 200);
}
# gets the stored ebook-data from page yaml for the ebook-plugin in page tab. We have to do it separately because fields are stripped out in tab.
public function getEbookTabData($request, $response, $args)
{
$params = $request->getParams();
$itempath = $params['itempath'];
$settings = $this->getSettings();
if($params['url'] == '/')
{
return $response->withJson(array('home' => true, 'errors' => ['message' => "The homepage does not support the ebook generation. Please go to the subpages or use the ebook tab in the settings if you want to create an ebook from the whole website."]), 422);
}
# get the metadata from page
$writeYaml = new WriteYaml();
$meta = $writeYaml->getYaml($settings['contentFolder'], $itempath . '.yaml');
$formdata = isset($meta['ebooks']) ? $meta['ebooks'] : false;
# get the ebook layouts
$booklayouts = $this->scanEbooklayouts();
return $response->withJson(array('formdata' => $formdata, 'layoutdata' => $booklayouts, 'errors' => false), 200);
}
# stores the ebook-data (book-details and navigation) from central ebook in settings-area into the data-folder
public function storeEbookData($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$uri = $request->getUri()->withUserInfo('');
$base_url = $uri->getBaseUrl();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
if(!$this->checkEbookFolder($folder))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'Please make sure that the folder data/ebooks exists and is writable.']), 500);
}
if(!isset($params['projectname']) OR $params['projectname'] == '' OR !preg_match("/^[a-z\-]*\.yaml$/", $params['projectname']))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'The projectname is not valid.']), 500);
}
$projectname = str_replace('.yaml', '', $params['projectname']);
$naviname = str_replace('ebookdata', 'navigation', $projectname);
# create objects to read and write data
$writeYaml = new WriteYaml();
$writeCache = new WriteCache();
$validatedParams = $this->validateEbookData($params, $writeYaml);
if(isset($validatedParams['errors']))
{
return $response->withJson(array('data' => false, 'errors' => $validatedParams['errors']), 422);
}
# write params
$ebookstored = $writeYaml->updateYaml($folderName, $projectname . '.yaml', $validatedParams['data']);
$navistored = $writeCache->updateCache($folderName, $naviname . '.txt', false, $validatedParams['navigation']);
if($ebookstored AND $navistored)
{
return $response->withJson(array("ebookdata" => $ebookstored, "navidata" => $navistored), 200);
}
return $response->withJson(array('data' => false, 'errors' => ['message' => 'We could not store all data. Please try again.']), 500);
}
# deletes the ebook-data (book-details and navigation) from central ebook in settings-area into the data-folder
public function deleteEbookData($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$uri = $request->getUri()->withUserInfo('');
$base_url = $uri->getBaseUrl();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
if(!$this->checkEbookFolder($folder))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'Please make sure that the folder data/ebooks exists and is writable.']), 500);
}
if(!isset($params['projectname']) OR $params['projectname'] == '' OR !preg_match("/^[a-z\-]*\.yaml$/", $params['projectname']))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'The projectname is not valid.']), 422);
}
$projectname = str_replace('.yaml', '', $params['projectname']);
$naviname = str_replace('ebookdata', 'navigation', $projectname);
# create objects to read and write data
$writeYaml = new WriteYaml();
if(!$writeYaml->checkFile($folderName, $projectname . '.yaml') && !$writeYaml->checkFile($folderName, $naviname . '.txt'))
{
return $response->withJson(array(), 200);
}
$ebookDeleted = $writeYaml->deleteFileWithPath($folderName . DIRECTORY_SEPARATOR . $projectname . '.yaml');
$naviDeleted = $writeYaml->deleteFileWithPath($folderName . DIRECTORY_SEPARATOR . $naviname . '.txt');
if(!$ebookDeleted OR !$naviDeleted)
{
$folderContent = array_diff(scandir($folder), array('..', '.', 'tmpitem.txt'));
if(!empty($folderContent))
{
return $response->withJson(array('data' => false, 'errors' => ['message' => 'We could not delete all ebook-data. Please try again.']), 422);
}
}
return $response->withJson(array("ebookdeleted" => $ebookDeleted, "navideleted" => $navideleted), 200);
}
# stores the ebook data from a page tab into the page-yaml
public function storeEbookTabData($request, $response, $args)
{
$params = $request->getParams();
$item = $params['item'];
$settings = $this->getSettings();
# create object to read and write yaml-data
$writeYaml = new WriteYaml();
# validate the data
$validatedParams = $this->validateEbookData($params, $writeYaml);
if(isset($validatedParams['errors']))
{
return $response->withJson(array('data' => false, 'errors' => $validatedParams['errors']), 422);
}
if(!isset($validatedParams['data']) OR empty($validatedParams['data']) OR !$validatedParams['data'])
{
return $response->withJson(array('data' => false, 'errors' => ['The data you send where empty']), 422);
}
# get the metadata from page
$meta = $writeYaml->getYaml($settings['contentFolder'], $item['pathWithoutType'] . '.yaml');
# add the tab-data for ebooks
$meta['ebooks'] = $validatedParams['data'];
# store the metadata for page
$writeYaml->updateYaml($settings['contentFolder'], $item['pathWithoutType'] . '.yaml', $meta);
return $response->withJson(array("ebookdata" => $meta['ebooks']), 200);
}
# stores the navigation for the ebook from a tab into a temporary file
public function storeEbookTabItem($request, $response, $args)
{
$params = $request->getParams();
$item = $params['item'];
$settings = $this->getSettings();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
# create object to read and write cache-data
$writeCache = new WriteCache();
$tmpitem = $writeCache->updateCache($folderName, 'tmpitem.txt', false, $item);
if($tmpitem)
{
return $response->withJson(array("tmpitem" => $tmpitem), 200);
}
return $response->withJson(array('data' => false, 'errors' => ['message' => 'We could not store all data. Please try again.']), 500);
}
# scans the folder with the ebooklayouts and returns layout-names as array
public function scanEbooklayouts()
{
# write params
$writeYaml = new WriteYaml();
# scan the ebooklayouts folder
$layoutfolders = array_diff(scandir(__DIR__ . '/booklayouts'), array('..', '.'));
$booklayouts = [];
foreach($layoutfolders as $layout)
{
# load config files from ebook layout
$configfolder = 'plugins' . DIRECTORY_SEPARATOR . 'ebooks' . DIRECTORY_SEPARATOR . 'booklayouts' . DIRECTORY_SEPARATOR . $layout;
$bookconfig = $writeYaml->getYaml($configfolder, 'config.yaml');
# load customcss
$customcss = $writeYaml->getFile('cache', 'ebooklayout-' . $layout . '-custom.css');
$bookconfig['customcss'] = $customcss ? $customcss : '';
$booklayouts[$layout] = $bookconfig;
}
return $booklayouts;
}
public function storeEbookLayoutCSS($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
if(!isset($params['layout']) OR $params['layout'] == '')
{
return $response->withJson(array('result' => false, 'errors' => ['message' => 'Layout name is missing.']), 500);
}
if(!isset($params['css']))
{
return $response->withJson(array('result' => false, 'errors' => ['message' => 'CSS parameter is missing.']), 500);
}
$layout = $params['layout'];
$customcss = $params['css'];
# write params
$write = new WriteCache();
# make sure no file is set if there is no custom css
if($customcss == '')
{
# delete the css file if exists
$write->deleteFileWithPath('cache' . DIRECTORY_SEPARATOR . 'ebooklayout-' . $layout . '-custom.css');
return $response->withJson(array('result' => true, 'message' => 'deleted css file.'), 200);
}
else
{
if ( $customcss != strip_tags($customcss) )
{
return $response->withJson(array('result' => false, 'errors' => ['message' => 'CSS contains html.']), 500);
}
else
{
# store css
$write->writeFile('cache', 'ebooklayout-' . $layout . '-custom.css', $customcss);
return $response->withJson(array('result' => true), 200);
}
}
}
# gets the ebook navigation from data folder or the general page navigation
public function getEbookNavi($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$folderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
$folder = $settings['rootPath'] . $folderName;
if(!$this->checkEbookFolder($folder))
{
return $response->withJson(array('navigation' => false, 'errors' => ['message' => 'Please make sure that the folder data/ebooks exists and is writable.']), 500);
}
if(!isset($params['projectname']) OR $params['projectname'] == '' OR !preg_match("/^[a-z\-]*\.yaml$/", $params['projectname']))
{
return $response->withJson(array('navigation' => false, 'errors' => ['message' => 'The projectname is not valid.']), 500);
}
$projectname = str_replace('.yaml', '', $params['projectname']);
$naviname = str_replace('ebookdata', 'navigation', $projectname);
# write params
$writeCache = new WriteCache();
$navigation = $writeCache->getCache($folderName, $naviname . '.txt');
if(!$navigation)
{
$navigation = $writeCache->getCache('cache', 'structure.txt');
}
if(!$navigation)
{
return $response->withJson(array('navigation' => false, 'errors' => ['message' => 'We did not find a content tree. Please visit the website frontend to generate the tree.', 'disable' => true]), 422);
}
return $response->withJson(array('navigation' => $navigation, 'errors' => false), 200);
}
# validates the ebook-input data from both, the tab and the centrally used ebook-feature
private function validateEbookData($params, $writeYaml)
{
$formdata = isset($params['data']) ? $params['data'] : false;
$layout = isset($params['data']['layout']) ? $params['data']['layout'] : false;
$errors = false;
# return error if either formdata or layoutdata not present
# check if navigation is there
if(!isset($params['navigation']) OR empty($params['navigation']) OR !$params['navigation'])
{
$errors['content'] = ['Content is missing'];
}
# list all standardfields
$standardfields = [
'layout',
'activeshortcodes',
'disableshortcodes',
'downgradeheadlines',
'excludebasefolder',
'epubidentifierisbn',
'epubidentifieruuid',
'epubidentifieruri',
'epubcover',
'epubdescription',
'epubsubjects',
'epubauthorfirstname',
'epubauthorlastname',
'epubpublishername',
'epubpublisherurl',
'epubtocname',
'epubtitlepage',
'epubchaptername',
'epubchapternumber',
'epubdebug'
];
# create validation object
$validation = new Validation();
# return standard valitron object for standardfields
$v = $validation->returnValidator($formdata);
$v->rule('noHTML', 'blurb');
$v->rule('noHTML', 'primarycolor');
$v->rule('noHTML', 'secondarycolor');
if(!$v->validate())
{
$errors = $v->errors();
}
# delete the standardfields from formdata
foreach($standardfields as $standardfield)
{
if(isset($formdata[$standardfield]))
{
unset($formdata[$standardfield]);
}
}
# validate the customforms: if formdata are not empty now, then we have customfields
if(!empty($formdata && $layout))
{
# get the customfield configurations from booklayout folder
$configfolder = 'plugins' . DIRECTORY_SEPARATOR . 'ebooks' . DIRECTORY_SEPARATOR . 'booklayouts' . DIRECTORY_SEPARATOR . $layout;
$bookconfig = $writeYaml->getYaml($configfolder, 'config.yaml');
if($bookconfig && isset($bookconfig['customforms']['fields']))
{
$customforms = $this->withoutFieldsets($bookconfig['customforms']['fields'], []);
# validation loop: code taken from metaApiController
foreach($formdata as $fieldName => $fieldValue)
{
# get the corresponding field definition from original plugin settings
$fieldDefinition = isset($customforms[$fieldName]) ? $customforms[$fieldName] : false;
if(!$fieldDefinition)
{
# we simply delete the params that are not defined to avoid errors. For example, if field-definitions have been changed in a new version
unset($params['data'][$fieldName]);
}
else
{
# validate user input for this field
$result = $validation->objectField($fieldName, $fieldValue, 'meta', $fieldDefinition);
if($result !== true)
{
$errors[$fieldName] = $result[$fieldName][0];
}
}
}
}
}
if($errors)
{
return array('errors' => $errors);
}
# return the validated params which also hold optimized data for customfields
return $params;
}
# generates the ebook-preview
public function ebookPreview($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$uri = $request->getUri()->withUserInfo('');
$base_url = $uri->getBaseUrl();
$writeYaml = new WriteYaml();
$writeCache = new WriteCache();
$ebookFolderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
# check if call comes from a tab
if(!empty($params) && isset($params['itempath']))
{
# wait for a second to make super sure that the temporary item has been stored by vue-script
usleep(200000);
# get bookdata from the page
$meta = $writeYaml->getYaml($settings['contentFolder'], $params['itempath'] . '.yaml');
$ebookdata = isset($meta['ebooks']) ? $meta['ebooks'] : false;
$navigation = $writeCache->getCache($ebookFolderName, 'tmpitem.txt');
# should we delete the old tmpitem.txt here or simply let next overwrite it?
}
# otherwise it is from the settings
elseif(!empty($params) && isset($params['projectname']))
{
$projectname = str_replace('.yaml', '', $params['projectname']);
$naviname = str_replace('ebookdata', 'navigation', $projectname);
# get bookdata
$ebookdata = $writeYaml->getYaml($ebookFolderName, $projectname .'.yaml');
# get navigationdata
$navigation = $writeCache->getCache($ebookFolderName, $naviname . '.txt');
}
# generate the book content from ebook-navigation
$parsedown = new ParsedownExtension($base_url, $settingsForHeadlineAnchors = false, $this->getDispatcher());
# disable attributes for images because of bug in pagedjs
$parsedown->withoutImageAttributes();
# the default mode is with footnotes, but user can activate endnotes too
if(!isset($ebookdata['endnotes']) or !$ebookdata['endnotes'])
{
# if default mode, then we get a different html from parsedown
$parsedown->withSpanFootnotes();
}
# check if shortcodes should be rendered
if(isset($ebookdata['disableshortcodes']) && $ebookdata['disableshortcodes'])
{
# empty array will stop all shortcodes
$parsedown->setAllowedShortcodes(array());
}
elseif(isset($ebookdata['activeshortcodes']) && is_array($ebookdata['activeshortcodes']) && !empty($ebookdata['activeshortcodes']))
{
# only selected shortcodes will be rendered
$parsedown->setAllowedShortcodes($ebookdata['activeshortcodes']);
}
# skip the base folder if activated
if(isset($ebookdata['excludebasefolder']) and $ebookdata['excludebasefolder'] and isset($navigation[0]['folderContent']))
{
$navigation = $navigation[0]['folderContent'];
}
$pathToContent = $settings['rootPath'] . $settings['contentFolder'];
$book = $this->generateContent([], $navigation, $pathToContent, $parsedown, $ebookdata);
# let us add the thumb index:
$thumbindex = false;
foreach($book as $chapter)
{
if( isset($chapter['metadata']['thumbindex']['language']) && ($chapter['metadata']['thumbindex']['language'] != 'clear'))
{
$thumbindex[$chapter['metadata']['thumbindex']['lang']] = ['lang' => $chapter['metadata']['thumbindex']['lang'], 'thumb' => $chapter['metadata']['thumbindex']['thumb'] ];
}
}
# we have to dispatch onTwigLoaded to get javascript from other plugins
$this->container->dispatcher->dispatch('onTwigLoaded');
$twig = $this->getTwig();
$loader = $twig->getLoader();
$loader->addPath(__DIR__ . '/templates', 'ebooks');
$loader->addPath(__DIR__ . '/booklayouts/' . $ebookdata['layout'], 'booklayouts');
$booklayouts = $this->scanEbooklayouts();
# load customcss
$customcss = $writeYaml->checkFile('cache', 'ebooklayout-' . $ebookdata['layout'] . '-custom.css');
if($customcss)
{
$this->container->assets->addCSS($base_url . '/cache/ebooklayout-' . $ebookdata['layout'] . '-custom.css');
}
return $twig->render($response, '@booklayouts/index.twig', [
'settings' => $settings,
'ebookdata' => $ebookdata,
'booklayout' => $booklayouts[$ebookdata['layout']],
'book' => $book,
'thumbindex' => $thumbindex
]);
}
public function generateContent($book, $navigation, $pathToContent, $parsedown, $ebookdata, $chapterlevel = NULL)
{
# before we use this logic, we have to check if the current layout supports that feature.
# please check here
# or we should delete everything that is not related to the layout in the ebook-data first.
$originalimages = isset($ebookdata['originalimages']) ? $ebookdata['originalimages'] : false;
$downgradeheadlines = isset($ebookdata['downgradeheadlines']) ? $ebookdata['downgradeheadlines'] : 0;
$chapterlevel = $chapterlevel ? $chapterlevel : 1;
foreach($navigation as $item)
{
if($item['status'] == "published")
{
# if page or folder is excluded from book content
if(isset($item['exclude']) && $item['exclude'] == true)
{
continue;
}
# set the filepath
$filePath = $pathToContent . $item['path'];
$metaPath = $pathToContent . $item['pathWithoutType'] . '.yaml';
# check if url is a folder and add index.md
if($item['elementType'] == 'folder')
{
$filePath = $filePath . DIRECTORY_SEPARATOR . 'index.md';
}
# read the content of the file
$chapter = file_exists($filePath) ? file_get_contents($filePath) : false;
# get the meta
$meta = file_exists($metaPath) ? file_get_contents($metaPath) : false;
if($meta)
{
$meta = \Symfony\Component\Yaml\Yaml::parse($meta);
}
# turn into an array
$chapterArray = $parsedown->text($chapter, $itemUrl = false);
# check the hierarchy of the current page within the navigation
# $chapterlevel = count($item['keyPathArray']);
# we have to overwrite headlines and/or image urls if user selected those options
# if( $originalimages OR ( !$originalheadlinelevels && $chapterlevel > 1 ) )
if( $originalimages OR $chapterlevel >= ($downgradeheadlines+1) )
{
# go through each content element
foreach($chapterArray as $key => $element)
{
# if user wants to use original images instead of small once
if($originalimages && isset($element['name']) && $element['name'] == 'figure')
{
# rewrite the image urls
$image = $element['elements'][0]['handler']['argument'];
$element['elements'][0]['handler']['argument'] = str_replace("media/live/", "media/original/", $image);
$chapterArray[$key] = $element;
}
/*
# by default and if user did not contradict to automatically adjust the headline levels
if(!$originalheadlinelevels AND isset($element['name'][1]) AND $element['name'][0] == 'h' AND is_numeric($element['name'][1]))
{
# lower the levels of headlines
$headlinelevel = $element['name'][1] + ($chapterlevel -1);
$headlinelevel = ($headlinelevel > 6) ? 6 : $headlinelevel;
$chapterArray[$key]['name'] = 'h' . $headlinelevel;
}
*/
if($downgradeheadlines == 0)
{
continue;
}
# adjust the headline levels
if( ($chapterlevel >= ($downgradeheadlines+1) ) AND isset($element['name'][1]) AND $element['name'][0] == 'h' AND is_numeric($element['name'][1]))
{
# lower the levels of headlines
$headlinelevel = $element['name'][1] + ($chapterlevel - $downgradeheadlines);
$headlinelevel = ($headlinelevel > 6) ? 6 : $headlinelevel;
$chapterArray[$key]['name'] = 'h' . $headlinelevel;
}
}
}
# turn into html
$chapterHTML = $parsedown->markup($chapterArray, $itemUrl = false);
$book[] = ['item' => $item, 'level' => $chapterlevel, 'content' => $chapterHTML, 'metadata' => $meta];
if($item['elementType'] == 'folder')
{
$book = $this->generateContent($book, $item['folderContent'], $pathToContent, $parsedown, $ebookdata, $chapterlevel + 1 );
}
}
}
return $book;
}
public function generateHeadlinePreview($request, $response, $args)
{
$params = $request->getParams();
$settings = $this->getSettings();
$uri = $request->getUri()->withUserInfo('');
$base_url = $uri->getBaseUrl();
$writeYaml = new WriteYaml();
$writeCache = new WriteCache();
$ebookFolderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
# check if call comes from a tab
if(isset($params['item']) && isset($params['ebookdata']))
{
$ebookdata = $params['ebookdata'];
$navigation = $params['item'];
}
# otherwise it is from the settings
else
{
# get bookdata
$ebookdata = $writeYaml->getYaml($ebookFolderName, 'ebookdata.yaml');
# get navigationdata
$navigation = $writeCache->getCache($ebookFolderName, 'navigation.txt');
}
# skip the base folder if activated
if(isset($ebookdata['excludebasefolder']) and $ebookdata['excludebasefolder'] and isset($navigation[0]['folderContent']))
{
$navigation = $navigation[0]['folderContent'];
}
# generate the book content from ebook-navigation
$parsedown = new ParsedownExtension($base_url);
$pathToContent = $settings['rootPath'] . $settings['contentFolder'];
$headlines = $this->generateArrayOfHeadlineElements([], $navigation, $pathToContent, $parsedown, $ebookdata);
return $response->withJson(array('headlines' => $headlines, 'errors' => false), 200);
}
private function generateArrayOfHeadlineElements($headlines, $navigation, $pathToContent, $parsedown, $ebookdata, $chapterlevel = NULL)
{
$downgradeheadlines = isset($ebookdata['downgradeheadlines']) ? $ebookdata['downgradeheadlines'] : 0;
$chapterlevel = $chapterlevel ? $chapterlevel : 1;
foreach($navigation as $item)
{
if($item['status'] == "published")
{
# if page or folder is excluded from book content
if(isset($item['exclude']) && $item['exclude'] == true)
{
continue;
}
# set the filepath
$filePath = $pathToContent . $item['path'];
# check if url is a folder and add index.md
if($item['elementType'] == 'folder')
{
$filePath = $filePath . DIRECTORY_SEPARATOR . 'index.md';
}
# read the content of the file
$chapter = file_exists($filePath) ? file_get_contents($filePath) : false;
# turn into an array
$chapterArray = $parsedown->text($chapter, $itemUrl = false);
# go through each content element
foreach($chapterArray as $key => $element)
{
# check if it is a headline
if( isset($element['name'][1]) AND $element['name'][0] == 'h' AND is_numeric($element['name'][1]))
{
if( ( $downgradeheadlines > 0 ) && ( $chapterlevel >= ($downgradeheadlines+1) ) )
{
# lower the levels of headlines
$headlinelevel = $element['name'][1] + ($chapterlevel - $downgradeheadlines);
$element['name'][1] = ($headlinelevel > 6) ? 6 : $headlinelevel;
}
$headlines[] = ['name' => $element['name'], 'level' => $element['name'][1], 'text' => $element['handler']['argument']];
}
}
if($item['elementType'] == 'folder')
{
$headlines = $this->generateArrayOfHeadlineElements($headlines, $item['folderContent'], $pathToContent, $parsedown, $ebookdata, $chapterlevel + 1 );
}
}
}
return $headlines;
}
# generates and returns the epub file
public function createEpub($request, $response, $args)
{
ob_end_flush();
error_reporting(E_ALL | E_STRICT);
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 0);
$params = $request->getParams();
$settings = $this->getSettings();
$uri = $request->getUri()->withUserInfo('');
$base_url = $uri->getBaseUrl();
$writeYaml = new WriteYaml();
$writeCache = new WriteCache();
$ebookFolderName = 'data' . DIRECTORY_SEPARATOR . 'ebooks';
# check if call comes from a tab
if(!empty($params) && isset($params['itempath']))
{
# wait for a second to make super sure that the temporary item has been stored by vue-script
usleep(200000);
# get bookdata from the page
$meta = $writeYaml->getYaml($settings['contentFolder'], $params['itempath'] . '.yaml');
$ebookdata = isset($meta['ebooks']) ? $meta['ebooks'] : false;
$navigation = $writeCache->getCache($ebookFolderName, 'tmpitem.txt');
}
# otherwise it is from the settings
elseif(!empty($params) && isset($params['projectname']))
{
$projectname = str_replace('.yaml', '', $params['projectname']);
$naviname = str_replace('ebookdata', 'navigation', $projectname);
# get bookdata
$ebookdata = $writeYaml->getYaml($ebookFolderName, $projectname .'.yaml');
# get navigationdata
$navigation = $writeCache->getCache($ebookFolderName, $naviname . '.txt');
}
if(!$navigation OR !$ebookdata)
{
$response->write('There is no navigation or no ebookdata for this book project.');
return $response;
}
# generate the book content from ebook-navigation
$parsedown = new ParsedownExtension($base_url);