PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 2.10.01
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v2.10.01
2.10.0 2.10.01 2.9.1 2.9.0 2.8.1 2.8.0 2.7.7 2.7.5 2.7.0 2.6.01 2.6.0 2.5.0 2.4.01 trunk 1.0.90 1.0.91 1.0.92 1.0.93 1.0.94 1.0.95 1.0.96 1.0.97 1.0.98 1.0.99 1.1.0 All 77 releases
fluent-community / app / Hooks / Handlers / FluentBlockEditorHandler.php

FluentBlockEditorHandler.php in FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses 2.10.01, at app/Hooks/Handlers/FluentBlockEditorHandler.php

1,229 lines 56.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCommunity\App\Hooks\Handlers;
4
5 use FluentCommunity\App\Functions\Utility;
6 use FluentCommunity\App\Models\BaseSpace;
7 use FluentCommunity\App\Services\Helper;
8 use FluentCommunity\Framework\Support\Arr;
9 use FluentCommunity\Modules\Course\Model\CourseLesson;
10
11 class FluentBlockEditorHandler
12 {
13 /**
14 * Extra fcomEditorVars entries contributed by whoever answered the
15 * fluent_community/block_editor_context filter. Stashed in renderCustomEditor()
16 * and merged in gutenberg_editor_scripts_and_styles(), which runs later in the
17 * same request off the wp_enqueue_scripts callback registered below.
18 *
19 * @var array
20 */
21 private $contextEditorVars = [];
22
23 public function register()
24 {
25 add_action('init', function () {
26
27 $editorPostTypes = apply_filters('fluent_community/block_editor_post_types', [
28 'fcom-dummy' => [
29 'label' => 'Lesson',
30 'public' => false,
31 'show_in_rest' => true,
32 'supports' => ['title', 'editor', 'thumbnail'],
33 ],
34 'fcom-lockscreen' => [
35 'label' => 'Lockscreen',
36 'public' => false,
37 'show_in_rest' => true,
38 'supports' => ['editor'],
39 ],
40 ]);
41
42 foreach ($editorPostTypes as $editorPostType => $editorPostTypeArgs) {
43 register_post_type($editorPostType, $editorPostTypeArgs);
44 }
45
46 if (!isset($_REQUEST['fluent_community_block_editor'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
47 return;
48 }
49
50 if (!defined('IFRAME_REQUEST')) {
51 define('IFRAME_REQUEST', true); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
52 }
53
54 remove_action('enqueue_block_editor_assets', 'wp_enqueue_editor_block_directory_assets');
55 add_action('fluent_community/block_editor_head', function () {
56 $url = FLUENT_COMMUNITY_PLUGIN_URL . 'Modules/Gutenberg/editor/index.css';
57 $contentStylingUrl = FLUENT_COMMUNITY_PLUGIN_URL . 'Modules/Gutenberg/editor/content_styling.css';
58 // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- emitted into a custom non-wp_head action hook, wp_enqueue_style not applicable
59 ?>
60 <link rel="stylesheet"
61 href="<?php echo esc_url($url); ?>?version=<?php echo esc_attr(FLUENT_COMMUNITY_PLUGIN_VERSION); ?>"
62 media="screen"/>
63 <link rel="stylesheet"
64 href="<?php echo esc_url($contentStylingUrl); ?>?version=<?php echo esc_attr(FLUENT_COMMUNITY_PLUGIN_VERSION); ?>"
65 media="screen"/>
66 <?php // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet ?>
67
68 <style>
69 /* No admin bar here; WP 7.1 offsets the editor by this var, leaving a gap. */
70 html { --wp-admin--admin-bar--height: 0; }
71 <?php echo wp_strip_all_tags($this->getColorSchemaCss()); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- generated CSS, no user input ?>
72 </style>
73
74 <?php
75 });
76 add_filter('should_load_separate_core_block_assets', '__return_false', 20);
77 $this->renderCustomEditor($_REQUEST); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
78
79 $actionHook = 'template_redirect';
80 if(is_admin()) {
81 $actionHook = 'admin_init';
82 }
83
84 add_action($actionHook, function () {
85 $this->renderPage();
86 exit(200);
87 }, -1000);
88 }, 2);
89 }
90
91 public function renderCustomEditor($data = [])
92 {
93 do_action('litespeed_control_set_nocache', 'fluentcommunity api request'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
94 // set no cache headers
95 nocache_headers();
96
97 $hasAccess = false;
98 $postType = 'fcom-dummy';
99 $context = Arr::get($data, 'context');
100
101 $lesson = null;
102
103 if ($context === 'course_lesson') {
104 $lessonId = Arr::get($data, 'lesson_id');
105 if ($lessonId) {
106 $lesson = CourseLesson::find($lessonId);
107 $hasAccess = $lesson && $lesson->course && $lesson->course->isCourseAdmin();
108 }
109 }
110
111 if ($context === 'lockscreen') {
112 $postType = 'fcom-lockscreen';
113 $spaceId = Arr::get($data, 'space_id');
114 if ($spaceId) {
115 $space = BaseSpace::query()->onlyMain()->find($spaceId);
116 $hasAccess = $space && $space->isAdmin(get_current_user_id(), true);
117 }
118 }
119
120 /*
121 * Extension point for editor contexts registered outside this plugin (the pro
122 * Space Pages module uses it). Handlers matching $context return their own
123 * access decision, post type and the content to seed the simulated post with.
124 */
125 $contextConfig = apply_filters('fluent_community/block_editor_context', [
126 'has_access' => $hasAccess,
127 'post_type' => $postType,
128 'has_content' => false,
129 'title' => '',
130 'content' => '',
131 ], $context, $data);
132
133 $hasAccess = !empty($contextConfig['has_access']);
134
135 $this->contextEditorVars = (array)Arr::get($contextConfig, 'editor_vars', []);
136
137 $contextPostType = Arr::get($contextConfig, 'post_type');
138 if ($contextPostType) {
139 $postType = $contextPostType;
140 }
141
142 if (!$hasAccess) {
143 echo '<h3 style="padding: 100px; text-align: center;">' . esc_html__('Sorry, you do not have access to this page.', 'fluent-community') . '</h3>';
144 exit(200);
145 }
146
147 add_filter('should_load_separate_core_block_assets', '__return_false', 20);
148 show_admin_bar(false);
149
150 $firstPost = Utility::getApp('db')->table('posts')
151 ->where('post_type', $postType)
152 ->first();
153
154 if ($firstPost) {
155 $simulatedPost = get_post($firstPost->ID);
156 $simulatedPost->post_content = '<!-- wp:paragraph --><p> </p><!-- /wp:paragraph -->';
157 } else {
158 $newPostId = wp_insert_post(array(
159 'post_title' => $context === 'course_lesson' ? 'Demo Lesson Title' : '',
160 'post_content' => '<!-- wp:paragraph --><p> </p><!-- /wp:paragraph -->',
161 'post_type' => $postType,
162 'post_status' => 'draft',
163 ));
164
165 $simulatedPost = get_post($newPostId);
166 }
167
168 global $post;
169 $post = $simulatedPost;
170
171 if ($lesson) {
172 $post->post_title = $lesson->title;
173 $post->post_content = $lesson->message ?: '<!-- wp:paragraph --><p> </p><!-- /wp:paragraph -->';
174 } elseif (!empty($contextConfig['has_content'])) {
175 $contextContent = Arr::get($contextConfig, 'content');
176 $post->post_title = Arr::get($contextConfig, 'title', '');
177 $post->post_content = $contextContent ? $contextContent : '<!-- wp:paragraph --><p> </p><!-- /wp:paragraph -->';
178 }
179
180 // renderPage() exits during admin_init and manually fires wp_enqueue_scripts in
181 // both the admin and frontend branches. admin_enqueue_scripts never runs here, so
182 // the apiFetch preload must ride wp_enqueue_scripts or the editor falls back to a
183 // live GET /wp/v2/fcom-dummy/{id}?context=edit — which 403s for users without
184 // edit_others_posts (e.g. contributors) on the shared, admin-authored dummy post.
185 add_action('wp_enqueue_scripts', function () use ($post) {
186 wp_enqueue_script('postbox', admin_url('js/postbox.min.js'), array('jquery-ui-sortable'), FLUENT_COMMUNITY_PLUGIN_VERSION, true);
187 wp_enqueue_style('dashicons');
188 wp_enqueue_style('media');
189 wp_enqueue_style('admin-menu');
190 wp_enqueue_style('admin-bar');
191 wp_enqueue_style('l10n');
192
193 wp_add_inline_script(
194 'wp-api-fetch',
195 \sprintf(
196 'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );',
197 wp_json_encode(
198 array(
199 '/wp/v2/' . $post->post_type . '/' . $post->ID . '?context=edit' => array(
200 'body' => array(
201 'id' => $post->ID,
202 'title' => array('raw' => $post->post_title),
203 'content' => array(
204 'block_format' => 1,
205 'raw' => $post->post_content,
206 ),
207 'excerpt' => array('raw' => ''),
208 'date' => '',
209 'date_gmt' => '',
210 'modified' => '',
211 'modified_gmt' => '',
212 'link' => home_url('/'),
213 'guid' => array(),
214 'parent' => 0,
215 'menu_order' => 0,
216 'author' => 0,
217 'featured_media' => 0,
218 'comment_status' => 'closed',
219 'ping_status' => 'closed',
220 'template' => '',
221 'meta' => array(),
222 '_links' => array(),
223 'type' => $post->post_type,
224 'status' => 'pending', // pending is the best state to remove draft saving possibilities.
225 'slug' => '',
226 'generated_slug' => '',
227 'permalink_template' => home_url('/'),
228 ),
229 ),
230 )
231 )
232 ),
233 'after'
234 );
235 }, 11);
236
237 add_action('wp_enqueue_scripts', function ($hook) use ($post) {
238 // Gutenberg requires the post-locking functions defined within:
239 // See `show_post_locked_dialog` and `get_post_metadata` filters below.
240 include_once ABSPATH . 'wp-admin/includes/post.php';
241 $this->gutenberg_editor_scripts_and_styles($hook, $post);
242 });
243
244 // Disable post locking dialogue.
245 add_filter('show_post_locked_dialog', '__return_false');
246
247 // Everyone can richedit! This avoids a case where a page can be cached where a user can't richedit.
248 $GLOBALS['wp_rich_edit'] = true;
249 add_filter('user_can_richedit', '__return_true', 1000);
250
251 // Homepage is always locked by @wordpressdotorg
252 // This prevents other logged-in users taking a lock of the post on the front-end.
253 add_filter('get_post_metadata', function ($value, $post_id, $meta_key) {
254 if ($meta_key !== '_edit_lock') {
255 return $value;
256 }
257 return time() . ':' . get_current_user_id(); // WordPressdotorg user ID
258 }, 10, 3);
259
260 // Disable Jetpack Blocks for now.
261 add_filter('jetpack_gutenberg', '__return_false');
262 }
263
264 private function gutenberg_editor_scripts_and_styles($hook, $post)
265 {
266 $initial_edits = array(
267 'title' => $post->post_title,
268 'content' => $post->post_content,
269 'excerpt' => $post->post_excerpt,
270 );
271
272 $editor_settings = $this->getEditorSettings($post);
273
274 $init_script =
275 "(function() {
276 window._wpLoadBlockEditor = new Promise(function(resolve) {
277 wp.domReady(function() {
278 resolve(wp.editPost.initializeEditor('editor', \"%s\", %d, %s, %s));
279 });
280 });
281 })();";
282
283 $script = sprintf(
284 $init_script,
285 $post->post_type,
286 $post->ID,
287 wp_json_encode($editor_settings),
288 wp_json_encode($initial_edits)
289 );
290 wp_add_inline_script('wp-edit-post', $script);
291
292 /**
293 * Scripts
294 */
295 wp_enqueue_media();
296
297 add_filter('user_can_richedit', '__return_true');
298 wp_tinymce_inline_scripts();
299 wp_enqueue_editor();
300
301 /**
302 * Styles
303 */
304 wp_enqueue_style('wp-edit-post');
305
306 // Include block styles needed when user is not signed in. See: https://github.com/WordPress/wporg-gutenberg/issues/26
307 wp_enqueue_style('global-styles');
308 wp_enqueue_style('wp-block-library');
309 wp_enqueue_style('wp-block-image');
310 wp_enqueue_style('wp-block-group');
311 wp_enqueue_style('wp-block-heading');
312 wp_enqueue_style('wp-block-button');
313 wp_enqueue_style('wp-block-paragraph');
314 wp_enqueue_style('wp-block-separator');
315 wp_enqueue_style('wp-block-columns');
316 wp_enqueue_style('wp-block-cover');
317 wp_enqueue_style('global-styles-css-custom-properties');
318 wp_enqueue_style('wp-block-spacer');
319
320 wp_register_style('fluent_com_editor_styles', FLUENT_COMMUNITY_PLUGIN_URL . 'Modules/Gutenberg/editor/style.css', [], FLUENT_COMMUNITY_PLUGIN_VERSION, 'all');
321
322 add_action('fluent_enqueue_block_editor_assets', 'wp_enqueue_editor_format_library_assets');
323
324 // WP 6.9+ loads the LaTeX-to-MathML converter as a script module; core wires this on
325 // 'enqueue_block_editor_assets', which this standalone editor page never fires.
326 if (function_exists('wp_enqueue_block_editor_script_modules')) {
327 add_action('fluent_enqueue_block_editor_assets', 'wp_enqueue_block_editor_script_modules');
328 }
329
330 /**
331 * Fires after block assets have been enqueued for the editing interface.
332 *
333 * Call `add_action` on any hook before 'admin_enqueue_scripts'.
334 *
335 * In the function call you supply, simply use `wp_enqueue_script` and
336 * `wp_enqueue_style` to add your functionality to the Gutenberg editor.
337 *
338 * @since 0.4.0
339 */
340 do_action('fluent_enqueue_block_editor_assets');
341
342 wp_enqueue_script('fcom_editor_custom', FLUENT_COMMUNITY_PLUGIN_URL . 'Modules/Gutenberg/editor/index.js', ['react', 'wp-components', 'wp-compose', 'wp-data', 'wp-edit-post', 'wp-i18n', 'wp-plugins'], FLUENT_COMMUNITY_PLUGIN_VERSION . time(), true);
343 wp_localize_script('fcom_editor_custom', 'fcomEditorI18n', $this->getEditorI18nStrings());
344 wp_localize_script('fcom_editor_custom', 'fcomEditorVars', array_merge([
345 'video_gate_default_threshold' => \FluentCommunity\Modules\Course\Services\LessonVideoGateService::getDefaultThreshold(),
346 'can_unfiltered_html' => current_user_can('unfiltered_html') ? 'yes' : 'no',
347 ], $this->contextEditorVars));
348 }
349
350 private function getEditorI18nStrings()
351 {
352 $strings = [
353 'Enable Video Embed' => __('Enable Video Embed', 'fluent-community'),
354 'Enable Comments' => __('Enable Comments', 'fluent-community'),
355 'Free Preview Lesson' => __('Free Preview Lesson', 'fluent-community'),
356 'If enabled, public users can view this lesson without enrolling the course.' => __('If enabled, public users can view this lesson without enrolling the course.', 'fluent-community'),
357 'Media Embed' => __('Media Embed', 'fluent-community'),
358 'Documents & Files' => __('Documents & Files', 'fluent-community'),
359 'Smartcodes' => __('Smartcodes', 'fluent-community'),
360 'You may use following smartcode in your lesson:' => __('You may use following smartcode in your lesson:', 'fluent-community'),
361 "User's Name:" => __("User's Name:", 'fluent-community'),
362 "User's Email:" => __("User's Email:", 'fluent-community'),
363 "User's photo HTML:" => __("User's photo HTML:", 'fluent-community'),
364 "User's Profile Link:" => __("User's Profile Link:", 'fluent-community'),
365 'Failed to fetch embed. Please check the URL.' => __('Failed to fetch embed. Please check the URL.', 'fluent-community'),
366 'Video thumbnail' => __('Video thumbnail', 'fluent-community'),
367 'Media embedded successfully' => __('Media embedded successfully', 'fluent-community'),
368 'Edit media' => __('Edit media', 'fluent-community'),
369 'Oembed' => __('Oembed', 'fluent-community'),
370 'Custom HTML' => __('Custom HTML', 'fluent-community'),
371 'Custom HTML Code' => __('Custom HTML Code', 'fluent-community'),
372 'Your account cannot save custom HTML. Scripts, iframes and similar tags are removed on save.' => __('Your account cannot save custom HTML. Scripts, iframes and similar tags are removed on save.', 'fluent-community'),
373 'Paste an iframe code' => __('Paste an iframe code', 'fluent-community'),
374 'Embed' => __('Embed', 'fluent-community'),
375 'Paste a URL to embed' => __('Paste a URL to embed', 'fluent-community'),
376 'Embed from Vimeo, YouTube, Wistia and more' => __('Embed from Vimeo, YouTube, Wistia and more', 'fluent-community'),
377 'FluentPlayer' => __('FluentPlayer', 'fluent-community'),
378 'Select Player Block' => __('Select Player Block', 'fluent-community'),
379 'Use FluentPlayer Block' => __('Use FluentPlayer Block', 'fluent-community'),
380 'The feature video is managed by the FluentPlayer block in the editor.' => __('The feature video is managed by the FluentPlayer block in the editor.', 'fluent-community'),
381 'A FluentPlayer block will be added at the top of the lesson content. Add or edit the video directly from that block in the editor.' => __('A FluentPlayer block will be added at the top of the lesson content. Add or edit the video directly from that block in the editor.', 'fluent-community'),
382 'Video Completion' => __('Video Completion', 'fluent-community'),
383 'Require video watch to complete' => __('Require video watch to complete', 'fluent-community'),
384 'Students must watch the video before they can mark this lesson as completed.' => __('Students must watch the video before they can mark this lesson as completed.', 'fluent-community'),
385 'Auto-complete lesson when the video ends' => __('Auto-complete lesson when the video ends', 'fluent-community'),
386 'Marks the lesson complete a few seconds after the student watches the video to the end.' => __('Marks the lesson complete a few seconds after the student watches the video to the end.', 'fluent-community'),
387 'Required watch percentage' => __('Required watch percentage', 'fluent-community'),
388 '100% means the video must be watched to the end.' => __('100% means the video must be watched to the end.', 'fluent-community'),
389 'Lesson Duration' => __('Lesson Duration', 'fluent-community'),
390 'Minutes' => __('Minutes', 'fluent-community'),
391 'Seconds' => __('Seconds', 'fluent-community'),
392 'View' => __('View', 'fluent-community'),
393 'No documents attached yet.' => __('No documents attached yet.', 'fluent-community'),
394 'Manage Documents & Files' => __('Manage Documents & Files', 'fluent-community'),
395 "User's Name" => __("User's Name", 'fluent-community'),
396 "User's Email" => __("User's Email", 'fluent-community'),
397 "User's photo HTML" => __("User's photo HTML", 'fluent-community'),
398 'Profile Link' => __('Profile Link', 'fluent-community'),
399 // Space page settings panel
400 'Who can view this page' => __('Who can view this page', 'fluent-community'),
401 'Everyone who can view the space' => __('Everyone who can view the space', 'fluent-community'),
402 'Space members only' => __('Space members only', 'fluent-community'),
403 'URL Slug' => __('URL Slug', 'fluent-community'),
404 'Changing the slug will break existing links to this page.' => __('Changing the slug will break existing links to this page.', 'fluent-community'),
405 'Show in space menu' => __('Show in space menu', 'fluent-community'),
406 'Menu Label' => __('Menu Label', 'fluent-community'),
407 'Leave empty to use the page title.' => __('Leave empty to use the page title.', 'fluent-community'),
408 'SEO' => __('SEO', 'fluent-community'),
409 'SEO Description' => __('SEO Description', 'fluent-community'),
410 'Used for search engines and link previews' => __('Used for search engines and link previews', 'fluent-community'),
411 // Space page layout picker. The template labels and descriptions are
412 // localized by whoever registers them (SpacePageHelper::getLayoutTemplates
413 // in pro); only the fallback names used when pro is absent live here.
414 'Page Layout' => __('Page Layout', 'fluent-community'),
415 'Show the page title' => __('Show the page title', 'fluent-community'),
416 'Show the featured image' => __('Show the featured image', 'fluent-community'),
417 'The title stays editable here and still names the page in the menu.' => __('The title stays editable here and still names the page in the menu.', 'fluent-community'),
418 'The image still appears in search results and link previews.' => __('The image still appears in search results and link previews.', 'fluent-community'),
419 'Standard' => __('Standard', 'fluent-community'),
420 'Classic' => __('Classic', 'fluent-community'),
421 'Full Width' => __('Full Width', 'fluent-community'),
422 'Unified' => __('Unified', 'fluent-community'),
423 ];
424
425 return apply_filters('fluent_community/editor_i18n_strings', $strings);
426 }
427
428 private function gutenberg_get_available_image_sizes()
429 {
430 $size_names = apply_filters(
431 'fluent_community/image_size_names_choose',
432 array(
433 'thumbnail' => __('Thumbnail', 'fluent-community'),
434 'medium' => __('Medium', 'fluent-community'),
435 'large' => __('Large', 'fluent-community'),
436 'full' => __('Full Size', 'fluent-community'),
437 )
438 );
439 $all_sizes = array();
440 foreach ($size_names as $size_slug => $size_name) {
441 $all_sizes[] = array(
442 'slug' => $size_slug,
443 'name' => $size_name,
444 );
445 }
446 return $all_sizes;
447 }
448
449 protected function renderPage()
450 {
451
452 remove_action( 'wp_print_styles', 'print_emoji_styles' );
453
454 add_action('fluent_community/block_editor_footer', function () {
455 wp_underscore_playlist_templates();
456 wp_print_footer_scripts();
457 $this->printScriptModules();
458 wp_print_media_templates();
459 wp_enqueue_global_styles();
460 if (function_exists('wp_enqueue_stored_styles')) {
461 wp_enqueue_stored_styles();
462 }
463 wp_maybe_inline_styles();
464 });
465
466 add_action('fluent_block_editor/head', 'wp_enqueue_scripts', 1);
467 add_action('fluent_block_editor/head', 'wp_resource_hints', 2);
468 add_action('fluent_block_editor/head', 'wp_preload_resources', 1);
469 add_action('fluent_block_editor/head', 'wp_print_styles', 8);
470 add_action('fluent_block_editor/head', 'wp_print_head_scripts', 9);
471 add_action('fluent_block_editor/head', 'wp_custom_css_cb', 101);
472
473 $this->unloadOtherScripts();
474 ?>
475 <!DOCTYPE html>
476 <html <?php language_attributes(); ?>>
477 <head>
478 <title>FluentCommunity Block Editor</title>
479 <meta charset='utf-8'>
480 <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover"/>
481 <meta name="mobile-web-app-capable" content="yes">
482 <meta name="robots" content="noindex">
483 <?php do_action('fluent_block_editor/head'); ?>
484 <?php do_action('fluent_community/block_editor_head'); ?>
485 </head>
486 <body class="fcom_custom_editor">
487 <div class="wp-site-blocks">
488 <div id="editor" class="gutenberg__editor"></div>
489 </div>
490 <?php
491 do_action('fluent_community/block_editor_footer');
492 ?>
493 </body>
494 </html>
495 <?php
496 }
497
498 /**
499 * Core prints script modules on 'wp_footer' / 'admin_print_footer_scripts'. This editor page
500 * renders its own document and fires neither, so blocks relying on script modules (core/math
501 * and its LaTeX-to-MathML converter on WP 6.9+) would never load.
502 */
503 protected function printScriptModules()
504 {
505 if (!function_exists('wp_script_modules')) {
506 return;
507 }
508
509 $scriptModules = wp_script_modules();
510
511 $scriptModules->print_import_map();
512 $scriptModules->print_enqueued_script_modules();
513 $scriptModules->print_script_module_preloads();
514
515 if (method_exists($scriptModules, 'print_script_module_translations')) {
516 $scriptModules->print_script_module_translations();
517 }
518 }
519
520 private function shouldBlockAsset(string $src, string $pluginUrl, string $themesUrl, string $approvedPattern): bool
521 {
522 $isPlugin = strpos($src, $pluginUrl) !== false;
523 $isTheme = strpos($src, $themesUrl) !== false;
524
525 if (!$isPlugin && !$isTheme) {
526 return false;
527 }
528
529 return !preg_match('#' . $approvedPattern . '#', $src);
530 }
531
532 private function unloadOtherScripts()
533 {
534 // skips scripts and styles both; fluent_community/skip_no_conflict is styles only
535 $isSkip = apply_filters('fluent_com_editor/skip_no_conflict', false);
536 if ($isSkip) {
537 return;
538 }
539
540 // scripts only; styles use fluent_community/asset_listed_slugs
541 $approvedSlugs = apply_filters('fluent_com_editor/asset_listed_slugs', [
542 '\/gutenberg\/'
543 ]);
544 $approvedSlugs[] = '\/fluent-community(-pro)?\/';
545 $approvedSlugs = array_unique($approvedSlugs);
546 $approvedSlugs = implode('|', $approvedSlugs);
547
548 $pluginUrl = str_replace(['http:', 'https:'], '', plugins_url());
549
550 $themesUrl = str_replace(['http:', 'https:'], '', get_theme_root_uri());
551
552 add_filter('script_loader_src', function ($src, $handle) use ($approvedSlugs, $pluginUrl, $themesUrl) {
553 if (!$src) {
554 return $src;
555 }
556
557 if ($this->shouldBlockAsset($src, $pluginUrl, $themesUrl, $approvedSlugs)) {
558 return false;
559 }
560
561 return $src;
562 }, 1, 2);
563
564 add_action('wp_print_scripts', function () use ($approvedSlugs, $pluginUrl, $themesUrl) {
565 global $wp_scripts;
566 if (!$wp_scripts) {
567 return;
568 }
569
570 foreach ($wp_scripts->queue as $script) {
571 if (empty($wp_scripts->registered[$script]) || empty($wp_scripts->registered[$script]->src)) {
572 continue;
573 }
574
575 $src = $wp_scripts->registered[$script]->src;
576 if ($this->shouldBlockAsset($src, $pluginUrl, $themesUrl, $approvedSlugs)) {
577 wp_dequeue_script($wp_scripts->registered[$script]->handle);
578 }
579 }
580 }, 1);
581
582 add_action('wp_print_styles', function () {
583 $isSkip = apply_filters('fluent_community/skip_no_conflict', false, 'styles');
584
585 if ($isSkip) {
586 return;
587 }
588
589 global $wp_styles;
590 if (!$wp_styles) {
591 return;
592 }
593
594 // styles only; scripts use fluent_com_editor/asset_listed_slugs
595 $approvedSlugs = apply_filters('fluent_community/asset_listed_slugs', [
596 '\/gutenberg\/',
597 ]);
598
599 $approvedSlugs[] = '\/fluent-community(-pro)?\/';
600
601 $approvedSlugs = array_unique($approvedSlugs);
602 $approvedSlugs = implode('|', $approvedSlugs);
603
604 $pluginUrl = plugins_url();
605 $themeUrl = get_theme_root_uri();
606
607 $pluginUrl = str_replace(['http:', 'https:'], '', $pluginUrl);
608 $themeUrl = str_replace(['http:', 'https:'], '', $themeUrl);
609
610 foreach ($wp_styles->queue as $script) {
611
612 if (empty($wp_styles->registered[$script]) || empty($wp_styles->registered[$script]->src)) {
613 continue;
614 }
615
616 $src = $wp_styles->registered[$script]->src;
617 $pluginMatched = (strpos($src, $pluginUrl) !== false) && !preg_match('#' . $approvedSlugs . '#', $src);
618 $themeMatched = (strpos($src, $themeUrl) !== false) && !preg_match('#' . $approvedSlugs . '#', $src);
619
620 if (!$pluginMatched && !$themeMatched) {
621 continue;
622 }
623
624 wp_dequeue_style($wp_styles->registered[$script]->handle);
625 }
626 }, 999999);
627 }
628
629 private function getEditorSettings($post)
630 {
631 // Media settings.
632 $max_upload_size = wp_max_upload_size();
633 if (!$max_upload_size) {
634 $max_upload_size = 0;
635 }
636
637 $lock_details = array(
638 'isLocked' => false,
639 'user' => '',
640 );
641
642 $editor_settings = array(
643 'maxUploadFileSize' => $max_upload_size,
644 'allowedMimeTypes' => get_allowed_mime_types(),
645 'postLock' => $lock_details,
646 'postLockUtils' => array(
647 'nonce' => wp_create_nonce('lock-post_' . $post->ID),
648 'unlockNonce' => wp_create_nonce('update-post_' . $post->ID),
649 'ajaxUrl' => admin_url('admin-ajax.php'),
650 ),
651 '__experimentalFeatures' => $this->getExperimentalFeatures(),
652 'colors' => $this->getColorPalette(),
653 '__experimentalDiscussionSettings' => [
654 'avatarURL' => 'https://secure.gravatar.com/avatar/?s=96&f=y&r=g',
655 'commentOrder' => 'asc',
656 'commentsPerPage' => '50',
657 'defaultCommentsPage' => 'newest',
658 'defaultCommentStatus' => 'open',
659 'pageComments' => '',
660 'threadComments' => '1',
661 'threadCommentsDepth' => '5'
662 ],
663 '__unstableGalleryWithImageBlocks' => false,
664 '__unstableIsBlockBasedTheme' => false,
665 'enableCustomUnits' => [
666 'px',
667 'em',
668 'rem',
669 '%',
670 'vh',
671 'vw'
672 ],
673 'fontSizes' => [
674 [
675 'name' => 'Small',
676 'size' => 'var(--fcom-font-size-small)',
677 'slug' => 'small'
678 ],
679 [
680 'name' => 'Medium',
681 'size' => 'var(--fcom-font-size-medium)',
682 'slug' => 'medium'
683 ],
684 [
685 'name' => 'Large',
686 'size' => 'var(--fcom-font-size-large)',
687 'slug' => 'large'
688 ],
689 [
690 'name' => 'Larger',
691 'size' => 'var(--fcom-font-size-larger)',
692 'slug' => 'larger'
693 ],
694 [
695 'name' => 'XX-Large',
696 'size' => 'var(--fcom-font-size-xxlarge)',
697 'slug' => 'xxlarge'
698 ]
699 ],
700 'fullscreenMode' => 1,
701 'enableCustomSpacing' => 1,
702 'enableCustomLineHeight' => 1,
703 'enableCustomFields' => false,
704 'disablePostFormats' => true,
705 'disableLayoutStyles' => false,
706 'disableCustomSpacingSizes' => false,
707 'disableCustomGradients' => 1,
708 'alignWide' => true,
709 'disableCustomFontSizes' => false,
710 'disableCustomColors' => false,
711 'canUpdateBlockBindings' => false,
712 'bodyPlaceholder' => __('Start writing or type / to choose a block for your lesson content', 'fluent-community'),
713 'allowedBlockTypes' => apply_filters('fluent_community/allowed_block_types', [
714 'core/audio',
715 'core/block',
716 'core/buttons',
717 'core/button',
718 'core/code',
719 'core/columns',
720 'core/column',
721 'core/cover',
722 'core/details',
723 'core/embed',
724 'core/footnotes',
725 'core/freeform',
726 'core/gallery',
727 'core/group',
728 'core/heading',
729 'core/html',
730 'core/image',
731 'core/list',
732 'core/list-item',
733 'core/math',
734 'core/media-text',
735 'core/missing',
736 'core/paragraph',
737 'core/preformatted',
738 'core/pullquote',
739 'core/quote',
740 'core/separator',
741 'core/social-link',
742 'core/social-links',
743 'core/spacer',
744 'core/table',
745 'core/verse'
746 ]),
747 'gradients' => [],
748 'imageDefaultSize' => 'large',
749 'imageEditing' => true,
750 'isRTL' => Helper::isRtl(),
751 'autosaveInterval' => 999,
752 'localAutosaveInterval' => 999,
753 'richEditingEnabled' => true,
754 'spacingSizes' => [
755 [
756 'name' => '2X-Small',
757 'size' => '0.44rem',
758 'slug' => '20'
759 ],
760 [
761 'name' => 'X-Small',
762 'size' => '0.67rem',
763 'slug' => '30'
764 ],
765 [
766 'name' => 'Small',
767 'size' => '1rem',
768 'slug' => '40'
769 ],
770 [
771 'name' => 'Medium',
772 'size' => '1.5rem',
773 'slug' => '50'
774 ],
775 [
776 'name' => 'Large',
777 'size' => '2.25rem',
778 'slug' => '60'
779 ],
780 [
781 'name' => 'X-Large',
782 'size' => '3.38rem',
783 'slug' => '70'
784 ],
785 [
786 'name' => '2X-Large',
787 'size' => '5.06rem',
788 'slug' => '80'
789 ]
790 ],
791 'titlePlaceholder' => __('Add Lesson title', 'fluent-community')
792 );
793
794 $editor_settings['styles'] = $this->getEditorStyles();
795 $editor_settings['__unstableResolvedAssets'] = $this->getResolvedAssets();
796 $editor_settings['defaultEditorStyles'] = $this->getDefaultEditorStyles();
797 $editor_settings['imageSizes'] = $this->gutenberg_get_available_image_sizes();
798
799 $editor_settings = apply_filters('fluent_community/block_editor_settings', $editor_settings);
800 return $editor_settings;
801 }
802
803 private function getExperimentalFeatures()
804 {
805 return array(
806 'appearanceTools' => true,
807 'useRootPaddingAwareAlignments' => false,
808 'border' => [
809 'color' => 1,
810 'radius' => 1,
811 'style' => 1,
812 'width' => 1,
813 ],
814 'color' => [
815 'background' => true,
816 'button' => 1,
817 'caption' => 1,
818 'customDuotone' => 0,
819 'defaultDuotone' => 0,
820 'defaultGradients' => 0,
821 'defaultPalette' => [],
822 'duotone' => [],
823 'gradients' => [],
824 'heading' => 1,
825 'link' => 1,
826 'palette' => [
827 'default' => [],
828 'theme' => [
829 [
830 'name' => 'Accent',
831 'slug' => 'theme-palette-color-1',
832 'color' => 'var(--theme-palette-color-1)',
833 ],
834 [
835 'name' => 'Accent - alt',
836 'slug' => 'theme-palette-color-2',
837 'color' => 'var(--theme-palette-color-2)',
838 ],
839 [
840 'name' => 'Strongest text',
841 'slug' => 'theme-palette-color-3',
842 'color' => 'var(--theme-palette-color-3)',
843 ],
844 [
845 'name' => 'Strong Text',
846 'slug' => 'theme-palette-color-4',
847 'color' => 'var(--theme-palette-color-4)',
848 ],
849 [
850 'name' => 'Medium text',
851 'slug' => 'theme-palette-color-5',
852 'color' => 'var(--theme-palette-color-5)',
853 ],
854 [
855 'name' => 'Subtle Text',
856 'slug' => 'theme-palette-color-6',
857 'color' => 'var(--theme-palette-color-6)',
858 ],
859 [
860 'name' => 'Subtle Background',
861 'slug' => 'theme-palette-color-7',
862 'color' => 'var(--theme-palette-color-7)',
863 ],
864 [
865 'name' => 'Lighter Background',
866 'slug' => 'theme-palette-color-8',
867 'color' => 'var(--theme-palette-color-8)',
868 ]
869 ]
870 ],
871 'text' => true,
872 ],
873 'dimensions' => [
874 'defaultAspectRatios' => true,
875 'aspectRatios' => [
876 'default' => [
877 [
878 'name' => 'Square - 1:1',
879 'slug' => 'square',
880 'ratio' => '1',
881 ],
882 [
883 'name' => 'Standard - 4:3',
884 'slug' => '4-3',
885 'ratio' => '4/3',
886 ],
887 [
888 'name' => 'Portrait - 3:4',
889 'slug' => '3-4',
890 'ratio' => '3/4',
891 ],
892 [
893 'name' => 'Classic - 3:2',
894 'slug' => '3-2',
895 'ratio' => '3/2',
896 ],
897 [
898 'name' => 'Classic Portrait - 2:3',
899 'slug' => '2-3',
900 'ratio' => '2/3',
901 ],
902 [
903 'name' => 'Wide - 16:9',
904 'slug' => '16-9',
905 'ratio' => '16/9',
906 ],
907 [
908 'name' => 'Tall - 9:16',
909 'slug' => '9-16',
910 'ratio' => '9/16',
911 ],
912 ]
913 ],
914 'aspectRatio' => 1,
915 'minHeight' => 1,
916 ],
917 'shadow' => [
918 'defaultPresets' => true,
919 'presets' => [
920 'default' => [
921 [
922 'name' => 'Natural',
923 'slug' => 'natural',
924 'shadow' => '6px 6px 9px rgba(0, 0, 0, 0.2)',
925 ],
926 [
927 'name' => 'Deep',
928 'slug' => 'deep',
929 'shadow' => '12px 12px 50px rgba(0, 0, 0, 0.4)',
930 ],
931 [
932 'name' => 'Sharp',
933 'slug' => 'sharp',
934 'shadow' => '6px 6px 0px rgba(0, 0, 0, 0.2)',
935 ],
936 [
937 'name' => 'Outlined',
938 'slug' => 'outlined',
939 'shadow' => '6px 6px 0px -3px rgba(255, 255, 255, 1), 6px 6px rgba(0, 0, 0, 1)',
940 ],
941 [
942 'name' => 'Crisp',
943 'slug' => 'crisp',
944 'shadow' => '6px 6px 0px rgba(0, 0, 0, 1)',
945 ],
946 ],
947 ],
948 ],
949 'spacing' => [
950 'blockGap' => 1,
951 'margin' => 1,
952 'padding' => 1,
953 'defaultSpacingSizes' => true,
954 'spacingScale' => [
955 'default' => [
956 'operator' => '*',
957 'increment' => 1.5,
958 'steps' => 7,
959 'mediumStep' => 1.5,
960 'unit' => 'rem',
961 ],
962 ],
963 'spacingSizes' => [
964 'default' => [
965 [
966 'name' => '2X-Small',
967 'slug' => '20',
968 'size' => '0.44rem',
969 ],
970 [
971 'name' => 'X-Small',
972 'slug' => '30',
973 'size' => '0.67rem',
974 ],
975 [
976 'name' => 'Small',
977 'slug' => '40',
978 'size' => '1rem',
979 ],
980 [
981 'name' => 'Medium',
982 'slug' => '50',
983 'size' => '1.5rem',
984 ],
985 [
986 'name' => 'Large',
987 'slug' => '60',
988 'size' => '2.25rem',
989 ],
990 [
991 'name' => 'X-Large',
992 'slug' => '70',
993 'size' => '3.38rem',
994 ],
995 [
996 'name' => '2X-Large',
997 'slug' => '80',
998 'size' => '5.06rem',
999 ],
1000 ],
1001 ],
1002 ],
1003 'typography' => [
1004 'defaultFontSizes' => NULL,
1005 'dropCap' => true,
1006 'fontSizes' => [
1007 'default' => [
1008 [
1009 'name' => 'Small',
1010 'slug' => 'small',
1011 'size' => '13px',
1012 ],
1013 [
1014 'name' => 'Medium',
1015 'slug' => 'medium',
1016 'size' => '20px',
1017 ],
1018 [
1019 'name' => 'Large',
1020 'slug' => 'large',
1021 'size' => '36px',
1022 ],
1023 [
1024 'name' => 'Extra Large',
1025 'slug' => 'x-large',
1026 'size' => '42px',
1027 ],
1028 ],
1029 'theme' => [
1030 [
1031 'name' => 'Small',
1032 'slug' => 'small',
1033 'size' => 'var(--fcom-font-size-small)',
1034 ],
1035 [
1036 'name' => 'Medium',
1037 'slug' => 'medium',
1038 'size' => 'var(--fcom-font-size-medium)',
1039 ],
1040 [
1041 'name' => 'Large',
1042 'slug' => 'large',
1043 'size' => 'var(--fcom-font-size-large)',
1044 ],
1045 [
1046 'name' => 'Larger',
1047 'slug' => 'larger',
1048 'size' => 'var(--fcom-font-size-larger)',
1049 ],
1050 [
1051 'name' => 'XX-Large',
1052 'slug' => 'xxlarge',
1053 'size' => 'var(--fcom-font-size-xxlarge)',
1054 ],
1055 ],
1056 ],
1057 'fontStyle' => true,
1058 'fontWeight' => true,
1059 'letterSpacing' => true,
1060 'textAlign' => true,
1061 'textDecoration' => true,
1062 'textTransform' => true,
1063 'writingMode' => false,
1064 'fluid' => 0,
1065 ],
1066 'blocks' => [
1067 'core/button' => [
1068 'border' => [
1069 'radius' => true,
1070 ]
1071 ],
1072 'core/image' => [
1073 'lightbox' => [
1074 'allowEditing' => true,
1075 ]
1076 ],
1077 'core/pullquote' => [
1078 'border' => [
1079 'color' => true,
1080 'radius' => true,
1081 'style' => true,
1082 'width' => true,
1083 ]
1084 ],
1085 'core/paragraph' => [
1086 'spacing' => [
1087 'margin' => 1,
1088 'padding' => 1,
1089 ]
1090 ]
1091 ],
1092 'layout' => [
1093 'contentSize' => 'var(--theme-block-max-width)',
1094 'wideSize' => 'var(--theme-block-wide-max-width)',
1095 ],
1096 'background' => [
1097 'backgroundImage' => 1,
1098 'backgroundSize' => 1,
1099 ],
1100 'position' => [
1101 'sticky' => 0,
1102 ]
1103 );
1104 }
1105
1106 private function getColorPalette()
1107 {
1108 return [
1109 [
1110 'color' => 'var(--fcom-primary-bg, #ffffff)',
1111 'name' => 'Accent',
1112 'slug' => 'theme-palette-color-1'
1113 ],
1114 [
1115 'color' => 'var(--fcom-secondary-bg, #f0f2f5)',
1116 'name' => 'Accent - alt',
1117 'slug' => 'theme-palette-color-2'
1118 ],
1119 [
1120 'color' => 'var(--fcom-secondary-text, #525866)',
1121 'name' => 'Strongest text',
1122 'slug' => 'theme-palette-color-3'
1123 ],
1124 [
1125 'color' => 'var(--fcom-secondary-content-bg, #f0f3f5)',
1126 'name' => 'Strong Text',
1127 'slug' => 'theme-palette-color-4'
1128 ],
1129 [
1130 'color' => 'var(--fcom-active-bg, #f0f3f5)',
1131 'name' => 'Medium text',
1132 'slug' => 'theme-palette-color-5'
1133 ],
1134 [
1135 'color' => 'var(--fcom-light-bg, #E1E4EA)',
1136 'name' => 'Subtle Text',
1137 'slug' => 'theme-palette-color-6'
1138 ],
1139 [
1140 'color' => 'var(--fcom-deep-bg, #E1E4EA)',
1141 'name' => 'Subtle Background',
1142 'slug' => 'theme-palette-color-7'
1143 ],
1144 [
1145 'color' => 'var(--fcom-primary-text, #19283a)',
1146 'name' => 'Lighter Background',
1147 'slug' => 'theme-palette-color-8'
1148 ]
1149 ];
1150 }
1151
1152 private function getEditorStyles()
1153 {
1154 $editorDir = FLUENT_COMMUNITY_PLUGIN_DIR . 'Modules/Gutenberg/editor/';
1155
1156 return [
1157 [
1158 '__unstableType' => 'colorSchema',
1159 'css' => $this->getColorSchemaCss(),
1160 'isGlobalStyles' => true
1161 ],
1162 [
1163 '__unstableType' => 'theme',
1164 'css' => file_get_contents($editorDir . 'editor-iframe-styles.css') ?: '',
1165 'isGlobalStyles' => true
1166 ],
1167 [
1168 'css' => file_get_contents($editorDir . 'editor.css') ?: '',
1169 '__unstableType' => 'user'
1170 ]
1171 ];
1172 }
1173
1174 private function getResolvedAssets()
1175 {
1176 $resolvedStyles = [
1177 'wp-components-css' => includes_url('/css/dist/components/style.min.css'),
1178 'wp-preferences-css' => includes_url('/css/dist/preferences/style.min.css'),
1179 'wp-block-editor-css' => includes_url('/css/dist/block-editor/style.min.css'),
1180 'wp-reusable-blocks-css' => includes_url('/css/dist/reusable-blocks/style.min.css'),
1181 'wp-patterns-css' => includes_url('/css/dist/patterns/style.min.css'),
1182 'wp-editor-css' => includes_url('/css/dist/editor/style.min.css'),
1183 'wp-block-library-css' => includes_url('/css/dist/block-library/style.min.css'),
1184 'wp-block-editor-content-css' => includes_url('/css/dist/block-editor/content.min.css'),
1185 'wp-edit-blocks-css' => includes_url('/css/dist/block-library/editor.min.css'),
1186 'fcom-content-styling' => FLUENT_COMMUNITY_PLUGIN_URL . 'Modules/Gutenberg/editor/content_styling.css'
1187 ];
1188
1189 global $wp_version;
1190 $cssFiles = '';
1191 foreach ($resolvedStyles as $name => $file) {
1192 $cssFiles .= "<link rel='stylesheet' id='{$name}' href='{$file}?ver={$wp_version}' media='all' />\n"; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
1193 }
1194
1195 return [
1196 'scripts' => '<script src="' . includes_url('/js/dist/vendor/wp-polyfill.min.js?ver=3.15.0') . '" id="wp-polyfill-js"></script>', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
1197 'styles' => $cssFiles
1198 ];
1199 }
1200
1201 private function getDefaultEditorStyles()
1202 {
1203 return [
1204 [
1205 '__unstableType' => 'user',
1206 'css' => ':root{--wp-admin-theme-color:#007cba;--wp-admin-theme-color--rgb:0, 124, 186;--wp-admin-theme-color-darker-10:#006ba1;--wp-admin-theme-color-darker-10--rgb:0, 107, 161;--wp-admin-theme-color-darker-20:#005a87;--wp-admin-theme-color-darker-20--rgb:0, 90, 135;--wp-admin-border-width-focus:2px;--wp-block-synced-color:#7a00df;--wp-block-synced-color--rgb:122, 0, 223;--wp-bound-block-color:var(--wp-block-synced-color);}@media (min-resolution:192dpi){:root{--wp-admin-border-width-focus:1.5px;}}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;font-size:18px;line-height:1.5;--wp--style--block-gap:2em;}p{line-height:1.8;}.editor-post-title__block{font-size:2.5em;font-weight:800;margin-bottom:1em;margin-top:2em;}'
1207 ]
1208 ];
1209 }
1210
1211 private function getColorSchemaCss()
1212 {
1213 $colorSchema = Utility::getColorSchemaConfig();
1214
1215 $darkSchemaConfig = Arr::get($colorSchema, 'dark');
1216
1217 $colorSchemaCss = ':root {';
1218 foreach (Arr::get($darkSchemaConfig, 'body', []) as $colorKey => $value) {
1219 if ($value) {
1220 $cssVar = ' --fcom-' . str_replace('_', '-', $colorKey);
1221 $colorSchemaCss .= $cssVar . ':' . $value . '; ';
1222 }
1223 }
1224 $colorSchemaCss .= '}';
1225
1226 return $colorSchemaCss;
1227 }
1228 }
1229