PluginProbe
Search Atlas SEO – OTTO AI SEO Automation for WordPress / 2.7.0
Search Atlas SEO – OTTO AI SEO Automation for WordPress v2.7.0
2.7.1 2.7.2 2.7.0 2.6.26 2.6.25 2.6.24 2.6.23 2.6.22 2.6.21 2.6.20 2.6.19 2.6.18 2.6.17 2.6.16 2.6.15 2.6.14 2.6.13 2.6.12 2.6.11 2.6.10 2.6.9 2.6.8 2.6.7 2.6.6 2.6.5 All 141 releases
metasync / includes / class-metasync.php

class-metasync.php in Search Atlas SEO – OTTO AI SEO Automation for WordPress 2.7.0, at includes/class-metasync.php

1,778 lines 64.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 // If this file is called directly, abort.
3 if (!defined('ABSPATH')) {
4 exit;
5 }
6
7
8 /**
9 * The file that defines the core plugin class
10 *
11 * A class definition that includes attributes and functions used across both the
12 * public-facing side of the site and the admin area.
13 *
14 * @link https://searchatlas.com
15 * @since 1.0.0
16 *
17 * @package Metasync
18 * @subpackage Metasync/includes
19 */
20
21 /**
22 * The core plugin class.
23 *
24 * This is used to define internationalization, admin-specific hooks, and
25 * public-facing site hooks.
26 *
27 * Also maintains the unique identifier of this plugin as well as the current
28 * version of the plugin.
29 *
30 * @since 1.0.0
31 * @package Metasync
32 * @subpackage Metasync/includes
33 * @author Engineering Team <[email protected]>
34 */
35 class Metasync
36 {
37
38 /**
39 * The loader that's responsible for maintaining and registering all hooks that power
40 * the plugin.
41 *
42 * @since 1.0.0
43 * @access protected
44 * @var Metasync_Loader $loader Maintains and registers all hooks for the plugin.
45 */
46 protected $loader;
47
48 /**
49 * The unique identifier of this plugin.
50 *
51 * @since 1.0.0
52 * @access protected
53 * @var string $plugin_name The string used to uniquely identify this plugin.
54 */
55 protected $plugin_name;
56
57 /**
58 * The current version of the plugin.
59 *
60 * @since 1.0.0
61 * @access protected
62 * @var string $version The current version of the plugin.
63 */
64 protected $version;
65
66 protected $database;
67
68 protected $db_redirection;
69
70 protected $db_heartbeat_errors;
71
72
73
74 public const option_name = "metasync_options";
75
76 /**
77 * Dedicated option key for heartbeat throttle timestamps.
78 *
79 * Stored separately from the main options blob so writes to last_heart_beat
80 * and last_heartbeat_at do not race with concurrent settings writes during
81 * the 15-second wp_remote_post window in SyncCustomerParams.
82 */
83 public const heartbeat_throttle_option = "metasync_heartbeat_throttle";
84
85 /**
86 * Search Atlas Domain Constants
87 * Centralized constants for all Search Atlas service endpoints
88 */
89 public const HOMEPAGE_DOMAIN = "https://searchatlas.com";
90 public const DASHBOARD_DOMAIN = "https://dashboard.searchatlas.com";
91 public const API_DOMAIN = "https://api.searchatlas.com";
92 public const CA_API_DOMAIN = "https://ca.searchatlas.com";
93 public const SUPPORT_EMAIL = "[email protected]";
94 public const DOCUMENTATION_DOMAIN = "https://help.searchatlas.com";
95
96 /**
97 * Storage prefix marking a Search Atlas API key value as encrypted at rest.
98 */
99 private const API_KEY_ENC_PREFIX = 'enc_v1:';
100
101 /**
102 * Request-scoped memo for the decrypted Search Atlas API key.
103 *
104 * null = not yet loaded this request
105 * false = load attempted but decryption failed (salts changed / corrupt)
106 * string = decrypted plaintext (may be '')
107 *
108 * Never written to a transient or the DB — exists only for the lifetime
109 * of the current request.
110 *
111 * @var string|false|null
112 */
113 private static $memo_api_key = null;
114
115 /**
116 * Define the core functionality of the plugin.
117 *
118 * Set the plugin name and the plugin version that can be used throughout the plugin.
119 * Load the dependencies, define the locale, and set the hooks for the admin area and
120 * the public-facing side of the site.
121 *
122 * @since 1.0.0
123 */
124 public function __construct()
125 {
126 if (defined('METASYNC_VERSION')) {
127 $this->version = METASYNC_VERSION;
128 } else {
129 $this->version = '1.0.0';
130 }
131 $this->plugin_name = 'metasync';
132
133 $this->load_dependencies();
134 // $this->set_locale(); // Language support removed - using default only
135 $this->init_api_key_monitor();
136 $this->define_admin_hooks();
137 $this->define_public_hooks();
138 }
139
140 /**
141 * Load the required dependencies for this plugin.
142 *
143 * Include the following files that make up the plugin:
144 *
145 * - Metasync_Loader. Orchestrates the hooks of the plugin.
146 * - Metasync_i18n. Defines internationalization functionality.
147 * - Metasync_Admin. Defines all hooks for the admin area.
148 * - Metasync_Public. Defines all hooks for the public side of the site.
149 *
150 * Create an instance of the loader which will be used to register the hooks
151 * with WordPress.
152 *
153 * @since 1.0.0
154 * @access private
155 */
156 private function load_dependencies()
157 {
158 // WordPress core — cannot be autoloaded.
159 require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
160
161 // Procedural init file — not a class, must stay explicit.
162 if (file_exists(plugin_dir_path(dirname(__FILE__)) . 'google-index/google-index-init.php')) {
163 require_once plugin_dir_path(dirname(__FILE__)) . 'google-index/google-index-init.php';
164 } else {
165 error_log('MetaSync Google Index: google-index-init.php not found at ' . plugin_dir_path(dirname(__FILE__)) . 'google-index/google-index-init.php');
166 }
167
168 // The SEO precedence resolver is referenced statically from the render
169 // filters, the sync layer and four admin screens. Require it explicitly
170 // for the same reason as the admin navigation below: a partial update can
171 // leave newer PHP files beside an older committed autoload classmap, and
172 // a missing class on wp_head or the posts list is a fatal, not a
173 // degradation.
174 if (!class_exists('Metasync_Seo_Precedence')) {
175 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-metasync-seo-precedence.php';
176 }
177
178 // Admin navigation is referenced statically from frontend-reachable
179 // includes (heartbeat/connect managers). Require it explicitly here so
180 // the static call never fatals when wp_head fires before autoload.
181 if (!class_exists('Metasync_Admin_Navigation')) {
182 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-metasync-admin-navigation.php';
183 }
184
185 // Hooked on init at priority 0, before any theme or plugin callback
186 // runs, so it cannot wait for a lazy autoload. See define_public_hooks.
187 if (!class_exists('Metasync_BookingPress_Compat')) {
188 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-metasync-bookingpress-compat.php';
189 }
190
191 $this->loader = new Metasync_Loader();
192 // Install aggregate-option password protection in every runtime context.
193 Metasync_Settings_Registration::instance();
194 $this->db_heartbeat_errors = new Metasync_HeartBeat_Error_Monitor_Database();
195 $this->db_redirection = new Metasync_Redirection_Database();
196 }
197
198 /**
199 * Define the locale for this plugin for internationalization.
200 *
201 * Uses the Metasync_i18n class in order to set the domain and to register the hook
202 * with WordPress.
203 *
204 * @since 1.0.0
205 * @access private
206 */
207 // Language support removed - using default only
208 /*
209 private function set_locale()
210 {
211 $plugin_i18n = new Metasync_i18n();
212
213 $this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');
214 }
215 */
216
217 /**
218 * Initialize the API Key Monitor for comprehensive API key change detection
219 *
220 * @since 1.0.0
221 * @access private
222 */
223 private function init_api_key_monitor()
224 {
225 // Initialize the singleton instance of the API Key Monitor
226 // This will automatically set up hooks to monitor all API key changes
227 Metasync_API_Key_Monitor::get_instance();
228
229 // Log successful initialization
230 #commented out to stop appending this to error.php
231 # error_log('MetaSync: API Key Monitor initialized successfully');
232 }
233
234 /**
235 * Register all of the hooks related to the admin area functionality
236 * of the plugin.
237 *
238 * @since 1.0.0
239 * @access private
240 */
241 private function define_admin_hooks()
242 {
243
244 $plugin_admin = new Metasync_Admin($this->get_plugin_name(), $this->get_version(), $this->database, $this->db_redirection, $this->db_heartbeat_errors); // , $this->data_error_log_list
245
246 // Initialize HTML Visual Editor
247 $html_visual_editor = new Metasync_HTML_Visual_Editor($this->get_plugin_name(), $this->get_version());
248 $html_visual_editor->init();
249
250 // Initialize OTTO Debug class for developers
251 if (class_exists('Metasync_Otto_Debug')) {
252 $otto_debug = new Metasync_Otto_Debug($this->get_plugin_name(), $this->get_version());
253 }
254
255 // Initialize SEO Sidebar for Gutenberg Block Editor
256 if (class_exists('Metasync_SEO_Sidebar')) {
257 new Metasync_SEO_Sidebar($this->get_version());
258 }
259
260 // Initialize Internal Link Suggestions for Gutenberg Block Editor
261 if (class_exists('Metasync_Link_Suggestions')) {
262 new Metasync_Link_Suggestions();
263 }
264
265 $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
266 $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
267
268 # Redirection import AJAX handler
269 $redirection_handler = new Metasync_Redirection($this->db_redirection);
270 $this->loader->add_action('wp_ajax_metasync_import_redirections', $redirection_handler, 'handle_import_ajax');
271 $this->loader->add_action('wp_ajax_metasync_check_redirects_health', $redirection_handler, 'handle_health_check_ajax');
272
273 // HeartBeat API Receive Respond and Settings.
274 $this->loader->add_action('heartbeat_settings', $plugin_admin, 'metasync_heartbeat_settings');
275 $this->loader->add_action('heartbeat_received', $plugin_admin, 'metasync_received_data', 10, 2);
276 $this->loader->add_action('wp_ajax_metasync_send_customer_params', $plugin_admin, 'lgSendCustomerParams');
277
278 // Search Atlas Connect endpoints - authenticates with Search Atlas platform to retrieve SA API key and Otto UUID
279 $this->loader->add_action('wp_ajax_metasync_generate_connect_url', $plugin_admin, 'generate_searchatlas_connect_url');
280 $this->loader->add_action('wp_ajax_metasync_check_connect_status', $plugin_admin, 'check_searchatlas_connect_status');
281 $this->loader->add_action('wp_ajax_metasync_reset_authentication', $plugin_admin, 'reset_searchatlas_authentication');
282
283 // Auto-update filter
284 $this->loader->add_filter('auto_update_plugin', $plugin_admin, 'control_plugin_auto_updates', 10, 2);
285
286 // Search Atlas Connect development/testing endpoints
287 $this->loader->add_action('wp_ajax_metasync_test_enhanced_tokens', $plugin_admin, 'test_enhanced_searchatlas_tokens');
288 $this->loader->add_action('wp_ajax_metasync_test_whitelabel_domain', $plugin_admin, 'test_whitelabel_domain');
289 $this->loader->add_action('wp_ajax_metasync_test_ajax_endpoint', $plugin_admin, 'test_searchatlas_ajax_endpoint');
290 $this->loader->add_action('wp_ajax_metasync_simple_ajax_test', $plugin_admin, 'simple_ajax_test');
291
292
293 $post_meta_setting = new Metasync_Post_Meta_Settings();
294 $this->loader->add_action('admin_init', $post_meta_setting, 'add_post_meta_data', 2);
295 $this->loader->add_action('admin_init', $post_meta_setting, 'show_top_admin_bar', 9);
296
297 // Unified "SEO Suite" meta box — consolidates the separate Classic-editor
298 // meta boxes above into one tabbed box (presentation-only; save handlers
299 // unchanged). Classic editor only; the block editor keeps its SEO sidebar.
300 // Self-registers its hooks in the constructor. Opt out via the
301 // `metasync_enable_seo_suite` filter.
302 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-metasync-seo-suite.php';
303 new Metasync_Seo_Suite();
304
305 // SEO Health CSV export: must run on admin_init (before output).
306 // Cheap $_GET check avoids loading the class on every admin page.
307 if (
308 isset($_GET['page'], $_GET['export'], $_GET['_wpnonce']) &&
309 $_GET['export'] === 'csv' &&
310 strpos($_GET['page'], '-seo-health') !== false
311 ) {
312 $this->loader->add_action('admin_init', Metasync_SEO_Health::get_instance(), 'handle_csv_export', 1);
313 }
314 $this->loader->add_action('wp', $post_meta_setting, 'show_top_admin_bar', 9);
315
316 // SEO meta columns on the posts/pages list tables (WP-624).
317 // Registered for both the `posts` and `pages` variants of each hook so the
318 // columns reach every supported post type; the callbacks bail on unsupported
319 // ones. Hidden by default — users opt in from Screen Options.
320 $seo_columns = Metasync_SEO_Columns::get_instance();
321 $this->loader->add_filter('manage_posts_columns', $seo_columns, 'add_columns', 10, 2);
322 $this->loader->add_filter('manage_pages_columns', $seo_columns, 'add_columns', 10, 1);
323 $this->loader->add_action('manage_posts_custom_column', $seo_columns, 'render_column', 10, 2);
324 $this->loader->add_action('manage_pages_custom_column', $seo_columns, 'render_column', 10, 2);
325 $this->loader->add_filter('default_hidden_columns', $seo_columns, 'default_hidden_columns', 10, 2);
326 $this->loader->add_filter('hidden_columns', $seo_columns, 'hidden_columns', 10, 3);
327 $this->loader->add_action('admin_head', $seo_columns, 'print_styles');
328 $this->loader->add_action('admin_notices', $seo_columns, 'companion_plugin_notice');
329
330 // Initialize XML Sitemap auto-update hooks if enabled
331 // Note: Must not be gated by is_admin() because Gutenberg saves posts
332 // via the REST API where is_admin() returns false, and REST_REQUEST
333 // is not yet defined at plugin load time
334 if (get_option('metasync_sitemap_auto_update', false)) {
335 $sitemap_generator = new Metasync_Sitemap_Generator();
336 $sitemap_generator->setup_auto_update_hooks();
337 }
338 // Initialize Schema Markup functionality
339 $schema_markup = new Metasync_Schema_Markup($this->get_plugin_name(), $this->get_version());
340 $this->loader->add_action('wp_ajax_metasync_get_schema_fields', $schema_markup, 'ajax_get_schema_fields');
341 $this->loader->add_action('wp_ajax_metasync_preview_schema', $schema_markup, 'ajax_preview_schema');
342
343 // Initialize Breadcrumbs functionality
344 if (class_exists('Metasync_Breadcrumbs')) {
345 new Metasync_Breadcrumbs($this->get_plugin_name(), $this->get_version());
346 }
347 if (class_exists('Metasync_Breadcrumbs_Schema')) {
348 new Metasync_Breadcrumbs_Schema($this->get_plugin_name(), $this->get_version());
349 }
350
351 // Initialize Developer Panel (for endpoint switching)
352 if (class_exists('Metasync_Dev_Panel')) {
353 $dev_panel = new Metasync_Dev_Panel($this->get_plugin_name(), $this->get_version());
354 }
355
356 // Initialize Site Health integration
357 if (class_exists('Metasync_Site_Health')) {
358 $site_health = new Metasync_Site_Health();
359 $site_health->register_tests();
360 }
361
362 // Initialize endpoint URL filtering for staging mode
363 $this->init_endpoint_filtering();
364
365 }
366
367 /**
368 * Register all of the hooks related to the public-facing functionality
369 * of the plugin.
370 *
371 * @since 1.0.0
372 * @access private
373 */
374 private function define_public_hooks()
375 {
376 // Header and Footer code snippets
377 $code_snippets = new Metasync_Code_Snippets();
378
379 $this->loader->add_action('wp_head', $code_snippets, 'get_header_snippet');
380 $this->loader->add_action('wp_footer', $code_snippets, 'get_footer_snippet');
381
382 $plugin_public = new Metasync_Public($this->get_plugin_name(), $this->get_version());
383 $rest_api = $plugin_public->get_rest_api();
384 $seo_output = $plugin_public->get_seo_output();
385 // Derive the basename from the actual file location: the plugin
386 // folder is not guaranteed to be named after the plugin (renamed
387 // installs), and a hardcoded name makes the settings links vanish.
388 $get_plugin_basename = plugin_basename(dirname(__DIR__) . '/metasync.php');
389
390 // Asset enqueue hooks (Metasync_Public)
391 $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
392 $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
393 $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_page_custom_css', 999);
394
395 // Registered here rather than from inside enqueue_scripts(), which would
396 // re-register the same filter on every front-end request.
397 $this->loader->add_filter('script_loader_tag', $plugin_public, 'add_defer_attribute', 10, 2);
398
399 // Elementor editor CSS injection
400 if (class_exists('\Elementor\Plugin')) {
401 $this->loader->add_action('elementor/preview/enqueue_styles', $plugin_public, 'enqueue_elementor_editor_css', 999);
402 }
403
404 // Divi builder CSS injection
405 if (function_exists('et_setup_theme')) {
406 $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_divi_builder_css', 999);
407 }
408
409 // Initialize centralized SEO conflict handler (singleton — suppresses
410 // third-party SEO plugin descriptions when MetaSync provides its own).
411 Metasync_SEO_Conflict_Handler::get_instance();
412
413 // Headless delivery: register the GraphQL SEO field. This only adds a
414 // callback on `graphql_register_types`, which never fires unless WPGraphQL
415 // is active, and the callback returns immediately unless Headless Mode is
416 // on — so with the mode off nothing about this request changes.
417 Metasync_Headless_Graphql::init();
418
419 // Headless stale-while-revalidate OTTO refresh: background safety net for
420 // missed/delayed OTTO deployment webhooks. Every branch is gated on
421 // Metasync_Headless_Config::is_active(), so with headless mode off this
422 // schedules no cron event and registers no route beyond an inert REST
423 // callback that itself checks the flag before doing anything.
424 Metasync_Headless_Refresh_Job::init();
425
426 // Term-level SEO plugin sync: propagate MetaSync term meta (category/tag
427 // archives) into Yoast/Rank Math/AIOSEO term storage on every write.
428 $this->loader->add_action('updated_term_meta', $this, 'on_term_meta_updated', 10, 4);
429 $this->loader->add_action('added_term_meta', $this, 'on_term_meta_updated', 10, 4);
430
431 // Post-level plugin sync: propagate MetaSync post meta into
432 // Yoast/Rank Math/AIOSEO post storage on every write.
433 $this->loader->add_action('updated_post_meta', $this, 'on_post_meta_updated', 10, 4);
434 $this->loader->add_action('added_post_meta', $this, 'on_post_meta_updated', 10, 4);
435 // Deletes matter too: clearing the last checkbox in a meta box removes
436 // the meta row, which fires neither hook above.
437 $this->loader->add_action('deleted_post_meta', $this, 'on_post_meta_deleted', 10, 3);
438
439 // SEO Output hooks (Metasync_Seo_Output)
440 $this->loader->add_action('wp_head', $seo_output, 'hook_metasync_metatags', 1, 1);
441 // LocalBusiness / Organization / Person JSON-LD from the Local Business page.
442 $this->loader->add_action('wp_head', $seo_output, 'output_local_business_schema', 2, 1);
443 $this->loader->add_action('template_redirect', $seo_output, 'inject_archive_seo_controls');
444
445 // Hreflang / language alternates output (wp_head @ priority 2). The
446 // emitter shares the SEO output instance for the noindex check.
447 $plugin_hreflang = new Metasync_Hreflang_Output($seo_output);
448 $this->loader->add_action('wp_head', $plugin_hreflang, 'output_hreflang_tags', 2);
449 // WPML prints its own hreflang set at wp_head priority 1, ahead of
450 // MetaSync's output at priority 2 — the suppression filter has to be
451 // in place before wp_head starts, hence template_redirect.
452 $this->loader->add_action('template_redirect', $plugin_hreflang, 'register_wpml_suppression', 1);
453
454 // Edge Cache: detect Cloudways Varnish and persist for settings UI
455 $this->loader->add_action('init', 'Metasync_Edge_Cache_Purge', 'detect_cloudways');
456
457 // BookingPress starts a PHP session on every front-end request (init
458 // at priority 1), which makes hosts skip page caching site-wide. Its
459 // booking flows manage their own sessions inside their AJAX handlers,
460 // so unhook the global start. Priority 0 keeps this ahead of theirs.
461 // Registered with add_action directly (like Metasync_Oxygen_Compat)
462 // because the loader's $component parameter is typed to objects.
463 add_action('init', ['Metasync_BookingPress_Compat', 'neutralize_bookingpress_session'], 0);
464
465 // Sitemap exclusions for disabled archive types
466 $this->loader->add_filter('wp_sitemaps_taxonomies', $seo_output, 'filter_sitemap_taxonomies');
467 $this->loader->add_filter('wp_sitemaps_users_entry', $seo_output, 'filter_sitemap_users', 10, 2);
468 $this->loader->add_filter('wp_sitemaps_add_provider', $seo_output, 'filter_sitemap_providers', 10, 2);
469 $this->loader->add_filter('wp_sitemaps_index_entry', $seo_output, 'filter_sitemap_index_entries', 10, 4);
470
471 // AMP cleanup functionality - remove metasync_optimized attribute from head on AMP pages
472 $this->loader->add_action('template_redirect', $seo_output, 'cleanup_amp_head_attribute', 1);
473 $this->loader->add_action('wp_footer', $seo_output, 'end_amp_head_cleanup', 999);
474
475 // Redirection functionality
476 $redirection = new Metasync_Redirection($this->db_redirection);
477 $this->loader->add_action('template_redirect', $redirection, 'handle_template_redirect', 5);
478
479 # Prevent WordPress from redirecting to draft posts via redirect_canonical
480 $this->loader->add_filter('redirect_canonical', $redirection, 'prevent_draft_post_redirects', 10, 2);
481
482 # Prevent WordPress old slug redirects to unpublished posts only
483 $this->loader->add_filter('old_slug_redirect_post_id', $redirection, 'prevent_old_slug_redirect_to_drafts', 10, 1);
484
485 // Auto-redirect on slug change - creates 301 redirect when post/page slug is changed
486 $auto_redirect = new Metasync_Auto_Redirect($this->db_redirection);
487 $auto_redirect->init();
488
489 # Custom HTML Pages functionality
490 # No additional loader hooks needed - class registers its own hooks
491 $custom_pages = new Metasync_Custom_Pages();
492
493 // 404 Error monitoring
494 $this->loader->add_action('template_redirect', $this, 'handle_404_monitoring', 10);
495 $this->loader->add_action('plugin_action_links_' . $get_plugin_basename, $plugin_public, 'metasync_plugin_links');
496
497 // REST API hooks (Metasync_Rest_Api)
498 $this->loader->add_action('rest_api_init', $rest_api, 'metasync_register_rest_routes');
499 // Coexist with third-party JWT auth plugins: clear their prior auth error
500 // for metasync/v1 requests when our own API key validates. The Tmeister
501 // "JWT Authentication for WP-API" plugin surfaces its jwt_auth_invalid_token
502 // 403 via rest_pre_dispatch (priority 10), so we hook the same filter at a
503 // later priority (11) to clear it for our namespace only.
504 $this->loader->add_filter('rest_pre_dispatch', $rest_api, 'allow_metasync_rest_auth', 11, 3);
505 // Coexist with site-wide "authenticated users only" REST restrictions.
506 // Those hook rest_authentication_errors, which WP applies before dispatch,
507 // so rest_pre_dispatch and permission_callback never run. Hook it late
508 // (99) to clear the error for metasync/v1 requests that present a valid
509 // plugin API key; every other route keeps the site's restriction.
510 $this->loader->add_filter('rest_authentication_errors', $rest_api, 'allow_metasync_rest_authentication', 99, 1);
511 $this->loader->add_action('init', $plugin_public, 'metasync_plugin_init', 5);
512 $this->loader->add_action('wp_ajax_metasync_lglogin', $rest_api, 'linkgraph_login');
513
514 // Robots meta filter (Metasync_Seo_Output)
515 $this->loader->add_filter('wp_robots', $seo_output, 'metasync_wp_robots_meta');
516
517
518
519 $metasyncTemplateClass = new Metasync_Template();
520 $this->loader->add_filter('theme_page_templates', $metasyncTemplateClass, 'metasync_template_landing_page', 10, 3);
521 $this->loader->add_filter('template_include', $metasyncTemplateClass, 'metasync_template_landing_page_load', 99 );
522 $templateCrawler = new MetaSyncHiddenPostManager(); # initialize the crawler class
523
524 $this->loader->add_action('wp_trash_post', $templateCrawler , 'prevent_post_deletion'); # Prevent post deletion when moved to trash
525 $this->loader->add_action('before_delete_post', $templateCrawler , 'prevent_post_deletion'); # Prevent permanent deletion
526 # $this->loader->add_filter('metasync_hidden_post_manager', $templateCrawler , 'init'); # run the crawler
527 # Hidden post manager now runs via cron instead of filter (to avoid interfering with post create/update)
528 $this->loader->add_action('metasync_hidden_post_check', $templateCrawler , 'init'); # run the crawler via cron
529
530 // Open Graph and Social Media Tags
531 $opengraph = new Metasync_OpenGraph($this->get_plugin_name(), $this->get_version());
532 $opengraph->init();
533
534 # Save current theme info to database (safe context - admin/init hooks)
535 $this->loader->add_action('after_switch_theme', $this, 'save_current_theme_info');
536 $this->loader->add_action('admin_init', $this, 'ensure_theme_info_saved');
537
538 // OTTO Frontend Toolbar
539 $otto_toolbar = new Metasync_Otto_Frontend_Toolbar($this->get_plugin_name(), $this->get_version());
540 $this->loader->add_action('wp_enqueue_scripts', $otto_toolbar, 'enqueue_styles');
541 $this->loader->add_action('wp_enqueue_scripts', $otto_toolbar, 'enqueue_scripts');
542 $this->loader->add_action('admin_bar_menu', $otto_toolbar, 'add_admin_bar_menu', 100);
543 $this->loader->add_action('wp_footer', $otto_toolbar, 'render_debug_bar', 999);
544
545 // Initialize Sitemap Generator on frontend (for virtual sitemap serving)
546 $sitemap_generator = new Metasync_Sitemap_Generator();
547
548 // Initialize LLMs.txt Generator (for virtual /llms.txt and /llms-full.txt serving)
549 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-metasync-html-to-markdown.php';
550 require_once plugin_dir_path(dirname(__FILE__)) . 'llms-txt/class-metasync-llms-txt-generator.php';
551 $llms_txt_generator = new Metasync_Llms_Txt_Generator();
552
553 // Serve the IndexNow key file virtually at /{key}.txt so it works
554 // on read-only web roots and nginx hosts that 403 direct static .txt access.
555 require_once plugin_dir_path(dirname(__FILE__)) . 'bing-index/class-metasync-bing-instant-index.php';
556 add_action('template_redirect', array('Metasync_Bing_Instant_Index', 'serve_virtual_key_file'), 0);
557
558 // Scheduled IndexNow submissions, deferred from save_post so a slow
559 // IndexNow round-trip cannot stall the editor or REST write. Registered
560 // statically because the class is loaded but never instantiated on
561 // cron loads. The hook name matches the uninstall cron sweep exactly.
562 add_action('metasync_bing_indexnow_submit_event', array('Metasync_Bing_Instant_Index', 'run_scheduled_submit'), 10, 1);
563
564 // Construct the robots.txt manager on the public load path so its
565 // `robots_txt` filter is registered before a plain GET /robots.txt is
566 // served. The filter is attached in the singleton's constructor, and
567 // previously only admin screens built the instance — so the virtual
568 // robots.txt rules and sitemap lines never rendered on the frontend.
569 require_once plugin_dir_path(dirname(__FILE__)) . 'robots-txt/class-metasync-robots-txt.php';
570 Metasync_Robots_Txt::get_instance();
571
572 // One-time upgrade: regenerate sitemap to remove any Beaver Builder template entries
573 if ( ! get_option( 'metasync_sitemap_bb_exclusion_applied' ) ) {
574 $this->loader->add_action('init', $this, 'maybe_regenerate_sitemap_after_upgrade');
575 }
576 }
577
578 /**
579 * One-time upgrade routine: regenerate the XML sitemap so that Beaver Builder
580 * template post types (fl-builder-template, fl-theme-layout) that were already
581 * present in previously-generated sitemaps are purged.
582 *
583 * Runs once on 'init' and sets a flag so it never runs again.
584 *
585 * @since 1.0.0
586 */
587 public function maybe_regenerate_sitemap_after_upgrade() {
588 $done_key = 'metasync_sitemap_bb_exclusion_applied';
589 if ( get_option( $done_key ) ) {
590 return;
591 }
592
593 // Only regenerate if the custom sitemap feature is actually in use.
594 if ( get_option( 'metasync_sitemap_auto_update', false ) || file_exists( ABSPATH . 'sitemap_index.xml' ) ) {
595 if ( ! class_exists( 'Metasync_Sitemap_Generator' ) ) {
596 require_once plugin_dir_path( dirname( __FILE__ ) ) . 'sitemap/class-metasync-sitemap-generator.php';
597 }
598 $sitemap = new Metasync_Sitemap_Generator();
599 $sitemap->generate_sitemap();
600 update_option( $done_key, true );
601 }
602 // If sitemap is not in use, don't set the flag — retry on next load
603 // so that enabling sitemaps later will still clean up BB templates.
604 }
605
606 /**
607 * Initialize endpoint URL filtering for staging mode
608 * Intercepts HTTP requests and replaces production URLs with staging URLs
609 */
610 private function init_endpoint_filtering() {
611 // Only add filter if Endpoint Manager is available and staging mode is active
612 if (!class_exists('Metasync_Endpoint_Manager') || !Metasync_Endpoint_Manager::is_staging_mode()) {
613 return;
614 }
615
616 // Add filter to intercept HTTP requests before they're sent
617 add_filter('pre_http_request', array($this, 'filter_http_request_urls'), 10, 3);
618 }
619
620 /**
621 * Filter HTTP request URLs to replace production endpoints with staging
622 *
623 * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value.
624 * @param array $args HTTP request arguments.
625 * @param string $url The request URL.
626 * @return false|array|WP_Error
627 */
628 public function filter_http_request_urls($preempt, $args, $url) {
629 // Only process if we're not preempting the request
630 if ($preempt !== false) {
631 return $preempt;
632 }
633
634 // Only process if staging mode is active
635 if (!class_exists('Metasync_Endpoint_Manager') || !Metasync_Endpoint_Manager::is_staging_mode()) {
636 return $preempt;
637 }
638
639 // Define URL replacements (production => staging)
640 $url_replacements = array(
641 'https://dashboard.searchatlas.com' => 'https://dashboard.staging.searchatlas.com',
642 'https://api.searchatlas.com' => 'https://api.staging.searchatlas.com',
643 'https://ca.searchatlas.com' => 'https://ca.staging.searchatlas.com',
644 'https://sa.searchatlas.com' => 'https://sa.staging.searchatlas.com',
645 );
646
647 // Check if URL needs to be replaced
648 $original_url = $url;
649 foreach ($url_replacements as $production => $staging) {
650 if (strpos($url, $production) === 0) {
651 $url = str_replace($production, $staging, $url);
652 error_log("MetaSync Endpoint Filter: Replaced {$production} with {$staging} in URL: {$original_url}");
653 break;
654 }
655 }
656
657 // If URL was changed, modify the args and make the request ourselves
658 if ($url !== $original_url) {
659 // Make the request with the modified URL
660 return wp_remote_request($url, $args);
661 }
662
663 return $preempt;
664 }
665
666 /**
667 * Term meta update hook: mirror MetaSync term meta (`_metasync_*`)
668 * into the active third-party SEO plugins' term storage.
669 *
670 * Registered on both `updated_term_meta` and `added_term_meta` so new
671 * fields are synced the first time they are written as well as on
672 * subsequent updates.
673 *
674 * @param int $meta_id Meta row ID (unused).
675 * @param int $object_id Term ID.
676 * @param string $meta_key Meta key being written.
677 * @param mixed $meta_value Meta value being written.
678 */
679 public function on_term_meta_updated($meta_id, $object_id, $meta_key, $meta_value) {
680 if (strncmp($meta_key, '_metasync_', 10) !== 0) {
681 return;
682 }
683
684 if (!class_exists('Metasync_Term_Plugin_Sync')) {
685 return;
686 }
687
688 $term = get_term((int) $object_id);
689 if (!$term || is_wp_error($term)) {
690 return;
691 }
692
693 $canonical_map = [
694 '_metasync_metatitle' => 'title',
695 '_metasync_metadesc' => 'desc',
696 '_metasync_robots_index' => 'noindex',
697 '_metasync_canonical_url' => 'canonical',
698 '_metasync_og_title' => 'og_title',
699 '_metasync_og_description' => 'og_desc',
700 '_metasync_og_image' => 'og_image',
701 '_metasync_twitter_title' => 'twitter_title',
702 '_metasync_twitter_description' => 'twitter_desc',
703 ];
704
705 if (!isset($canonical_map[$meta_key])) {
706 return;
707 }
708
709 $canonical_key = $canonical_map[$meta_key];
710
711 Metasync_Term_Plugin_Sync::get_instance()->sync_term(
712 (int) $object_id,
713 (string) $term->taxonomy,
714 [$canonical_key => $meta_value]
715 );
716 }
717
718 /**
719 * Post meta update hook: mirror MetaSync post meta (`_metasync_*`)
720 * into the active third-party SEO plugins' post storage.
721 *
722 * Registered on both `updated_post_meta` and `added_post_meta` so new
723 * fields are synced the first time they are written as well as on
724 * subsequent updates.
725 *
726 * @param int $meta_id Meta row ID (unused).
727 * @param int $post_id Post ID.
728 * @param string $meta_key Meta key being written.
729 * @param mixed $meta_value Meta value being written.
730 */
731 public function on_post_meta_updated($meta_id, $post_id, $meta_key, $meta_value) {
732 if (!self::is_metasync_meta_key($meta_key)) {
733 return;
734 }
735
736 if (!self::sync_layer_handles('on_meta_updated')) {
737 return;
738 }
739
740 Metasync_Plugin_Sync::get_instance()->on_meta_updated($meta_id, $post_id, $meta_key, $meta_value);
741 }
742
743 /**
744 * Bridge deleted_post_meta to the sync layer.
745 *
746 * Clearing the last checkbox in a meta box deletes its meta row rather than
747 * updating it, so the update hooks above never fire and mirrored values can
748 * go stale. Only the legacy robots keys are acted on; see
749 * Metasync_Plugin_Sync::on_meta_deleted().
750 *
751 * @param array $meta_ids Meta row IDs (unused).
752 * @param int $post_id Post ID.
753 * @param string $meta_key Meta key being deleted.
754 */
755 public function on_post_meta_deleted($meta_ids, $post_id, $meta_key) {
756 if (!self::is_metasync_meta_key($meta_key)) {
757 return;
758 }
759
760 if (!self::sync_layer_handles('on_meta_deleted')) {
761 return;
762 }
763
764 Metasync_Plugin_Sync::get_instance()->on_meta_deleted($meta_ids, $post_id, $meta_key);
765 }
766
767 /**
768 * Is this meta key one the post sync layer could possibly care about?
769 *
770 * Cheap string gate, no autoload, no singleton. Every watched post key is
771 * either `_metasync_*` (sidebar, OTTO and the mirrored robots JSON) or
772 * `metasync_*` (the legacy meta box keys), so this keeps third-party meta
773 * writes out of the sync layer entirely — `deleted_post_meta` and
774 * `updated_post_meta` fire for every key on the site, including on front-end
775 * requests, and crossing into the sync layer for keys it will only discard
776 * costs an autoload plus a singleton on the hot path.
777 *
778 * Deliberately broader than the sync layer's own key maps: those stay the
779 * single source of exact truth, so a new MetaSync key needs no change here.
780 *
781 * @param string $meta_key Meta key being written or deleted.
782 * @return bool
783 */
784 private static function is_metasync_meta_key($meta_key) {
785 return strncmp($meta_key, '_metasync_', 10) === 0
786 || strncmp($meta_key, 'metasync_', 9) === 0;
787 }
788
789 /**
790 * Can the post sync layer actually handle this hook right now?
791 *
792 * A partially updated install can leave a newer class-metasync.php beside an
793 * older class-metasync-plugin-sync.php — stale opcache bytecode for one file
794 * is enough. Calling a method the loaded class does not define is a fatal,
795 * and because these bridges run on `wp_head` via third-party meta writes it
796 * takes the front end down rather than degrading. Check before dispatching.
797 *
798 * Checked on the class, not an instance, so a mismatch skips the singleton.
799 *
800 * @param string $method Sync-layer method about to be called.
801 * @return bool
802 */
803 private static function sync_layer_handles($method) {
804 return class_exists('Metasync_Plugin_Sync')
805 && method_exists('Metasync_Plugin_Sync', 'get_instance')
806 && method_exists('Metasync_Plugin_Sync', $method);
807 }
808
809 /**
810 * Save current theme information to MetaSync options
811 * This runs in WordPress admin context, not during REST API requests
812 * Safe to use wp_get_theme() here
813 */
814 public function save_current_theme_info() {
815 $theme = wp_get_theme();
816 $metasync_data = self::get_option();
817
818 if (!isset($metasync_data['general'])) {
819 $metasync_data['general'] = array();
820 }
821
822 $metasync_data['general']['current_theme_name'] = $theme->get('Name');
823 $metasync_data['general']['current_theme_template'] = $theme->get_template();
824 $metasync_data['general']['theme_info_updated'] = time();
825
826 self::set_option($metasync_data);
827 }
828
829 /**
830 * Ensure theme info is saved on admin_init if not already saved
831 * This ensures theme info is available even if theme wasn't switched
832 */
833 public function ensure_theme_info_saved() {
834 $metasync_data = self::get_option('general');
835
836 # Only run once per day to avoid overhead
837 if (empty($metasync_data['theme_info_updated']) ||
838 (time() - $metasync_data['theme_info_updated']) > 86400) {
839 $this->save_current_theme_info();
840 }
841 }
842
843 public static function get_option($key = null, $default = null)
844 {
845 $options = get_option(Metasync::option_name);
846 if (empty($options)) $options = [];
847 if ($key === null) return $options;
848 return $options[$key] ?? ($default !== null ? $default : null);
849 }
850
851 public static function set_option($data)
852 {
853 #return update_option(Metasync::option_name, $data);
854 $result = update_option(Metasync::option_name, $data);
855
856 // NEW: Structured error logging for database errors (only log if it's a real DB error)
857 global $wpdb;
858 if ($result === false && class_exists('Metasync_Error_Logger') && !empty($wpdb->last_error)) {
859 // Check if it's actually a database error (not just same value)
860 $saved_data = get_option(Metasync::option_name);
861 if ($saved_data !== $data) {
862 // Value is different but save failed - this is a real database error
863 Metasync_Error_Logger::log(
864 Metasync_Error_Logger::CATEGORY_DATABASE_ERROR,
865 Metasync_Error_Logger::SEVERITY_ERROR,
866 'Failed to save plugin main options to database',
867 [
868 'option_name' => Metasync::option_name,
869 'wpdb_error' => $wpdb->last_error,
870 'wpdb_last_query' => $wpdb->last_query,
871 'operation' => 'set_option',
872 'has_api_key' => !empty($data['general']['searchatlas_api_key'] ?? null),
873 'has_auth_token' => !empty($data['general']['apikey'] ?? null)
874 ]
875 );
876 }
877 }
878
879 return $result;
880 }
881
882 /**
883 * Derive the 32-byte AES key from existing WordPress salts.
884 *
885 * No new secret is stored anywhere — the key material is the concatenation
886 * of three WordPress salts, hashed to a fixed 32 bytes. If the salts change
887 * (e.g. wp-config regenerated) the derived key changes and previously
888 * encrypted values can no longer be decrypted, which is handled gracefully
889 * by the callers (re-authenticate state) rather than fataling.
890 *
891 * @return string 32 raw bytes.
892 */
893 private static function api_key_crypto_key()
894 {
895 $material = wp_salt('secure_auth') . wp_salt('logged_in') . wp_salt('nonce');
896 return hash('sha256', $material, true);
897 }
898
899 /**
900 * Determine whether a stored value is in the encrypted-at-rest format.
901 *
902 * @param mixed $value
903 * @return bool
904 */
905 public static function is_encrypted_api_key($value)
906 {
907 return is_string($value) && strncmp($value, self::API_KEY_ENC_PREFIX, strlen(self::API_KEY_ENC_PREFIX)) === 0;
908 }
909
910 /**
911 * Encrypt a plaintext Search Atlas API key for storage at rest.
912 *
913 * Uses AES-256-GCM (authenticated) with a random 12-byte IV. The IV, the
914 * 16-byte GCM tag and the ciphertext are concatenated and base64-encoded
915 * behind an `enc_v1:` prefix. An empty string is stored as-is (no key set).
916 *
917 * When OpenSSL is unavailable or encryption fails the plaintext is stored
918 * unchanged (availability over hard-fail) and the degradation is logged so
919 * it cannot go unnoticed.
920 *
921 * @param string $plaintext
922 * @return string Encrypted blob, or '' when $plaintext is empty.
923 */
924 public static function encrypt_api_key($plaintext)
925 {
926 $plaintext = (string) $plaintext;
927 if ($plaintext === '') {
928 return '';
929 }
930
931 // Already encrypted — do not double-encrypt.
932 if (self::is_encrypted_api_key($plaintext)) {
933 return $plaintext;
934 }
935
936 if (!function_exists('openssl_encrypt')) {
937 // OpenSSL unavailable — store plaintext rather than lose the key.
938 error_log('MetaSync: OpenSSL is unavailable — the Search Atlas API key was stored WITHOUT encryption at rest.');
939 return $plaintext;
940 }
941
942 $key = self::api_key_crypto_key();
943 $iv = random_bytes(12);
944 $tag = '';
945 $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16);
946
947 if ($ciphertext === false) {
948 // Encryption failed — fall back to plaintext storage, but say so.
949 error_log('MetaSync: API key encryption failed — the Search Atlas API key was stored WITHOUT encryption at rest.');
950 return $plaintext;
951 }
952
953 return self::API_KEY_ENC_PREFIX . base64_encode($iv . $tag . $ciphertext);
954 }
955
956 /**
957 * Decrypt a stored Search Atlas API key value.
958 *
959 * Accepts either the encrypted `enc_v1:` format or a legacy plaintext value
960 * (returned unchanged, supporting installs that pre-date encryption). On any
961 * decryption failure (salt change / corruption) returns false so callers can
962 * surface a re-authenticate state instead of using a bad key.
963 *
964 * @param mixed $value
965 * @return string|false Plaintext, or false when an encrypted value cannot be decrypted.
966 */
967 public static function decrypt_api_key($value)
968 {
969 if (!is_string($value) || $value === '') {
970 return '';
971 }
972
973 if (!self::is_encrypted_api_key($value)) {
974 // Legacy plaintext key.
975 return $value;
976 }
977
978 if (!function_exists('openssl_decrypt')) {
979 return false;
980 }
981
982 $raw = base64_decode(substr($value, strlen(self::API_KEY_ENC_PREFIX)), true);
983 if ($raw === false || strlen($raw) < 12 + 16 + 1) {
984 return false;
985 }
986
987 $iv = substr($raw, 0, 12);
988 $tag = substr($raw, 12, 16);
989 $ciphertext = substr($raw, 28);
990
991 $key = self::api_key_crypto_key();
992 $plaintext = openssl_decrypt($ciphertext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
993
994 if ($plaintext === false) {
995 return false;
996 }
997
998 return $plaintext;
999 }
1000
1001 /**
1002 * Get the decrypted Search Atlas API key, memoized for the request.
1003 *
1004 * Decrypts at most once per request and never persists the decrypted value
1005 * anywhere. When a legacy plaintext key is found it is migrated to the
1006 * encrypted format in place (one-time migration on load). Returns:
1007 * - the plaintext key (string, possibly '')
1008 * - false when an encrypted value exists but cannot be decrypted
1009 * (salts changed / corrupt) — callers should treat this as a
1010 * "please re-authenticate" state.
1011 *
1012 * @return string|false
1013 */
1014 public static function get_searchatlas_api_key()
1015 {
1016 if (self::$memo_api_key !== null) {
1017 return self::$memo_api_key;
1018 }
1019
1020 $general = self::get_option('general');
1021 $stored = is_array($general) ? ($general['searchatlas_api_key'] ?? '') : '';
1022
1023 // One-time migration: a non-empty legacy plaintext value is encrypted
1024 // in place the first time it is read after this feature ships.
1025 if ($stored !== '' && is_string($stored) && !self::is_encrypted_api_key($stored)) {
1026 $encrypted = self::encrypt_api_key($stored);
1027 if (self::is_encrypted_api_key($encrypted)) {
1028 $options = self::get_option();
1029 if (!is_array($options)) {
1030 $options = [];
1031 }
1032 $options['general']['searchatlas_api_key'] = $encrypted;
1033 self::set_option($options);
1034 }
1035 }
1036
1037 self::$memo_api_key = self::decrypt_api_key($stored);
1038 return self::$memo_api_key;
1039 }
1040
1041 /**
1042 * Clear the request-scoped decrypted-key memo.
1043 *
1044 * Call after any write that changes the stored searchatlas_api_key so a
1045 * subsequent read in the same request reflects the new value.
1046 */
1047 public static function invalidate_api_key_cache()
1048 {
1049 self::$memo_api_key = null;
1050 }
1051
1052 /**
1053 * Read the heartbeat throttle state from its dedicated option.
1054 *
1055 * Backfills from the legacy location (`metasync_options['general']`) the
1056 * first time the dedicated option is empty, so existing installs keep
1057 * their throttle history across the migration.
1058 */
1059 public static function get_heartbeat_throttle(): array
1060 {
1061 $value = get_option(self::heartbeat_throttle_option, []);
1062 if (is_array($value) && !empty($value)) {
1063 return $value;
1064 }
1065
1066 $general = self::get_option('general');
1067 if (is_array($general) && (array_key_exists('last_heart_beat', $general) || array_key_exists('last_heartbeat_at', $general))) {
1068 $throttle = [
1069 'last_heart_beat' => $general['last_heart_beat'] ?? 0,
1070 'last_heartbeat_at' => $general['last_heartbeat_at'] ?? null,
1071 ];
1072 update_option(self::heartbeat_throttle_option, $throttle);
1073 return $throttle;
1074 }
1075
1076 return [];
1077 }
1078
1079 /**
1080 * Merge fields into the dedicated heartbeat throttle option.
1081 *
1082 * Writes via update_option directly so the main metasync_options blob is
1083 * never read or rewritten — avoiding the read-modify-write race with
1084 * concurrent settings saves.
1085 */
1086 public static function set_heartbeat_throttle(array $fields): void
1087 {
1088 $existing = get_option(self::heartbeat_throttle_option, []);
1089 if (!is_array($existing)) {
1090 $existing = [];
1091 }
1092 $merged = array_merge($existing, $fields);
1093 update_option(self::heartbeat_throttle_option, $merged);
1094 }
1095
1096 /**
1097 * Storage prefix marking a secret value as encrypted at rest.
1098 */
1099 private const SECRET_ENC_PREFIX = 'enc_v1:';
1100
1101 /**
1102 * Derive the 32-byte AES key from existing WordPress salts.
1103 *
1104 * No new secret is stored anywhere — the key material is the concatenation
1105 * of three WordPress salts, hashed to a fixed 32 bytes. If the salts change
1106 * (e.g. wp-config regenerated) the derived key changes and previously
1107 * encrypted values can no longer be decrypted, which callers handle
1108 * gracefully rather than fataling.
1109 *
1110 * @return string 32 raw bytes.
1111 */
1112 private static function secret_crypto_key()
1113 {
1114 $material = wp_salt('secure_auth') . wp_salt('logged_in') . wp_salt('nonce');
1115 return hash('sha256', $material, true);
1116 }
1117
1118 /**
1119 * Determine whether a stored value is in the encrypted-at-rest format.
1120 *
1121 * @param mixed $value
1122 * @return bool
1123 */
1124 public static function is_encrypted_secret($value)
1125 {
1126 return is_string($value) && strncmp($value, self::SECRET_ENC_PREFIX, strlen(self::SECRET_ENC_PREFIX)) === 0;
1127 }
1128
1129 /**
1130 * Encrypt a plaintext secret (e.g. the whitelabel settings password) for
1131 * storage at rest.
1132 *
1133 * Uses AES-256-GCM (authenticated) with a random 12-byte IV. The IV, the
1134 * 16-byte GCM tag and the ciphertext are concatenated and base64-encoded
1135 * behind an `enc_v1:` prefix. An empty string is stored as-is (no secret).
1136 *
1137 * When OpenSSL is unavailable or encryption fails the plaintext is stored
1138 * unchanged (availability over hard-fail) and the degradation is logged so
1139 * it cannot go unnoticed.
1140 *
1141 * @param string $plaintext
1142 * @return string Encrypted blob, or '' when $plaintext is empty.
1143 */
1144 public static function encrypt_secret($plaintext)
1145 {
1146 $plaintext = (string) $plaintext;
1147 if ($plaintext === '') {
1148 return '';
1149 }
1150
1151 // Already encrypted — do not double-encrypt.
1152 if (self::is_encrypted_secret($plaintext)) {
1153 return $plaintext;
1154 }
1155
1156 if (!function_exists('openssl_encrypt')) {
1157 // OpenSSL unavailable — store plaintext rather than lose the secret.
1158 error_log('MetaSync: OpenSSL is unavailable — a secret was stored WITHOUT encryption at rest.');
1159 return $plaintext;
1160 }
1161
1162 $key = self::secret_crypto_key();
1163 $iv = random_bytes(12);
1164 $tag = '';
1165 $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16);
1166
1167 if ($ciphertext === false) {
1168 // Encryption failed — fall back to plaintext storage, but say so.
1169 error_log('MetaSync: Secret encryption failed — a secret was stored WITHOUT encryption at rest.');
1170 return $plaintext;
1171 }
1172
1173 return self::SECRET_ENC_PREFIX . base64_encode($iv . $tag . $ciphertext);
1174 }
1175
1176 /**
1177 * Decrypt a stored secret value.
1178 *
1179 * Accepts either the encrypted `enc_v1:` format or a legacy plaintext value
1180 * (returned unchanged, supporting installs that pre-date encryption). On any
1181 * decryption failure (salt change / corruption) returns false so callers can
1182 * degrade gracefully instead of using a bad value.
1183 *
1184 * @param mixed $value
1185 * @return string|false Plaintext, or false when an encrypted value cannot be decrypted.
1186 */
1187 public static function decrypt_secret($value)
1188 {
1189 if (!is_string($value) || $value === '') {
1190 return '';
1191 }
1192
1193 if (!self::is_encrypted_secret($value)) {
1194 // Legacy plaintext value.
1195 return $value;
1196 }
1197
1198 if (!function_exists('openssl_decrypt')) {
1199 return false;
1200 }
1201
1202 $raw = base64_decode(substr($value, strlen(self::SECRET_ENC_PREFIX)), true);
1203 if ($raw === false || strlen($raw) < 12 + 16 + 1) {
1204 return false;
1205 }
1206
1207 $iv = substr($raw, 0, 12);
1208 $tag = substr($raw, 12, 16);
1209 $ciphertext = substr($raw, 28);
1210
1211 $key = self::secret_crypto_key();
1212 $plaintext = openssl_decrypt($ciphertext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
1213
1214 if ($plaintext === false) {
1215 return false;
1216 }
1217
1218 return $plaintext;
1219 }
1220
1221 /**
1222 * Get the decrypted whitelabel settings password.
1223 *
1224 * Reads the stored (encrypted) value and returns the plaintext for
1225 * verification or authorized display. A legacy plaintext value found in
1226 * storage is migrated to the encrypted format in place (one-time migration
1227 * on read). Returns '' when no password is set or when an encrypted value
1228 * can no longer be decrypted (salts changed / corrupt) — in that case the
1229 * stored value still counts as "password set" for protection checks, but
1230 * the user password cannot authenticate until it is reset.
1231 *
1232 * @return string
1233 */
1234 public static function get_whitelabel_password()
1235 {
1236 $whitelabel = self::get_whitelabel_settings();
1237 $stored = $whitelabel['settings_password'] ?? '';
1238
1239 if (!is_string($stored) || $stored === '') {
1240 return '';
1241 }
1242
1243 // One-time migration: encrypt a legacy plaintext value in place.
1244 // This is a whole-blob read-modify-write of metasync_options during a
1245 // read request; a concurrent settings save could theoretically clobber
1246 // it, but it fires at most once per legacy install so the window is
1247 // accepted rather than adding a dedicated option.
1248 if (!self::is_encrypted_secret($stored)) {
1249 $encrypted = self::encrypt_secret($stored);
1250 if (self::is_encrypted_secret($encrypted)) {
1251 $options = self::get_option();
1252 if (!is_array($options)) {
1253 $options = [];
1254 }
1255 $options['whitelabel']['settings_password'] = $encrypted;
1256 self::set_option($options);
1257 }
1258 return $stored;
1259 }
1260
1261 $plaintext = self::decrypt_secret($stored);
1262 return $plaintext === false ? '' : $plaintext;
1263 }
1264
1265 /**
1266 * Get whitelabel settings
1267 * Helper method to retrieve whitelabel configuration
1268 */
1269 public static function get_whitelabel_settings()
1270 {
1271 $whitelabel = self::get_option('whitelabel');
1272 return is_array($whitelabel) ? $whitelabel : array(
1273 'is_whitelabel' => false,
1274 'domain' => '',
1275 'logo' => '',
1276 'logo_light' => '',
1277 'logo_dark' => '',
1278 'company_name' => '',
1279 'color_palette' => array(),
1280 'updated_at' => 0
1281 );
1282 }
1283
1284 /**
1285 * Check if whitelabel mode is enabled
1286 */
1287 public static function is_whitelabel_enabled()
1288 {
1289 $whitelabel = self::get_whitelabel_settings();
1290 return isset($whitelabel['is_whitelabel']) && $whitelabel['is_whitelabel'] === true;
1291 }
1292
1293 /**
1294 * Get effective dashboard domain for the plugin
1295 * Returns whitelabel domain if set (regardless of is_whitelabel flag), otherwise respects staging/production mode
1296 */
1297 public static function get_dashboard_domain()
1298 {
1299 $whitelabel = self::get_whitelabel_settings();
1300
1301 // Priority 1: Use whitelabel domain if it's not empty (regardless of is_whitelabel flag)
1302 if (!empty($whitelabel['domain'])) {
1303 return $whitelabel['domain'];
1304 }
1305
1306 // Priority 2: Use endpoint manager to respect staging/production mode
1307 if (class_exists('Metasync_Endpoint_Manager')) {
1308 return Metasync_Endpoint_Manager::get_endpoint('DASHBOARD_DOMAIN');
1309 }
1310
1311 // Priority 3: Fallback to production default domain
1312 return self::DASHBOARD_DOMAIN;
1313 }
1314
1315 /**
1316 * Get whitelabel logo URL
1317 * Returns the whitelabel logo URL if logo is set
1318 */
1319 public static function get_whitelabel_logo()
1320 {
1321 $whitelabel = self::get_whitelabel_settings();
1322
1323 // Return logo if it's set and is a valid URL
1324 // Users should be able to set a custom logo without requiring a custom domain
1325 if (!empty($whitelabel['logo'])) {
1326 return $whitelabel['logo'];
1327 }
1328
1329 return null;
1330 }
1331
1332 /**
1333 * Get whitelabel logo URL for light theme
1334 * Falls back to legacy 'logo' field if logo_light is not set
1335 */
1336 public static function get_whitelabel_logo_light()
1337 {
1338 $whitelabel = self::get_whitelabel_settings();
1339
1340 if (!empty($whitelabel['logo_light'])) {
1341 return $whitelabel['logo_light'];
1342 }
1343
1344 if (!empty($whitelabel['logo'])) {
1345 return $whitelabel['logo'];
1346 }
1347
1348 return null;
1349 }
1350
1351 /**
1352 * Get whitelabel logo URL for dark theme
1353 * Falls back to legacy 'logo' field if logo_dark is not set
1354 */
1355 public static function get_whitelabel_logo_dark()
1356 {
1357 $whitelabel = self::get_whitelabel_settings();
1358
1359 if (!empty($whitelabel['logo_dark'])) {
1360 return $whitelabel['logo_dark'];
1361 }
1362
1363 if (!empty($whitelabel['logo'])) {
1364 return $whitelabel['logo'];
1365 }
1366
1367 return null;
1368 }
1369
1370 /**
1371 * Get whitelabel company name
1372 * Returns the whitelabel company name if whitelabel is active and company name is set
1373 */
1374 public static function get_whitelabel_company_name()
1375 {
1376 $whitelabel = self::get_whitelabel_settings();
1377
1378 // Return company name only if whitelabel is active and company name is set
1379 if (isset($whitelabel['is_whitelabel']) && $whitelabel['is_whitelabel'] === true && !empty($whitelabel['company_name'])) {
1380 return $whitelabel['company_name'];
1381 }
1382
1383 return null;
1384 }
1385
1386 /**
1387 * Get whitelabel OTTO name
1388 * Returns the custom OTTO name if set, otherwise returns 'OTTO'
1389 */
1390 public static function get_whitelabel_otto_name()
1391 {
1392 $general_settings = self::get_option('general');
1393
1394 // Return custom OTTO name if set, otherwise fallback to 'OTTO'
1395 if (!empty($general_settings['whitelabel_otto_name'])) {
1396 return $general_settings['whitelabel_otto_name'];
1397 }
1398
1399 return 'OTTO';
1400 }
1401
1402 /**
1403 * Check if the current user has access to the plugin based on role settings
1404 *
1405 * @return bool True if user has access, false otherwise
1406 */
1407 public static function current_user_has_plugin_access()
1408 {
1409 $user = wp_get_current_user();
1410 if (!$user || !$user->exists()) {
1411 return false;
1412 }
1413
1414 // Administrators always have access
1415 if (in_array('administrator', (array) $user->roles)) {
1416 return true;
1417 }
1418
1419 // Get the plugin access roles setting
1420 $general_options = self::get_option('general');
1421
1422 // If setting not configured, default to admin-only access
1423 if (!isset($general_options['plugin_access_roles'])) {
1424 return false;
1425 }
1426
1427 $allowed_roles = $general_options['plugin_access_roles'];
1428
1429 // If it's a string (single role), convert to array
1430 if (!is_array($allowed_roles)) {
1431 $allowed_roles = array($allowed_roles);
1432 }
1433
1434 // If "all" is selected, allow access
1435 if (in_array('all', $allowed_roles)) {
1436 return true;
1437 }
1438
1439 // If array is empty, deny access (only admins allowed)
1440 if (empty($allowed_roles)) {
1441 return false;
1442 }
1443
1444 // Check if user has any of the allowed roles
1445 $user_roles = (array) $user->roles;
1446 return !empty(array_intersect($user_roles, $allowed_roles));
1447 }
1448
1449 /**
1450 * Get active JWT token for Search Atlas API authentication
1451 * Convenience method accessible from anywhere in the plugin
1452 *
1453 * @param bool $force_refresh Force generation of new token even if cached one exists
1454 * @return string|false JWT token on success, false on failure
1455 */
1456 public static function get_jwt_token($force_refresh = false)
1457 {
1458 // Delegate to admin class method
1459 return Metasync_Admin::get_active_jwt_token($force_refresh);
1460 }
1461
1462 /**
1463 * Get effective plugin name
1464 * Returns plugin name respecting white label settings
1465 * Priority: 1) white_label_plugin_name 2) company branding + base_name 3) base_name
1466 */
1467 public static function get_effective_plugin_name($base_name = 'Search Atlas')
1468 {
1469 $general_settings = self::get_option('general');
1470
1471 // Priority 1: Use white_label_plugin_name if set and not empty
1472 if (!empty($general_settings['white_label_plugin_name'])) {
1473 return $general_settings['white_label_plugin_name'];
1474 }
1475
1476 $whitelabel = self::get_whitelabel_settings();
1477
1478 // Priority 2: If whitelabel is enabled and company name is provided, enhance the plugin name
1479 if (isset($whitelabel['is_whitelabel']) && $whitelabel['is_whitelabel'] === true && !empty($whitelabel['company_name'])) {
1480 return $whitelabel['company_name'] . ' ' . $base_name;
1481 }
1482
1483 // Priority 3: Return base_name as fallback
1484 return $base_name;
1485 }
1486
1487 /**
1488 * Render a standalone info-icon tooltip (the same visual/JS pattern used by
1489 * get_field_tooltips() + render_accordion_sections() in Metasync_Settings_Fields).
1490 * Use this on any admin page whose fields are NOT rendered through that
1491 * accordion field-loop (custom render_callback pages, standalone view files) —
1492 * the trigger/hover/positioning JS in admin/js/metasync-admin.js binds to
1493 * `.metasync-tooltip-trigger` globally, so no extra wiring is needed as long
1494 * as this markup is present on a page where metasync-admin.js is enqueued
1495 * (i.e. any admin page under this plugin's menu).
1496 *
1497 * @param string $tooltip_id Unique id for this tooltip (unique per page).
1498 * @param string $text Plain-English help text (escaped internally).
1499 */
1500 public static function render_tooltip_icon($tooltip_id, $text)
1501 {
1502 echo self::get_tooltip_icon_html($tooltip_id, $text);
1503 }
1504
1505 /**
1506 * Same tooltip markup as render_tooltip_icon(), but RETURNS the HTML string
1507 * instead of echoing it. Use this when the tooltip needs to be concatenated
1508 * into another string — e.g. appended to the $title argument of
1509 * add_settings_field(), which WordPress core echoes raw next to the label.
1510 *
1511 * The whole trigger+popup pair is wrapped in its own small
1512 * `position: relative` anchor span. The popup CSS (.metasync-tooltip) is
1513 * `position: absolute; left: 100%` and positions itself relative to the
1514 * nearest positioned ancestor — on the main settings accordion that's the
1515 * `.metasync-field-label-wrapper` div, but standalone pages (custom
1516 * render_callback templates, add_settings_field titles on plain
1517 * do_settings_sections() pages, etc.) usually have no such ancestor, so
1518 * the popup would escape to whatever distant positioned element exists
1519 * on the page (rendering in the wrong corner of the screen). Wrapping
1520 * here makes every tooltip self-contained regardless of where it's placed.
1521 *
1522 * @param string $tooltip_id Unique id for this tooltip (unique per page).
1523 * @param string $text Plain-English help text (escaped internally).
1524 * @return string HTML markup for the info-icon trigger + tooltip content.
1525 */
1526 public static function get_tooltip_icon_html($tooltip_id, $text)
1527 {
1528 $html = '<span class="metasync-tooltip-anchor" style="position:relative;display:inline-block;vertical-align:middle;margin-left:8px;">';
1529 $html .= '<button type="button" class="metasync-tooltip-trigger" data-tooltip-id="' . esc_attr($tooltip_id) . '" aria-label="More information">';
1530 $html .= '<svg class="metasync-info-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
1531 $html .= '<circle cx="12" cy="12" r="10"></circle>';
1532 $html .= '<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>';
1533 $html .= '<line x1="12" y1="17" x2="12.01" y2="17"></line>';
1534 $html .= '</svg>';
1535 $html .= '</button>';
1536
1537 $html .= '<div class="metasync-tooltip" id="tooltip-' . esc_attr($tooltip_id) . '" role="tooltip">';
1538 $html .= '<div class="metasync-tooltip-arrow"></div>';
1539 $html .= '<div class="metasync-tooltip-content">' . esc_html($text) . '</div>';
1540 $html .= '</div>';
1541 $html .= '</span>';
1542
1543 return $html;
1544 }
1545
1546 /**
1547 * Centralized API Key Event Logging
1548 * Provides structured logging for all API key related events with consistent formatting
1549 *
1550 * @since 1.0.0
1551 * @param string $event_type Type of event (change, refresh, reset, etc.)
1552 * @param string $api_key_type Type of API key (plugin_auth_token, searchatlas_api_key)
1553 * @param array $details Additional details about the event
1554 * @param string $level Log level (info, warning, error)
1555 */
1556 public static function log_api_key_event($event_type, $api_key_type, $details = array(), $level = 'info')
1557 {
1558 try {
1559 // Build structured log entry
1560 $log_data = array(
1561 'timestamp' => current_time('mysql'),
1562 'event_type' => $event_type,
1563 'api_key_type' => $api_key_type,
1564 'level' => $level
1565 );
1566
1567 // Add details if provided
1568 if (!empty($details)) {
1569 $log_data['details'] = $details;
1570 }
1571
1572 // Format log message with consistent structure
1573 $log_prefix = strtoupper($level) . ' - MetaSync API Key Event';
1574 $log_message = sprintf('[%s] %s: %s (%s)',
1575 $log_data['timestamp'],
1576 $log_prefix,
1577 $event_type,
1578 $api_key_type
1579 );
1580
1581 // Add details to log message if present
1582 if (!empty($details)) {
1583 $formatted_details = array();
1584 foreach ($details as $key => $value) {
1585 $formatted_details[] = $key . ': ' . (is_string($value) ? $value : json_encode($value));
1586 }
1587 $log_message .= ' - ' . implode(', ', $formatted_details);
1588 }
1589
1590
1591 // Optionally store in database for admin dashboard (future enhancement)
1592 // This could be extended to store in a dedicated log table
1593
1594 } catch (Exception $e) {
1595 // Fallback logging if structured logging fails
1596 error_log('MetaSync API Key Event Logging Error: ' . $e->getMessage());
1597 }
1598 }
1599
1600 /**
1601 * Handle 404 error monitoring
1602 */
1603 public function handle_404_monitoring()
1604 {
1605 // Only process on frontend
1606 if (is_admin()) {
1607 return;
1608 }
1609
1610 // Check if this is a 404 error
1611 if (!is_404()) {
1612 return;
1613 }
1614
1615 // PROTECTION 0: Skip WordPress system paths — these are not "broken links"
1616 $request_uri = $_SERVER['REQUEST_URI'] ?? '';
1617 $skip_prefixes = [
1618 '/wp-json/',
1619 '/wp-admin/',
1620 '/feed/',
1621 '/xmlrpc.php',
1622 '/wp-login.php',
1623 '/wp-cron.php',
1624 ];
1625 foreach ($skip_prefixes as $prefix) {
1626 if (stripos($request_uri, $prefix) === 0) {
1627 return;
1628 }
1629 }
1630
1631 // PROTECTION 1: Exclude static assets to reduce noise
1632 $static_extensions = ['.css', '.js', '.jpg', '.jpeg', '.png', '.gif', '.ico', '.svg', '.woff', '.woff2', '.ttf', '.eot', '.map','.webp'];
1633 foreach ($static_extensions as $ext) {
1634 if (stripos($request_uri, $ext) !== false) {
1635 return; // Skip logging static asset 404s
1636 }
1637 }
1638
1639 // PROTECTION 2: Bot detection - Block known bot patterns
1640 $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
1641 $bot_patterns = ['bot', 'crawler', 'spider', 'scraper', 'curl', 'wget', 'python', 'java'];
1642 foreach ($bot_patterns as $pattern) {
1643 if (stripos($user_agent, $pattern) !== false) {
1644 // Rate limit bot 404s more aggressively
1645 $bot_rate_key = 'metasync_404_bot_rate';
1646 $bot_hits = get_transient($bot_rate_key);
1647 if ($bot_hits !== false && $bot_hits >= 10) {
1648 // Bot has hit 10+ 404s in last minute - stop logging
1649 return;
1650 }
1651 set_transient($bot_rate_key, $bot_hits === false ? 1 : $bot_hits + 1, 60);
1652 break;
1653 }
1654 }
1655
1656 // PROTECTION 3: Global rate limiting - Prevent 404 logging storms
1657 $global_rate_key = 'metasync_404_global_rate';
1658 $global_hits = get_transient($global_rate_key);
1659 if ($global_hits !== false && $global_hits >= 50) {
1660 // More than 50 404s per minute - stop logging to protect database
1661 if ($global_hits === 50) {
1662 error_log('MetaSync 404 Monitor: Rate limit exceeded - 50+ 404s per minute. Pausing logging.');
1663 }
1664 set_transient($global_rate_key, $global_hits + 1, 60);
1665 return;
1666 }
1667 set_transient($global_rate_key, $global_hits === false ? 1 : $global_hits + 1, 60);
1668
1669 // Get current URL
1670 $current_url = $this->get_current_url();
1671
1672 // PROTECTION 4: Per-URL caching - Prevent same URL from being logged repeatedly
1673 $url_cache_key = 'metasync_404_cached_' . md5($current_url);
1674 if (get_transient($url_cache_key)) {
1675 // This URL was already logged in last 5 minutes - skip DB write
1676 return;
1677 }
1678
1679 // PROTECTION 5: URL validation - Skip obviously malicious URLs
1680 if (strlen($current_url) > 500 || preg_match('/[<>{}\\\\|]/', $current_url)) {
1681 return; // Skip potentially malicious or malformed URLs
1682 }
1683
1684 // Initialize 404 monitor database
1685 require_once plugin_dir_path(dirname(__FILE__)) . '404-monitor/class-metasync-404-monitor-database.php';
1686 $db_404 = new Metasync_Error_Monitor_Database();
1687
1688 // Get user agent (sanitized)
1689 $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';
1690
1691 // Log the 404 error
1692 $result = $db_404->update([
1693 'uri' => $current_url,
1694 'user_agent' => $user_agent,
1695 'date_time' => current_time('mysql'),
1696 'hits_count' => 1
1697 ]);
1698
1699 // Cache this URL for 5 minutes to prevent repeated DB writes
1700 set_transient($url_cache_key, true, 300);
1701 }
1702
1703 /**
1704 * Get current URL
1705 */
1706 private function get_current_url()
1707 {
1708 $protocol = is_ssl() ? 'https://' : 'http://';
1709
1710 // Safely get HTTP_HOST with fallback
1711 $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
1712 if (empty($host) && isset($_SERVER['SERVER_NAME'])) {
1713 $host = $_SERVER['SERVER_NAME'];
1714 }
1715 if (empty($host)) {
1716 // Fallback to WordPress site URL if available
1717 $host = parse_url(home_url(), PHP_URL_HOST);
1718 }
1719
1720 // Safely get REQUEST_URI with fallback
1721 $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
1722
1723 // Decode URL-encoded characters
1724 $uri = urldecode($uri);
1725
1726 // Ensure URI starts with /
1727 if (!str_starts_with($uri, '/')) {
1728 $uri = '/' . $uri;
1729 }
1730
1731 return $protocol . $host . $uri;
1732 }
1733
1734 /**
1735 * Run the loader to execute all of the hooks with WordPress.
1736 *
1737 * @since 1.0.0
1738 */
1739 public function run()
1740 {
1741 $this->loader->run();
1742 }
1743
1744 /**
1745 * The name of the plugin used to uniquely identify it within the context of
1746 * WordPress and to define internationalization functionality.
1747 *
1748 * @since 1.0.0
1749 * @return string The name of the plugin.
1750 */
1751 public function get_plugin_name()
1752 {
1753 return $this->plugin_name;
1754 }
1755
1756 /**
1757 * The reference to the class that orchestrates the hooks with the plugin.
1758 *
1759 * @since 1.0.0
1760 * @return Metasync_Loader Orchestrates the hooks of the plugin.
1761 */
1762 public function get_loader()
1763 {
1764 return $this->loader;
1765 }
1766
1767 /**
1768 * Retrieve the version number of the plugin.
1769 *
1770 * @since 1.0.0
1771 * @return string The version number of the plugin.
1772 */
1773 public function get_version()
1774 {
1775 return $this->version;
1776 }
1777 }
1778