Repository navigation
Expand file tree
/
Copy pathmodern-editor.php
More file actions
2553 lines (2231 loc) · 124 KB
/
Copy pathmodern-editor.php
File metadata and controls
2553 lines (2231 loc) · 124 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
namespace Grav\Plugin;
use Grav\Common\Plugin;
use Grav\Common\Grav;
use RocketTheme\Toolbox\Event\Event;
/*
* Modern Editor Plugin for Grav 2.0
*
* Replaces the default "content" page field (default markdown editor)
* with a visual WYSIWYG editor (TinyMCE), integrated as a Custom Field for
* Admin Next using a Web Component (admin-next/fields/moderneditor.js).
*
* HOW THE "CONTENT" FIELD OVERRIDE WORKS (without modifying the theme):
*
* Grav resolves page blueprints via the standard "@extends" mechanism
* + the blueprints://pages stream, which merges files from multiple
* sources (core, theme, plugins). For each page template defined by the
* active theme (default.html.twig, item.html.twig, etc.), this plugin
* dynamically generates (at cache://blueprints/modern-editor/pages/)
* a small YAML file that extends that template and overrides only the
* "content" field in the Content tab. The generated folder is
* registered in the blueprints://pages stream via onGetPageBlueprints,
* so Grav finds it and merges it as it would with a handwritten file
* in the theme.
*
* This way, the editor appears on ANY theme template, even if new
* templates are added in the future, without requiring the user to write
* or copy anything manually.
*/
class ModernEditorPlugin extends Plugin
{
/** @var string Path (stream) where the override blueprints are generated */
protected $generatedPath = 'cache://modern-editor/blueprints/pages';
/*
* Pinned versions of the two small MIT-licensed markdown helper
* libraries (markdown <-> HTML conversion) used by the editor's
* markdown mode. Both are MIT-licensed (see NOTICE.md), so
* self-hosting them under "local" mode raises no license concern —
* unlike TinyMCE, MIT only requires keeping the copyright/license
* notice in the distributed file, which npm's published builds
* already include. Keep these in sync with the CDN fallback URLs
* hardcoded in admin-next/fields/moderneditor.js.
*/
private const MARKED_VERSION = '12.0.0';
private const TURNDOWN_VERSION = '7.1.3';
/*
* Required so Grav can find ModernEditorApiController (classes/ dir),
* used by the Grav 2.0 / Admin2 REST API integration below.
*/
public function autoload(): \Composer\Autoload\ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', -100],
];
}
public function onPluginsInitialized(): void
{
if (!$this->config->get('plugins.modern-editor.enabled')) {
return;
}
$this->enable([
'onGetPageBlueprints' => ['onGetPageBlueprints', 0],
'onBlueprintCreated' => ['onBlueprintCreated', 0],
'onAssetsInitialized' => ['onAssetsInitialized', 0],
'onPagesInitialized' => ['onPagesInitialized', 0],
'onAdminSave' => ['onAdminSave', 0],
'onPageContentRaw' => ['onPageContentRaw', 0],
// Grav 2.0 / Admin2: real REST endpoints. This is the correct
// replacement for the old ?action=get_status/get_config query
// params, which never reach PHP under Admin2 (it's a decoupled
// SPA served by its own thin wrapper — see onApiRegisterRoutes()).
'onApiRegisterRoutes' => ['onApiRegisterRoutes', 0],
'onSchedulerInitialized' => ['onSchedulerInitialized', 0],
]);
}
/**
* Register scheduled cron job with Grav Scheduler (Grav 1.6+ / 2.0+).
* Runs daily to check updates for TinyMCE and Markdown libraries, and
* automatically downloads and installs them if auto-update is enabled.
*/
public function onSchedulerInitialized(Event $event): void
{
$scheduler = $event['scheduler'] ?? null;
if (!$scheduler) {
return;
}
$job = $scheduler->addFunction([$this, 'runSchedulerJob'], 'modern-editor-update-check');
$job->daily();
}
/**
* Callback executed by the Grav Scheduler cron job.
*/
public function runSchedulerJob(): bool
{
$this->performPeriodicUpdateCheck(true, true);
return true;
}
/*
* Registers /modern-editor/status, /modern-editor/config,
* /modern-editor/download, /modern-editor/check-updates and
* /modern-editor/remove on the Grav API plugin (Grav 2.0+ / Admin2),
* which is the only supported way to trigger these actions — the
* classic ?action=... query-string handlers that used to also serve
* these requests have been removed (see NOTICE below / CHANGELOG).
*/
public function onApiRegisterRoutes(Event $event): void
{
$routes = $event['routes'];
$controller = \Grav\Plugin\ModernEditor\ModernEditorApiController::class;
$routes->get('/modern-editor/status', [$controller, 'status']);
$routes->get('/modern-editor/config', [$controller, 'config']);
$routes->post('/modern-editor/download', [$controller, 'download']);
$routes->post('/modern-editor/check-updates', [$controller, 'checkUpdates']);
$routes->post('/modern-editor/remove', [$controller, 'remove']);
}
/*
* Handle custom backend action triggers when pages and user session are fully initialized.
*/
public function onPagesInitialized(Event $event): void
{
if (!$this->isAdminContext()) {
return;
}
$action = $_GET['action'] ?? null;
if (!$action || !is_string($action)) {
return;
}
$isAjax = isset($_GET['ajax']) || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
$lang = $this->getUiLanguage();
if ($action === 'remove_tinymce_local') {
$result = $this->removeTinyMceLocalAction();
if ($isAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
exit;
}
if ($this->grav['admin'] ?? null) {
$this->grav['admin']->setMessage($result['message'], 'info');
}
$this->grav->redirect($this->getAdminBaseUrl() . '/plugins/modern-editor');
} elseif ($action === 'download_tinymce') {
$library = $_GET['library'] ?? 'tinymce';
$version = $_GET['version'] ?? null;
$result = $this->downloadLibraryAction((string)$library, $version ? (string)$version : null);
if ($isAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
exit;
}
if ($this->grav['admin'] ?? null) {
$this->grav['admin']->setMessage($result['message'], $result['status'] === 'success' ? 'info' : 'error');
}
$this->grav->redirect($this->getAdminBaseUrl() . '/plugins/modern-editor');
} elseif ($action === 'check_updates') {
$result = $this->checkUpdatesAction();
if ($isAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
exit;
}
if ($this->grav['admin'] ?? null) {
$this->grav['admin']->setMessage($result['message'], $result['status'] === 'success' ? 'info' : 'error');
}
$this->grav->redirect($this->getAdminBaseUrl() . '/plugins/modern-editor');
} elseif ($action === 'get_status') {
if ($isAjax) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->getStatusData());
exit;
}
}
}
/*
* Generates (if necessary) the override blueprints for each template
* of the active theme, then registers the generated folder as an
* additional page blueprint source.
*/
public function onGetPageBlueprints(Event $event): void
{
$types = $event['types'] ?? $event->types ?? null;
if (!$types) {
return;
}
$this->generateOverrideBlueprints();
// Register the generated folder first (per-template override),
// then the plugin's static folder (any manual extensions
// added by advanced users, see blueprints/pages/).
$types->scanBlueprints($this->generatedPath);
$types->scanBlueprints('plugin://' . $this->name . '/blueprints');
}
/*
* Scans page templates (.html.twig) available in the active theme
* and core, and generates an override file for each, saving it in
* cache. They are regenerated only if missing or if the plugin's
* configuration has changed (via a version/hash control file).
*/
private function generateOverrideBlueprints(): void
{
$grav = Grav::instance();
/** @var \Grav\Common\Filesystem\Locator $locator */
$locator = $grav['locator'];
$targetDir = $locator->findResource($this->generatedPath, true, true);
if (!is_dir($targetDir)) {
@mkdir($targetDir, 0775, true);
}
$markdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$markdownEnabled = false;
}
// NOTE: the installed local TinyMCE version must be part of this
// hash. buildOverrideYaml() bakes the editor_url (which now
// includes a "?v=<version>" cache-buster, see getEditorScriptUrl())
// directly into the cached YAML file. Without the version here,
// updating TinyMCE (e.g. 7.4.0 -> 8.0.0) would not trigger a
// regeneration, so pages would keep serving the stale cached
// editor_url pointing at the previous version indefinitely.
$cfgHash = md5(json_encode([
$this->config->get('plugins.modern-editor.height'),
$this->config->get('plugins.modern-editor.menubar'),
$this->config->get('plugins.modern-editor.plugins'),
$this->config->get('plugins.modern-editor.toolbar'),
$this->config->get('plugins.modern-editor.editor_source'),
$markdownEnabled,
$this->getInstalledTinyMCEVersion(),
]));
$hashFile = $targetDir . '/.config-hash';
$needsRegen = !file_exists($hashFile) || trim((string) @file_get_contents($hashFile)) !== $cfgHash;
$templates = $this->discoverPageTemplates($locator);
foreach ($templates as $templateName) {
$targetFile = $targetDir . '/' . $templateName . '.yaml';
if (!$needsRegen && file_exists($targetFile)) {
continue;
}
file_put_contents($targetFile, $this->buildOverrideYaml($templateName));
}
if ($needsRegen) {
@file_put_contents($hashFile, $cfgHash);
}
}
/*
* Finds available page template names (.html.twig) by scanning
* the active theme and Grav core. Modular/partials/error are excluded
* because they do not represent "normal" editable pages.
*
* @return string[] List of template names, e.g. ['default', 'item', 'blog']
*/
private function discoverPageTemplates($locator): array
{
$names = [];
$dirs = [];
// Active theme.
$themeTemplates = $locator->findResource('theme://templates', true, true);
if ($themeTemplates && is_dir($themeTemplates)) {
$dirs[] = $themeTemplates;
}
// Page templates added by other plugins.
foreach ((array) $locator->findResources('theme://templates') as $dir) {
if (is_dir($dir)) {
$dirs[] = $dir;
}
}
$exclude = ['error', 'modular', 'partials', 'forms'];
foreach (array_unique($dirs) as $dir) {
$files = @glob($dir . '/*.html.twig') ?: [];
foreach ($files as $file) {
$base = basename($file, '.html.twig');
if (in_array($base, $exclude, true)) {
continue;
}
// Excludes modular templates (convention: inside a
// "modular/" subdirectory), which are handled separately.
if (str_contains($file, '/modular/')) {
continue;
}
$names[$base] = true;
}
}
// Always guarantee at least "default", even if the theme doesn't
// explicitly expose it as a physical file.
$names['default'] = true;
return array_keys($names);
}
/*
* Builds the YAML content of a single override file.
*/
private function buildOverrideYaml(string $templateName): string
{
$height = (int) $this->config->get('plugins.modern-editor.height', 500);
$menubar = $this->config->get('plugins.modern-editor.menubar', false) ? 'true' : 'false';
$plugins = $this->yamlString((string) $this->config->get(
'plugins.modern-editor.plugins',
'lists link image table code fullscreen searchreplace media anchor'
));
$toolbar = $this->yamlString((string) $this->config->get(
'plugins.modern-editor.toolbar',
'undo redo | blocks | bold italic underline forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | link anchor image media table | code fullscreen'
));
$editorUrl = $this->getEditorScriptUrl();
$editorUrlYaml = $this->yamlString($editorUrl);
$markdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$markdownEnabled = false;
}
if ($templateName === 'html' || str_ends_with($templateName, '.html')) {
$markdownEnabled = false;
}
$markdownEnabledYaml = $markdownEnabled ? 'true' : 'false';
return <<<YAML
# Automatically generated by Modern Editor — do not modify by hand,
# it will be overwritten. To customize, change the plugin's settings
# in Admin Next, or add a manual override in
# blueprints/pages/{$templateName}.yaml inside this plugin.
'@extends':
type: {$templateName}
context: blueprints://pages
form:
fields:
tabs:
type: tabs
fields:
content:
type: tab
fields:
content:
type: moderneditor
height: {$height}
menubar: {$menubar}
plugins: {$plugins}
toolbar: {$toolbar}
editor_url: {$editorUrlYaml}
markdown_enabled: {$markdownEnabledYaml}
YAML;
}
private function yamlString(string $value): string
{
return "'" . str_replace("'", "''", $value) . "'";
}
/*
* Handles injecting local status HTML in our plugin's settings blueprint.
* Fallback for classic admin (Grav 1.7): directly rewrites the "content" field.
*/
public function onBlueprintCreated(Event $event): void
{
$blueprint = $event['blueprint'] ?? null;
$type = $event['type'] ?? '';
if (!$blueprint) {
return;
}
// If it is our plugin configuration blueprint, inject the status dynamically!
if ($blueprint->get('form/fields/local_status') !== null || $type === 'plugins/modern-editor' || $type === 'plugins/modern-editor/modern-editor' || $type === 'modern-editor') {
$fields = $blueprint->get('form/fields');
if (is_array($fields)) {
$statusHtml = $this->getLocalStatusHtml();
if (isset($fields['local_status'])) {
$fields['local_status']['type'] = 'moderneditorstatus';
$fields['local_status']['content'] = $statusHtml;
}
$blueprint->set('form/fields', $fields);
}
return;
}
if ($type !== '' && !str_starts_with($type, 'pages/') && $type !== 'pages') {
return;
}
$fields = $blueprint->get('form/fields');
if (!is_array($fields)) {
return;
}
// 1. If 'content' field exists and is not 'moderneditor', convert it
if (isset($fields['content']) && is_array($fields['content']) && ($fields['content']['type'] ?? null) !== 'moderneditor') {
$markdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$markdownEnabled = false;
}
if (isset($fields['content']['markdown']) && ($fields['content']['markdown'] === false || $fields['content']['markdown'] === 'false')) {
$markdownEnabled = false;
}
if (isset($fields['content']['markdown_enabled']) && ($fields['content']['markdown_enabled'] === false || $fields['content']['markdown_enabled'] === 'false')) {
$markdownEnabled = false;
}
$procMd = $blueprint->get('form/fields/header.process.markdown/default');
if ($procMd === 0 || $procMd === false || $procMd === '0' || $procMd === 'false') {
$markdownEnabled = false;
}
$fields['content'] = array_merge($fields['content'], [
'type' => 'moderneditor',
'height' => $this->config->get('plugins.modern-editor.height', '500'),
'menubar' => (bool) $this->config->get('plugins.modern-editor.menubar', false),
'plugins' => $this->config->get('plugins.modern-editor.plugins'),
'toolbar' => $this->config->get('plugins.modern-editor.toolbar'),
'editor_url' => $this->getEditorScriptUrl(),
'markdown_enabled' => $markdownEnabled,
]);
}
// 2. Recursively find and update any 'moderneditor' fields with the active config settings
$this->updateModernEditorFields($fields);
$blueprint->set('form/fields', $fields);
}
/*
* Recursively updates all fields of type 'moderneditor' with current config values.
*/
private function updateModernEditorFields(array &$fields): void
{
$globalMarkdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$globalMarkdownEnabled = false;
}
// Detect if the currently edited page disables markdown via header.process.markdown,
// header.markdown, .html extension, or html template.
$pageDisablesMarkdown = false;
try {
$admin = $this->grav['admin'] ?? null;
$page = null;
if ($admin && method_exists($admin, 'page')) {
$page = $admin->page(true);
}
if (!$page && isset($this->grav['page'])) {
$page = $this->grav['page'];
}
if ($page) {
$header = (array) ($page->header() ? (array) $page->header() : []);
$process = (array) ($header['process'] ?? []);
if (isset($process['markdown']) && ($process['markdown'] === false || $process['markdown'] === 0 || $process['markdown'] === '0' || $process['markdown'] === 'false')) {
$pageDisablesMarkdown = true;
}
if (isset($header['markdown']) && ($header['markdown'] === false || $header['markdown'] === 0 || $header['markdown'] === '0' || $header['markdown'] === 'false')) {
$pageDisablesMarkdown = true;
}
$ext = method_exists($page, 'extension') ? $page->extension() : '';
if ($ext === 'html' || $ext === '.html') {
$pageDisablesMarkdown = true;
}
$tpl = method_exists($page, 'template') ? $page->template() : '';
if ($tpl === 'html' || str_ends_with($tpl, '.html')) {
$pageDisablesMarkdown = true;
}
}
} catch (\Throwable $e) {
// defensive fallback
}
foreach ($fields as $key => &$field) {
if (!is_array($field)) {
continue;
}
if (($field['type'] ?? null) === 'moderneditor') {
$fieldMarkdownEnabled = $globalMarkdownEnabled;
if ($pageDisablesMarkdown) {
$fieldMarkdownEnabled = false;
}
if (isset($field['markdown']) && ($field['markdown'] === false || $field['markdown'] === 'false')) {
$fieldMarkdownEnabled = false;
}
if (isset($field['markdown_enabled']) && ($field['markdown_enabled'] === false || $field['markdown_enabled'] === 'false')) {
$fieldMarkdownEnabled = false;
}
$field['editor_url'] = $this->getEditorScriptUrl();
$field['height'] = $this->config->get('plugins.modern-editor.height', '500');
$field['menubar'] = (bool) $this->config->get('plugins.modern-editor.menubar', false);
$field['plugins'] = $this->config->get('plugins.modern-editor.plugins');
$field['toolbar'] = $this->config->get('plugins.modern-editor.toolbar');
$field['markdown_enabled'] = $fieldMarkdownEnabled;
}
if (isset($field['fields']) && is_array($field['fields'])) {
$this->updateModernEditorFields($field['fields']);
}
}
}
/*
* Determines current local status HTML to display in the plugin admin panel.
*/
/*
* Detects the language the ADMIN PANEL is displayed in, which is not
* necessarily the same as the site's content language returned by
* $grav['language']->getActive() (that one reflects the language of
* the page being edited / the site's default, e.g. "en" for an
* English-authored site, even if the admin user has their own admin
* UI set to Italian — exactly the mismatch that made the status card
* render in English despite the rest of the admin being in Italian).
* Priority: the logged-in admin user's own language preference (Grav
* 2.0 stores this on the user account), then the browser's
* Accept-Language header, then finally the site's content language.
*/
/*
* Normalizes a BCP-47 language tag ("it-IT", "en_US", "IT", ...) down
* to its primary subtag ("it"/"en"), lowercased. Every raw language
* source in getUiLanguage() below MUST be passed through this before
* being compared/returned: several of them (Grav's own
* $language->getActive(), a user's account language, the browser-
* computed override sent by the client) can legitimately come back as
* a region-qualified tag rather than a bare "it", and a strict
* '=== "it"' comparison against that silently fails even though the
* language IS Italian — exactly what left the status card in English
* while the rest of the (Grav-translated) admin UI was in Italian.
*/
private function normalizeLangTag(?string $value): ?string
{
if ($value === null || $value === '') {
return null;
}
$primary = strtolower(preg_split('/[-_]/', $value)[0]);
return ($primary === 'it' || $primary === 'en') ? $primary : null;
}
private function getUiLanguage(?string $override = null): string
{
// Explicit, manually-chosen setting (plugins.modern-editor.ui_language,
// see blueprints.yaml) always wins. Auto-detecting Admin Next's own
// UI language proved unreliable across different Grav 2.0 builds —
// this manual setting is the one thing guaranteed to work regardless
// of how (or whether) a given installation exposes it.
$configuredLang = $this->normalizeLangTag((string) $this->config->get('plugins.modern-editor.ui_language', 'auto'));
if ($configuredLang !== null) {
return $configuredLang;
}
// "Auto" mode from here on: best-effort detection, still fully
// Grav-side. The REST API requests (Admin2's own decoupled
// /api/v1/... routes, see ModernEditorApiController) run in a
// lighter request lifecycle that may not register every service
// the same way a normal Twig-rendered admin page load does, so the
// client passes along the value already computed on page load
// (see onAssetsInitialized / window.__MODERN_EDITOR_ADMIN_LANG__,
// and window.__GRAV_I18N.locale on the client side) to guarantee
// both contexts agree.
$normalizedOverride = $this->normalizeLangTag($override);
if ($normalizedOverride !== null) {
return $normalizedOverride;
}
// $grav['language']->getActive() is the SAME value Grav itself
// uses to translate this plugin's own blueprint field labels
// (PLUGIN_MODERN_EDITOR.* keys) and the rest of the admin UI
// ("Dashboard/Configurazione/Pagine..."). Since that's demonstrably
// what's already rendering correctly, it must be the primary,
// authoritative source here too — not a secondary guess as before.
if (isset($this->grav['language'])) {
$active = $this->normalizeLangTag((string) $this->grav['language']->getActive());
if ($active !== null) {
return $active;
}
}
// Fallbacks below only matter for Grav/Admin builds where the
// above isn't available; still purely Grav-side (admin account /
// session), never the browser.
$admin = $this->grav['admin'] ?? null;
if ($admin) {
if (method_exists($admin, 'getLanguage')) {
$adminLang = $this->normalizeLangTag((string) $admin->getLanguage());
if ($adminLang !== null) {
return $adminLang;
}
}
$adminLangProp = $this->normalizeLangTag((string) ($admin->language ?? ''));
if ($adminLangProp !== null) {
return $adminLangProp;
}
}
$user = $this->grav['user'] ?? null;
if ($user) {
$userLang = $this->normalizeLangTag((string) ($user->language ?? ''));
if ($userLang !== null) {
return $userLang;
}
}
$session = $this->grav['session'] ?? null;
if ($session) {
$sessionLang = $this->normalizeLangTag((string) ($session->admin_lang ?? ''));
if ($sessionLang !== null) {
return $sessionLang;
}
}
return 'en';
}
public function downloadTinyMceAction(string $version, ?string $langOverride = null): array
{
if (!preg_match('/^[0-9]+\.[0-9]+\.[0-9]+$/', $version)) {
$version = '7.4.0';
}
$success = $this->downloadAndExtractTinyMCE($version);
if ($success && isset($this->grav['session'])) {
$this->grav['session']->modern_editor_latest_version = null;
}
$lang = $this->getUiLanguage($langOverride);
return [
'status' => $success ? 'success' : 'error',
'message' => $success
? ($lang === 'it' ? "TinyMCE v{$version} è stato scaricato ed estratto con successo localmente!" : "TinyMCE v{$version} has been successfully downloaded and extracted locally!")
: ($lang === 'it' ? "Impossibile scaricare TinyMCE v{$version}. Controlla i dettagli dell'errore." : "Failed to download TinyMCE v{$version}. Check error details."),
'html' => $this->getLocalStatusHtml($langOverride)
];
}
public function checkUpdatesAction(?string $langOverride = null): array
{
$lang = $this->getUiLanguage($langOverride);
$latestVersion = $this->fetchLatestTinyMCEVersion();
$pluginDir = $this->grav['locator']->findResource('plugin://' . $this->name, true, true);
$localJs = $pluginDir . '/assets/tinymce/tinymce.min.js';
$versionFile = $pluginDir . '/assets/tinymce/.version';
$isInstalled = file_exists($localJs);
$installedVersion = $isInstalled && file_exists($versionFile) ? trim((string) @file_get_contents($versionFile)) : null;
// Also check the markdown helper libraries
$latestMarked = $this->fetchLatestNpmVersion('marked');
$latestTurndown = $this->fetchLatestNpmVersion('turndown');
if (isset($this->grav['session'])) {
if ($latestVersion) {
$this->grav['session']->modern_editor_latest_version = $latestVersion;
}
if ($latestMarked) {
$this->grav['session']->modern_editor_latest_marked_version = $latestMarked;
}
if ($latestTurndown) {
$this->grav['session']->modern_editor_latest_turndown_version = $latestTurndown;
}
}
$markedInfo = $this->getMarkdownLibraryInstallInfo('marked', 'marked.umd.js');
$turndownInfo = $this->getMarkdownLibraryInstallInfo('turndown', 'turndown.js');
$editorSource = $this->config->get('plugins.modern-editor.editor_source', 'local');
$status = 'success';
$hasAnyUpdate = false;
$items = [];
// TinyMCE
if ($latestVersion) {
if ($editorSource === 'local') {
if ($installedVersion && $installedVersion === $latestVersion) {
$items[] = $lang === 'it'
? "• TinyMCE: aggiornato all'ultima versione (v{$installedVersion})"
: "• TinyMCE: up to date with the latest version (v{$installedVersion})";
} elseif ($installedVersion) {
$hasAnyUpdate = true;
$items[] = $lang === 'it'
? "• TinyMCE: aggiornamento disponibile! Nuova versione v{$latestVersion} (installata: v{$installedVersion})"
: "• TinyMCE: update available! New version v{$latestVersion} (installed: v{$installedVersion})";
} else {
$hasAnyUpdate = true;
$items[] = $lang === 'it'
? "• TinyMCE: non ancora installato localmente (ultima su NPM: v{$latestVersion})"
: "• TinyMCE: not installed locally yet (latest on NPM: v{$latestVersion})";
}
} else {
$items[] = $lang === 'it'
? "• TinyMCE (Cloud CDN): v{$latestVersion} disponibile su NPM"
: "• TinyMCE (Cloud CDN): v{$latestVersion} available on NPM";
}
} else {
$status = 'error';
$items[] = $lang === 'it'
? "• TinyMCE: impossibile verificare la versione su NPM al momento"
: "• TinyMCE: unable to verify version on NPM at this time";
}
// marked
if ($latestMarked) {
if ($markedInfo['installed']) {
if ($markedInfo['version'] === $latestMarked) {
$items[] = $lang === 'it'
? "• marked: aggiornato all'ultima versione (v{$markedInfo['version']})"
: "• marked: up to date with the latest version (v{$markedInfo['version']})";
} else {
$hasAnyUpdate = true;
$items[] = $lang === 'it'
? "• marked: aggiornamento disponibile! Nuova versione v{$latestMarked} (installata: v{$markedInfo['version']})"
: "• marked: update available! New version v{$latestMarked} (installed: v{$markedInfo['version']})";
}
} else {
$items[] = $lang === 'it'
? "• marked: in uso da CDN (ultima versione su NPM: v{$latestMarked})"
: "• marked: loaded from CDN (latest on NPM: v{$latestMarked})";
}
}
// turndown
if ($latestTurndown) {
if ($turndownInfo['installed']) {
if ($turndownInfo['version'] === $latestTurndown) {
$items[] = $lang === 'it'
? "• turndown: aggiornato all'ultima versione (v{$turndownInfo['version']})"
: "• turndown: up to date with the latest version (v{$turndownInfo['version']})";
} else {
$hasAnyUpdate = true;
$items[] = $lang === 'it'
? "• turndown: aggiornamento disponibile! Nuova versione v{$latestTurndown} (installata: v{$turndownInfo['version']})"
: "• turndown: update available! New version v{$latestTurndown} (installed: v{$turndownInfo['version']})";
}
} else {
$items[] = $lang === 'it'
? "• turndown: in uso da CDN (ultima versione su NPM: v{$latestTurndown})"
: "• turndown: loaded from CDN (latest on NPM: v{$latestTurndown})";
}
}
if ($lang === 'it') {
$header = $hasAnyUpdate
? "Verifica completata: sono disponibili nuovi aggiornamenti!"
: "Verifica completata: l'editor e le librerie Markdown sono aggiornati!";
} else {
$header = $hasAnyUpdate
? "Update check complete: new updates are available!"
: "Update check complete: editor and Markdown libraries are up to date!";
}
$msg = $header . "\n\n" . implode("\n", $items);
$this->performPeriodicUpdateCheck(true);
return ['status' => $status, 'message' => $msg, 'html' => $this->getLocalStatusHtml($langOverride)];
}
public function getCachedUpdateInfo(): array
{
$pluginDir = $this->grav['locator']->findResource('plugin://' . $this->name, true, true);
$cacheFile = $pluginDir . '/assets/.updates-cache.json';
if (file_exists($cacheFile)) {
$raw = @file_get_contents($cacheFile);
if ($raw) {
$data = @json_decode($raw, true);
if (is_array($data)) {
return $data;
}
}
}
return [];
}
public function performPeriodicUpdateCheck(bool $force = false, bool $fromCron = false): void
{
if (!$fromCron && !$this->isAdminContext()) {
return;
}
$pluginDir = $this->grav['locator']->findResource('plugin://' . $this->name, true, true);
$cacheFile = $pluginDir . '/assets/.updates-cache.json';
$cacheData = [];
if (file_exists($cacheFile)) {
$raw = @file_get_contents($cacheFile);
if ($raw) {
$cacheData = @json_decode($raw, true) ?: [];
}
}
$now = time();
$lastCheck = $cacheData['last_check'] ?? 0;
if (!$force && ($now - $lastCheck) < 86400 && !empty($cacheData['tinymce'])) {
$this->applyAutoUpdateIfNeeded($cacheData);
return;
}
$latestTinyMce = $this->fetchLatestTinyMCEVersion() ?: ($cacheData['tinymce'] ?? null);
$latestMarked = $this->fetchLatestNpmVersion('marked') ?: ($cacheData['marked'] ?? null);
$latestTurndown = $this->fetchLatestNpmVersion('turndown') ?: ($cacheData['turndown'] ?? null);
if (!$latestTinyMce) {
return;
}
$cacheData = [
'last_check' => $now,
'tinymce' => $latestTinyMce,
'marked' => $latestMarked,
'turndown' => $latestTurndown
];
@file_put_contents($cacheFile, json_encode($cacheData, JSON_PRETTY_PRINT));
if (isset($this->grav['session'])) {
$this->grav['session']->modern_editor_latest_version = $latestTinyMce;
if ($latestMarked) $this->grav['session']->modern_editor_latest_marked_version = $latestMarked;
if ($latestTurndown) $this->grav['session']->modern_editor_latest_turndown_version = $latestTurndown;
}
$this->applyAutoUpdateIfNeeded($cacheData);
}
private function applyAutoUpdateIfNeeded(array $cacheData): void
{
$autoUpdate = (bool) $this->config->get('plugins.modern-editor.auto_update', true);
if (!$autoUpdate) {
return;
}
$editorSource = $this->config->get('plugins.modern-editor.editor_source', 'local');
if ($editorSource === 'local') {
$installedTinyMce = $this->getInstalledTinyMCEVersion();
$latestTinyMce = $cacheData['tinymce'] ?? null;
if ($latestTinyMce && $installedTinyMce && $installedTinyMce !== $latestTinyMce) {
$this->downloadAndExtractTinyMCE($latestTinyMce);
}
$markdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$markdownEnabled = false;
}
// Only update Markdown libraries if they are already installed locally.
// Do NOT automatically re-download if the user deleted them!
if ($markdownEnabled) {
$markedInfo = $this->getMarkdownLibraryInstallInfo('marked', 'marked.umd.js');
$turndownInfo = $this->getMarkdownLibraryInstallInfo('turndown', 'turndown.js');
$latestMarked = $cacheData['marked'] ?? null;
$latestTurndown = $cacheData['turndown'] ?? null;
if ($markedInfo['installed'] && $latestMarked && $markedInfo['version'] !== $latestMarked) {
$this->downloadMarkedAction($latestMarked);
}
if ($turndownInfo['installed'] && $latestTurndown && $turndownInfo['version'] !== $latestTurndown) {
$this->downloadTurndownAction($latestTurndown);
}
}
}
}
public function removeTinyMceLocalAction(?string $langOverride = null): array
{
$lang = $this->getUiLanguage($langOverride);
$pluginDir = $this->grav['locator']->findResource('plugin://' . $this->name, true, true);
$targetDir = $pluginDir . '/assets/tinymce';
$vendorDir = $pluginDir . '/assets/vendor';
$errorFile = $pluginDir . '/.download-error';
if (file_exists($errorFile)) {
@unlink($errorFile);
}
if (is_dir($targetDir)) {
$this->recursiveRmdir($targetDir);
}
// Also remove the self-hosted marked/turndown copies downloaded
// alongside TinyMCE for local mode, so "remove offline files"
// fully reverts back to CDN-only, with no orphaned assets left
// on disk.
if (is_dir($vendorDir)) {
$this->recursiveRmdir($vendorDir);
}
return [
'status' => 'success',
'message' => $lang === 'it'
? "I file offline dell'editor e le librerie Markdown (marked / turndown) sono stati rimossi con successo!"
: "Offline editor files and Markdown libraries (marked / turndown) have been successfully removed!",
'html' => $this->getLocalStatusHtml($langOverride)
];
}
public function getStatusData(?string $langOverride = null): array
{
$pluginDir = $this->grav['locator']->findResource('plugin://' . $this->name, true, true);
$localJs = $pluginDir . '/assets/tinymce/tinymce.min.js';
$versionFile = $pluginDir . '/assets/tinymce/.version';
$errorFile = $pluginDir . '/assets/tinymce/.error';
$isInstalled = file_exists($localJs);
$installedVersion = $isInstalled && file_exists($versionFile) ? trim((string) @file_get_contents($versionFile)) : null;
$hasError = file_exists($errorFile);
$errorMessage = $hasError ? trim((string) @file_get_contents($errorFile)) : '';
$lang = $this->getUiLanguage($langOverride);
$latestVersion = null;
if (isset($this->grav['session'])) {
$latestVersion = $this->grav['session']->modern_editor_latest_version ?? null;
}
$adminBase = $this->getAdminBaseUrl() . '/plugins/modern-editor';
return [
'is_installed' => $isInstalled,
'installed_version' => $installedVersion,
'latest_version' => $latestVersion,
'has_error' => $hasError,
'error_message' => $errorMessage,
'lang' => $lang,
'check_url' => $adminBase . '?action=check_updates',
'reinstall_url' => $adminBase . '?action=download_tinymce&version=7.4.0',
'update_url_prefix' => $adminBase . '?action=download_tinymce&version=',
'html' => $this->getLocalStatusHtml($langOverride)
];
}
public function getConfigData(?string $langOverride = null): array
{
// marked_url/turndown_url are included here (mirroring editor_url)
// so the browser has a reliable fallback for these two URLs even
// when window.__MODERN_EDITOR_MD_URLS__ never reaches the page —
// which can happen because addInlineJs() only takes effect if the
// current response actually renders Grav's queued assets, and
// Admin Next's decoupled SPA shell does not always do so on every
// route. This REST endpoint, unlike that inline script, is always
// fetched explicitly by the field's JS (see fetchConfig()), so it
// is a dependable second source of truth instead of the CDN
// hardcoded fallback silently kicking in even in "local" mode.
$mdUrls = $this->getMarkdownLibraryUrls();
$markdownEnabled = (bool) $this->config->get('plugins.modern-editor.markdown_enabled', true);
if ($this->config->get('system.pages.markdown.enabled') === false) {
$markdownEnabled = false;
}
$updates = $this->getCachedUpdateInfo();
$autoUpdate = (bool) $this->config->get('plugins.modern-editor.auto_update', true);
$latestTinyMce = $updates['tinymce'] ?? null;
$installedTinyMce = $this->getInstalledTinyMCEVersion();
$editorSource = $this->config->get('plugins.modern-editor.editor_source', 'local');
$hasUpdate = false;
if ($latestTinyMce && $installedTinyMce && $installedTinyMce !== $latestTinyMce) {
$hasUpdate = true;
} elseif ($latestTinyMce && $editorSource !== 'local' && $latestTinyMce !== '7.4.0') {
$hasUpdate = true;
}
$lang = $this->getUiLanguage($langOverride);
$updateInfo = [
'autoUpdate' => $autoUpdate,
'hasUpdate' => $hasUpdate,
'latestVersion' => $latestTinyMce ?: '7.4.0',
'bannerTitle' => $lang === 'it' ? 'Modern Editor: Aggiornamenti disponibili' : 'Modern Editor: Updates Available',
'bannerMessage' => $lang === 'it'
? 'Sono disponibili nuove versioni dell\'editor o delle librerie Markdown. L\'aggiornamento può risolvere bug o problemi di sicurezza.'
: 'New versions of the editor or markdown libraries are available. Updating may resolve bugs and security issues.',
'dismissLabel' => $lang === 'it' ? 'Nascondi fino a una nuova versione' : 'Dismiss until next update'
];