Repository navigation
Expand file tree
/
Copy pathconvertCore.php
More file actions
executable file
·3510 lines (3384 loc) · 299 KB
/
Copy pathconvertCore.php
File metadata and controls
executable file
·3510 lines (3384 loc) · 299 KB
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 if (php_sapi_name() !== 'cli') print('<!DOCTYPE HTML>'.PHP_EOL);
// / -----------------------------------------------------------------------------------
// / Copyright Information ...
// / HRConvert2, Copyright on 9/22/2026 by Justin Grimes, www.github.com/zelon88
// /
// / License Information ...
// / This project is protected by the GNU GPLv3 Open-Source license.
// / https://www.gnu.org/licenses/gpl-3.0.html
// /
// / Application Information ...
// / This application is designed to provide a web-interface for converting file formats
// / on a server for users of any web browser without authentication.
// /
// / File Information ...
// / v4.4.2.
// / HRConvert2 Convert Core.
// / This file contains the core logic of the application.
// /
// / Hardware Requirements ...
// / This application requires at least a Raspberry Pi Model B+ or greater.
// / This application will run on just about any x86 or x64 computer.
// /
// / Dependency Requirements ...
// / The authoritative list of dependencies is Resources/Engine/depends.php & Resources/Contract/depends.php, the Engine's half & the application's, & nothing else.
// / Run php convertCore.php -v to see what this installation has.
// /
// / <3 Open-Source
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to verify that this installation is complete, current & usable.
// / Returns a verification boolean, the path of the config file, the version reported by
// / versionInfo.php & the core loaded flag, in that order.
// / The pins below are this application's, & they are all it supplies.
// / Everything else is the kernel's verifyInstallationState, which every application built on the Engine boots through.
// / It finds who runs this process, reads versionInfo.php & config.php, checks both against these pins, derives every location & reads the install secret.
// / Every failure other than the secret is fatal & halts there, because nothing downstream
// / can operate without a config file or against a mismatched core.
function verifyInstallation() {
// / Set variables.
global $HRConvertVersion, $EngineApplicationVersion, $RequiredConfigVersion, $RequiredGuiVersion, $RequiredLanguageVersion, $RequiredSetupCoreVersion, $RequiredDependencyCoreVersion, $RequiredDependsVersion, $RequiredPipelineCoreVersion, $RequiredGateCoreVersion, $RequiredWorkflowCoreVersion, $RequiredAuthenticationCoreVersion, $RequiredEmailCoreVersion, $RequiredEventCoreVersion, $RequiredEngineVersion, $RequiredConfigScript, $RequiredSecretVersion, $CoreLoaded, $Version, $EnableMemoryProtection;
$InstallationIsVerified = FALSE;
$configFile = '';
$CoreLoaded = TRUE;
// / Define what version of HRConvert2 this core file represents.
// / Note that this number does not have to match the version numbers of individual components listed below.
// / The version of the core is typically several versions ahead of individual component versions. This is normal.
$HRConvertVersion = 'v4.4.2';
$HRConvertVersion = ltrim($HRConvertVersion, 'vV');
// / Handed to the Engine here, where it is defined, so there is only ever one copy.
$EngineApplicationVersion = $HRConvertVersion;
// / Define the minimum acceptable config.php version that this convertCore.php can accept.
// / This is only raised when a release adds or removes a config setting.
// / A release that changes no settings leaves this alone, so existing config files keep working.
// / Any config.php version that is greater (newer) than the version listed below is considered acceptable.
$RequiredConfigVersion = 'v4.2.8';
$RequiredConfigVersion = ltrim($RequiredConfigVersion, 'vV');
// / Define the GUI version that this convertCore.php can accept.
// / Note that this check looks for the component version to be identical to what is listed below.
// / A GUI version that does not exactly match the version listed below is not considered acceptable.
// / This is because Guis are not always guaranteed to be forward or reverse compatible.
$RequiredGuiVersion = 'v4.3.2';
$RequiredGuiVersion = ltrim($RequiredGuiVersion, 'vV');
// / Define the Language Pack version that this convertCore.php can accept.
// / Note that this check looks for the component version to be identical to what is listed below.
// / A Language Pack version that does not exactly match the version listed below is not considered acceptable.
// / This is because Language Packs are not always guaranteed to be forward or reverse compatible.
$RequiredLanguageVersion = 'v4.3.0';
$RequiredLanguageVersion = ltrim($RequiredLanguageVersion, 'vV');
// / No Core Manager version is pinned here. Every manager role is a subcomponent of the
// / Engine & getAcceptedManagers() inside the Engine pins each one exactly.
// / The Setup Core component version this core requires.
// / This is an exact match. A component built for another core may not be called safely.
// / Raise this when the Setup Core itself changes.
// / The configuration model is the Engine's engineConfigModel() & applicationConfigModel() in this file, & their defaults are the two templates, so a new setting raises nothing here.
$RequiredSetupCoreVersion = 'v5.0.0ur';
$RequiredSetupCoreVersion = ltrim($RequiredSetupCoreVersion, 'vV');
// / The Dependency Core component version this core requires.
// / This is an EXACT match. A component built for another core may not be called safely.
$RequiredDependencyCoreVersion = 'v5.0.0ur';
$RequiredDependencyCoreVersion = ltrim($RequiredDependencyCoreVersion, 'vV');
// / The dependency manifest version this core requires.
// / Raise this whenever a dependency is added, removed, or its minimum version moves.
// / A manifest from another release may name a package that no longer exists.
$RequiredDependsVersion = 'v4.4.1';
$RequiredDependsVersion = ltrim($RequiredDependsVersion, 'vV');
// / The Pipeline Core component version this core requires.
// / This is an exact match, because a component built for another core may declare an entry point whose arguments have moved, or capabilities this core cannot honour.
// / Raise this when the Pipeline Core itself changes & for nothing else.
// / It is an Engine core, at Resources/Engine/Cores/pipelineCore.php.
// / The pipelines this application accepts are listed in its contract, in app-engine-config.php, so adding a pipeline or moving one to a new version raises nothing here.
$RequiredPipelineCoreVersion = 'v5.0.0ur';
$RequiredPipelineCoreVersion = ltrim($RequiredPipelineCoreVersion, 'vV');
// / The Gate Core component version this core requires, from v4.3.9.
// / This is an exact match, for the reason every Engine core's is. The Engine loads it after the Pipeline Core, & it runs the gate
// / program a pipeline names for an input before that pipeline opens it. It is an Engine core, at Resources/Engine/Cores/gateCore.php.
// / The gate programs this application accepts are listed in its contract, in app-engine-config.php, as the pipelines are.
$RequiredGateCoreVersion = 'v5.0.1ur';
$RequiredGateCoreVersion = ltrim($RequiredGateCoreVersion, 'vV');
// / The Workflow Core component version this core requires.
// / This is an exact match, because a component built for another core may call an operation with arguments that have moved.
// / Raise this when the Workflow Core itself changes & for nothing else. It is an Engine core, at Resources/Engine/Cores/workflowCore.php.
$RequiredWorkflowCoreVersion = 'v4.3.1r';
$RequiredWorkflowCoreVersion = ltrim($RequiredWorkflowCoreVersion, 'vV');
// / The Authentication Core & Email Core component versions this core requires.
// / Each is an exact match, for the reason every Engine core's is. The Engine loads them where accounts are on.
// / They are Engine cores, at Resources/Engine/Cores/authenticationCore.php & Resources/Engine/Cores/emailCore.php.
$RequiredAuthenticationCoreVersion = 'v5.0.0r';
$RequiredAuthenticationCoreVersion = ltrim($RequiredAuthenticationCoreVersion, 'vV');
$RequiredEmailCoreVersion = 'v5.0.0r';
$RequiredEmailCoreVersion = ltrim($RequiredEmailCoreVersion, 'vV');
// / The Event Core component version this core requires, from v4.3.1.
// / This is an exact match, for the reason every Engine core's is. The Engine loads it where a command keeps or reads an event.
// / It is an Engine core, at Resources/Engine/Cores/eventCore.php, & -v reports it whether or not this application keeps an event.
$RequiredEventCoreVersion = 'v4.3.1r';
$RequiredEventCoreVersion = ltrim($RequiredEventCoreVersion, 'vV');
// / The Engine version this application requires.
// / This is an EXACT match & it is free, because the Engine is bundled with this release
// / rather than installed beside it. The updater replaces both together, so the pin & the
// / file it points at cannot drift apart on an installation nobody has edited by hand.
// / An administrator who edits the Engine by hand loses the edit at the next update. That
// / is the same bargain every bundled component makes.
// / --build cannot write this pin, because it runs inside the Engine. Move it by hand.
$RequiredEngineVersion = 'v5.0.0ur';
$RequiredEngineVersion = ltrim($RequiredEngineVersion, 'vV');
// / The bootstrap script version this core expects, as an exact match.
// / The Engine compares the script against this, & -fp disables it as root when it differs.
$RequiredConfigScript = 'v4.0.1';
$RequiredConfigScript = ltrim($RequiredConfigScript, 'vV');
// / The secret file version this core requires.
// / This is an EXACT match. A secret file reporting anything else is deleted & rewritten.
// / Raise this to force every installation in the wild off an exposed or outdated secret.
// / Raising it invalidates every active session on the next request. That is the point.
$RequiredSecretVersion = 'v3.7.7';
$RequiredSecretVersion = ltrim($RequiredSecretVersion, 'vV');
// / The kernel verifies the installation against the pins above.
list ($InstallationIsVerified, $configFile) = verifyInstallationState(__FILE__, $HRConvertVersion, $RequiredConfigVersion);
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
// / $configFile is not purged, because it is a return value.
purgeSensitiveMemory($EnableMemoryProtection);
return array($InstallationIsVerified, $configFile, $Version, $CoreLoaded); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to verify that all required POST & GET inputs are properly sanitized.
function verifyInputs() {
// / Set variables.
global $ShowGUI, $EnableMemoryProtection, $NoGui, $ShowFiles, $FileListOnly, $StreamBaseURL, $UserURLDownload, $LogoURL, $ResolvedLogoURL, $SupportedLanguages, $SupportedColors, $SupportedGuis;
$InputsAreVerified = TRUE;
$GUI = $Color = $Language = $Token1 = $Token2 = $Height = $Width = $Rotate = $Bitrate = $Method = $Download = $UserFilename = $UserExtension = $Archive = $UserScanType = $IdentifyReport = $IdentifyFilename = $Sort = $WorkflowName = $WorkflowDocument = $WorkflowCheck = $WorkflowExport = $WorkflowPreview = $WorkflowPreviewDocument = $WorkflowStage = $WorkflowStageDescriptions = $RenamePattern = $ConversionFamily = $var = $rawInput = '';
$variableIsSanitized = $ConvertSelected = $PDFWorkSelected = $FilesToArchive = $FilesToScan = $FilesToDelete = $FilesToIdentify = $FilesToExtract = $FilesToRename = $FilesToStrip = $FilesToMerge = $FilesToSplit = $WorkflowFiles = $logoParts = $logoQuery = array();
$key = 0;
// / Determine whether or not to display a full GUI or a minimalized GUI.
// / The default action is set in config.php. The user can opt for less than the default, but never more.
// / The user can only disable the full GUI and fall back to a minimal one.
// / The user can never force enable a full GUI if $ShowGUI is set to FALSE in config.php.
if (isset($_GET['noGui'])) $ShowGUI = FALSE;
if (!$ShowGUI) $_GET['noGui'] = TRUE;
// / Every superglobal this application reads is read here & nowhere else.
// / An interface that reads $_GET defines API surface, & an interface is not entitled to
// / define API surface. These three carry no data, only presence, so the value is
// / discarded & a boolean is handed on. Nothing downstream needs to sanitize a boolean.
// / A GUI receives these through buildGUI & must never look at $_GET for itself.
$NoGui = isset($_GET['noGui']);
$ShowFiles = isset($_GET['showFiles']);
$FileListOnly = isset($_GET['fileListOnly']);
// / Sanitize each variable as needed & build a list of error check results.
if (isset($_POST['filesToDelete'])) list ($FilesToDelete, $variableIsSanitized[$key++]) = sanitize($_POST['filesToDelete'], TRUE);
if (isset($_POST['language'])) list ($Language, $variableIsSanitized[$key++]) = sanitize($_POST['language'], TRUE);
if (isset($_GET['language'])) list ($_GET['language'], $variableIsSanitized[$key++]) = sanitize($_GET['language'], TRUE);
if (isset($_GET['language'])) list ($Language, $variableIsSanitized[$key++]) = sanitize($_GET['language'], TRUE);
if (isset($_POST['color'])) list ($Color, $variableIsSanitized[$key++]) = sanitize($_POST['color'], TRUE);
if (isset($_GET['color'])) list ($_GET['color'], $variableIsSanitized[$key++]) = sanitize($_GET['color'], TRUE);
if (isset($_GET['color'])) list ($Color, $variableIsSanitized[$key++]) = sanitize($_GET['color'], TRUE);
if (isset($_POST['gui'])) list ($GUI, $variableIsSanitized[$key++]) = sanitize($_POST['gui'], TRUE);
if (isset($_GET['gui'])) list ($_GET['gui'], $variableIsSanitized[$key++]) = sanitize($_GET['gui'], TRUE);
if (isset($_GET['gui'])) list ($GUI, $variableIsSanitized[$key++]) = sanitize($_GET['gui'], TRUE);
// / The sort order rides in the address, as the language, the colour & the interface do, & is read from nowhere else.
if (isset($_GET['sort'])) list ($Sort, $variableIsSanitized[$key++]) = sanitize($_GET['sort'], TRUE);
if (isset($_POST['Token1'])) list ($Token1, $variableIsSanitized[$key++]) = sanitize($_POST['Token1'], TRUE);
if (isset($_POST['Token2'])) list ($Token2, $variableIsSanitized[$key++]) = sanitize($_POST['Token2'], TRUE);
if (isset($_POST['height'])) list ($Height, $variableIsSanitized[$key++]) = sanitize($_POST['height'], TRUE);
if (isset($_POST['width'])) list ($Width, $variableIsSanitized[$key++]) = sanitize($_POST['width'], TRUE);
// / An empty base is the normal case & means the playlist must carry full URLs.
$StreamBaseURL = $UserURLDownload = '';
if (isset($_POST['rotate'])) list ($Rotate, $variableIsSanitized[$key++]) = sanitize($_POST['rotate'], TRUE);
if (isset($_POST['bitrate'])) list ($Bitrate, $variableIsSanitized[$key++]) = sanitize($_POST['bitrate'], TRUE);
if (isset($_POST['method'])) list ($Method, $variableIsSanitized[$key++]) = sanitize($_POST['method'], TRUE);
if (isset($_POST['download'])) list ($Download, $variableIsSanitized[$key++]) = sanitize($_POST['download'], TRUE);
if (isset($_POST['archive'])) list ($Archive, $variableIsSanitized[$key++]) = sanitize($_POST['archive'], TRUE);
if (isset($_POST['extension'])) list ($UserExtension, $variableIsSanitized[$key++]) = sanitize($_POST['extension'], TRUE);
if (isset($_POST['filesToArchive'])) list ($FilesToArchive, $variableIsSanitized[$key++]) = sanitize($_POST['filesToArchive'], TRUE);
if (isset($_POST['archextension'])) list ($UserExtension, $variableIsSanitized[$key++]) = sanitize($_POST['archextension'], TRUE);
if (isset($_POST['userfilename'])) list ($UserFilename, $variableIsSanitized[$key++]) = sanitize($_POST['userfilename'], TRUE);
if (isset($_POST['userconvertfilename'])) list ($UserFilename, $variableIsSanitized[$key++]) = sanitize($_POST['userconvertfilename'], TRUE);
if (isset($_POST['pdfworkSelected'])) list ($PDFWorkSelected, $variableIsSanitized[$key++]) = sanitize($_POST['pdfworkSelected'], TRUE);
if (isset($_POST['convertSelected'])) list ($ConvertSelected, $variableIsSanitized[$key++]) = sanitize($_POST['convertSelected'], TRUE);
// / The family a conversion was asked of, which each menu sends, from v4.2.8. A request that names none is converted by the first family that can.
if (isset($_POST['conversionFamily'])) list ($ConversionFamily, $variableIsSanitized[$key++]) = sanitize($_POST['conversionFamily'], TRUE);
// / The logo destination is computed here, where the session values already are.
// /
// / 'preserve-session' is not an address & is never emitted as one. It means build a link
// / back to this page carrying what a user has already chosen, so clicking the logo
// / returns them to a clean page rather than out of the application. This server has no
// / navigation, so a logo that leaves takes the session with it & the files with that.
// /
// / The three carried values are language, colour & interface. Each has ALREADY been
// / through sanitize() above, & each is checked against the list of what this
// / installation supports before it is put in a URL. A value that is not in the list is
// / left out rather than corrected, because a link is not the place to argue with input.
// /
// / The session tokens are deliberately NOT carried. A session belongs to the browser
// / that holds it & putting one in a link makes it something that can be copied out of a
// / history, a referrer header or somebody's shoulder.
// /
// / A configured address is used as written & is required to be http or https. Anything
// / else falls back to preserving the session, because a logo pointing at javascript: or
// / data: is a way to run something in a visitor's browser.
$ResolvedLogoURL = 'convertCore.php';
if (isset($LogoURL) && strtolower(trim((string)$LogoURL)) !== 'preserve-session') {
$logoParts = @parse_url(trim((string)$LogoURL));
if (is_array($logoParts) && isset($logoParts['scheme']) && in_array(strtolower($logoParts['scheme']), array('http', 'https'), TRUE)) $ResolvedLogoURL = trim((string)$LogoURL);
else warningEntry('The configured Logo URL is not an http or https address & was refused. The logo will return to this page instead.'); }
else {
$logoQuery = array();
if (isset($Language) && isset($SupportedLanguages) && is_array($SupportedLanguages) && array_key_exists($Language, $SupportedLanguages)) $logoQuery[] = 'language='.rawurlencode($Language);
if (isset($Color) && isset($SupportedColors) && is_array($SupportedColors) && in_array($Color, $SupportedColors, TRUE)) $logoQuery[] = 'color='.rawurlencode($Color);
if (isset($GUI) && isset($SupportedGuis) && is_array($SupportedGuis) && in_array($GUI, $SupportedGuis, TRUE)) $logoQuery[] = 'gui='.rawurlencode($GUI);
if (sortCodeIsValid($Sort)) $logoQuery[] = 'sort='.rawurlencode($Sort);
if (!empty($logoQuery)) $ResolvedLogoURL = 'convertCore.php?'.implode('&', $logoQuery); }
// / The logo carries the sort order too, because the order a user chose is one of the choices it keeps.
// / The stream base address is NOT passed through sanitize() & that is deliberate.
// / sanitize() removes the characters a filename must never hold, which are the ones a
// / URL is made of. It would return a filename rather than an address.
// / normalizeStreamBaseURL() in the Engine rebuilds it from parsed components instead &
// / applies sanitize() to the host, which is the one part that is filename shaped.
// / It is stored raw here & normalized at the point of use, so the reason a bad one was
// / refused can be reported to the operator who typed it.
if (isset($_POST['streamBaseURL']) && is_string($_POST['streamBaseURL'])) $StreamBaseURL = $_POST['streamBaseURL'];
// / The download address is read raw for the same reason the stream base is. A URL that
// / has been through sanitize() is a filename & is no longer an address.
// / fetchUserSuppliedURL rebuilds it & every check a playlist URL receives is applied to
// / it before anything is fetched.
if (isset($_POST['userURLDownload']) && is_string($_POST['userURLDownload'])) $UserURLDownload = $_POST['userURLDownload'];
// / A workflow a page sends is read raw for the same reason, & that is deliberate.
// / It is JSON, & sanitize() removes the quotes, braces & slashes JSON is written with, so a sanitized workflow is no longer one.
// / The Workflow Core reads it only as data, & checks every key & value it holds before anything acts on it, more strictly than sanitize() would.
// / A name it gives what an operation makes is sanitized where the operation uses it, as a name a user types for a button is.
if (isset($_POST['workflowDocument']) && is_string($_POST['workflowDocument'])) $WorkflowDocument = $_POST['workflowDocument'];
if (isset($_POST['workflowCheck']) && is_string($_POST['workflowCheck'])) $WorkflowCheck = $_POST['workflowCheck'];
if (isset($_POST['workflowPreviewDocument']) && is_string($_POST['workflowPreviewDocument'])) $WorkflowPreviewDocument = $_POST['workflowPreviewDocument'];
// / A workflow an administrator stages for every user is read raw for the same reason, & so is what describes it, which is JSON too, from v4.2.2.
// / The Workflow Core checks both as it checks any workflow a page sends, & only for a request signed in to an administrator's account.
if (isset($_POST['workflowStage']) && is_string($_POST['workflowStage'])) $WorkflowStage = $_POST['workflowStage'];
if (isset($_POST['workflowStageDescriptions']) && is_string($_POST['workflowStageDescriptions'])) $WorkflowStageDescriptions = $_POST['workflowStageDescriptions'];
// / A raw input is read only when it is text. Anything else is refused & named, because casting a list to text is a PHP warning, & no page sends one.
foreach (array('streamBaseURL', 'userURLDownload', 'workflowDocument', 'workflowCheck', 'workflowPreviewDocument', 'workflowStage', 'workflowStageDescriptions') as $rawInput) if (isset($_POST[$rawInput]) && !is_string($_POST[$rawInput])) warningEntry('A request carried '.$rawInput.' as something other than text, & it was refused.');
if (isset($_POST['pdfextension'])) list ($UserExtension, $variableIsSanitized[$key++]) = sanitize($_POST['pdfextension'], TRUE);
if (isset($_POST['userpdfconvertfilename'])) list ($UserFilename, $variableIsSanitized[$key++]) = sanitize($_POST['userpdfconvertfilename'], TRUE);
if (isset($_POST['scantype'])) list ($UserScanType, $variableIsSanitized[$key++]) = sanitize($_POST['scantype'], TRUE);
if (isset($_POST['filesToScan'])) list ($FilesToScan, $variableIsSanitized[$key++]) = sanitize($_POST['filesToScan'], TRUE);
// / Identify reads the files to identify, whether to write a report, & the name to give it.
if (isset($_POST['filesToIdentify'])) list ($FilesToIdentify, $variableIsSanitized[$key++]) = sanitize($_POST['filesToIdentify'], TRUE);
if (isset($_POST['identifyreport'])) list ($IdentifyReport, $variableIsSanitized[$key++]) = sanitize($_POST['identifyreport'], TRUE);
if (isset($_POST['identifyfilename'])) list ($IdentifyFilename, $variableIsSanitized[$key++]) = sanitize($_POST['identifyfilename'], TRUE);
// / Extract reads the archives to extract & nothing else, because every file is named as its archive names it.
if (isset($_POST['filesToExtract'])) list ($FilesToExtract, $variableIsSanitized[$key++]) = sanitize($_POST['filesToExtract'], TRUE);
// / Rename reads the files to rename & the pattern their new names are made from, which sanitizeNamePattern() sanitizes, keeping its tokens.
if (isset($_POST['filesToRename'])) list ($FilesToRename, $variableIsSanitized[$key++]) = sanitize($_POST['filesToRename'], TRUE);
if (isset($_POST['renamepattern'])) list ($RenamePattern, $variableIsSanitized[$key++]) = sanitizeNamePattern($_POST['renamepattern']);
// / Strip Metadata, Merge & Split read the files they work on. A name Merge gives what it makes arrives as userfilename.
if (isset($_POST['filesToStrip'])) list ($FilesToStrip, $variableIsSanitized[$key++]) = sanitize($_POST['filesToStrip'], TRUE);
if (isset($_POST['filesToMerge'])) list ($FilesToMerge, $variableIsSanitized[$key++]) = sanitize($_POST['filesToMerge'], TRUE);
if (isset($_POST['filesToSplit'])) list ($FilesToSplit, $variableIsSanitized[$key++]) = sanitize($_POST['filesToSplit'], TRUE);
// / A workflow run reads the workflow to run & the files, in the order a user selected them. A preview of a library's workflow names it as a run does.
if (isset($_POST['workflowRun'])) list ($WorkflowName, $variableIsSanitized[$key++]) = sanitize($_POST['workflowRun'], TRUE);
if (isset($_POST['workflowPreview'])) list ($WorkflowPreview, $variableIsSanitized[$key++]) = sanitize($_POST['workflowPreview'], TRUE);
if (isset($_POST['workflowFiles'])) list ($WorkflowFiles, $variableIsSanitized[$key++]) = sanitize($_POST['workflowFiles'], TRUE);
// / An export names a workflow in the library by its identifier.
if (isset($_POST['workflowExport'])) list ($WorkflowExport, $variableIsSanitized[$key++]) = sanitize($_POST['workflowExport'], TRUE);
// / Check the list of error check results and see if any errors occurred.
foreach ($variableIsSanitized as $var) if (!$var) ($InputsAreVerified = FALSE);
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $logoParts, $logoQuery, $variableIsSanitized, $key, $var, $rawInput);
return array($InputsAreVerified, $ShowGUI, $GUI, $Color, $Language, $Token1, $Token2, $Height, $Width, $Rotate, $Bitrate, $Method, $Download, $UserFilename, $UserExtension, $FilesToArchive, $PDFWorkSelected, $ConvertSelected, $FilesToScan, $FilesToDelete, $UserScanType, $UserURLDownload, $FilesToIdentify, $IdentifyReport, $IdentifyFilename, $Sort, $WorkflowName, $WorkflowFiles, $WorkflowDocument, $WorkflowCheck, $WorkflowExport, $FilesToExtract, $FilesToRename, $RenamePattern, $FilesToStrip, $FilesToMerge, $FilesToSplit, $WorkflowPreview, $WorkflowPreviewDocument, $WorkflowStage, $WorkflowStageDescriptions, $ConversionFamily); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to set the styles to use for the session.
function verifyColors($ButtonStyle) {
// / Set variables.
global $Color, $SupportedColors, $AllowUserSelectableColor, $ColorToUse, $GreenButtonCode, $BlueButtonCode, $RedButtonCode, $OrangeButtonCode, $PurpleButtonCode, $DarkButtonCode, $DefaultButtonCode, $EnableMemoryProtection;
$ColorsAreSet = FALSE;
$ColorToUse = 'blue';
$ButtonStyle = strtolower($ButtonStyle);
$ButtonCode = $DefaultButtonCode;
$validColors = array('green', 'blue', 'red', 'grey', 'orange', 'purple', 'dark');
// / Make sure $SupportedColors is valid.
if (!isset($SupportedColors) or !is_array($SupportedColors)) $SupportedColors = $validColors;
// / Make sure the Default Color is valid.
if (isset($ButtonStyle)) if (in_array($ButtonStyle, $SupportedColors)) $ColorToUse = $ButtonStyle;
// / If allowed and if specified, detect the user's specified color and set that as the color to use.
if (isset($AllowUserSelectableColor)) {
if ($AllowUserSelectableColor) if (isset($Color)) if (in_array($Color, $SupportedColors)) {
$ColorToUse = $Color; } }
// / Set the $Color variable to whatever the current color is so the next page will use the same one.
$_GET['color'] = $ColorToUse;
// / Validate the desired color and set it as the color to use if possible.
if (in_array($ColorToUse, $validColors)) {
$ColorsAreSet = TRUE;
if ($ColorToUse === 'green') $ButtonCode = $GreenButtonCode;
if ($ColorToUse === 'blue') $ButtonCode = $BlueButtonCode;
if ($ColorToUse === 'red') $ButtonCode = $RedButtonCode;
if ($ColorToUse === 'orange') $ButtonCode = $OrangeButtonCode;
if ($ColorToUse === 'purple') $ButtonCode = $PurpleButtonCode;
if ($ColorToUse === 'dark') $ButtonCode = $DarkButtonCode;
if ($ColorToUse === 'grey') $ButtonCode = $DefaultButtonCode; }
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $validColors);
return array($ColorsAreSet, $ButtonCode); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to set the GUI to use for the session.
function verifyGui() {
// / Set variables.
global $GUI, $DefaultGui, $SupportedGuis, $AllowUserSelectableGui, $GuiFiles, $GuiDir, $GuiResourcesDir, $GuiImageDir, $GuiCSSDir, $GuiJSDir, $GuiHeaderFile, $GuiFooterFile, $GuiUI1File, $GuiUI2File, $GuiEngineFile, $GuiTaskbarFile, $GreenButtonCode, $BlueButtonCode, $RedButtonCode, $OrangeButtonCode, $PurpleButtonCode, $DarkButtonCode, $DefaultButtonCode, $Font, $GuiVersion, $RequiredGuiVersion, $EnableMemoryProtection, $CoreLoaded, $GuiWidth, $GuiMaxWidth, $GUIAlignment;
// / The interface width is decided ONCE, here, before the stylesheet that uses it loads.
// / $GuiWidth is FLUID rather than fixed. min() takes whichever is smaller, so a phone is
// / bounded by its own viewport & a wide monitor by the configured ceiling.
// / A fixed pixel width does one of two wrong things. Too small & a large display wastes
// / most of itself. Too large & a phone scrolls sideways, which is the most irritating
// / thing an interface can do on a device held in one hand.
// / 96vw rather than 100vw leaves room for a scrollbar. A page sized to the whole viewport
// / gains a horizontal scrollbar the moment it gains a vertical one.
// / A value outside the sane range is a typo rather than a preference & the default is
// / used instead of trusting it.
// / This is what makes the separate Wide interface unnecessary. It differed from Original
// / by one number hardcoded in four files, & that number is a setting now.
$GuiWidth = 'min('.((isset($GuiMaxWidth) && (int)$GuiMaxWidth >= 600 && (int)$GuiMaxWidth <= 3840) ? (int)$GuiMaxWidth : 1400).'px, 96vw)';
$reqFile = $GuiIsSet = FALSE;
$GuiToUse = $defaultGui = 'Default';
$styleCoreFile = $guiVersionFile = '';
$GuiFiles = $guiFiles = array();
// / Only installed interfaces are listed, because a fallback naming one that is not installed is the failure this list exists to prevent.
$defaultGuis = array('Default', 'Original');
// / Make sure $SupportedGuis is valid.
if (!isset($SupportedGuis) or !is_array($SupportedGuis)) $SupportedGuis = $defaultGuis;
// / Make sure the Default GUI is valid.
if (isset($DefaultGui)) if (in_array($DefaultGui, $SupportedGuis)) $GuiToUse = $DefaultGui;
// / If allowed and if specified, detect the user's specified GUI and set that as the GUI to use.
if (isset($AllowUserSelectableGui)) {
if ($AllowUserSelectableGui) if (isset($GUI)) if (in_array($GUI, $SupportedGuis)) {
$GuiToUse = $GUI; }
if (!$AllowUserSelectableGui) {
$GuiToUse = $defaultGui;
if (in_array($DefaultGui, $SupportedGuis)) $GuiToUse = $DefaultGui; } }
// / Build the list of candidate GUIs to try, in order of preference.
// / The default is appended so a broken or version incompatible GUI has somewhere to fall
// / back to. A user cannot choose their way out of a broken GUI, so the fallback is silent
// / to them & noisy in the log.
$candidateGuis = array($GuiToUse);
if ($GuiToUse !== $defaultGui) array_push($candidateGuis, $defaultGui);
foreach ($candidateGuis as $candidateGui) {
// / Set the variables to a URL safe relative path to required UI files.
$GuiToUse = $candidateGui;
$GuiDir = 'UI/'.$GuiToUse.'/';
$styleCoreFile = $GuiDir.'styleCore.php';
$GuiHeaderFile = $GuiDir.'header.php';
$GuiFooterFile = $GuiDir.'footer.php';
$GuiUI1File = $GuiDir.'convertGui1.php';
$GuiUI2File = $GuiDir.'convertGui2.php';
// / The page the Engine names, drawn in place of the two above when the Engine answers a request with a page of its own.
$GuiEngineFile = $GuiDir.'engineGui.php';
// / The bar at the top of both pages, from v4.2.1. Both pages draw it, so it is drawn once.
$GuiTaskbarFile = $GuiDir.'taskbar.php';
$guiVersionFile = $GuiDir.'uiVersionInfo.php';
$GuiResourcesDir = $GuiDir.'Resources/';
$GuiImageDir = $GuiResourcesDir.'Image/';
$GuiCSSDir = $GuiResourcesDir.'CSS/';
$GuiJSDir = $GuiResourcesDir.'JS/';
$guiFiles = array($GuiHeaderFile, $GuiFooterFile, $GuiUI1File, $GuiUI2File, $GuiEngineFile, $GuiTaskbarFile, $styleCoreFile, $guiVersionFile);
// / The resources folder is part of a GUI, not an optional extra.
// / It began as an optional convenience & the documentation still called it optional,
// / but the core had quietly come to depend on it. header.php builds five asset paths
// / out of these directories on every render & never asks whether they are there, so a
// / GUI without them did not fail verification. It rendered, with no stylesheet, no
// / script library & a broken favicon, & the first sign of trouble was an interface
// / that did nothing when clicked.
// / A GUI that cannot be styled or scripted is not a working GUI. Checking here means
// / such a GUI is refused while there is still a Default to fall back to, & the log
// / says which folder was missing instead of leaving an administrator to infer it from
// / a blank looking page.
$guiDirs = array($GuiResourcesDir, $GuiImageDir, $GuiCSSDir, $GuiJSDir);
$GuiFiles = array();
$guiDirsExist = TRUE;
// / Verify that the required GUI folder & every required file exists.
if (is_dir($GuiDir)) {
foreach ($guiDirs as $reqDir) if (!is_dir($reqDir)) {
$guiDirsExist = FALSE;
warningEntry('GUI '.$GuiToUse.' is missing its '.$reqDir.' folder.'); }
foreach ($guiFiles as $reqFile) if (file_exists($reqFile)) array_push($GuiFiles, $reqFile);
// / uiVersionInfo.php only assigns variables, so a failed GUI can still be replaced here.
// / Nothing has printed yet, unlike the language pack case in buildGUI().
if (count($guiFiles) === count($GuiFiles) && $guiDirsExist) {
require($guiVersionFile);
if ($GuiVersion === $RequiredGuiVersion) $GuiIsSet = TRUE;
else warningEntry('GUI '.$GuiToUse.' reports version '.$GuiVersion.' but this core requires '.$RequiredGuiVersion.'.'); }
else if (count($guiFiles) !== count($GuiFiles)) warningEntry('GUI '.$GuiToUse.' is missing one or more required files.'); }
else warningEntry('GUI '.$GuiToUse.' does not exist at '.$GuiDir.'.');
// / A usable GUI has been found, so stop looking.
if ($GuiIsSet) break; }
// / Set the $GUI variable to whatever the current GUI is so the next page will use the same one.
$_GET['gui'] = $GuiToUse;
// / Load the style data once a compatible GUI has been settled on.
if ($GuiIsSet) {
// / Every button code is initialized before the style file is read.
// / The file assigns these lowercase names into this scope, which nothing here shows, so initializing them says where they come from.
// / It also gives each one a fallback configuration cannot overwrite.
$greenButtonCode = $blueButtonCode = $redButtonCode = $orangeButtonCode = '';
$purpleButtonCode = $darkButtonCode = $defaultButtonCode = '';
require_once($styleCoreFile);
$GreenButtonCode = $greenButtonCode;
$BlueButtonCode = $blueButtonCode;
$RedButtonCode = $redButtonCode;
$OrangeButtonCode = $orangeButtonCode;
$PurpleButtonCode = $purpleButtonCode;
$DarkButtonCode = $darkButtonCode;
$DefaultButtonCode = $defaultButtonCode;
// / A style file that supplied nothing usable is worth saying so, because every button
// / on the page will render without styling & the page will otherwise look merely odd.
if ($DefaultButtonCode === '') warningEntry('The style file for GUI '.$GuiToUse.' supplied no default button code. Buttons will render unstyled.'); }
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $defaultGuis, $defaultGui, $candidateGuis, $candidateGui, $reqFile, $reqDir, $guiFiles, $guiDirs, $guiDirsExist, $styleCoreFile, $guiVersionFile, $greenButtonCode, $blueButtonCode, $redButtonCode, $orangeButtonCode, $purpleButtonCode, $darkButtonCode, $defaultButtonCode);
return array($GuiIsSet, $GuiToUse, $GuiDir, $GuiFiles); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to set the language to use for the session.
function verifyLanguage() {
// / Set variables.
global $Language, $DefaultLanguage, $SupportedLanguages, $AllowUserSelectableLanguage, $LanguageFiles, $GuiDir, $LanguageDir, $LanguageStringsFile, $LanguageFlagFile, $LanguageBaselineFile, $EnableMemoryProtection;
$reqFile = $LanguageIsSet = FALSE;
$LanguageToUse = $defaultLanguage = 'en';
$LanguageFiles = $languageFiles = array();
$defaultLanguages = array(
'en' => 'English', 'fr' => 'Français', 'es' => 'Español',
'zh' => '中文', 'hi' => 'हिन्दी', 'ar' => 'العربية',
'ru' => 'Русский', 'uk' => 'Українська', 'bn' => 'বাংলা',
'de' => 'Deutsch', 'ko' => '한국어', 'it' => 'Italiano',
'pt' => 'Português', 'vi' => 'Tiếng Việt', 'tr' => 'Türkçe',
'ja' => '日本語', 'id' => 'Bahasa Indonesia',
'pl' => 'Polski', 'nl' => 'Nederlands', 'sw' => 'Kiswahili',
'my' => 'မြန်မာ', 'ur' => 'اردو', 'fa' => 'فارسی',
'he' => 'עברית', 'aii' => 'ܣܘܪܝܝܐ', 'arc' => 'ܐܪܡܝܐ');
// / Make sure $SupportedLanguages is valid.
if (!isset($SupportedLanguages) or !is_array($SupportedLanguages)) $SupportedLanguages = $defaultLanguages;
// / Make sure the Default Language is valid.
// / The language code is a KEY in this array & the endonym is the value, so membership
// / is tested with array_key_exists() rather than with in_array().
if (isset($DefaultLanguage)) if (array_key_exists($DefaultLanguage, $SupportedLanguages)) $LanguageToUse = $DefaultLanguage;
// / If allowed and if specified, detect the user's specified language and set that as the language to use.
if (isset($AllowUserSelectableLanguage)) {
if ($AllowUserSelectableLanguage) if (isset($Language)) if (array_key_exists($Language, $SupportedLanguages)) {
$LanguageToUse = $Language; }
if (!$AllowUserSelectableLanguage) {
$LanguageToUse = $defaultLanguage;
if (array_key_exists($DefaultLanguage, $SupportedLanguages)) $LanguageToUse = $DefaultLanguage; } }
// / A language listed in config.php is not a promise that every GUI carries it.
// / config.php lists the languages the installation offers, & a language pack lives inside a GUI, whose author ships the packs they care about.
// / So this falls back the way verifyGui() does, through the selection, then the configured default, then English, & the first one present wins.
// / A user cannot choose their way out of a missing pack, so the fallback is silent to them & noisy here.
$candidateLanguages = array($LanguageToUse);
if (isset($DefaultLanguage) && !in_array($DefaultLanguage, $candidateLanguages)) array_push($candidateLanguages, $DefaultLanguage);
if (!in_array($defaultLanguage, $candidateLanguages)) array_push($candidateLanguages, $defaultLanguage);
foreach ($candidateLanguages as $candidateLanguage) {
$LanguageFiles = array();
$LanguageDir = $GuiDir.'Languages/'.$candidateLanguage.'/';
$LanguageStringsFile = $LanguageDir.'languageStrings.php';
$LanguageFlagFile = $LanguageDir.'flag.png';
$languageFiles = array($LanguageStringsFile, $LanguageFlagFile);
// / Verify that the language folder & every required file within it exists.
if (is_dir($LanguageDir)) {
foreach ($languageFiles as $reqFile) if (file_exists($reqFile)) array_push($LanguageFiles, $reqFile);
if (count($languageFiles) === count($LanguageFiles)) $LanguageIsSet = TRUE;
else warningEntry('Language pack '.$candidateLanguage.' at '.$LanguageDir.' is missing one or more required files.'); }
else warningEntry('The GUI at '.$GuiDir.' does not carry a '.$candidateLanguage.' language pack.');
// / A usable pack has been found, so stop looking.
if ($LanguageIsSet) {
$LanguageToUse = $candidateLanguage;
break; } }
// / The baseline is what makes a partial pack usable.
// / buildGUI loads this FIRST & then loads the selected pack over the top, so a pack that
// / is missing a string inherits it instead of leaving an undefined variable for an
// / interface to print. It is only worth loading when it is a different file to the one
// / that was selected.
$LanguageBaselineFile = '';
foreach ($candidateLanguages as $candidateLanguage) {
$baselineFile = $GuiDir.'Languages/'.$candidateLanguage.'/languageStrings.php';
if ($candidateLanguage !== $LanguageToUse && file_exists($baselineFile)) {
$LanguageBaselineFile = $baselineFile;
break; } }
// / Set the $Language variable to whatever the current language is so the next page will use the same one.
$_GET['language'] = $LanguageToUse;
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $defaultLanguages, $reqFile, $languageFiles, $defaultLanguage, $candidateLanguages, $candidateLanguage, $baselineFile);
return array($LanguageIsSet, $LanguageToUse, $LanguageDir, $LanguageFiles); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to set this application's own global variables for the session.
// / Accepts nothing. Returns a validity boolean, which is TRUE once every one has been set.
// / The Engine's are set before this runs, by the Engine's startEngine(), & the data locations by the kernel. They were set here until v4.2.4.
// / What is left is HRConvert2's own. What its pipelines retry with, what its interfaces draw with, the files it refuses to touch, where its
// / own resources are, the report a user's scan writes & the formats each enabled subsystem reads & writes.
// / $Allowed is every extension any enabled subsystem reads or writes. An upload is judged against it, the Engine reads it as AllowedExtensions
// / through the contract's map to judge a fetched file the same way, & a language pack reads $SupportedFormatCount.
// / Every list is read from a setting the kernel confirmed config.php holds, so there is nothing here that can fail, & the check is reaching the end.
// / A format the core refuses is taken out of the list that names it, with a warning naming the setting, from v4.2.7.
// / The stream output list is the audio & video output lists, so it is made from them once each has been through that.
function verifyGlobals() {
// / Set variables.
global $InstLoc, $DirSep, $RetryCount, $StopCounter, $SleepTimer, $ConvertGuiCounter1, $File, $FCPlural, $FCPlural1, $FCPlural2, $FCPlural3, $GreenButtonCode, $BlueButtonCode, $RedButtonCode, $PurpleButtonCode, $OrangeButtonCode, $DarkButtonCode, $DefaultButtonCode, $HeaderDisplayed, $UIDisplayed, $FooterDisplayed, $LanguageStringsLoaded, $GUIDisplayed, $GUIDirection, $GUIAlignment, $Alert, $Alert1, $Alert2, $Alert3, $DefaultApps, $DangerousFiles, $ResourcesDir, $BootloadersDir, $ConsolidatedLogFileName, $SupportedConversionTypes, $Allowed, $SupportedFormatCount, $ArchiveArray, $DearchiveArray, $DocumentInputArray, $DocumentOutputArray, $SpreadsheetInputArray, $SpreadsheetOutputArray, $PresentationInputArray, $PresentationOutputArray, $XPSInputArray, $XPSOutputArray, $MediaInputArray, $MediaOutputArray, $VideoInputArray, $VideoOutputArray, $StreamArray, $SVGInputArray, $SVGOutputArray, $ModelArray, $SubtitleInputArray, $SubtitleOutputArray, $PDFWorkArr, $StreamOutputArray, $SCADInputArray, $SCADOutputArray, $EbookInputArray, $EbookOutputArray, $BootableIsoArray, $ImageInputArray, $ImageOutputArray, $DrawingInputArray, $DrawingOutputArray, $ModelInputArray, $ModelOutputArray,
$DataInputArray, $DataOutputArray, $LaTeXInputArray, $LaTeXOutputArray, $TraceInputArray, $TraceOutputArray, $EmailInputArray, $EmailOutputArray, $MarkupInputArray, $MarkupOutputArray, $GraphInputArray, $GraphOutputArray,
$UserArchiveArray, $UserDearchiveArray, $UserDocumentInputArray, $UserDocumentOutputArray, $UserSpreadsheetInputArray, $UserSpreadsheetOutputArray, $UserXPSInputArray, $UserXPSOutputArray, $UserPresentationInputArray, $UserPresentationOutputArray, $UserImageInputArray, $UserImageOutputArray, $UserMediaInputArray, $UserMediaOutputArray, $UserVideoInputArray, $UserVideoOutputArray, $UserStreamArray, $UserDrawingInputArray, $UserDrawingOutputArray, $UserSVGInputArray, $UserSVGOutputArray, $UserModelArray, $UserModelInputArray, $UserModelOutputArray, $UserSCADInputArray, $UserSCADOutputArray, $UserSubtitleInputArray, $UserSubtitleOutputArray, $UserPDFWorkArr, $UserEbookInputArray, $UserEbookOutputArray, $UserBootableIsoArray, $AllowBootableIsoImage,
$UserDataInputArray, $UserDataOutputArray, $UserLaTeXInputArray, $UserLaTeXOutputArray, $UserTraceInputArray, $UserTraceOutputArray, $UserEmailInputArray, $UserEmailOutputArray, $UserMarkupInputArray, $UserMarkupOutputArray, $UserGraphInputArray, $UserGraphOutputArray, $EnableMemoryProtection;
$GlobalsAreVerified = FALSE;
// / Pipeline related variables. A pipeline that retries reads how many attempts remain, & how long to wait between them.
$SleepTimer = 0;
$StopCounter = $RetryCount;
// / UI Related variables.
$ConvertGuiCounter1 = 0;
$File = $FCPlural = $FCPlural1 = $FCPlural2 = $FCPlural3 = $GreenButtonCode = $BlueButtonCode = $RedButtonCode = $PurpleButtonCode = $OrangeButtonCode = $DarkButtonCode = $DefaultButtonCode = '';
$HeaderDisplayed = $UIDisplayed = $FooterDisplayed = $LanguageStringsLoaded = $GUIDisplayed = FALSE;
$GUIDirection = 'ltr';
$GUIAlignment = 'left';
$Alert = 'Cannot convert this file! Try changing the name.';
$Alert1 = 'Cannot perform a virus scan on this file!';
$Alert2 = 'File Link Copied to Clipboard!';
$Alert3 = 'Operation Failed!';
// / Security related variables.
$DefaultApps = array('.', '..');
// / A calibre recipe is a program calibre runs, & an OPF names by path the files it packs, so neither is handled, from v4.2.7.
$DangerousFiles = array(NULL, '.js', '.php', '.html', '.css', '.phar', '.recipe', '.opf', '..', 'index.php', 'index.html', '--');
// / Directory related variables.
$ResourcesDir = $InstLoc.$DirSep.'Resources';
$BootloadersDir = $ResourcesDir.$DirSep.'Bootloaders';
// / A/V related variables.
// / The report a user's scan writes is named here, because a page asks for it by name to download it.
// / The Scan pipeline writes it, & keeps each scanner's own log beside a user's files, from v4.1.6.
$ConsolidatedLogFileName = 'User_Consolidated_Virus_Scan_Report.txt';
// / Format related variables.
$ImageInputArray = $ImageOutputArray = $SCADInputArray = $SCADOutputArray = array();
$DrawingInputArray = $DrawingOutputArray = array();
$ModelInputArray = $ModelOutputArray = array();
$DataInputArray = $DataOutputArray = $LaTeXInputArray = $LaTeXOutputArray = $TraceInputArray = $TraceOutputArray = $EmailInputArray = $EmailOutputArray = $MarkupInputArray = $MarkupOutputArray = $GraphInputArray = $GraphOutputArray = array();
$ArchiveArray = $DearchiveArray = $DocumentInputArray = $DocumentOutputArray = $SpreadsheetInputArray = $SpreadsheetOutputArray = $PresentationInputArray = $PresentationOutputArray = $XPSInputArray = $XPSOutputArray = $MediaInputArray = $MediaOutputArray = $VideoInputArray = $VideoOutputArray = $StreamArray = $ModelArray = $SubtitleInputArray = $SubtitleOutputArray = $PDFWorkArr = $StreamOutputArray = $SCADOutputArray = $SVGInputArray = $SVGOutputArray = $EbookInputArray = $EbookOutputArray = $BootableIsoArray = $allArrays = array();
// / The Dearchive list is what an archive may be read from, & the Archive list what one may be written as, so they are the Archive
// / family's input & output lists, from v4.2.8. Until then the Archive list was both, & a file the Dearchive list offered a menu for failed.
if (in_array('Archive', $SupportedConversionTypes)) $ArchiveArray = withoutRefusedFormats($UserArchiveArray, 'Supported Archive Formats');
if (in_array('Archive', $SupportedConversionTypes)) $DearchiveArray = withoutRefusedFormats($UserDearchiveArray, 'Supported Dearchive Formats');
if (in_array('Archive', $SupportedConversionTypes) && $AllowBootableIsoImage) {
$BootableIsoArray = withoutRefusedFormats($UserBootableIsoArray, 'Supported Bootable ISO Output Formats');
$ArchiveArray = array_map('strtolower', array_merge($ArchiveArray, $BootableIsoArray)); }
// / Documents & spreadsheets each keep an input list & an output list, from v4.2.8, as presentations & XPS do, so a format can be read & not written.
if (in_array('Document', $SupportedConversionTypes)) {
$DocumentInputArray = withoutRefusedFormats($UserDocumentInputArray, 'Supported Document Input Formats');
$DocumentOutputArray = withoutRefusedFormats($UserDocumentOutputArray, 'Supported Document Output Formats');
$SpreadsheetInputArray = withoutRefusedFormats($UserSpreadsheetInputArray, 'Supported Spreadsheet Input Formats');
$SpreadsheetOutputArray = withoutRefusedFormats($UserSpreadsheetOutputArray, 'Supported Spreadsheet Output Formats'); }
if (in_array('Document', $SupportedConversionTypes)) $XPSInputArray = withoutRefusedFormats($UserXPSInputArray, 'Supported XPS Input Formats');
if (in_array('Document', $SupportedConversionTypes)) $XPSOutputArray = withoutRefusedFormats($UserXPSOutputArray, 'Supported XPS Output Formats');
if (in_array('Document', $SupportedConversionTypes)) $PresentationInputArray = withoutRefusedFormats($UserPresentationInputArray, 'Supported Presentation Input Formats');
if (in_array('Document', $SupportedConversionTypes)) $PresentationOutputArray = withoutRefusedFormats($UserPresentationOutputArray, 'Supported Presentation Output Formats');
if (in_array('Image', $SupportedConversionTypes)) {
$ImageInputArray = withoutRefusedFormats($UserImageInputArray, 'Supported Image Input Formats');
$ImageOutputArray = withoutRefusedFormats($UserImageOutputArray, 'Supported Image Output Formats'); }
if (in_array('Audio', $SupportedConversionTypes)) $MediaInputArray = withoutRefusedFormats($UserMediaInputArray, 'Supported Audio Input Formats');
if (in_array('Audio', $SupportedConversionTypes)) $MediaOutputArray = withoutRefusedFormats($UserMediaOutputArray, 'Supported Audio Output Formats');
if (in_array('Video', $SupportedConversionTypes)) $VideoInputArray = withoutRefusedFormats($UserVideoInputArray, 'Supported Video Input Formats');
if (in_array('Video', $SupportedConversionTypes)) $VideoOutputArray = withoutRefusedFormats($UserVideoOutputArray, 'Supported Video Output Formats');
// / Stream is already split & is not given an input & output pair like the others.
// / $StreamArray is what may be fetched & $StreamOutputArray is derived from the audio
// / and video lists, because a stream is written as a media file rather than as another
// / stream. A configured output list here would be a third place to keep in step with
// / those two & would be wrong the first time either changed.
if (in_array('Stream', $SupportedConversionTypes) && in_array('Audio', $SupportedConversionTypes) && in_array('Video', $SupportedConversionTypes)) $StreamArray = withoutRefusedFormats($UserStreamArray, 'Supported Stream Formats');
if (in_array('Stream', $SupportedConversionTypes) && in_array('Audio', $SupportedConversionTypes) && in_array('Video', $SupportedConversionTypes)) $StreamOutputArray = array_merge($MediaOutputArray, $VideoOutputArray);
if (in_array('Drawing', $SupportedConversionTypes)) {
$DrawingInputArray = withoutRefusedFormats($UserDrawingInputArray, 'Supported Drawing Input Formats');
$DrawingOutputArray = withoutRefusedFormats($UserDrawingOutputArray, 'Supported Drawing Output Formats'); }
if (in_array('SVG', $SupportedConversionTypes)) $SVGInputArray = withoutRefusedFormats($UserSVGInputArray, 'Supported SVG Input Formats');
if (in_array('SVG', $SupportedConversionTypes)) $SVGOutputArray = withoutRefusedFormats($UserSVGOutputArray, 'Supported SVG Output Formats');
// / The Model lists are read directly, because both are in the required configuration list & a configuration missing either one never reaches this line.
// / The required list is what the startup check reads, so a setting absent from it is never verified & a fallback for it would become permanent.
// / It is also how the core decides a configuration is valid at all.
// / $UserModelArray remains required & still feeds $ModelArray, which other code reads.
if (in_array('Model', $SupportedConversionTypes)) {
$ModelArray = withoutRefusedFormats($UserModelArray, 'Supported Model Formats');
$ModelInputArray = withoutRefusedFormats($UserModelInputArray, 'Supported Model Input Formats');
$ModelOutputArray = withoutRefusedFormats($UserModelOutputArray, 'Supported Model Output Formats'); }
if (in_array('Scad', $SupportedConversionTypes)) {
$SCADInputArray = withoutRefusedFormats($UserSCADInputArray, 'Supported SCAD Input Formats');
$SCADOutputArray = withoutRefusedFormats($UserSCADOutputArray, 'Supported SCAD Output Formats'); }
// / The SCAD output list is read rather than derived, so the upload list & the output list are each declared.
if (in_array('Subtitle', $SupportedConversionTypes)) $SubtitleInputArray = withoutRefusedFormats($UserSubtitleInputArray, 'Supported Subtitle Input Formats');
if (in_array('Subtitle', $SupportedConversionTypes)) $SubtitleOutputArray = withoutRefusedFormats($UserSubtitleOutputArray, 'Supported Subtitle Output Formats');
if (in_array('OCR', $SupportedConversionTypes) && in_array('Document', $SupportedConversionTypes)) $PDFWorkArr = withoutRefusedFormats($UserPDFWorkArr, 'Supported OCR Formats');
if (in_array('Ebook', $SupportedConversionTypes)) $EbookInputArray = withoutRefusedFormats($UserEbookInputArray, 'Supported Ebook Input Formats');
if (in_array('Ebook', $SupportedConversionTypes)) $EbookOutputArray = withoutRefusedFormats($UserEbookOutputArray, 'Supported Ebook Output Formats');
// / The five families added in v4.2.5 each keep an input list & an output list, as every family since the Model lists does.
if (in_array('Data', $SupportedConversionTypes)) {
$DataInputArray = withoutRefusedFormats($UserDataInputArray, 'Supported Data Input Formats');
$DataOutputArray = withoutRefusedFormats($UserDataOutputArray, 'Supported Data Output Formats'); }
if (in_array('LaTeX', $SupportedConversionTypes)) {
$LaTeXInputArray = withoutRefusedFormats($UserLaTeXInputArray, 'Supported LaTeX Input Formats');
$LaTeXOutputArray = withoutRefusedFormats($UserLaTeXOutputArray, 'Supported LaTeX Output Formats'); }
if (in_array('Trace', $SupportedConversionTypes)) {
$TraceInputArray = withoutRefusedFormats($UserTraceInputArray, 'Supported Trace Input Formats');
$TraceOutputArray = withoutRefusedFormats($UserTraceOutputArray, 'Supported Trace Output Formats'); }
if (in_array('Email', $SupportedConversionTypes)) {
$EmailInputArray = withoutRefusedFormats($UserEmailInputArray, 'Supported Email Input Formats');
$EmailOutputArray = withoutRefusedFormats($UserEmailOutputArray, 'Supported Email Output Formats'); }
if (in_array('Markup', $SupportedConversionTypes)) {
$MarkupInputArray = withoutRefusedFormats($UserMarkupInputArray, 'Supported Markup Input Formats');
$MarkupOutputArray = withoutRefusedFormats($UserMarkupOutputArray, 'Supported Markup Output Formats'); }
if (in_array('Graph', $SupportedConversionTypes)) {
$GraphInputArray = withoutRefusedFormats($UserGraphInputArray, 'Supported Graph Input Formats');
$GraphOutputArray = withoutRefusedFormats($UserGraphOutputArray, 'Supported Graph Output Formats'); }
$allArrays = array(
$ArchiveArray, $DearchiveArray, $DocumentInputArray, $DocumentOutputArray, $SpreadsheetInputArray, $SpreadsheetOutputArray,
$PresentationInputArray, $PresentationOutputArray,
$MediaInputArray, $MediaOutputArray, $VideoInputArray, $VideoOutputArray,
$StreamArray, $StreamOutputArray, $SVGInputArray,
$SVGOutputArray, $ModelArray, $ModelInputArray, $ModelOutputArray,
$ImageInputArray, $ImageOutputArray, $SCADInputArray, $SCADOutputArray,
$DrawingInputArray, $DrawingOutputArray, $SubtitleInputArray, $SubtitleOutputArray,
$PDFWorkArr, $XPSInputArray, $XPSOutputArray, $BootableIsoArray,
$EbookInputArray, $EbookOutputArray, $DataInputArray, $DataOutputArray, $LaTeXInputArray, $LaTeXOutputArray,
$TraceInputArray, $TraceOutputArray, $EmailInputArray, $EmailOutputArray, $MarkupInputArray, $MarkupOutputArray, $GraphInputArray, $GraphOutputArray);
$Allowed = array_map('strtolower', array_unique(array_merge(...$allArrays)));
$SupportedFormatCount = count($Allowed);
$GlobalsAreVerified = TRUE;
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $allArrays);
return array($GlobalsAreVerified); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to ask ImageMagick where its configuration actually lives.
// / Accepts no arguments.
// / Returns the absolute configuration directory, or an empty string when none is found.
// / A distribution package puts policy.xml in /etc/ImageMagick-7, & a build from source puts it under its prefix, usually /usr/local/etc/ImageMagick-7.
// / ImageMagick reports its own configuration path, so it is asked rather than guessed.
// / Nothing is written there, & it is asked so the policy an earlier release wrote there is found & put back.
function resolveImageMagickConfigDir() {
// / Set variables.
global $Verbose, $EnableMemoryProtection;
static $cachedDirectory = NULL;
$ConfigDirectory = '';
$magickBinary = $outputLine = '';
$commandOutput = $pathMatches = $candidateDirectories = array();
$commandExitCode = 1;
$candidateDirectory = '';
if ($cachedDirectory !== NULL) $ConfigDirectory = $cachedDirectory;
else {
$magickBinary = locateDependency('magick');
if ($magickBinary === '') $magickBinary = locateDependency('convert');
// / -list configure prints CONFIGURE_PATH, which is where this build reads policy.xml.
if ($magickBinary !== '') {
exec(escapeshellarg($magickBinary).' -list configure 2>&1', $commandOutput, $commandExitCode);
if ($commandExitCode === 0) {
foreach ($commandOutput as $outputLine) {
if ($ConfigDirectory === '' && preg_match('/^CONFIGURE_PATH\s+(\S.*?)\s*$/', (string)$outputLine, $pathMatches)) $ConfigDirectory = rtrim(trim($pathMatches[1]), DIRECTORY_SEPARATOR); } } }
// / A build that will not say is looked for in the usual places, newest first.
if ($ConfigDirectory === '') {
$candidateDirectories = array('/usr/local/etc/ImageMagick-7', '/etc/ImageMagick-7', '/usr/local/etc/ImageMagick-6', '/etc/ImageMagick-6');
foreach ($candidateDirectories as $candidateDirectory) {
if ($ConfigDirectory === '' && is_dir($candidateDirectory)) $ConfigDirectory = $candidateDirectory; }
if ($ConfigDirectory !== '') warningEntry('ImageMagick would not report its configuration path, so '.$ConfigDirectory.' was located by search. Confirm it is the directory this build actually reads.'); }
if ($Verbose) logEntry('ImageMagick configuration path: '.($ConfigDirectory === '' ? 'NOT FOUND' : $ConfigDirectory).'.');
$cachedDirectory = $ConfigDirectory; }
// / The static is never purged. The answer is kept for the life of the process, because ImageMagick is asked by
// / running it, & purging a static empties it. It holds a path & nothing secret.
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $magickBinary, $outputLine, $commandOutput, $pathMatches, $candidateDirectories, $commandExitCode, $candidateDirectory);
return $ConfigDirectory; }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to cover the policy.xml the installed ImageMagick reads, inside one sandbox profile.
// / Accepts the sandbox profile a conversion is about to run under.
// / Returns TRUE when that profile now covers the file, & FALSE when ImageMagick named no folder.
// / The profiles name where a package or a build from source keeps the policy. A build with another
// / prefix keeps it somewhere else, so ImageMagick is asked, as it is everywhere else, & the answer
// / joins the profile's Overlays. It is asked as a conversion that needs the answer is about to run,
// / because asking as every request starts would run ImageMagick for requests that convert nothing.
function coverResolvedImageMagickPolicy($sandboxProfile) {
// / Set variables.
global $EngineSandboxProfiles, $DirSep, $EnableMemoryProtection;
$PolicyIsCovered = FALSE;
$configDirectory = $policyPath = '';
$configDirectory = resolveImageMagickConfigDir();
if ($configDirectory !== '' && is_array($EngineSandboxProfiles) && isset($EngineSandboxProfiles[$sandboxProfile]) && is_array($EngineSandboxProfiles[$sandboxProfile])) {
$policyPath = $configDirectory.$DirSep.'policy.xml';
if (!isset($EngineSandboxProfiles[$sandboxProfile]['Overlays']) or !is_array($EngineSandboxProfiles[$sandboxProfile]['Overlays'])) $EngineSandboxProfiles[$sandboxProfile]['Overlays'] = array();
if (!isset($EngineSandboxProfiles[$sandboxProfile]['Overlays'][$policyPath])) $EngineSandboxProfiles[$sandboxProfile]['Overlays'][$policyPath] = 'policy.xml';
$PolicyIsCovered = TRUE; }
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $configDirectory, $policyPath, $sandboxProfile);
return $PolicyIsCovered; }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to check the ImageMagick policy each conversion carries, & to take back the one an
// / earlier release wrote into the host.
// / Accepts a boolean permitting a change.
// / Returns a validity boolean & a status word, in that order.
// / Each pipeline that runs ImageMagick carries its own policy, in a Policy folder beside its converter, & takes it into every conversion's sandbox.
// / Nothing is written into the host.
// / A copy an earlier release wrote over the host's policy.xml is put back from the copy verifyPolicyFile() kept, so the directory is resolved from the binary rather than guessed.
// / A pipeline that is installed & is missing its policy is reported, because its conversions then run under the host's own.
// / A copy of this application's that kept no backup of what it replaced is left in place & called kept, because removing it would leave ImageMagick with no policy at all.
// / Every ImageMagick on the host is looked at, not only the one the conversions run, because a host with a package & a build keeps a policy for each.
// / Where several say different things, the status that most needs saying is the one reported.
// / The answer is kept for the life of the process by the Engine's policyAnswerMemory(), which says when a kept answer is used.
function verifyImageMagickPolicy($mayRepair) {
// / Set variables.
global $Verbose, $EnableMemoryProtection, $DirSep, $InstLoc;
$PolicyIsValid = $answerIsKept = FALSE;
$PolicyStatus = 'unchecked';
$configDirectory = $retireStatus = $pipelineName = $pipelineFolder = $policyPath = $copyStatus = '';
$hostCopyIsRetired = $policyIsCarried = FALSE;
$policyPaths = $foundPaths = array();
$statusRanks = array('none' => 0, 'retired' => 1, 'kept' => 2, 'outdated' => 3, 'refused' => 4);
list ($answerIsKept, $PolicyIsValid, $PolicyStatus) = policyAnswerMemory('ImageMagick', $mayRepair, '', array());
if (!$answerIsKept) {
$configDirectory = resolveImageMagickConfigDir();
$retireStatus = 'none';
if ($configDirectory !== '') $policyPaths[] = $configDirectory.$DirSep.'policy.xml';
$foundPaths = array_merge((array)glob('/etc/ImageMagick-*/policy.xml'), (array)glob('/usr/local/etc/ImageMagick-*/policy.xml'));
foreach ($foundPaths as $policyPath) if (is_string($policyPath) && !in_array($policyPath, $policyPaths, TRUE)) $policyPaths[] = $policyPath;
foreach ($policyPaths as $policyPath) {
list ($hostCopyIsRetired, $copyStatus) = retirePolicyFile('ImageMagick', $policyPath, $mayRepair, FALSE);
if (isset($statusRanks[$copyStatus]) && $statusRanks[$copyStatus] > $statusRanks[$retireStatus]) $retireStatus = $copyStatus; }
// / Every pipeline here that runs ImageMagick carries a policy, & is judged only if it is installed. Trace does, from v4.2.5.
$policyIsCarried = TRUE;
foreach (array('Image', 'OCR', 'Identify', 'Trace') as $pipelineName) {
$pipelineFolder = $InstLoc.$DirSep.'Resources'.$DirSep.'Pipelines'.$DirSep.$pipelineName;
if (is_file($pipelineFolder.$DirSep.'pipeline.php') && !is_file($pipelineFolder.$DirSep.'Policy'.$DirSep.'policy.xml')) $policyIsCarried = FALSE; }
if (!$policyIsCarried) $PolicyStatus = 'not carried';
else if ($retireStatus === 'outdated' or $retireStatus === 'refused') $PolicyStatus = $retireStatus;
else if ($retireStatus === 'retired' or $retireStatus === 'kept') $PolicyStatus = $retireStatus;
else if ($configDirectory === '') $PolicyStatus = 'absent';
else $PolicyStatus = 'carried';
$PolicyIsValid = ($PolicyStatus === 'carried' or $PolicyStatus === 'retired' or $PolicyStatus === 'kept' or $PolicyStatus === 'absent');
if ($Verbose) logEntry('Policy Check: ImageMagick, Status: '.$PolicyStatus.'.');
list ($answerIsKept) = policyAnswerMemory('ImageMagick', $mayRepair, '', array(), array($PolicyIsValid, $PolicyStatus)); }
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $answerIsKept, $configDirectory, $retireStatus, $pipelineName, $pipelineFolder, $policyPath, $copyStatus, $hostCopyIsRetired, $policyIsCarried, $policyPaths, $foundPaths, $statusRanks, $mayRepair);
return array($PolicyIsValid, $PolicyStatus); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to check what confines OpenSCAD on this host, & to take back the override an
// / earlier release added to it.
// / Accepts a boolean permitting a change.
// / Returns a validity boolean & a status word, in that order.
// / Nothing is added to a profile that confines OpenSCAD.
// / A render runs in its sandbox, where the session area is /work, so a grant by host path never reaches one.
// / An override an earlier release added is taken back here, & a profile that confines OpenSCAD is reported, because it is what governs a render.
// / Most distributions do not confine OpenSCAD at all, & then there is nothing to report.
// / The answer is kept for the life of the process by the Engine's policyAnswerMemory(), which says when a kept answer is used.
function verifyOpenScadPolicy($mayRepair) {
// / Set variables.
global $Verbose, $EnableMemoryProtection;
$PolicyIsValid = $answerIsKept = FALSE;
$PolicyStatus = 'unchecked';
$confiningProfile = $overridePath = $retireStatus = $candidateProfile = '';
$candidateProfiles = array('/etc/apparmor.d/usr.bin.openscad', '/etc/apparmor.d/openscad');
$overrideIsRetired = FALSE;
list ($answerIsKept, $PolicyIsValid, $PolicyStatus) = policyAnswerMemory('OpenSCAD AppArmor', $mayRepair, '', array());
if (!$answerIsKept) {
foreach ($candidateProfiles as $candidateProfile) {
if ($confiningProfile === '' && file_exists($candidateProfile)) $confiningProfile = $candidateProfile; }
if ($confiningProfile === '') {
// / No profile confines OpenSCAD, so there is nothing to report & nothing is wrong.
$PolicyIsValid = TRUE;
$PolicyStatus = 'unconfined';
// / Logged once per process rather than per conversion. A host where nothing confines
// / OpenSCAD reports this on every single model, which is noise about a non event.
if ($Verbose) logEntry('Policy Check: OpenSCAD, Status: unconfined, nothing confines it & the sandbox is what isolates it.'); }
else {
$overridePath = '/etc/apparmor.d/local/'.basename($confiningProfile);
list ($overrideIsRetired, $retireStatus) = retirePolicyFile('OpenSCAD AppArmor', $overridePath, $mayRepair, TRUE);
// / The profile is loaded again without what was added to it.
if ($retireStatus === 'retired') reloadApparmorProfile($confiningProfile);
$PolicyStatus = ($retireStatus === 'none' ? 'confined' : $retireStatus);
$PolicyIsValid = ($PolicyStatus === 'confined' or $PolicyStatus === 'retired');
if ($Verbose) logEntry('Policy Check: OpenSCAD, Status: '.$PolicyStatus.', confined by '.$confiningProfile.'.'); }
list ($answerIsKept) = policyAnswerMemory('OpenSCAD AppArmor', $mayRepair, '', array(), array($PolicyIsValid, $PolicyStatus)); }
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $answerIsKept, $confiningProfile, $overridePath, $retireStatus, $candidateProfile, $candidateProfiles, $overrideIsRetired, $mayRepair);
return array($PolicyIsValid, $PolicyStatus); }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to give the Engine's version report what only HRConvert2 knows.
// / Accepts nothing. Returns the rows & sections the report places among its own, keyed by where each goes.
// / The Engine prints -v & names this in $EngineReportProvider, so this application writes no report of its own.
// / Dependencies A row for every dependency HRConvert2 runs, under the manifest line.
// / DependencyNotes Rows after the sandbox line, at the end of the dependencies.
// / SectionsAfterDependencies Titled sections after the dependencies.
// / SwitchedOff Each feature of HRConvert2 that is installed & switched off, & the setting that switches it on.
// / SectionsAfterSwitchedOff Titled sections after the features that are switched off.
// / SectionsAfterResources Titled sections after resource awareness, at the end of the report.
// / A row is a Label, a Text & whether it Failed, & a failed row is counted with the report's own.
// / Every dependency check here is the IDENTICAL check the matching converter performs, through toolPath(), so this
// / answers whether an installation will actually work rather than what is configured.
// / An interface or language pack version is read by PATTERN rather than by loading the
// / file, because loading twenty version files would overwrite the variable each time.
function applicationVersionReport() {
// / Set variables.
global $RequiredGuiVersion, $RequiredLanguageVersion, $InstLoc, $SupportedConversionTypes, $SupportedGuis, $SupportedLanguages, $DirSep, $AllowBootableIsoImage, $AllowUserURLDownload, $AllowUserVirusScan, $VirusScan, $AllowUserShare, $AllowUserIdentify, $EnableMemoryProtection;
$ReportSections = array('Dependencies' => array(), 'DependencyNotes' => array(), 'SectionsAfterDependencies' => array(), 'SwitchedOff' => array(), 'SectionsAfterSwitchedOff' => array(), 'SectionsAfterResources' => array());
$modelsAreValid = $ocrToolsAreValid = $archiveToolsAreValid = $libreOfficeIsValid = $subsystemIsReady = FALSE;
$ffmpegBinary = $inkscapeBinary = $diaBinary = $scadBinary = $imageBinary = $ebookBinary = FALSE;
$assimpBinary = $pythonBinary = $pyMeshLabPath = $pyMeshLabIsValid = $tesseractBinary = $pdftotextBinary = FALSE;
$pyMeshLabStatus = $pyMeshLabOutput = $pyMeshLabShortfall = '';
$sevenZipBinary = $rarBinary = $zipBinary = $tarBinary = $mkisofsBinary = $isoHybridBinary = FALSE;
$fileBinary = $probeBinary = $pdfInfoBinary = $gxpsBinary = FALSE;
$pdfUniteBinary = $pdfSeparateBinary = $mat2Binary = FALSE;
$daselBinary = $yqBinary = $latexBinary = $potraceBinary = $emailBinary = $pandocBinary = $resvgBinary = $graphvizBinary = FALSE;
$dependencyChecks = $dependencyState = $subsystemChecks = $sectionRows = $guiMatches = $langMatches = array();
$dependencyName = $subsystemName = $installedGui = $installedLang = $installedEndonym = $checkDir = $checkFile = $foundVersion = $langLine = '';
$langOk = $langTotal = 0;
// / Run every dependency check so this reports what WORKS, not what is configured.
$ffmpegBinary = toolPath('FFMPEG');
$libreOfficeIsValid = (toolPath('LibreOffice') !== FALSE);
$inkscapeBinary = toolPath('Inkscape');
$diaBinary = toolPath('Dia');
$scadBinary = toolPath('OpenSCAD');
$imageBinary = toolPath('ImageMagick');
$ebookBinary = toolPath('Calibre');
$assimpBinary = toolPath('Assimp');
// / PyMeshLab is a library, so toolPath() verifies it & hands back no path, & its verdict says whether it may be used, from v4.3.7.
// / It is the one the Model pipeline runs, HRConvert2's own build, with the Python 3.14 that loads it, & nothing stands in for it.
$pythonBinary = toolPath('Python 3.14');
if ($pythonBinary !== FALSE && function_exists('verifiedToolVerdict')) {
$pyMeshLabPath = toolPath('PyMeshLab');
list ($pyMeshLabStatus, $pyMeshLabOutput) = verifiedToolVerdict('PyMeshLab'); }
$pyMeshLabIsValid = ($pythonBinary !== FALSE && $pyMeshLabStatus === 'ok');
$modelsAreValid = ($assimpBinary !== FALSE && $pyMeshLabIsValid);
$tesseractBinary = toolPath('Tesseract');
$pdftotextBinary = toolPath('Poppler Utils');
// / XPS & OXPS are converted by GXPS Utils' xpstopdf, which --install-depends installs from v4.4.0.
$gxpsBinary = toolPath('GXPS Utils');
$ocrToolsAreValid = ($tesseractBinary !== FALSE && $pdftotextBinary !== FALSE);
$sevenZipBinary = toolPath('7-Zip');
$rarBinary = toolPath('RAR');
$zipBinary = toolPath('Zip');
$tarBinary = toolPath('Tar');
$mkisofsBinary = toolPath('Genisoimage');
$archiveToolsAreValid = ($sevenZipBinary !== FALSE && $zipBinary !== FALSE && $tarBinary !== FALSE && $mkisofsBinary !== FALSE);
$isoHybridBinary = toolPath('Syslinux Utils');
// / Identify reads a file with each of these where it is installed, & hashes it whether or not they are.
// / ImageMagick & 7-Zip are listed already, for the conversions they serve.
$fileBinary = toolPath('File');
$probeBinary = toolPath('FFprobe');
$pdfInfoBinary = toolPath('PDFInfo');
// / Merge runs PDFUnite, Split runs PDFSeparate, & Strip Metadata runs MAT2.
// / Each operation is offered while its pipeline is installed, so a missing tool is named here before a request fails on it.
$pdfUniteBinary = toolPath('PDFUnite');
$pdfSeparateBinary = toolPath('PDFSeparate');
$mat2Binary = toolPath('MAT2');
// / The five families added in v4.2.5 each run one tool, & Data & SVG each have one that only some conversions need, from v4.2.5.
$daselBinary = toolPath('Dasel');
$yqBinary = toolPath('yq');
$latexBinary = toolPath('XeLaTeX');
$potraceBinary = toolPath('Potrace');
$emailBinary = toolPath('msgconvert');
$pandocBinary = toolPath('Pandoc');
$resvgBinary = toolPath('Resvg');
// / The Graph family added in v4.2.6 runs one tool.
$graphvizBinary = toolPath('Graphviz');
// / Dependencies. An optional one says so, because losing it costs a feature rather than a subsystem.
// / A tool that fails says how it falls short, from v4.4.0, so a tool that is missing & one that is too old no longer read alike.
// / PyMeshLab is asked only where the Python that loads it answers, so where that Python does not, the line says so instead.
$pyMeshLabShortfall = ($pythonBinary === FALSE ? 'Python 3.14 '.toolShortfall('Python 3.14') : ($pyMeshLabStatus === 'absent' ? 'HRConvert2\'s build is not installed' : 'HRConvert2\'s build, '.toolShortfall('PyMeshLab')));
$dependencyChecks = array(
'FFMPEG, media & streams' => array($ffmpegBinary !== FALSE, toolShortfall('FFMPEG'), TRUE),
'LibreOffice, documents' => array($libreOfficeIsValid, toolShortfall('LibreOffice'), TRUE),
'GXPS Utils, XPS' => array($gxpsBinary !== FALSE, toolShortfall('GXPS Utils'), FALSE),
'ImageMagick, images' => array($imageBinary !== FALSE, toolShortfall('ImageMagick'), TRUE),
'Inkscape, SVG' => array($inkscapeBinary !== FALSE, toolShortfall('Inkscape'), TRUE),
'Dia, drawings' => array($diaBinary !== FALSE, toolShortfall('Dia'), TRUE),
'OpenSCAD, scad' => array($scadBinary !== FALSE, toolShortfall('OpenSCAD'), TRUE),
'Assimp, models' => array($assimpBinary !== FALSE, toolShortfall('Assimp'), TRUE),
'PyMeshLab, models' => array($pyMeshLabIsValid, $pyMeshLabShortfall, FALSE),
'Tesseract, OCR' => array($tesseractBinary !== FALSE, toolShortfall('Tesseract'), TRUE),
'Pdftotext, OCR' => array($pdftotextBinary !== FALSE, toolShortfall('Poppler Utils'), TRUE),
'7-Zip, all extraction' => array($sevenZipBinary !== FALSE, toolShortfall('7-Zip'), TRUE),
'Zip, archives' => array($zipBinary !== FALSE, toolShortfall('Zip'), TRUE),
'Tar, archives' => array($tarBinary !== FALSE, toolShortfall('Tar'), TRUE),
'Mkisofs, iso' => array($mkisofsBinary !== FALSE, toolShortfall('Genisoimage'), TRUE),
'Rar, archives' => array($rarBinary !== FALSE, toolShortfall('RAR'), FALSE),
'Isohybrid, iso' => array($isoHybridBinary !== FALSE, toolShortfall('Syslinux Utils'), FALSE),
'Calibre, e-books' => array($ebookBinary !== FALSE, toolShortfall('Calibre'), TRUE),
'File, identification' => array($fileBinary !== FALSE, toolShortfall('File'), FALSE),
'FFprobe, identification' => array($probeBinary !== FALSE, toolShortfall('FFprobe'), FALSE),
'PDFInfo, identification' => array($pdfInfoBinary !== FALSE, toolShortfall('PDFInfo'), FALSE),
'PDFUnite, merging' => array($pdfUniteBinary !== FALSE, toolShortfall('PDFUnite'), FALSE),
'PDFSeparate, splitting' => array($pdfSeparateBinary !== FALSE, toolShortfall('PDFSeparate'), FALSE),
'MAT2, metadata' => array($mat2Binary !== FALSE, toolShortfall('MAT2'), FALSE),
'Dasel, data' => array($daselBinary !== FALSE, toolShortfall('Dasel'), TRUE),
'yq, XML data' => array($yqBinary !== FALSE, toolShortfall('yq'), FALSE),
'XeLaTeX, LaTeX' => array($latexBinary !== FALSE, toolShortfall('XeLaTeX'), TRUE),
'Potrace, tracing' => array($potraceBinary !== FALSE, toolShortfall('Potrace'), TRUE),
'msgconvert, email' => array($emailBinary !== FALSE, toolShortfall('msgconvert'), TRUE),
'Pandoc, markup' => array($pandocBinary !== FALSE, toolShortfall('Pandoc'), TRUE),
'Resvg, SVG to PNG' => array($resvgBinary !== FALSE, toolShortfall('Resvg'), FALSE),
'Graphviz, graphs' => array($graphvizBinary !== FALSE, toolShortfall('Graphviz'), TRUE));
foreach ($dependencyChecks as $dependencyName => $dependencyState) {
if ($dependencyState[0]) $ReportSections['Dependencies'][] = array('Label' => $dependencyName, 'Text' => 'OK'.($dependencyState[2] ? '' : ', optional'), 'Failed' => FALSE);
else $ReportSections['Dependencies'][] = array('Label' => $dependencyName, 'Text' => 'FAILED, '.$dependencyState[1].($dependencyState[2] ? '' : ', optional'), 'Failed' => TRUE); }
// / A subsystem is ready only when every dependency it needs is.
// / Its line is not counted as a failure, from v4.4.0, because the dependency line above it that says FAILED already is, & the
// / closing count is the number of lines that say FAILED.
$subsystemChecks = array(
'3D models' => $modelsAreValid,
'OCR' => $ocrToolsAreValid,
'Archives' => $archiveToolsAreValid);
foreach ($subsystemChecks as $subsystemName => $subsystemIsReady) $sectionRows[] = array('Label' => $subsystemName, 'Text' => ($subsystemIsReady ? 'READY' : 'NOT READY'), 'Failed' => FALSE);
if (!$AllowBootableIsoImage) $sectionRows[] = array('Label' => 'Bootable disk images', 'Text' => 'DISABLED in config.php', 'Failed' => FALSE);
else $sectionRows[] = array('Label' => 'Bootable disk images', 'Text' => ($mkisofsBinary === FALSE ? 'NOT READY' : 'READY'), 'Failed' => FALSE);
$ReportSections['SectionsAfterDependencies']['Subsystem readiness'] = $sectionRows;
// / Features that are installed & switched off, each with the setting that switches it on.
if (!$AllowUserURLDownload) $ReportSections['SwitchedOff'][] = array('Fetch from a URL', 'Allow User URL Download');
if (!$AllowUserVirusScan) $ReportSections['SwitchedOff'][] = array('User virus scanning', 'User Virus Scanning');
if (!$VirusScan) $ReportSections['SwitchedOff'][] = array('Virus scanning', 'Virus Scanning');
if (!$AllowUserShare) $ReportSections['SwitchedOff'][] = array('Share a file', 'User Shareable File Links');
if (!$AllowUserIdentify) $ReportSections['SwitchedOff'][] = array('Identify a file', 'User File Identification');
// / Every installed interface, named, & whether it matches the version the core requires.
$sectionRows = array();
foreach ($SupportedGuis as $installedGui) {
$checkDir = $InstLoc.$DirSep.'UI'.$DirSep.$installedGui;
$checkFile = $checkDir.$DirSep.'uiVersionInfo.php';
$foundVersion = '';
if (!is_dir($checkDir)) $sectionRows[] = array('Label' => $installedGui, 'Text' => 'FAILED, no folder', 'Failed' => TRUE);
else if (!file_exists($checkFile)) $sectionRows[] = array('Label' => $installedGui, 'Text' => 'FAILED, no uiVersionInfo.php', 'Failed' => TRUE);
else {
// / The literal is read & then stripped of its leading v, because the file strips it
// / too. Comparing the raw literal against the stripped requirement never matches.
if (preg_match_all('/\$GuiVersion\s*=\s*[\'"]([^\'"]+)[\'"]/', (string)@file_get_contents($checkFile), $guiMatches)) $foundVersion = ltrim(end($guiMatches[1]), 'vV');
if ($foundVersion === $RequiredGuiVersion) $sectionRows[] = array('Label' => $installedGui, 'Text' => 'OK, '.$foundVersion, 'Failed' => FALSE);
else $sectionRows[] = array('Label' => $installedGui, 'Text' => 'FAILED, reports '.($foundVersion === '' ? 'no version' : $foundVersion), 'Failed' => TRUE); } }
$ReportSections['SectionsAfterSwitchedOff']['Installed interfaces'] = $sectionRows;
// / Language pack coverage, per interface. A pack that fails is named.
$sectionRows = array();
foreach ($SupportedGuis as $installedGui) {
$langOk = $langTotal = 0;
$langLine = '';
foreach ($SupportedLanguages as $installedLang => $installedEndonym) {
$langTotal++;
$checkFile = $InstLoc.$DirSep.'UI'.$DirSep.$installedGui.$DirSep.'Languages'.$DirSep.$installedLang.$DirSep.'languageStrings.php';
$foundVersion = '';
if (file_exists($checkFile)) {
if (preg_match('/\$LanguageVersion\s*=\s*[\'"]([^\'"]+)[\'"]/', (string)@file_get_contents($checkFile), $langMatches)) $foundVersion = ltrim($langMatches[1], 'vV'); }
if ($foundVersion === $RequiredLanguageVersion) $langOk++;
else $langLine .= ' '.$installedLang; }
$sectionRows[] = array('Label' => $installedGui, 'Text' => ($langLine === '' ? '' : 'FAILED, ').$langOk.' of '.$langTotal.' OK'.($langLine === '' ? '' : ', not matching:'.$langLine), 'Failed' => ($langLine !== '')); }
$ReportSections['SectionsAfterSwitchedOff']['Installed language packs'] = $sectionRows;
// / What this installation converts ends the report.
$ReportSections['SectionsAfterResources']['Enabled conversion types'] = array(array('Label' => '', 'Text' => implode(', ', $SupportedConversionTypes), 'Failed' => FALSE));
// / Manually clean up sensitive memory. Helps to keep track of variable assignments.
purgeSensitiveMemory($EnableMemoryProtection, $modelsAreValid, $ocrToolsAreValid, $archiveToolsAreValid, $libreOfficeIsValid, $subsystemIsReady, $ffmpegBinary, $inkscapeBinary, $diaBinary, $scadBinary, $imageBinary, $ebookBinary, $assimpBinary, $pythonBinary, $pyMeshLabPath, $pyMeshLabIsValid, $pyMeshLabStatus, $pyMeshLabOutput, $pyMeshLabShortfall, $gxpsBinary, $tesseractBinary, $pdftotextBinary, $sevenZipBinary, $rarBinary, $zipBinary, $tarBinary, $mkisofsBinary, $isoHybridBinary, $fileBinary, $probeBinary, $pdfInfoBinary, $pdfUniteBinary, $pdfSeparateBinary, $mat2Binary, $daselBinary, $yqBinary, $latexBinary, $potraceBinary, $emailBinary, $pandocBinary, $resvgBinary, $graphvizBinary, $dependencyChecks, $dependencyState, $subsystemChecks, $sectionRows, $guiMatches, $langMatches, $dependencyName, $subsystemName, $installedGui, $installedLang, $installedEndonym, $checkDir, $checkFile, $foundVersion, $langLine, $langOk, $langTotal);
return $ReportSections; }
// / -----------------------------------------------------------------------------------
// / -----------------------------------------------------------------------------------
// / A function to give the help -h prints what only this application knows.
// / Accepts nothing. Returns the description, the arguments, the sections & the address the Engine's showHelpInfo() prints, keyed by those names.
// / The help is the Engine's, from v4.2.4, so it lists the Engine's commands itself. This is a summary & deliberately not a manual.
// / Everything HRConvert2 does is documented at length in the Documentation folder, & this points there rather than attempting to reproduce it.
// / HRConvert2 has no arguments of its own yet, so it lists none.
function applicationHelpInfo() {
// / Set variables.
$HelpInfo = array(
'Description' => 'A self hosted file conversion server.',
'Arguments' => array(),
'Sections' => array('Documentation' => array(
' Documentation/INSTALLATION_INSTRUCTIONS.txt Installing & configuring a server.',
' Documentation/ERROR_DESCRIPTIONS.txt Every numbered error, its cause & its fix.',
' Documentation/CREATING_GUIS.txt Building & installing an interface.',
' Documentation/CREATING_LANGUAGE_PACKS.txt Translating the interface.',
' Documentation/CODING_CONVENTIONS.txt Conventions this codebase follows.',
' Documentation/DOCKER_BUILD_INSTRUCTIONS.txt Building the container image.',
' Documentation/CHANGELOG.txt What changed & when.',
' Documentation/DEVELOPMENT_NOTES.txt Why each subsystem is built the way it is.')),
'Address' => 'https://github.com/zelon88/HRConvert2');