128, 'meta-title' => 128, 'meta-description' => 256, 'keywords' => 512, 'facebook-title' => 128, 'facebook-description' => 256, 'twitter-title' => 128, 'twitter-description' => 256, 'title' => 256, 'alt-text' => 256, 'caption' => 256, 'description' => 512, 'fallback' => 512, ); // =========================================================================================== \\ /** * function to return the change log of the plugin * @return array[] the change log of the plugin */ function ai4seo_get_change_log(): array { return [ [ 'date' => 'November 20th, 2025', 'version' => '2.2.2', 'important' => true, 'updates' => [ 'Bug Fixes & Maintenance: Fixed 9 minor bugs, implemented 3 usability improvements, and resolved 2 security issues.' ], ], [ 'date' => 'November 15th, 2025', 'version' => '2.2.1', 'important' => true, 'updates' => [ 'Bug Fixes & Maintenance: Fixed 5 minor bugs', ], ], [ 'date' => 'November 14th, 2025', 'version' => '2.2.0', 'important' => true, 'updates' => [ 'Changed how Credits are consumed. Credits are now charged per generated field instead of per entry. Use the “Active Meta Tags” and “Active Media Attributes” settings to control which fields are generated and how many Credits each action requires.', 'Added Focus Keyphrase generation, editing, and syncing for Yoast SEO and RankMath.', 'Added Meta Keywords generation, editing, and front-end output.', 'Added WooCommerce price inclusion modes for AI-generated metadata (Never, Fixed Price, Dynamic Price).', 'Added additional “Generate with AI” buttons inside the Gutenberg editor when RankMath is active.', 'Added “Generate with AI” buttons for Focus Keyphrase (Yoast SEO) and Focus Keyword (RankMath) inside their editors.', 'Added a filter bar to the Posts and Media views including SEO-status filters and a text search.', 'Added placeholder support for prefixes and suffixes across all syntaxes ({TITLE}, [TITLE], %%TITLE%% and their placeholder variants).', 'Added a setting to include existing values when generating metadata and media attributes (Basic Plan+).', 'Added a setting to enable enhanced entity recognition for media attributes (Pro Plan+).', 'Added a setting to enable advanced celebrity face recognition for media attributes (Premium Plan+).', 'Added configurable meta tag fallback rules to reuse existing values when no generated data is available.', 'Added a toggle to control JavaScript-based alt text injection separately from render-level injection.', 'Added a troubleshooting toggle to pause database refresh operations during debugging.', 'Added the “Active Meta Tags” setting to control which meta tags the plugin should generate.', 'Added the “Active Post Types” setting to define which post types the plugin should process.', 'Added a reminder and one-click removal option for previously generated SEO-relevant data within the SEO Autopilot modal.', 'Added a “Generate Data for X Empty Fields” button in the Metadata and Media Attribute Editors.', 'Added a “Save & edit next” button in the Metadata and Media Attribute Editors for faster sequential editing.', 'Added a “Retry all failed” quick action to the Dashboard when failed entries are detected.', 'Added Credits badges across the plugin UI to indicate the cost of generation actions.', 'Added an “SEO-Expert Concierge” card to the Dashboard with direct contact options.', 'Submit and Abort buttons are now sticky for easier access during editing.', 'Bug Fixes & Maintenance: Fixed 21 minor bugs, implemented 29 usability improvements, implemented 35 stability improvements, and resolved 8 security issues.' ], ], [ 'date' => 'September 23th, 2025', 'version' => '2.1.5', 'important' => false, 'updates' => [ 'Added a new feature to easily retrieve lost license data. Go to your Account page, click "Lost your license data?", and follow the instructions.', 'Bug Fixes & Maintenance: Fixed 2 minor bugs and implemented 4 usability improvements.' ], ], [ 'date' => 'August 28th, 2025', 'version' => '2.1.3', 'important' => true, 'updates' => [ 'Dashboard now refreshes automatically; manual page reload is no longer required.', 'Added compatibility with the SEOKey plugin.', 'Alt Text Injection is now disabled by default. To re-enable, go to Settings > Show Advanced Settings (top right) > Troubleshooting & Experimental > Alt Text Injection.', 'Added a submenu for direct plugin access via the WordPress admin menu.', 'Added a "Refresh" button to dashboard statistics. Recommended for large sites (>10,000 entries) to update statistics on demand.', 'Added a new FAQ area under Help > Troubleshooting, covering common problems and solutions.', 'Bug Fixes & Maintenance: Fixed 11 minor bugs, implemented 13 performance and usability improvements, and resolved 2 security issues.', ] ], [ 'date' => 'August 3rd, 2025', 'version' => '2.1.0', 'important' => true, 'updates' => [ 'Added "Generate with AI" buttons in the media section of the Gutenberg editor, allowing users to generate media attributes directly from the editor.', 'Improved context awareness for pages, posts, and products, especially for content with short text. Ensures AI-generated metadata is more relevant and tailored.', 'Added a setting for render-level alt text injection. This checkbox setting (enabled by default) ensures images always have the correct alt text, even if themes or other mechanisms fail to display it.', 'Added a setting for render-level image title injection. Includes a select input to choose what should be injected as the title attribute: Disabled, Inject image title, Inject alt text (default), Inject caption, or Inject image description.', 'Added a setting to the "SEO Autopilot" modal that allows users to customize the reference time used by the "Generate Metadata for" option. This gives more precise control over how new and old entries are distinguished.', 'Added an "Export/Import" button to the plugin settings, enabling users to export their configuration and import it on another website. Useful for SEO and web agencies managing multiple sites.', 'Added a "Restore Default" button to the plugin settings.', 'Added a "Show/Hide Advanced Settings" toggle in the plugin settings. Some advanced settings are now hidden by default to simplify the interface for most users.', 'Made setting descriptions more concise and user-friendly. Rearranged several settings for improved clarity and usability.', 'Private or pending posts, pages, and attachments are now ignored by the plugin, preventing them from being processed.', #'The plugin now indicates posts, pages, and attachments correctly when ignored by the SEO Autopilot, fully respecting the user\'s selection and settings.', 'Improved UX: The AI for SEO sidebar is now sticky on desktop, keeping it visible during page scrolling for easier navigation.', 'Changed how plugin notifications are handled. All notifications are now indicated by a red bubble in the admin menu. Detailed notices can be viewed in the AI for SEO dashboard.', 'Added new notifications: ', 'Bug Fixes & Maintenance: Fixed 17 minor bugs, added 6 quality-of-life improvements, implemented 3 performance optimizations, and 2 security updates.' ] ], [ 'date' => 'July 1st, 2025', 'version' => '2.0.7', 'important' => false, 'updates' => [ 'Bug Fixes & Maintenance: Fixed 7 minor bugs, added 3 quality of life improvements, and implemented security updates.' ] ], [ 'date' => 'June 23nd, 2025', 'version' => '2.0.6', 'important' => false, 'updates' => [ 'Bug Fixes & Maintenance: Fixed 3 minor bug' ] ], [ 'date' => 'June 22nd, 2025', 'version' => '2.0.5', 'important' => true, 'updates' => [ 'Added a setting to force the image upload to use either the image url only or convert the contents to base64. This can be useful for users who experience issues with the generation of media attributes.', 'Added support for AVIF image files', 'Bug Fixes & Maintenance: Fixed 11 minor bugs and implemented security updates.' ] ], [ 'date' => 'May 9th, 2025', 'version' => '2.0.4', 'important' => false, 'updates' => [ 'Added support for NextGen Gallery: The plugin now recognizes and processes media attributes for images created with the NextGen Gallery plugin. Use the new "Import" button in the media page to import all images from the NextGen Gallery into the *AI for SEO* plugin.', 'Bug Fixes & Maintenance: Fixed 2 minor bugs' ] ], [ 'date' => 'May 4th, 2025', 'version' => '2.0.3', 'important' => false, 'updates' => [ 'SEO Autopilot now more accurately reflects its current status and includes an option to immediately schedule the next run.', 'Bug Fixes & Maintenance: Fixed 15 minor bugs, corrected typos, and implemented security updates.' ] ], [ 'date' => 'April 08th, 2025', 'version' => '2.0.2', 'important' => false, 'updates' => [ 'Improved Prefix & Suffix Support: Prefixes and suffixes are now correctly applied when using the "Generate with AI" button in both the Metadata Editor and the Attachment Attributes Editor.', 'Enhanced Mobile UX: Better responsiveness and usability on the Pages / Posts and Media Files views for mobile devices.', 'Account Page Improvements: Added direct buttons for managing your active subscription and customizing Pay-As-You-Go settings.', 'Updated Help Section: Improved help content and clearer "First Steps" guidance for new users.', 'Bug Fixes & Maintenance: Fixed 11 minor bugs, corrected typos, and implemented security updates.' ] ], [ 'date' => 'March 20th, 2025', 'version' => '2.0.0', 'important' => true, 'updates' => [ 'Complete UI/UX Overhaul: The look, feel, design, layout, and navigation of the plugin have been completely redesigned.', 'Enhanced Mobile Experience: Improved usability and user experience for mobile users.', 'New "Account" Page: Users can now manage their license key directly from this page.', 'Incognito Mode: SEO and web agencies can hide the plugin from other users/admins (available in the new "Account" page).', 'White-Label Feature: SEO and web agencies can rebrand the plugin with their own name or further hide it from other users/admins (available in the new "Account" page).', 'Customizable Generator Hints: Added a setting to modify or disable generator hints in the source code for additional privacy (available in the "Account" page).', 'Privacy & Data Policy Update: Moved to the new "Account" page.', 'New Metadata Customization Options: Added settings to apply prefixes and suffixes to metadata and media attributes.', 'Advanced Media Attribute Control: New setting allows users to specify which media attributes the plugin should use.', '"SEO Autopilot" Feature: Replaces bulk generation checkboxes with a more intuitive and easy-to-use interface, directly accessible from the dashboard.', '"Recent Activity" Dashboard Section: Track all manual and automatic metadata and media attribute generations in one place.', 'Implemented new ways to get credits:
  1. * Introduced Credit Packs, allowing users to purchase additional credits as needed.
  2. * Added a Pay-As-You-Go option for automatic credit refills when running low.
  3. * All credit purchasing options are now combined in a "Get more Credits" modal, accessible from the dashboard.
', '"Guarantee" Section: Review our Guarantees and Refund Policy directly on the dashboard.', '"Recent Plugin Updates" Section: Stay informed about the latest updates from the dashboard.', 'New "Support & Feedback" Section: Easily access support and provide feedback directly from the dashboard.', 'Tons more minor improvements, bug fixes, and performance enhancements.' ] ], ]; } /** * Function to return the credits packs available for purchase * @return array[] */ function ai4seo_get_credits_packs(): array { $credits_packs = array( "price_1S6ThfHNyvfVK0r9KimFGz1E" => array( "credits_amount" => 500, "price_usd" => 9, "reference_price_usd" => 9, "price_eur" => 8, "reference_price_eur" => 8, "stripe_product_id" => "prod_RD8C2kl2gPqozh", "stripe_payment_link" => "https://buy.stripe.com/5kA00X7yF5Rc3BK8ww", ), "price_1S6TjQHNyvfVK0r9WttAsfP9" => array( "credits_amount" => 1500, "price_usd" => 19, "reference_price_usd" => 19, "price_eur" => 16, "reference_price_eur" => 16, "stripe_product_id" => "prod_RD8JI7ELrXPSWg", "stripe_payment_link" => "", ), "price_1S6TlCHNyvfVK0r9s0CZ3z1Z" => array( "credits_amount" => 5000, "price_usd" => 49, "reference_price_usd" => 49, "price_eur" => 45, "reference_price_eur" => 45, "stripe_product_id" => "prod_RD8KgysYBIyi2Z", "stripe_payment_link" => "", ), ); # Large Credit Packs for users in group B-E if ((!ai4seo_robhub_api()->is_group('a') && !ai4seo_robhub_api()->is_group('f')) || isset($_GET["ai4seo_show_all_credits_packs"])) { $credits_packs += array( "price_1R4N2vHNyvfVK0r9s3WhZxCl" => array( "credits_amount" => 15000, "price_usd" => 179.00, "reference_price_usd" => 179.00, "stripe_product_id" => "prod_RD8LcGkIHN7O0K", "stripe_payment_link" => "", ), "price_1R4MwkHNyvfVK0r9sgPn4ppM" => array( "credits_amount" => 50000, "price_usd" => 499.00, "reference_price_usd" => 499.00, "stripe_product_id" => "prod_RD8LWAmW1fQ32n", "stripe_payment_link" => "", ), ); } return $credits_packs; } /** * function to get the SVG icons used in the plugin * @return string[] associative array with icon names as keys and SVG strings as values */ function ai4seo_get_svg_tags(): array { return array( "ai-for-seo-main-menu-icon" => ' ', "all-in-one-seo" => '', "angle-down" => '', "arrow-right" => '', "arrow-up-right-from-square" => '', "bars-sort" => '', "betheme" => 'Be', "bolt" => '', "caret-down" => '', "caret-up" => '', "check" => '', 'circle' => '', 'circle-check' => '', "circle-plus" => '', "circle-question" => '', 'crown' => '', "circle-up" => '', "circle-xmark" => '', "code" => '', "copy" => '', "download" => '', "envelope" => '', "eye" => '', "eye-slash" => '', "file-arrow-down" => '', "file-arrow-up" => '', "file-export" => '', 'flag' => '', "gear" => '', "gift" => '', "globe" => '', "handshake" => '', 'hashtag' => '', "headline" => '', 'hourglass-start' => '', 'image' => '', 'image-slash' => '', 'key' => '', 'key-slash' => '', 'list' => '', "magnifying-glass" => ' ', "rank-math" => '', "robot" => '', "rotate" => '', "pen-to-square" => '', "rocket" => '', "rocket-chat" => '', "seopress" => '', "shopping-cart" => '', "sliders" => '', "square-check" => '', "square-facebook" => '', "square-twitter-x" => '', "square-xmark" => '', "star" => '', "stripe" => '', "subtitle" => '', "subtitles" => '', "triangle-exclamation" => '', "xmark" => '', "yoast" => '', "woocommerce" => 'WooCommerce Logoimage/svg+xml' ); } const AI4SEO_STRIPE_BILLING_URL = "https://aiforseo.ai/manage-plan"; const AI4SEO_POST_TYPES_PLUGIN_PAGE_NAME = "post"; // Constants for the wp_options entries const AI4SEO_FULLY_COVERED_METADATA_POST_IDS_OPTION_NAME = "ai4seo_fully_covered_metadata_post_ids"; const AI4SEO_MISSING_METADATA_POST_IDS_OPTION_NAME = "ai4seo_missing_metadata_post_ids"; const AI4SEO_PENDING_METADATA_POST_IDS_OPTION_NAME = "ai4seo_pending_metadata_post_ids"; const AI4SEO_PROCESSING_METADATA_POST_IDS_OPTION_NAME = "ai4seo_processing_metadata_post_ids"; const AI4SEO_GENERATED_METADATA_POST_IDS_OPTION_NAME = "ai4seo_generated_metadata_post_ids"; const AI4SEO_FAILED_METADATA_POST_IDS_OPTION_NAME = "ai4seo_failed_metadata_post_ids"; const AI4SEO_LATEST_ACTIVITY_OPTION_NAME = "_ai4seo_latest_activity"; # todo: replace with database table const AI4SEO_FULLY_COVERED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_fully_covered_attachment_attributes_post_ids"; const AI4SEO_MISSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_missing_attachment_attributes_post_ids"; const AI4SEO_PENDING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_pending_attachment_attributes_post_ids"; const AI4SEO_PROCESSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_processing_attachment_attributes_post_ids"; const AI4SEO_GENERATED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_generated_attachment_attributes_post_ids"; const AI4SEO_FAILED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME = "ai4seo_failed_attachment_attributes_post_ids"; const AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_OPTION_NAME = "_ai4seo_additional_tos_accept_details"; const AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_LAST_TRY_TIMESTAMP_OPTION_NAME = "_ai4seo_additional_tos_accept_details_last_try_timestamp"; // all wp_options that contain post ids const AI4SEO_ALL_POST_ID_OPTIONS = array( AI4SEO_MISSING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_GENERATED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_FULLY_COVERED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_PENDING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_PROCESSING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_FAILED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_MISSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_GENERATED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_FULLY_COVERED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_PENDING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_PROCESSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_FAILED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, ); // all wp_options that define the seo coverage // a post id cannot be in MISSING and one of the other options at the same time const AI4SEO_SEO_COVERAGE_POST_ID_OPTIONS = array( AI4SEO_MISSING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_FULLY_COVERED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_GENERATED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_MISSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_FULLY_COVERED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_GENERATED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, ); // all wp-Options that define the generation status of a given post // a post id cannot be in PENDING and PROCESSING at the same time const AI4SEO_GENERATION_STATUS_POST_ID_OPTIONS = array( AI4SEO_PENDING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_PROCESSING_METADATA_POST_IDS_OPTION_NAME, AI4SEO_FAILED_METADATA_POST_IDS_OPTION_NAME, AI4SEO_PENDING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_PROCESSING_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, AI4SEO_FAILED_ATTACHMENT_ATTRIBUTES_POST_IDS_OPTION_NAME, ); // === CRON JOBS ========================================================================================== \\ const AI4SEO_BULK_GENERATION_CRON_JOB_NAME = "ai4seo_automated_generation_cron_job"; const AI4SEO_ANALYSE_PLUGIN_PERFORMANCE_CRON_JOB_NAME = "ai4seo_analyze_plugin_performance"; // === THIRD PARTY PLUGINS ================================================================================= \\ // Constants for third party plugin identifiers // editors const AI4SEO_THIRD_PARTY_PLUGIN_ELEMENTOR = "elementor"; // shops const AI4SEO_THIRD_PARTY_PLUGIN_WOOCOMMERCE = "woocommerce"; // traditional seo plugins const AI4SEO_THIRD_PARTY_PLUGIN_YOAST_SEO = "yoast-seo"; const AI4SEO_THIRD_PARTY_PLUGIN_ALL_IN_ONE_SEO = "all-in-one-seo-pack"; const AI4SEO_THIRD_PARTY_PLUGIN_THE_SEO_FRAMEWORK = "the-seo-framework"; const AI4SEO_THIRD_PARTY_PLUGIN_RANK_MATH = "rank-math"; const AI4SEO_THIRD_PARTY_PLUGIN_SEOPRESS = "seopress"; const AI4SEO_THIRD_PARTY_PLUGIN_SEO_SIMPLE_PACK = "seo-simple-pack"; const AI4SEO_THIRD_PARTY_PLUGIN_SLIM_SEO = "slim-seo"; const AI4SEO_THIRD_PARTY_PLUGIN_SQUIRRLY_SEO = "squirrly-seo"; const AI4SEO_THIRD_PARTY_PLUGIN_SEO_KEY = "seo-key"; // editors + seo plugins const AI4SEO_THIRD_PARTY_PLUGIN_BETHEME = "betheme"; // social media plugins const AI4SEO_THIRD_PARTY_PLUGIN_BLOG2SOCIAL = "blog2social"; // multi-language plugins const AI4SEO_THIRD_PARTY_PLUGIN_WPML = "wpml"; // attachments / images plugins const AI4SEO_THIRD_PARTY_PLUGIN_NEXTGEN_GALLERY = "nextgen-gallery"; // details for the third party seo plugins function ai4seo_get_third_party_seo_plugin_details(): array { return array( AI4SEO_THIRD_PARTY_PLUGIN_YOAST_SEO => array( 'name' => 'Yoast SEO', 'icon' => 'yoast', 'icon-css-class' => 'ai4seo-purple-icon', 'generation-field-postmeta-keys' => array( 'focus-keyphrase' => '_yoast_wpseo_focuskw', 'meta-title' => '_yoast_wpseo_title', 'meta-description' => '_yoast_wpseo_metadesc', 'facebook-title' => '_yoast_wpseo_opengraph-title', 'facebook-description' => '_yoast_wpseo_opengraph-description', 'twitter-title' => '_yoast_wpseo_twitter-title', 'twitter-description' => '_yoast_wpseo_twitter-description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_BETHEME => array( 'name' => 'BeTheme', 'icon' => 'betheme', 'icon-css-class' => 'ai4seo-blue-icon', 'generation-field-postmeta-keys' => array( 'meta-title' => 'mfn-meta-seo-title', 'meta-description' => 'mfn-meta-seo-description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_ALL_IN_ONE_SEO => array( 'name' => 'All in One SEO', 'icon' => 'all-in-one-seo', 'generation-field-postmeta-keys' => array( # workaround: in addition, this plugin saves its data into wp_ai4seo_posts 'meta-title' => '_aioseo_title', 'meta-description' => '_aioseo_description', 'facebook-title' => '_aioseo_og_title', 'facebook-description' => '_aioseo_og_description', 'twitter-title' => '_aioseo_twitter_title', 'twitter-description' => '_aioseo_twitter_description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_RANK_MATH => array( 'name' => 'Rank Math', 'icon' => 'rank-math', 'icon-css-class' => 'ai4seo-purple-icon', 'seo-score-postmeta-key' => 'rank_math_seo_score', # todo: make this dynamic 'generation-field-postmeta-keys' => array( 'focus-keyphrase' => 'rank_math_focus_keyword', 'meta-title' => 'rank_math_title', 'meta-description' => 'rank_math_description', 'facebook-title' => 'rank_math_facebook_title', 'facebook-description' => 'rank_math_facebook_description', 'twitter-title' => 'rank_math_twitter_title', 'twitter-description' => 'rank_math_twitter_description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_SEO_SIMPLE_PACK => array( 'name' => 'SEO Simple Pack', 'generation-field-postmeta-keys' => array( 'meta-title' => 'ssp_meta_title', 'meta-description' => 'ssp_meta_description', 'facebook-title' => 'ssp_meta_title', 'facebook-description' => 'ssp_meta_description', 'twitter-title' => 'ssp_meta_title', 'twitter-description' => 'ssp_meta_description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_SEOPRESS => array( 'name' => 'SEOPress', 'icon' => 'seopress', 'generation-field-postmeta-keys' => array( 'meta-title' => '_seopress_titles_title', 'meta-description' => '_seopress_titles_desc', 'facebook-title' => '_seopress_social_fb_title', 'facebook-description' => '_seopress_social_fb_desc', 'twitter-title' => '_seopress_social_twitter_title', 'twitter-description' => '_seopress_social_twitter_desc', ), ), AI4SEO_THIRD_PARTY_PLUGIN_SLIM_SEO => array( 'name' => 'Slim SEO', 'generation-field-postmeta-keys' => array( 'meta-title' => '_ai4seo_workaround', 'meta-description' => '_ai4seo_workaround', ), ), AI4SEO_THIRD_PARTY_PLUGIN_SQUIRRLY_SEO => array( 'name' => 'Squirrly SEO', 'generation-field-postmeta-keys' => array( 'meta-title' => '_ai4seo_workaround', 'meta-description' => '_ai4seo_workaround', 'facebook-title' => '_ai4seo_workaround', 'facebook-description' => '_ai4seo_workaround', 'twitter-title' => '_ai4seo_workaround', 'twitter-description' => '_ai4seo_workaround', ), ), AI4SEO_THIRD_PARTY_PLUGIN_THE_SEO_FRAMEWORK => array( 'name' => 'The SEO Framework', 'generation-field-postmeta-keys' => array( 'meta-title' => '_genesis_title', 'meta-description' => '_genesis_description', 'facebook-title' => '_open_graph_title', 'facebook-description' => '_open_graph_description', 'twitter-title' => '_twitter_title', 'twitter-description' => '_twitter_description', ), ), AI4SEO_THIRD_PARTY_PLUGIN_BLOG2SOCIAL => array( 'name' => 'Blog2Social', 'generation-field-postmeta-keys' => array( 'facebook-title' => '_ai4seo_workaround', 'facebook-description' => '_ai4seo_workaround', 'twitter-title' => '_ai4seo_workaround', 'twitter-description' => '_ai4seo_workaround', ), ), AI4SEO_THIRD_PARTY_PLUGIN_SEO_KEY => array( 'name' => 'SEOKEY', 'generation-field-postmeta-keys' => array( 'meta-title' => 'seokey-metatitle', 'meta-description' => 'seokey-metadesc', ), ), ); } function ai4seo_get_allowed_currencies(): array { return array( "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTC", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLF", "CLP", "CNH", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "YER", "ZAR", "ZMW", "ZWL" ); } // === PLUGIN'S SETTINGS ================================================================================= \\ /** Check .agent/rules/settings.md for a guide on how to use Plugin's settings */ // SETTINGS FROM THE SETTINGS PAGE const AI4SEO_SETTING_SHOW_ADVANCED_SETTINGS = 'show_advanced_settings'; const AI4SEO_SETTING_VISIBLE_META_TAGS = 'visible_meta_tags'; # deprecated < 2.2.0 const AI4SEO_SETTING_ACTIVE_META_TAGS = 'active_meta_tags'; # added in 2.2.0 const AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE = 'metadata_fallback_meta_title'; const AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION = 'metadata_fallback_meta_description'; const AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE = 'metadata_fallback_facebook_title'; const AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION = 'metadata_fallback_facebook_description'; const AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE = 'metadata_fallback_twitter_title'; const AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION = 'metadata_fallback_twitter_description'; const AI4SEO_SETTING_META_TAG_OUTPUT_MODE = 'meta_tags_output_method'; const AI4SEO_SETTING_APPLY_CHANGES_TO_THIRD_PARTY_SEO_PLUGINS = 'apply_changes_to_this_party_seo_plugins'; const AI4SEO_SETTING_SYNC_ONLY_THESE_METADATA = 'sync_only_these_metadata'; const AI4SEO_SETTING_METADATA_GENERATION_LANGUAGE = 'metadata_generation_language'; const AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_GENERATION_LANGUAGE = 'attachment_attributes_generation_language'; const AI4SEO_SETTING_ACTIVE_ATTACHMENT_ATTRIBUTES = 'active_attachment_attributes'; const AI4SEO_SETTING_OVERWRITE_EXISTING_METADATA = 'overwrite_existing_metadata'; const AI4SEO_SETTING_OVERWRITE_EXISTING_ATTACHMENT_ATTRIBUTES = 'overwrite_existing_attachment_attributes'; const AI4SEO_SETTING_GENERATE_METADATA_FOR_FULLY_COVERED_ENTRIES = 'generate_metadata_for_fully_covered_entries'; const AI4SEO_SETTING_GENERATE_ATTACHMENT_ATTRIBUTES_FOR_FULLY_COVERED_ENTRIES = 'generate_attachment_attributes_for_fully_covered_entries'; const AI4SEO_SETTING_ENABLE_RENDER_LEVEL_ALT_TEXT_INJECTION = 'enable_render_level_alt_text_injection'; const AI4SEO_SETTING_ENABLE_JS_ALT_TEXT_INJECTION = 'enable_js_alt_text_injection'; const AI4SEO_SETTING_IMAGE_TITLE_INJECTION_MODE = 'image_title_injection_mode'; const AI4SEO_SETTING_METADATA_PREFIXES = 'metadata_prefix'; const AI4SEO_SETTING_METADATA_SUFFIXES = 'metadata_suffix'; const AI4SEO_SETTING_INCLUDE_PRODUCT_PRICE_IN_METADATA = 'include_product_price_in_metadata'; const AI4SEO_SETTING_USE_EXISTING_METADATA_AS_REFERENCE = 'use_existing_metadata_as_reference'; const AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_PREFIXES = 'attachment_attributes_prefix'; const AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_SUFFIXES = 'attachment_attributes_suffix'; const AI4SEO_SETTING_USE_EXISTING_ATTACHMENT_ATTRIBUTES_AS_REFERENCE = 'use_existing_attachment_attributes_as_reference'; const AI4SEO_SETTING_ENABLE_ENHANCED_ENTITY_RECOGNITION = 'enable_enhanced_entity_recognition'; const AI4SEO_SETTING_ENABLE_ENHANCED_CELEBRITY_RECOGNITION = 'enable_enhanced_celebrity_recognition'; const AI4SEO_SETTING_IMAGE_UPLOAD_METHOD = 'image_upload_method'; const AI4SEO_SETTING_ALLOWED_USER_ROLES = 'allowed_user_roles'; const AI4SEO_SETTING_DISABLED_POST_TYPES = 'disabled_post_types'; const AI4SEO_SETTING_BULK_GENERATION_DURATION = 'bulk_generation_duration'; const AI4SEO_SETTING_DISABLE_HEAVY_DB_OPERATIONS = 'disable_heavy_db_operations'; const AI4SEO_ALL_SETTING_PAGE_SETTINGS = array( AI4SEO_SETTING_SHOW_ADVANCED_SETTINGS, AI4SEO_SETTING_ACTIVE_META_TAGS, AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE, AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION, AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE, AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION, AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE, AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION, AI4SEO_SETTING_META_TAG_OUTPUT_MODE, AI4SEO_SETTING_APPLY_CHANGES_TO_THIRD_PARTY_SEO_PLUGINS, AI4SEO_SETTING_SYNC_ONLY_THESE_METADATA, AI4SEO_SETTING_METADATA_GENERATION_LANGUAGE, AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_GENERATION_LANGUAGE, AI4SEO_SETTING_ACTIVE_ATTACHMENT_ATTRIBUTES, AI4SEO_SETTING_OVERWRITE_EXISTING_METADATA, AI4SEO_SETTING_OVERWRITE_EXISTING_ATTACHMENT_ATTRIBUTES, AI4SEO_SETTING_GENERATE_METADATA_FOR_FULLY_COVERED_ENTRIES, AI4SEO_SETTING_GENERATE_ATTACHMENT_ATTRIBUTES_FOR_FULLY_COVERED_ENTRIES, AI4SEO_SETTING_ENABLE_RENDER_LEVEL_ALT_TEXT_INJECTION, AI4SEO_SETTING_ENABLE_JS_ALT_TEXT_INJECTION, AI4SEO_SETTING_IMAGE_TITLE_INJECTION_MODE, AI4SEO_SETTING_METADATA_PREFIXES, AI4SEO_SETTING_METADATA_SUFFIXES, AI4SEO_SETTING_INCLUDE_PRODUCT_PRICE_IN_METADATA, AI4SEO_SETTING_USE_EXISTING_METADATA_AS_REFERENCE, AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_PREFIXES, AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_SUFFIXES, AI4SEO_SETTING_USE_EXISTING_ATTACHMENT_ATTRIBUTES_AS_REFERENCE, AI4SEO_SETTING_ENABLE_ENHANCED_ENTITY_RECOGNITION, AI4SEO_SETTING_ENABLE_ENHANCED_CELEBRITY_RECOGNITION, AI4SEO_SETTING_IMAGE_UPLOAD_METHOD, AI4SEO_SETTING_ALLOWED_USER_ROLES, AI4SEO_SETTING_DISABLED_POST_TYPES, AI4SEO_SETTING_BULK_GENERATION_DURATION, AI4SEO_SETTING_DISABLE_HEAVY_DB_OPERATIONS, ); // SETTINGS FROM THE SEO AUTOPILOT MODAL const AI4SEO_SETTING_ENABLED_BULK_GENERATION_POST_TYPES = 'enabled_bulk_generation_post_types'; const AI4SEO_SETTING_BULK_GENERATION_ORDER = 'bulk_generation_order'; const AI4SEO_SETTING_BULK_GENERATION_NEW_OR_EXISTING_FILTER = 'bulk_generation_new_or_existing_filter'; const AI4SEO_ALL_SEO_AUTOPILOT_SETTINGS = array( AI4SEO_SETTING_ENABLED_BULK_GENERATION_POST_TYPES, AI4SEO_SETTING_BULK_GENERATION_ORDER, AI4SEO_SETTING_BULK_GENERATION_NEW_OR_EXISTING_FILTER, ); // SETTINGS FROM THE ACCOUNT PAGE const AI4SEO_SETTING_ENABLE_INCOGNITO_MODE = 'enable_incognito_mode'; const AI4SEO_SETTING_INCOGNITO_MODE_USER_ID = 'incognito_mode_user_id'; const AI4SEO_SETTING_ENABLE_WHITE_LABEL = 'enable_white_label'; const AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_NAME = 'installed_plugins_plugin_name'; const AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_DESCRIPTION = 'installed_plugins_plugin_description'; const AI4SEO_SETTING_ADD_GENERATOR_HINTS = 'add_generator_hints'; const AI4SEO_SETTING_META_TAGS_BLOCK_STARTING_HINT = 'meta_tags_block_starting_hint'; const AI4SEO_SETTING_META_TAGS_BLOCK_ENDING_HINT = 'meta_tags_block_ending_hint'; const AI4SEO_ALL_ACCOUNT_PAGE_SETTINGS = array( AI4SEO_SETTING_ENABLE_INCOGNITO_MODE, AI4SEO_SETTING_INCOGNITO_MODE_USER_ID, AI4SEO_SETTING_ENABLE_WHITE_LABEL, AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_NAME, AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_DESCRIPTION, AI4SEO_SETTING_ADD_GENERATOR_HINTS, AI4SEO_SETTING_META_TAGS_BLOCK_STARTING_HINT, AI4SEO_SETTING_META_TAGS_BLOCK_ENDING_HINT, ); // SETTINGS FROM THE GET MORE CREDITS MODAL const AI4SEO_SETTING_PREFERRED_CURRENCY = 'preferred_currency'; const AI4SEO_SETTING_PAYG_ENABLED = 'payg_enabled'; const AI4SEO_SETTING_PAYG_STRIPE_PRICE_ID = 'payg_stripe_price_id'; const AI4SEO_SETTING_PAYG_DAILY_BUDGET = 'payg_daily_budget'; const AI4SEO_SETTING_PAYG_MONTHLY_BUDGET = 'payg_monthly_budget'; const AI4SEO_ALL_GET_MORE_CREDITS_MODAL_SETTINGS = array( AI4SEO_SETTING_PREFERRED_CURRENCY, AI4SEO_SETTING_PAYG_ENABLED, AI4SEO_SETTING_PAYG_STRIPE_PRICE_ID, AI4SEO_SETTING_PAYG_DAILY_BUDGET, AI4SEO_SETTING_PAYG_MONTHLY_BUDGET, ); // NOT IMPORTABLE SETTINGS const AI4SEO_NOT_IMPORTABLE_SETTINGS = array( AI4SEO_SETTING_INCOGNITO_MODE_USER_ID ); // DEFAULT SETTINGS const AI4SEO_DEFAULT_SETTINGS = array( AI4SEO_SETTING_SHOW_ADVANCED_SETTINGS => "hide", AI4SEO_SETTING_BULK_GENERATION_DURATION => 60, AI4SEO_SETTING_META_TAG_OUTPUT_MODE => "replace", AI4SEO_SETTING_APPLY_CHANGES_TO_THIRD_PARTY_SEO_PLUGINS => array(AI4SEO_THIRD_PARTY_PLUGIN_YOAST_SEO, AI4SEO_THIRD_PARTY_PLUGIN_RANK_MATH, AI4SEO_THIRD_PARTY_PLUGIN_SEOPRESS, AI4SEO_THIRD_PARTY_PLUGIN_THE_SEO_FRAMEWORK, AI4SEO_THIRD_PARTY_PLUGIN_SEO_SIMPLE_PACK, AI4SEO_THIRD_PARTY_PLUGIN_SEO_KEY), AI4SEO_SETTING_SYNC_ONLY_THESE_METADATA => array("focus-keyphrase", "meta-title", "meta-description", "facebook-title", "facebook-description", "twitter-title", "twitter-description"), AI4SEO_SETTING_ALLOWED_USER_ROLES => array("administrator"), AI4SEO_SETTING_DISABLED_POST_TYPES => array(), AI4SEO_SETTING_ENABLED_BULK_GENERATION_POST_TYPES => array(), AI4SEO_SETTING_BULK_GENERATION_ORDER => "newest", AI4SEO_SETTING_BULK_GENERATION_NEW_OR_EXISTING_FILTER => "both", AI4SEO_SETTING_METADATA_GENERATION_LANGUAGE => "auto", AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_GENERATION_LANGUAGE => "auto", AI4SEO_SETTING_ACTIVE_META_TAGS => array("focus-keyphrase", "meta-title", "meta-description", "keywords", "facebook-title", "facebook-description", "twitter-title", "twitter-description"), AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE => 'no-fallback', AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION => 'no-fallback', AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE => 'no-fallback', AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION => 'no-fallback', AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE => 'no-fallback', AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION => 'no-fallback', AI4SEO_SETTING_ACTIVE_ATTACHMENT_ATTRIBUTES => array("title", "alt-text", "caption", "description"), AI4SEO_SETTING_OVERWRITE_EXISTING_METADATA => array(), AI4SEO_SETTING_OVERWRITE_EXISTING_ATTACHMENT_ATTRIBUTES => array(), AI4SEO_SETTING_GENERATE_METADATA_FOR_FULLY_COVERED_ENTRIES => false, AI4SEO_SETTING_INCLUDE_PRODUCT_PRICE_IN_METADATA => 'never', AI4SEO_SETTING_USE_EXISTING_METADATA_AS_REFERENCE => false, AI4SEO_SETTING_GENERATE_ATTACHMENT_ATTRIBUTES_FOR_FULLY_COVERED_ENTRIES => false, AI4SEO_SETTING_ENABLE_RENDER_LEVEL_ALT_TEXT_INJECTION => false, AI4SEO_SETTING_ENABLE_JS_ALT_TEXT_INJECTION => false, AI4SEO_SETTING_DISABLE_HEAVY_DB_OPERATIONS => false, AI4SEO_SETTING_USE_EXISTING_ATTACHMENT_ATTRIBUTES_AS_REFERENCE => false, AI4SEO_SETTING_ENABLE_ENHANCED_ENTITY_RECOGNITION => true, AI4SEO_SETTING_ENABLE_ENHANCED_CELEBRITY_RECOGNITION => false, AI4SEO_SETTING_IMAGE_TITLE_INJECTION_MODE => "disabled", AI4SEO_SETTING_METADATA_PREFIXES => array( "meta-title" => "", "meta-description" => "", "facebook-title" => "", "facebook-description" => "", "twitter-title" => "", "twitter-description" => "", ), AI4SEO_SETTING_METADATA_SUFFIXES => array( "meta-title" => "", "meta-description" => "", "facebook-title" => "", "facebook-description" => "", "twitter-title" => "", "twitter-description" => "", ), AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_PREFIXES => array( "title" => "", "alt-text" => "", "caption" => "", "description" => "", ), AI4SEO_SETTING_ATTACHMENT_ATTRIBUTES_SUFFIXES => array( "title" => "", "alt-text" => "", "caption" => "", "description" => "", ), AI4SEO_SETTING_IMAGE_UPLOAD_METHOD => "auto", AI4SEO_SETTING_ENABLE_INCOGNITO_MODE => false, AI4SEO_SETTING_INCOGNITO_MODE_USER_ID => "0", AI4SEO_SETTING_ENABLE_WHITE_LABEL => false, AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_NAME => AI4SEO_PLUGIN_NAME, AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_DESCRIPTION => AI4SEO_PLUGIN_DESCRIPTION, AI4SEO_SETTING_ADD_GENERATOR_HINTS => true, AI4SEO_SETTING_META_TAGS_BLOCK_STARTING_HINT => "[{NAME}] This site is optimized with the {NAME} plugin v{VERSION} - {WEBSITE}", AI4SEO_SETTING_META_TAGS_BLOCK_ENDING_HINT => "[{NAME}] End", AI4SEO_SETTING_PREFERRED_CURRENCY => "usd", AI4SEO_SETTING_PAYG_ENABLED => false, AI4SEO_SETTING_PAYG_STRIPE_PRICE_ID => "", # defaults to previously purchased pack AI4SEO_SETTING_PAYG_DAILY_BUDGET => 0, # defaults to cost credits pack AI4SEO_SETTING_PAYG_MONTHLY_BUDGET => 0, # defaults to recommended credits pack entry, ); const AI4SEO_METADATA_FALLBACK_MAPPING = array( 'meta-title' => AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE, 'meta-description' => AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION, 'facebook-title' => AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE, 'facebook-description' => AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION, 'twitter-title' => AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE, 'twitter-description' => AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION, ); $ai4seo_settings = AI4SEO_DEFAULT_SETTINGS; $ai4seo_fallback_allowed_user_roles = array("administrator" => "Administrator"); $ai4seo_forbidden_allowed_user_roles = array("subscriber", "customer"); $ai4seo_can_manage_this_plugin = null; # cache variable const AI4SEO_AVAILABLE_BULK_GENERATION_ORDER_OPTIONS = array("random", "oldest", "newest"); const AI4SEO_AVAILABLE_BULK_GENERATION_NEW_OR_EXISTING_FILTER_OPTIONS = array("both", "new", "existing"); // init parameters with translation add_action("init", function() { define('AI4SEO_BULK_GENERATION_ORDER_TRANSLATED_OPTIONS', array( "random" => __("Random", "ai-for-seo"), "oldest" => __("Oldest to newest", "ai-for-seo"), "newest" => __("Newest to oldest", "ai-for-seo") ) ); define('AI4SEO_BULK_GENERATION_NEW_OR_EXISTING_FILTER_TRANSLATED_OPTIONS', array( "both" => __("New entries and existing entries", "ai-for-seo"), "new" => __("New entries only", "ai-for-seo"), "existing" => __("Existing entries only", "ai-for-seo") ) ); }, 9); // === ENVIRONMENTAL VARIABLES ================================================================================= \\ const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION = "last_known_plugin_version"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_CRON_JOB_CALL = "last_cronjob_call"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_SPECIFIC_CRON_JOB_CALLS = "last_specific_cronjob_call"; const AI4SEO_ENVIRONMENTAL_VARIABLE_CRON_JOB_STATUS_LIST = "cron_job_status_list"; const AI4SEO_ENVIRONMENTAL_VARIABLE_CRON_JOB_STATUS_LAST_UPDATE_TIMES = "cron_job_status_last_update_times"; const AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_TOC_AND_PP_ACCEPTED_TIME = "tos_toc_and_pp_accepted_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_TOS_DETAILS_CHECKSUM = "last_tos_details_checksum"; const AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_LAST_MODAL_OPEN_TIME = "tos_last_modal_open_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED = "enhanced_reporting_accepted"; const AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED_TIME = "enhanced_reporting_accepted_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_REVOKED_TIME = "enhanced_reporting_revoke_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_WEBSITE_TOC_AND_PP_UPDATE_TIME = "last_website_toc_and_pp_update_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_BULK_GENERATION_NEW_OR_EXISTING_FILTER_REFERENCE_TIME = "bulk_generation_new_or_existing_filter_reference_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_HAS_PURCHASED_SOMETHING = "has_purchased_something"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_SEO_AUTOPILOT_SET_UP_TIME = "last_seo_autopilot_set_up_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_UNREAD_NOTIFICATIONS_COUNT = "unread_notifications_count"; const AI4SEO_ENVIRONMENTAL_VARIABLE_NUM_POSTS_TABLE_ENTRIES = "num_posts_table_entries"; const AI4SEO_ENVIRONMENTAL_VARIABLE_CURRENT_DISCOUNT = "current_discount"; const AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME = "plugin_activation_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_PERFORMANCE_ANALYSIS_TIME = "last_performance_analysis_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_PAYG_STATUS = "payg_status"; const AI4SEO_ENVIRONMENTAL_VARIABLE_JUST_PURCHASED_SOMETHING_TIME = "just_purchased_something_time"; const AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_LAST_POST_ID = "posts_table_analysis_last_post_id"; const AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_STATE = "posts_table_analysis_state"; const AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_START_TIME = "posts_table_analysis_start_time"; const AI4SEO_NOTIFICATION_AUTO_DISMISS_DAYS = 7; const AI4SEO_DEFAULT_ENVIRONMENTAL_VARIABLES = array( AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION => "0.0.0", AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_CRON_JOB_CALL => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_CRON_JOB_STATUS_LIST => array(), AI4SEO_ENVIRONMENTAL_VARIABLE_CRON_JOB_STATUS_LAST_UPDATE_TIMES => array(), AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_LAST_MODAL_OPEN_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_SPECIFIC_CRON_JOB_CALLS => array(), AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_TOC_AND_PP_ACCEPTED_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED => false, AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_REVOKED_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_WEBSITE_TOC_AND_PP_UPDATE_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_TOS_DETAILS_CHECKSUM => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_BULK_GENERATION_NEW_OR_EXISTING_FILTER_REFERENCE_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_HAS_PURCHASED_SOMETHING => false, AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_SEO_AUTOPILOT_SET_UP_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_UNREAD_NOTIFICATIONS_COUNT => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_NUM_POSTS_TABLE_ENTRIES => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_CURRENT_DISCOUNT => array(), AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_PERFORMANCE_ANALYSIS_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_PAYG_STATUS => 'idle', AI4SEO_ENVIRONMENTAL_VARIABLE_JUST_PURCHASED_SOMETHING_TIME => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_LAST_POST_ID => 0, AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_STATE => 'idle', AI4SEO_ENVIRONMENTAL_VARIABLE_POSTS_TABLE_ANALYSIS_START_TIME => 0, ); $ai4seo_environmental_variables = AI4SEO_DEFAULT_ENVIRONMENTAL_VARIABLES; $ai4seo_persistent_does_user_need_to_accept_tos_toc_and_pp = null; # cache variable $ai4seo_scripts_version_number = isset($_GET["ai4seo_debug_uncached_assets"]) && $_GET["ai4seo_debug_uncached_assets"] ? time() : AI4SEO_PLUGIN_VERSION_NUMBER; $ai4seo_user_has_at_least_plan = array(); # cache variable to store if user has at least a specific plan // used to store various details about all supported metadata fields to use it on many places throughout the plugin add_action('init', function() { define('AI4SEO_METADATA_DETAILS', array( "focus-keyphrase" => array( "name" => esc_html__("Focus Keyphrase", "ai-for-seo"), "icon" => "flag", "input" => "textfield", "hint" => esc_html__("Best Practice: A primary SEO keyword or keyphrase that best represents the main topic of this entry. It should be specific, relevant, and reflect the content accurately to help improve search engine rankings.

The focus keyphrase is added to the meta title and meta description for best SEO results. Make sure to first generate the keyphrase before generating the meta title and meta description or just generate all at once.", "ai-for-seo"), "api-identifier" => "focus_keyphrase", "flat-credits-cost" => 2, ), "meta-title" => array( "name" => esc_html__("Meta Title", "ai-for-seo"), "icon" => "globe", "input" => "textarea", "hint" => __("Best Practice: A unique and concise title for this entry, which will be displayed on search engine results pages (SERPs) and in the browser tab. This helps users understand your content and enhances visibility.

The AI aims to generate a meta title with an optimal length of 50 to 60 characters.

The meta title is added to the title tag of your website.", "ai-for-seo"), "api-identifier" => "meta_title", "output-tag-type" => "title", "output-tag-identifier" => "", "meta-tag-regex" => '/(.*?)<\/title>/is', "meta-tag-regex-match-index" => 1, "flat-credits-cost" => 1, ), "meta-description" => array( "name" => esc_html__("Meta Description", "ai-for-seo"), "icon" => "globe", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> A compelling and relevant meta description for your page or post, which will appear on search engine results pages (SERPs) beneath the meta title. This description provides a summary of your content, helping to attract clicks and improve visibility.<br><br>The AI aims to generate a meta description with an optimal length of <strong>135 to 150</strong> characters.<br><br>The meta description is added to the <strong>meta description tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_description", "output-tag-type" => "meta name", "output-tag-identifier" => "description", "meta-tag-regex" => '/<meta\s+[^>]*name=(["\'])description\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 2, ), "keywords" => array( "name" => esc_html__("Keywords", "ai-for-seo"), "icon" => "hashtag", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> Provide a concise, comma-separated list of the most relevant SEO keywords for this entry. Focus on specific phrases that best describe the content and avoid duplicates or keyword stuffing.<br><br>The meta keywords are added to the <strong>meta keywords tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_keywords", "output-tag-type" => "meta name", "output-tag-identifier" => "keywords", "meta-tag-regex" => '/<meta\s+[^>]*name=(["\'])keywords\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 1, ), "facebook-title" => array( "name" => esc_html__("Facebook Title", "ai-for-seo"), "icon" => "square-facebook", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> This title will be displayed as the headline in the preview when your content is shared on Facebook, helping to capture attention and increase engagement.<br><br>The AI aims to generate a Facebook title with an optimal length of <strong>50 to 60</strong> characters.<br><br>The Facebook title is added to the <strong>og:title tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_facebook_title", "output-tag-type" => "meta property", "output-tag-identifier" => "og:title", "meta-tag-regex" => '/<meta\s+[^>]*property=(["\'])og:title\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 1, ), "facebook-description" => array( "name" => esc_html__("Facebook Description", "ai-for-seo"), "icon" => "square-facebook", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> This description will appear in the preview when your content is shared, providing a summary that encourages users to engage with your content.<br><br>The AI aims to generate a Facebook description with an optimal length of <strong>55 to 65</strong> characters.<br><br>The Facebook description is added to the <strong>og:description tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_facebook_description", "output-tag-type" => "meta property", "output-tag-identifier" => "og:description", "meta-tag-regex" => '/<meta\s+[^>]*property=(["\'])og:description\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 1, ), "twitter-title" => array( "name" => esc_html__("Twitter/X Title", "ai-for-seo"), "icon" => "square-twitter-x", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> An attention-grabbing title for your page or post, optimized for sharing on Twitter/X. This title will be displayed as the headline in the preview when your content is tweeted, helping to increase visibility and encourage clicks.<br><br>The AI aims to generate a Twitter/X title with an optimal length of <strong>50 to 60</strong> characters.<br><br>The Twitter/X title is added to the <strong>twitter:title tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_twitter_title", "output-tag-type" => "meta name", "output-tag-identifier" => "twitter:title", "meta-tag-regex" => '/<meta\s+[^>]*name=(["\'])twitter:title\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 1, ), "twitter-description" => array( "name" => esc_html__("Twitter/X Description", "ai-for-seo"), "icon" => "square-twitter-x", "input" => "textarea", "hint" => __("<strong>Best Practice:</strong> A concise and engaging description for your page or post, optimized for sharing on Twitter/X. This description will appear in the preview when your content is tweeted, providing a brief summary that encourages users to click and interact.<br><br>The AI aims to generate a Twitter/X description with an optimal length of <strong>55 to 65</strong> characters.<br><br>The Twitter/X description is added to the <strong>twitter:description tag</strong> of your website.", "ai-for-seo"), "api-identifier" => "meta_twitter_description", "output-tag-type" => "meta name", "output-tag-identifier" => "twitter:description", "meta-tag-regex" => '/<meta\s+[^>]*name=(["\'])twitter:description\1[^>]*content=(["\'])(.*?)\2[^>]*>/i', "meta-tag-regex-match-index" => 3, "flat-credits-cost" => 1, ), )); define ('AI4SEO_ATTACHMENT_ATTRIBUTES_DETAILS', array( "title" => array( "name" => esc_html__("Title", "ai-for-seo"), "icon" => "headline", "mime-type-restrictions" => array(), "input-type" => "textarea", "hint" => __("<strong>Best Practice:</strong> A descriptive and unique title for your image that helps users and search engines understand the content of the image. This title is displayed when the image is loaded in the browser and may be used as the default filename if someone downloads the image.<br><br>The AI aims to generate an image title with an optimal length of <strong>20 to 50</strong> characters.<br><br>The image title is not directly visible on your website but is stored in the <strong>image metadata</strong>. A well-crafted title can aid in organizing your media library and improve searchability within WordPress.", "ai-for-seo"), "api-identifier" => "image_title", "flat-credits-cost" => 1, ), "alt-text" => array( "name" => esc_html__("Alt Text", "ai-for-seo"), "icon" => "code", "mime-type-restrictions" => array( "image/jpeg", "image/gif", "image/png", "image/bmp", "image/tiff", "image/webp", "image/avif", "image/x-icon", "image/heic", ), "input-type" => "textarea", "hint" => __("<strong>Best Practice:</strong> An informative and clear alt text for your image that describes its content and function. This text is used by screen readers to assist visually impaired users and is displayed in place of the image if it cannot be loaded. It also contributes to SEO by providing context to search engines.<br><br>The AI aims to generate alt text with an optimal length of <strong>145 to 155</strong> characters.<br><br>Alt text is added to the <strong>alt attribute</strong> of the image HTML tag.", "ai-for-seo"), "api-identifier" => "image_alt_text", "flat-credits-cost" => 2, ), "caption" => array( "name" => esc_html__("Caption", "ai-for-seo"), "icon" => "subtitle", "mime-type-restrictions" => array(), "input-type" => "textarea", "hint" => __("<strong>Best Practice:</strong> A brief and engaging caption for your image that provides additional context or credit information. Captions are typically displayed below the image on your website and can help enhance user engagement and provide useful information.<br><br>The AI aims to generate a caption with an optimal length of <strong>50 to 125</strong> characters.<br><br>The caption is added to the <strong>caption field</strong> in the WordPress Media Library and is displayed directly on the page where the image appears.", "ai-for-seo"), "api-identifier" => "image_caption", "flat-credits-cost" => 1, ), "description" => array( "name" => esc_html__("Description", "ai-for-seo"), "icon" => "subtitles", "mime-type-restrictions" => array(), "input-type" => "textarea", "hint" => __("<strong>Best Practice:</strong> A detailed and informative description of your image, which helps users understand the image's content and context. This description is particularly useful for internal reference and can aid in organizing and managing your media library.<br><br>The AI aims to generate a description with an optimal length of <strong>155 to 165</strong> characters.<br><br>The description is stored in the <strong>image metadata</strong> and is not directly visible to users on your website. A well-crafted description can aid in organizing your media library and improve searchability within WordPress.", "ai-for-seo"), "api-identifier" => "image_description", "flat-credits-cost" => 1, ), #"file-name" => array( # "name" => esc_html__("File Name", "ai-for-seo"), # "mime-type-restrictions" => array(), # "input-type" => "textfield", # "hint" => __("The AI will generate a file name for your image based on its content. A descriptive file name can improve SEO and help search engines understand the image. Review the file name to ensure it accurately reflects the image.", "ai-for-seo"), # "api-identifier" => "image_file_name", # "flat-credits-cost" => 2, #), )); define('AI4SEO_TRANSLATED_LANGUAGE_NAMES', array( "en" => __("English", "ai-for-seo"), "de" => __("German", "ai-for-seo"), "fr" => __("French", "ai-for-seo"), "es" => __("Spanish", "ai-for-seo"), "it" => __("Italian", "ai-for-seo"), "nl" => __("Dutch", "ai-for-seo"), "pt" => __("Portuguese", "ai-for-seo"), "ru" => __("Russian", "ai-for-seo"), "zh" => __("Chinese", "ai-for-seo"), "ja" => __("Japanese", "ai-for-seo"), "ko" => __("Korean", "ai-for-seo"), )); }, 7); function ai4seo_get_allowed_html_tags_and_attributes(): array { static $ai4seo_allowed_html_tags_and_attributes = array( "div" => array( "id" => array(), "class" => array(), "onclick" => array(), "style" => array(), "title" => array(), ), "img" => array( "class" => array(), "src" => array(), "alt" => array(), "onclick" => array(), "style" => array(), ), 'meta' => array( 'name' => array(), 'content' => array(), 'property' => array(), ), 'title' => array(), 'svg' => array( 'viewbox' => array(), 'aria-label' => array(), 'class' => array(), 'xmlns' => array(), ), 'rect' => array( 'width' => array(), 'height' => array(), 'rx' => array(), 'ry' => array(), 'x' => array(), 'y' => array(), 'fill' => array(), ), 'line' => array( 'x1' => array(), 'y1' => array(), 'x2' => array(), 'y2' => array(), 'stroke' => array(), 'stroke-width' => array(), ), 'defs' => array(), 'style' => array(), 'path' => array( 'class' => array(), 'd' => array(), 'fill-rule' => array(), 'fill' => array(), 'clip-rule' => array(), ), 'g' => array( 'class' => array(), ), 'circle' => array( 'cx' => array(), 'cy' => array(), 'r' => array(), 'fill' => array(), ), 'polygon' => array( 'points' => array(), 'fill' => array(), ), 'text' => array( 'x' => array(), 'y' => array(), 'font-size' => array(), 'font-family' => array(), 'font-weight' => array(), 'fill' => array(), ), "button" => array( "type" => array(), "onclick" => array(), "class" => array(), "id" => array(), "disabled" => array(), "style" => array(), "data-clipboard-text" => array(), "data-time-left" => array(), "aria-controls" => array(), "aria-expanded" => array(), ), "span" => array( "id" => array(), "class" => array(), "style" => array(), "data-trigger" => array(), "data-time-left" => array(), "onclick" => array(), ), "h1" => array( "class" => array(), "style" => array(), ), "h2" => array( "class" => array(), "style" => array(), ), "p" => array( "class" => array(), "style" => array(), ), "b" => array(), "u" => array(), "a" => array( "href" => array(), "target" => array(), "rel" => array(), "title" => array(), "class" => array(), "onclick" => array(), "data-time-left" => array(), ), "i" => array( "onclick" => array(), "class" => array(), "id" => array(), "style" => array(), ), "select" => array( "id" => array(), "class" => array(), "style" => array(), "onchange" => array(), ), "option" => array( "value" => array(), "selected" => array(), ), "br" => array(), "strong" => array( "class" => array(), ), "input" => array( "type" => array(), "id" => array(), "class" => array(), "style" => array(), "value" => array(), "name" => array(), "placeholder" => array(), "onchange" => array(), "onclick" => array(), "disabled" => array(), "data-target" => array(), ), "textarea" => array( "id" => array(), "class" => array(), "style" => array(), "onchange" => array(), "onclick" => array(), "disabled" => array(), ), "label" => array( "for" => array(), "class" => array(), "style" => array(), ), "center" => array(), "ol" => array( "class" => array(), "style" => array(), ), "ul" => array( "class" => array(), "style" => array(), ), "li" => array( "class" => array(), "style" => array(), ), "em" => array(), ); return $ai4seo_allowed_html_tags_and_attributes; } $ai4seo_cached_active_plugins_and_themes = array(); $ai4seo_cached_supported_post_types = array(); $ai4seo_checked_supported_post_types = array(); $ai4seo_allowed_attachment_mime_types = array("image/jpeg", "image/png", "image/gif", "image/webp", "image/avif"); # IMPORTANT! Also apply changes to the api-service AND to ai4seo_supported_mime_types-variable in JS-file $ai4seo_allowed_image_mime_types = array("image/jpeg", "image/png", "image/gif", "image/webp", "image/avif"); $ai4seo_allowed_image_file_type_names = array("jpg", "jpeg", "png", "gif", "webp", "avif"); // Define the constants for full and base language code mappings const AI4SEO_FULL_LANGUAGE_CODE_MAPPING = array( 'zh_cn' => 'simplified chinese', 'zh_tw' => 'traditional chinese', 'pt_br' => 'brazilian portuguese', 'pt_pt' => 'european portuguese', 'fr_ca' => 'canadian french', 'en_us' => 'american english', 'en_gb' => 'british english', ); const AI4SEO_BASE_LANGUAGE_CODE_MAPPING = array( 'sq' => 'albanian', 'ar' => 'arabic', 'bg' => 'bulgarian', 'zh' => 'chinese', // General Chinese fallback 'hr' => 'croatian', 'cs' => 'czech', 'da' => 'danish', 'nl' => 'dutch', 'en' => 'english', // General English fallback 'et' => 'estonian', 'fi' => 'finnish', 'fr' => 'french', // General French fallback 'de' => 'german', 'el' => 'greek', 'he' => 'hebrew', 'hi' => 'hindi', 'hu' => 'hungarian', 'is' => 'icelandic', 'id' => 'indonesian', 'it' => 'italian', 'ja' => 'japanese', 'ko' => 'korean', 'lv' => 'latvian', 'lt' => 'lithuanian', 'mk' => 'macedonian', 'mt' => 'maltese', 'no' => 'norwegian', 'pl' => 'polish', 'pt' => 'portuguese', // General Portuguese fallback 'ro' => 'romanian', 'ru' => 'russian', 'sr' => 'serbian', 'sk' => 'slovak', 'sl' => 'slovenian', 'es' => 'spanish', // General Spanish fallback 'sv' => 'swedish', 'th' => 'thai', 'tr' => 'turkish', 'uk' => 'ukrainian', 'vi' => 'vietnamese', ); // allowed ajax function (also change in javascript file) const AI4SEO_ALLOWED_AJAX_FUNCTIONS = array( "ai4seo_save_anything", "ai4seo_show_metadata_editor", "ai4seo_show_attachment_attributes_editor", "ai4seo_generate_metadata", "ai4seo_generate_attachment_attributes", "ai4seo_reject_tos", "ai4seo_accept_tos", "ai4seo_show_terms_of_service", "ai4seo_dismiss_notification", "ai4seo_get_dashboard_html", "ai4seo_reset_plugin_data", "ai4seo_stop_bulk_generation", "ai4seo_retry_all_failed_attachment_attributes", "ai4seo_retry_all_failed_metadata", "ai4seo_disable_payg", "ai4seo_init_purchase", "ai4seo_track_subscription_pricing_visit", "ai4seo_import_nextgen_gallery_images", "ai4seo_export_settings", "ai4seo_show_import_settings_preview", "ai4seo_import_settings", "ai4seo_restore_default_settings", "ai4seo_request_lost_licence_data", "ai4seo_refresh_dashboard_statistics", "ai4seo_refresh_robhub_account", ); // the robhub api communicator is used to communicate with the robhub api which handles all the ai stuff $ai4seo_robhub_api = null; $ai4seo_are_settings_currently_being_initialized = false; $ai4seo_are_settings_initialized = false; // ___________________________________________________________________________________________ \\ // === INITIALIZATION ======================================================================== \\ // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ \\ // init settings add_action("init", "ai4seo_init_settings", 8); // CRON CALL ONLY if (wp_doing_cron()) { // init cron jobs add_action("init", "ai4seo_init_robhub_api", 9); add_action("init", "ai4seo_init_cron_jobs", 10); // exit here return; } // FOR FRONTEND, LOGGED-OUT USERS. ALSO FOR: LOGGED-IN USERS, ADMIN AREA // init plugin injections for all users for the frontend add_action("init", "ai4seo_enqueue_frontend_scripts"); add_action("init", "ai4seo_init_frontend_injections"); // FOR LOGGED-IN USERS. ALSO FOR: ADMIN AREA // init (logged-in) user essentials after all plugins have been loaded, used for admin area and frontend add_action("init", "ai4seo_init_user_essentials"); // perform ajax nonce check add_action( 'admin_init', 'ai4seo_ajax_nonce_check', 9999 ); // not admin area -> exit here if (!ai4seo_is_function_usable("is_admin") || !is_admin()) { return; } // init admin essentials for the backend after all plugins have been loaded add_action("init", "ai4seo_init_admin_area_essentials", 12); // on plugin deactivation register_deactivation_hook(__FILE__, "ai4seo_on_deactivation"); if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { return; } // init cron jobs add_action("init", "ai4seo_init_cron_jobs"); // do some checks after all plugins have been loaded add_action('init', 'ai4seo_check_and_handle_plugin_update'); // check for unfinished post table analysis add_action('init', 'ai4seo_try_start_posts_table_analysis', 9); // check for new notifications add_action('init', 'ai4seo_check_for_new_notifications', 13); // init admin essentials for the backend after all plugins have been loaded add_action("init", "ai4seo_send_additional_tos_accept_details"); // on saving a post, check if the all ceo meta tags are filled add_action("save_post", "ai4seo_mark_post_to_be_analyzed", 20, 3); // analyze the post after it has been saved, call ai4seo_handle_posts_to_be_analyzed() at the end of the request add_action("shutdown", "ai4seo_handle_posts_to_be_analyzed"); // on plugin activation register_activation_hook(__FILE__, "ai4seo_on_activation"); // === INIT FUNCTIONS ======================================================================== \\ /** * Function to init plugin injections for all users for the frontend * @return void */ function ai4seo_init_frontend_injections() { if (!ai4seo_singleton(__FUNCTION__)) { return; } // make sure we are on the frontend and not in the admin area, also exclude feeds, REST requests and AJAX requests if ( is_admin() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { return; } // workaround for Squirrly SEO, as they use their own buffer $is_squirrly_seo_active = ai4seo_is_plugin_or_theme_active(AI4SEO_THIRD_PARTY_PLUGIN_SQUIRRLY_SEO); if ($is_squirrly_seo_active) { // Squirrly SEO workaround, as they use their own buffer add_action("sq_buffer", "ai4seo_inject_our_meta_tags_into_the_html_head", 20); add_action("sq_buffer", "ai4seo_inject_image_attributes_into_html", 20); return; } // inject meta tags and image attributes into html add_action( 'template_redirect', function(){ ob_start( function( $html ) { $html = ai4seo_inject_our_meta_tags_into_the_html_head( $html ); return ai4seo_inject_image_attributes_into_html( $html ); } ); }, PHP_INT_MAX ); add_action( 'shutdown', function(){ if ( ob_get_length() ) { echo ob_get_clean(); } } ); /* // add alt text injection to images (for logged-in users and guests) add_filter("the_content", "ai4seo_inject_image_attributes", 99999); // also filter block output for gutenberg blocks to inject alt text add_filter("render_block", "ai4seo_inject_image_attributes_for_gutenberg", 99999, 2); // Also cover images output via wp_get_attachment_image() and similar. add_filter('wp_get_attachment_image_attributes', 'ai4seo_filter_wp_image_attrs', 10, 3); add_filter( 'post_thumbnail_html', 'ai4seo_inject_image_attributes', 99999, 5 ); add_filter( 'wp_get_attachment_image_attributes', 'ai4seo_inject_image_attributes', 99999, 3 ); add_filter( 'get_image_tag', 'ai4seo_inject_image_attributes', 99999, 6 ); add_filter( 'get_avatar', 'ai4seo_inject_image_attributes', 99999, 6 ); add_filter( 'widget_text', 'ai4seo_inject_image_attributes', 99999 ); add_filter( 'the_excerpt', 'ai4seo_inject_image_attributes', 99999 ); add_filter( 'get_the_excerpt', 'ai4seo_inject_image_attributes', 99999 ); */ } // =========================================================================================== \\ /** * Function to init plugin essentials for admins in the front and backend * @return void */ function ai4seo_init_user_essentials() { // Make sure that the user is allowed to use this plugin if (!ai4seo_can_manage_this_plugin()) { return; } // enqueue scripts and styles add_action('wp_enqueue_scripts', 'ai4seo_enqueue_admin_scripts'); add_action('admin_enqueue_scripts', 'ai4seo_enqueue_admin_scripts'); // init ajax functions foreach (AI4SEO_ALLOWED_AJAX_FUNCTIONS AS $this_ajax_function) { add_action("wp_ajax_{$this_ajax_function}", $this_ajax_function); } // add modal schemas to the footer add_action("wp_footer", "ai4seo_include_modal_schemas_file"); add_action("get_footer", "ai4seo_include_modal_schemas_file"); add_action("admin_footer", "ai4seo_include_modal_schemas_file"); // register compatibility with other plugins if (ai4seo_is_plugin_or_theme_active(AI4SEO_THIRD_PARTY_PLUGIN_NEXTGEN_GALLERY)) { register_post_type( AI4SEO_NEXTGEN_GALLERY_POST_TYPE, array( 'label' => AI4SEO_NEXTGEN_GALLERY_POST_TYPE, 'public' => false, 'show_ui' => false, 'show_in_menu' => false, 'exclude_from_search' => true, 'publicly_queryable' => false, 'query_var' => false, 'rewrite' => false, 'capability_type' => 'post', 'supports' => array( 'title', 'editor' ), 'can_export' => false, 'show_in_rest' => false, ) ); } // user needs to accept tos? stop here, to prevent further plugin actions if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { return; } // admin bar menu item add_action("admin_bar_menu", "ai4seo_add_admin_menu_item", 999); } // =========================================================================================== \\ /** * Function to init plugin essentials for admins in the backend * @return void */ function ai4seo_init_admin_area_essentials() { // ADMIN AREA ONLY (REST OF INIT CODE FROM HERE) -> // make sure the robhub api communicator is initialized before anything else if (!ai4seo_init_robhub_api()) { // if the robhub api communicator could not be initialized, we cannot continue // show notice add_action('admin_notices', function() { echo '<div class="notice notice-error"><p>' . esc_html__("The AI for SEO plugin could not be initialized. Class 'Ai4Seo_RobHubApiCommunicator' could not be initialized. Please check your server configuration and try again.", "ai-for-seo") . '</p></div>'; }); // exit here return; } // Overwrite the plugin-details for white-label-settings add_filter("all_plugins", "ai4seo_modify_plugin_details_for_white_label", 10, 1); // Make sure that the user is allowed to use this plugin if (!ai4seo_can_manage_this_plugin()) { return; } $is_user_inside_our_plugin_admin_pages = ai4seo_is_user_inside_our_plugin_admin_pages(); // Add menu-item to main menu, sub menu-items and page titles add_filter('admin_title', 'ai4seo_filter_admin_title', 10, 2 ); add_action('admin_menu', "ai4seo_add_menu_entries"); add_filter('parent_file', 'ai4seo_mark_parent_menu_active'); add_filter('submenu_file', 'ai4seo_mark_submenu_active'); // plugin action link use filter "plugin_action_links_ + plugin_basename" $this_plugin_basename = sanitize_text_field(ai4seo_get_plugin_basename()); add_filter("plugin_action_links_{$this_plugin_basename}", 'ai4seo_add_links_to_the_plugin_directory', 999); // show terms of service if not accepted yet $last_tos_modal_open_time = (int) ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_LAST_MODAL_OPEN_TIME); // outside the plugin admin pages, show the modal only once a week if ($is_user_inside_our_plugin_admin_pages || $last_tos_modal_open_time < time() - WEEK_IN_SECONDS) { if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { add_action("wp_footer", "ai4seo_show_terms_of_service_modal"); add_action("get_footer", "ai4seo_show_terms_of_service_modal"); add_action("admin_footer", "ai4seo_show_terms_of_service_modal"); } } if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { // stop here, to prevent further plugin actions return; } // put our code into the post and page table add_filter("manage_post_posts_columns", "ai4seo_add_metadata_editor_column_to_posts_table"); add_filter("manage_page_posts_columns", "ai4seo_add_metadata_editor_column_to_posts_table"); #add_filter("manage_edit-product_columns", "ai4seo_add_metadata_editor_column_to_posts_table"); add_action("manage_post_posts_custom_column", "ai4seo_add_metadata_editor_button_to_posts_table", 10, 2); add_action("manage_page_posts_custom_column", "ai4seo_add_metadata_editor_button_to_posts_table", 10, 2); #add_action("manage_product_posts_custom_column", "ai4seo_add_metadata_editor_button_to_posts_table", 10, 2); // add ajax nonce field to the footer add_action( 'admin_print_footer_scripts', 'ai4seo_print_ajax_nonce_field' ); // if user is inside our plugin admin pages, check for account sync if ($is_user_inside_our_plugin_admin_pages) { ai4seo_check_for_robhub_account_sync(); } } // === FUNCTION TO INIT AI4SEO-PLUGIN-SETTINGS =============================================== \\ /** * Function to init the plugin-settings * @return void */ function ai4seo_init_settings() { global $ai4seo_settings; global $ai4seo_are_settings_initialized; global $ai4seo_are_settings_currently_being_initialized; // Make sure that settings are only initialized once if ($ai4seo_are_settings_initialized) { return; } if ($ai4seo_are_settings_currently_being_initialized) { error_log("AI4SEO Init Settings: Settings are already being initialized. Exiting to prevent recursion."); //error_log(__FUNCTION__ . "() @ " . __LINE__ . ": " . print_r("AI4SEO Init Settings: Settings are already being initialized. Exiting to prevent recursion.", true) . "\r\n\r\nBACKTRACE\r\n " . ai4seo_get_backtrace_debug_message("\r\n") . "\r\n\r\n"); return; } $ai4seo_are_settings_currently_being_initialized = true; try { // Read settings from database $from_database_settings = ai4seo_read_settings(); // Loop through settings and add the new values to $ai4seo_settings foreach ($from_database_settings as $setting_name => $setting_value) { // Make sure that this setting is valid if (!ai4seo_validate_setting_value($setting_name, $setting_value)) { continue; } // Save the new values to $ai4seo_settings $ai4seo_settings[$setting_name] = $setting_value; } $ai4seo_are_settings_currently_being_initialized = false; $ai4seo_are_settings_initialized = true; } finally { $ai4seo_are_settings_currently_being_initialized = false; } } // =========================================================================================== \\ function ai4seo_read_settings() : array { // Read settings from database $settings = ai4seo_get_option(AI4SEO_SETTINGS_OPTION_NAME); // Make sure that settings could be read from database if (!$settings) { $settings = array(); } $settings = maybe_unserialize($settings); // Make sure that $settings is array if (!is_array($settings)) { if (is_string($settings) && ai4seo_is_json($settings)) { $settings = json_decode($settings, true); } } if (!is_array($settings)) { $settings = array(); } $settings = ai4seo_deep_sanitize($settings); $settings = ai4seo_deep_sanitize($settings, 'ai4seo_wp_unslash'); return $settings; } // =========================================================================================== \\ /** * Things to do on plugin activation * @return void */ function ai4seo_on_activation() { // set AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME if (!ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME)) { ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME, time()); } // init cron jobs ai4seo_init_cron_jobs(); } // =========================================================================================== \\ /** * Things to do on plugin deactivation * @return void */ function ai4seo_on_deactivation() { // un schedule all cron jobs ai4seo_un_schedule_cron_jobs(); ai4seo_robhub_api()->perform_product_deactivated_call(); // Check for function get_current_user_id() if (!function_exists("get_current_user_id")) { return; } // Define variables for the incognito-setting $ai4seo_setting_enable_incognito_mode = ai4seo_is_incognito_mode_enabled(); $ai4seo_setting_incognito_mode_user_id = ai4seo_get_setting(AI4SEO_SETTING_INCOGNITO_MODE_USER_ID); $current_user_id = get_current_user_id(); // Delete plugin if it was deactivated by non-incognito mode user if ($ai4seo_setting_enable_incognito_mode && $ai4seo_setting_incognito_mode_user_id != AI4SEO_DEFAULT_SETTINGS[AI4SEO_SETTING_INCOGNITO_MODE_USER_ID] && $ai4seo_setting_incognito_mode_user_id != $current_user_id) { // Make sure we can call delete_plugins() if (!function_exists("delete_plugins")) { include_once(ABSPATH . "wp-admin/includes/plugin.php"); } // Attempt to delete this plugin's files if (function_exists("delete_plugins")) { delete_plugins([plugin_basename(__FILE__)]); } } } // =========================================================================================== \\ function ai4seo_is_incognito_mode_enabled(): bool { if (isset($_REQUEST["ai4seo_debug_bypass_incognito_mode"]) && $_REQUEST["ai4seo_debug_bypass_incognito_mode"]) { // If the debug bypass parameter is set, we can bypass the incognito mode return false; } // Check if the incognito mode is enabled $ai4seo_setting_enable_incognito_mode = ai4seo_get_setting(AI4SEO_SETTING_ENABLE_INCOGNITO_MODE); // If the incognito mode is enabled, return true if ($ai4seo_setting_enable_incognito_mode) { return true; } // Otherwise, return false return false; } // =========================================================================================== \\ /** * Function to check if we have updated recently and do some actions accordingly * @return void */ function ai4seo_check_and_handle_plugin_update() { $last_known_plugin_version = strval(ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION)); // same plugin version as last known version? -> skip if ($last_known_plugin_version == AI4SEO_PLUGIN_VERSION_NUMBER) { return; } // save new version to database ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION, AI4SEO_PLUGIN_VERSION_NUMBER); // workaround for version 0.0.0 -> remove $last_known_plugin_version if ($last_known_plugin_version == AI4SEO_DEFAULT_ENVIRONMENTAL_VARIABLES[AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION]) { $last_known_plugin_version = ""; } // tidy up some old version parameters, tables and options ai4seo_tidy_up($last_known_plugin_version); // call "product-updated" endpoint to RobHub if we are not on a fresh install if ($last_known_plugin_version) { // call robhub api endpoint "client/product-updated" with the old and new plugin version $robhub_api_parameters = array( "old_version" => $last_known_plugin_version, "new_version" => AI4SEO_PLUGIN_VERSION_NUMBER, ); ai4seo_robhub_api()->call("client/product-updated", $robhub_api_parameters); // maybe push a new plugin update notification ai4seo_check_for_plugin_update_notification($last_known_plugin_version, true); } } // =========================================================================================== \\ /** * Function to clean up old version's options, variables etc. Clean-up. Clean_up, Tidy-up * @param $last_known_plugin_version string The last known plugin version, used to determine which cleanup actions to perform * @return void */ function ai4seo_tidy_up(string $last_known_plugin_version = AI4SEO_PLUGIN_VERSION_NUMBER) { // reestablish cron jobs ai4seo_un_schedule_cron_jobs(); ai4seo_init_cron_jobs(); // start cron jobs in 10 seconds ai4seo_inject_additional_cronjob_call(AI4SEO_BULK_GENERATION_CRON_JOB_NAME, 10); ai4seo_inject_additional_cronjob_call(AI4SEO_ANALYSE_PLUGIN_PERFORMANCE_CRON_JOB_NAME, 10); // unset temporary environmental variables ai4seo_robhub_api()->reset_last_account_sync(); ai4seo_robhub_api()->tidy_up_api_locks(); ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_CRON_JOB_CALL, time() - 300); ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_SPECIFIC_CRON_JOB_CALLS, array()); // we need the raw settings to check for old variations of the settings $raw_settings = ai4seo_read_settings(); // we need the raw environmental variables to check for old variations $raw_environmental_variables = ai4seo_get_option(AI4SEO_ENVIRONMENTAL_VARIABLES_OPTION_NAME); if($raw_environmental_variables) { $raw_environmental_variables = maybe_unserialize($raw_environmental_variables); $raw_environmental_variables = ai4seo_deep_sanitize($raw_environmental_variables); } // === V1.1.X ================================================================================= \\ // remove old options (from older versions) // required after V1.1.1 if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.1.1', '<')) { ai4seo_delete_option("_ai4seo_current_credits_balance"); } // if old option ai4seo_missing_seo_data_post_ids is set, rename it to ai4seo_processing_metadata_post_ids // required after V1.1.2 if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.1.2', '<')) { if (ai4seo_get_option("ai4seo_missing_seo_data_post_ids")) { $missing_seo_data_post_ids = ai4seo_get_option("ai4seo_missing_seo_data_post_ids"); ai4seo_update_option("ai4seo_processing_metadata_post_ids", $missing_seo_data_post_ids); ai4seo_delete_option("ai4seo_missing_seo_data_post_ids"); } // if old option _ai4seo_num_existing_going_to_fill_this_post_ids_by_post_type is set, rename it to _ai4seo_num_processing_metadata_post_ids_by_post_type // required after V1.1.2 if (ai4seo_get_option("_ai4seo_num_existing_going_to_fill_this_post_ids_by_post_type")) { $num_existing_going_to_fill_this_post_ids_by_post_type = ai4seo_get_option("_ai4seo_num_existing_going_to_fill_this_post_ids_by_post_type"); ai4seo_update_option("_ai4seo_num_processing_metadata_post_ids_by_post_type", $num_existing_going_to_fill_this_post_ids_by_post_type); ai4seo_delete_option("_ai4seo_num_existing_going_to_fill_this_post_ids_by_post_type"); } // clear schedule of old cronjobs, as of V1.1.2 we use new cronjobs wp_clear_scheduled_hook("ai4seo_search_missing_seo_data_posts"); wp_clear_scheduled_hook("ai4seo_search_missing_metadata_posts"); wp_clear_scheduled_hook("ai4seo_automated_seo_data_generation"); } // V1.1.8: clear schedule of old cronjob "ai4seo_automated_metadata_generation", it's now called "ai4seo_automated_generation_cron_job" if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.1.8', '<')) { wp_clear_scheduled_hook("ai4seo_automated_metadata_generation"); ai4seo_delete_option("ai4seo_is_automation_activated_for_posts"); ai4seo_delete_option("ai4seo_is_automation_activated_for_pages"); ai4seo_delete_option("ai4seo_is_automation_activated_for_products"); } // === V1.2.X ================================================================================= \\ // if old option ai4seo_already_filled_post_ids is set, rename it to ai4seo_already_filled_metadata_post_ids // required after V1.2 if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.2', '<')) { if (ai4seo_get_option("ai4seo_already_filled_post_ids")) { $already_filled_metadata_post_ids = ai4seo_get_option("ai4seo_already_filled_post_ids"); ai4seo_update_option("ai4seo_already_filled_metadata_post_ids", $already_filled_metadata_post_ids); ai4seo_delete_option("ai4seo_already_filled_post_ids"); } // if old option ai4seo_failed_to_fill_post_ids is set, rename it to ai4seo_failed_to_fill_metadata_post_ids // required after V1.2 if (ai4seo_get_option("ai4seo_failed_to_fill_post_ids")) { $failed_to_fill_metadata_post_ids = ai4seo_get_option("ai4seo_failed_to_fill_post_ids"); ai4seo_update_option("ai4seo_failed_to_fill_metadata_post_ids", $failed_to_fill_metadata_post_ids); ai4seo_delete_option("ai4seo_failed_to_fill_post_ids"); } // V1.2: check for table "wp_ai4seo_cache" (id, post_id, data), if available, save all it's "data" to the post_meta of the corresponding post_id, using ai4seo_save_generated_data() ai4seo_tidy_up_old_ai4seo_cache_table(); } // V1.2.1: Delete old summary options if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.2.1', '<')) { if (ai4seo_get_option("_ai4seo_num_processing_metadata_post_ids_by_post_type")) { ai4seo_delete_option("_ai4seo_num_processing_metadata_post_ids_by_post_type"); } if (ai4seo_get_option("_ai4seo_num_failed_to_fill_post_ids_by_post_type")) { ai4seo_delete_option("_ai4seo_num_failed_to_fill_post_ids_by_post_type"); } if (ai4seo_get_option("_ai4seo_num_already_filled_post_ids_by_post_type")) { ai4seo_delete_option("_ai4seo_num_already_filled_post_ids_by_post_type"); } if (ai4seo_get_option("_ai4seo_num_posts_not_filled_by_post_type")) { ai4seo_delete_option("_ai4seo_num_posts_not_filled_by_post_type"); } if (ai4seo_get_option("ai4seo_already_filled_metadata_post_ids")) { ai4seo_delete_option("ai4seo_already_filled_metadata_post_ids"); } if (ai4seo_get_option("ai4seo_already_filled_attributes_attachment_post_ids")) { ai4seo_delete_option("ai4seo_already_filled_attributes_attachment_post_ids"); } // V1.2.1: Rename some post ids options // (ai4seo_failed_to_fill_metadata_post_ids -> ai4seo_failed_metadata_post_ids) // (ai4seo_failed_to_fill_attributes_attachment_post_ids -> ai4seo_failed_attributes_attachment_post_ids) if (ai4seo_get_option("ai4seo_failed_to_fill_metadata_post_ids")) { $failed_metadata_post_ids = ai4seo_get_option("ai4seo_failed_to_fill_metadata_post_ids"); ai4seo_update_option("ai4seo_failed_metadata_post_ids", $failed_metadata_post_ids); ai4seo_delete_option("ai4seo_failed_to_fill_metadata_post_ids"); } if (ai4seo_get_option("ai4seo_failed_to_fill_attributes_attachment_post_ids")) { $failed_attributes_attachment_post_ids = ai4seo_get_option("ai4seo_failed_to_fill_attributes_attachment_post_ids"); ai4seo_update_option("ai4seo_failed_attributes_attachment_post_ids", $failed_attributes_attachment_post_ids); ai4seo_delete_option("ai4seo_failed_to_fill_attributes_attachment_post_ids"); } } // V1.2.6: Save various options into the new environmental variables option if ($last_known_plugin_version && version_compare($last_known_plugin_version, '1.2.6', '<')) { if (ai4seo_get_option("_ai4seo_robhub_last_credit_balance_check") !== false) { ai4seo_delete_option("_ai4seo_robhub_last_credit_balance_check"); } if (ai4seo_get_option("ai4seo_robhub_auth_data") !== false) { $old_robhub_auth_data = ai4seo_get_option("ai4seo_robhub_auth_data"); $old_api_username = sanitize_text_field($old_robhub_auth_data[0] ?? ""); $old_api_password = sanitize_text_field($old_robhub_auth_data[1] ?? ""); ai4seo_robhub_api()->update_environmental_variable(ai4seo_robhub_api()::ENVIRONMENTAL_VARIABLE_API_USERNAME, $old_api_username); ai4seo_robhub_api()->update_environmental_variable(ai4seo_robhub_api()::ENVIRONMENTAL_VARIABLE_API_PASSWORD, $old_api_password); ai4seo_delete_option("ai4seo_robhub_auth_data"); } if (ai4seo_get_option("_ai4seo_robhub_credits_balance") !== false) { ai4seo_robhub_api()->update_environmental_variable(ai4seo_robhub_api()::ENVIRONMENTAL_VARIABLE_CREDITS_BALANCE, (int) ai4seo_get_option("_ai4seo_robhub_credits_balance")); ai4seo_delete_option("_ai4seo_robhub_credits_balance"); } if (ai4seo_get_option("_ai4seo_version") !== false) { ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_KNOWN_PLUGIN_VERSION, ai4seo_get_option("_ai4seo_version")); ai4seo_delete_option("_ai4seo_version"); } if (ai4seo_get_option("_ai4seo_licence_key_shown") !== false) { #ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LICENSE_KEY_SHOWN, (bool) ai4seo_get_option("_ai4seo_licence_key_shown")); ai4seo_delete_option("_ai4seo_licence_key_shown"); } if (ai4seo_get_option("_ai4seo_last_cronjob_call") !== false) { # we defined the new variable earlier in this function, therefore we can safely delete the old one ai4seo_delete_option("_ai4seo_last_cronjob_call"); } if (ai4seo_get_option("_ai4seo_last_cronjob_call_for_ai4seo_automated_generation_cron_job") !== false) { # we defined the new variable earlier in this function, therefore we can safely delete the old one ai4seo_delete_option("_ai4seo_last_cronjob_call_for_ai4seo_automated_generation_cron_job"); } if (ai4seo_get_option("_ai4seo_last_cronjob_call_for_ai4seo_automated_metadata_generation") !== false) { # we defined the new variable earlier in this function, therefore we can safely delete the old one ai4seo_delete_option("_ai4seo_last_cronjob_call_for_ai4seo_automated_metadata_generation"); } if (ai4seo_get_option("_ai4seo_performance_notice_dismissed_timestamp") !== false) { # we defined the new variable earlier in this function, therefore we can safely delete the old one ai4seo_delete_option("_ai4seo_performance_notice_dismissed_timestamp"); } } // === V2.0.X ================================================================================= \\ // V2.0.0: // robhub auth data changed from environmental variable "auth_data" to "api_username" and "api_password" if ($last_known_plugin_version && version_compare($last_known_plugin_version, '2.0.0', '<')) { ai4seo_robhub_api()->tidy_up_deprecated_auth_data(); // V2.0.0: Settings migration // enabled_automated_generations -> enabled_bulk_generation_post_types if (isset($raw_settings['enabled_automated_generations']) && is_array($raw_settings['enabled_automated_generations'])) { $new_enabled_bulk_generation_post_types = array(); foreach ($raw_settings['enabled_automated_generations'] AS $this_post_type => $this_is_enabled) { if ($this_is_enabled) { $new_enabled_bulk_generation_post_types[] = $this_post_type; } } if ($new_enabled_bulk_generation_post_types) { ai4seo_update_setting(AI4SEO_SETTING_ENABLED_BULK_GENERATION_POST_TYPES, $new_enabled_bulk_generation_post_types); } } // automated_generation_order (array) -> bulk_generation_order (string) if (isset($raw_settings['automated_generation_order']) && is_array($raw_settings['automated_generation_order'])) { // get first element of the array, set it as the new value if (count($raw_settings['automated_generation_order']) >= 1) { $new_bulk_generation_order = reset($raw_settings['automated_generation_order']); if ($new_bulk_generation_order) { ai4seo_update_setting(AI4SEO_SETTING_BULK_GENERATION_ORDER, $new_bulk_generation_order); } } } // automated_generation_new_or_existing_filter (array) -> bulk_generation_new_or_existing_filter (string) if (isset($raw_settings['automated_generation_new_or_existing_filter']) && is_array($raw_settings['automated_generation_new_or_existing_filter'])) { // get first element of the array, set it as the new value if (count($raw_settings['automated_generation_new_or_existing_filter']) >= 1) { $new_bulk_generation_new_or_existing_filter = reset($raw_settings['automated_generation_new_or_existing_filter']); if ($new_bulk_generation_new_or_existing_filter) { ai4seo_update_setting(AI4SEO_SETTING_BULK_GENERATION_NEW_OR_EXISTING_FILTER, $new_bulk_generation_new_or_existing_filter); } } } // automated_generation_new_or_existing_filter_reference_times (array) -> bulk_generation_new_or_existing_filter_reference_time (string) // environmental variable if (isset($raw_environmental_variables['automated_generation_new_or_existing_filter_reference_times']) && is_array($raw_environmental_variables['automated_generation_new_or_existing_filter_reference_times'])) { // get first element of the array, set it as the new value if (count($raw_environmental_variables['automated_generation_new_or_existing_filter_reference_times']) >= 1) { $new_bulk_generation_new_or_existing_filter_reference_time = reset($raw_environmental_variables['automated_generation_new_or_existing_filter_reference_times']); if ($new_bulk_generation_new_or_existing_filter_reference_time) { ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_BULK_GENERATION_NEW_OR_EXISTING_FILTER_REFERENCE_TIME, $new_bulk_generation_new_or_existing_filter_reference_time); } } } } // === 2.1.X ================================================================================= \\ // V2.1.0: if ($last_known_plugin_version && version_compare($last_known_plugin_version, '2.1.0', '<')) { // Remove old environmental variable "performance_notice_dismissed_time" and dismissed_one_time_notices, feature was removed in V2.1.0 ai4seo_delete_environmental_variable("performance_notice_dismissed_time"); ai4seo_delete_environmental_variable("dismissed_one_time_notices"); ai4seo_delete_environmental_variable("is_first_purchase_discount_available"); ai4seo_delete_environmental_variable("early_bird_discount_time_left"); // delete option "_ai4seo_plugin_activation_time" -> deprecated in V2.1.0 if (ai4seo_get_option("_ai4seo_plugin_activation_time") !== false) { ai4seo_delete_option("_ai4seo_plugin_activation_time"); } } // V2.1.1: if ($last_known_plugin_version && version_compare($last_known_plugin_version, '2.1.1', '<')) { // delete old robhub environmental variable last_credit_balance_check ai4seo_robhub_api()->delete_environmental_variable("last_credit_balance_check"); } // === 2.2.X ================================================================================= \\ if ($last_known_plugin_version && version_compare($last_known_plugin_version, '2.2.0', '<')) { // handle default visible meta tags setting change to new active meta tags setting if (!isset($raw_settings[AI4SEO_SETTING_VISIBLE_META_TAGS]) || !$raw_settings[AI4SEO_SETTING_VISIBLE_META_TAGS]) { // old default value for visible meta tags ai4seo_update_setting(AI4SEO_SETTING_ACTIVE_META_TAGS, array("meta-title", "meta-description", "facebook-title", "facebook-description")); } // if visible meta tags were set, apply the same to active meta tags if (isset($raw_settings[AI4SEO_SETTING_VISIBLE_META_TAGS]) && $raw_settings[AI4SEO_SETTING_VISIBLE_META_TAGS]) { ai4seo_update_setting(AI4SEO_SETTING_ACTIVE_META_TAGS, $raw_settings[AI4SEO_SETTING_VISIBLE_META_TAGS]); } // set AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE to 'facebook-title' and set AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION to 'facebook-description' ai4seo_update_setting(AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE, 'facebook-title'); ai4seo_update_setting(AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION, 'facebook-description'); } // to finish the tidy up, we re-analyze the plugin performance and by adding notifications ai4seo_analyze_plugin_performance(); // force push various notifications, if applicable ai4seo_check_for_missing_entries_notification(true); ai4seo_check_for_low_credits_balance_notification(true); // refresh unread notifications count ai4seo_refresh_unread_notifications_count(); } // =========================================================================================== \\ /** * Function to tidy up old ai4seo_cache table * @return void */ function ai4seo_tidy_up_old_ai4seo_cache_table() { global $wpdb; $table_name = $wpdb->prefix . "ai4seo_cache"; // Check if the table exists $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)); if ($table_exists) { $sql = "SELECT * FROM $table_name"; $results = $wpdb->get_results($sql, ARRAY_A); foreach ($results as $result) { $post_id = sanitize_key($result["post_id"]); $data = ai4seo_deep_sanitize(json_decode($result["data"], true)); ai4seo_save_generated_data_to_postmeta($post_id, $data); } // Drop the table $wpdb->query("DROP TABLE IF EXISTS $table_name"); } } // =========================================================================================== \\ /** * Function to init cron jobs * @return void */ function ai4seo_init_cron_jobs() { if (!ai4seo_init_robhub_api()) { return; } if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { return; } // Add custom cron schedule add_filter("cron_schedules", "ai4seo_add_cron_job_intervals"); // add cron jobs to automate content generation add_action(AI4SEO_BULK_GENERATION_CRON_JOB_NAME, AI4SEO_BULK_GENERATION_CRON_JOB_NAME); // add cron jobs to analyze current state of the plugins performance add_action(AI4SEO_ANALYSE_PLUGIN_PERFORMANCE_CRON_JOB_NAME, AI4SEO_ANALYSE_PLUGIN_PERFORMANCE_CRON_JOB_NAME); // schedule cron jobs if not already scheduled ai4seo_schedule_cron_jobs(); } // =========================================================================================== \\ /** * Function to init robhub-api-communicator * @return bool true if the class is found, false if not */ function ai4seo_init_robhub_api(): bool { global $ai4seo_robhub_api; // Include RobHubApiCommunicator class include_once(ai4seo_get_includes_api_path("class-robhub-api-communicator.php")); // return false if the class is not found if (!class_exists("Ai4Seo_RobHubApiCommunicator")) { return false; } // check if $ai4seo_robhub_api_communicator is already set if ($ai4seo_robhub_api instanceof Ai4Seo_RobHubApiCommunicator) { return true; } $product_activation_time = ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_PLUGIN_ACTIVATION_TIME); $ai4seo_robhub_api = new Ai4Seo_RobHubApiCommunicator(); $ai4seo_robhub_api->set_environmental_variables_option_name(AI4SEO_ROBHUB_ENVIRONMENTAL_VARIABLES_OPTION_NAME); $ai4seo_robhub_api->set_product_parameters("ai4seo", AI4SEO_PLUGIN_VERSION_NUMBER, $product_activation_time); // do we need to accept the terms of service? $does_user_need_to_accept_tos_toc_and_pp = ai4seo_does_user_need_to_accept_tos_toc_and_pp(); $ai4seo_robhub_api->set_does_user_need_to_accept_tos_toc_and_pp($does_user_need_to_accept_tos_toc_and_pp); return true; } // =========================================================================================== \\ /** * Adjusts the browser title for all AI for SEO plugin admin pages. * * Uses ai4seo_is_user_inside_our_plugin_admin_pages(), ai4seo_get_active_subpage(), * ai4seo_get_active_post_type(), and ai4seo_get_plugins_menu_registry() * to determine the current page label. * * @param string $admin_title Default admin title. * @param string $title Original page title. * @return string Filtered admin title. */ function ai4seo_filter_admin_title(string $admin_title, string $title ): string { if ( ! ai4seo_is_user_inside_our_plugin_admin_pages() ) { return $admin_title; } $registry = ai4seo_get_plugins_menu_registry(); $active_subpage = ai4seo_get_active_subpage(); $active_post_type_subpage = ai4seo_get_active_post_type_subpage(); // default label $active_page_label = __( 'Dashboard', 'ai-for-seo' ); if ( ! empty( $active_subpage ) && isset( $registry[ $active_subpage ] ) ) { // Static subpages: settings, media, account, help $active_page_label = $registry[ $active_subpage ]['label']; } elseif ( $active_subpage === 'post' && ! empty( $active_post_type_subpage ) && isset( $registry['post_types'][ $active_post_type_subpage ] ) ) { // Dynamic post-type subpages $active_page_label = $registry['post_types'][ $active_post_type_subpage ]['label']; } $website_name = get_bloginfo( 'name' ); // build everything together and sanitize $browser_title = $active_page_label . ' ‹ ' . AI4SEO_PLUGIN_NAME . ' ‹ ' . $website_name; $browser_title = wp_strip_all_tags( $browser_title ); $browser_title = str_replace( array( '&', '&' ), '&', $browser_title ); $browser_title = str_replace( array( '<', '<' ), '<', $browser_title ); $browser_title = str_replace( array( '>', '>' ), '>', $browser_title ); $browser_title = str_replace( array( '"', '"' ), '"', $browser_title ); $browser_title = str_replace( array( ''', ''' ), "'", $browser_title ); return $browser_title; } // === FUNCTION TO ADD MENU-ITEM TO MAIN MENU ================================================ \\ /** * Build a registry of AI4SEO menu entries: labels and slugs. * * @return array{ * dashboard: array{label:string, slug:string}, * media: array{label:string, slug:string}, * account: array{label:string, slug:string}, * settings: array{label:string, slug:string}, * help: array{label:string, slug:string}, * post_types: array<string, array{label:string, slug:string}> * } */ function ai4seo_get_plugins_menu_registry(): array { // Static pages. $dashboard_slug = str_replace( '?page=', '', ai4seo_get_subpage_url( 'dashboard', array(), false ) ); // typically 'ai-for-seo' $settings_slug = str_replace( '?page=', '', ai4seo_get_subpage_url( 'settings', array(), false ) ); // e.g. 'ai-for-seo&ai4seo_subpage=settings' $media_slug = str_replace( '?page=', '', ai4seo_get_subpage_url( 'media', array(), false ) ); // e.g. 'ai-for-seo&ai4seo_subpage=media' $account_slug = str_replace( '?page=', '', ai4seo_get_subpage_url( 'account', array(), false ) ); // e.g. 'ai-for-seo&ai4seo_subpage=account' $help_slug = str_replace( '?page=', '', ai4seo_get_subpage_url( 'help', array(), false ) ); // e.g. 'ai-for-seo&ai4seo_subpage=help' // Dynamic post-type pages: use a stable slug (no pagination or other volatile args). $post_types = ai4seo_get_supported_post_types(); $post_type_map = array(); foreach ( $post_types as $this_post_type ) { $this_post_type = sanitize_key( $this_post_type ); $label = ai4seo_get_nice_label( ai4seo_get_post_type_translation( $this_post_type, true ) ); $slug = AI4SEO_PLUGIN_IDENTIFIER . '&ai4seo_subpage=post&ai4seo_post_type=' . $this_post_type; $post_type_map[ $this_post_type ] = array( 'label' => $label, 'slug' => $slug, ); } return array( 'dashboard' => array( 'label' => __( 'Dashboard', 'ai-for-seo' ), 'slug' => $dashboard_slug, ), 'media' => array( 'label' => _n( 'Media', 'Media', 2, 'ai-for-seo' ), 'slug' => $media_slug, ), 'account' => array( 'label' => __( 'Account', 'ai-for-seo' ), 'slug' => $account_slug, ), 'settings' => array( 'label' => __( 'Settings', 'ai-for-seo' ), 'slug' => $settings_slug, ), 'help' => array( 'label' => __( 'Help', 'ai-for-seo' ), 'slug' => $help_slug, ), 'post_types' => $post_type_map, ); } // =========================================================================================== \\ /** * Register AI4SEO menu and submenus. * * @return void */ function ai4seo_add_menu_entries() { $svg_tags = ai4seo_get_svg_tags(); if ( ! isset( $svg_tags['ai-for-seo-main-menu-icon'] ) ) { return; } $encoded_svg = 'data:image/svg+xml;base64,' . base64_encode( $svg_tags['ai-for-seo-main-menu-icon'] ); // Top-level title with notification bubble. $menu_title = AI4SEO_PLUGIN_NAME; $notification_count = (int) ai4seo_get_num_unread_notification(); if ( $notification_count > 0 ) { $menu_title .= " <span class='update-plugins count-{$notification_count}'><span class='plugin-count'>{$notification_count}</span></span>"; } // Central registry for labels and slugs. $plugins_menu_registries = ai4seo_get_plugins_menu_registry(); // Top-level. add_menu_page( AI4SEO_PLUGIN_NAME, $menu_title, // Contains markup for bubble. Keep as-is. 'edit_posts', AI4SEO_PLUGIN_IDENTIFIER, 'ai4seo_include_menu_frame_file', $encoded_svg, 99 ); // Dashboard (main page uses parent slug as submenu slug). add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $plugins_menu_registries['dashboard']['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $plugins_menu_registries['dashboard']['label'], 'edit_posts', AI4SEO_PLUGIN_IDENTIFIER, 'ai4seo_include_menu_frame_file' ); // Dynamic post-type submenus. foreach ( $plugins_menu_registries['post_types'] as $this_post_type ) { add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $this_post_type['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $this_post_type['label'], 'edit_posts', $this_post_type['slug'], 'ai4seo_include_menu_frame_file' ); } // Media. add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $plugins_menu_registries['media']['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $plugins_menu_registries['media']['label'], 'edit_posts', $plugins_menu_registries['media']['slug'], 'ai4seo_include_menu_frame_file' ); // Account. add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $plugins_menu_registries['account']['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $plugins_menu_registries['account']['label'], 'edit_posts', $plugins_menu_registries['account']['slug'], 'ai4seo_include_menu_frame_file' ); // Settings. add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $plugins_menu_registries['settings']['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $plugins_menu_registries['settings']['label'], 'edit_posts', $plugins_menu_registries['settings']['slug'], 'ai4seo_include_menu_frame_file' ); // Help. add_submenu_page( AI4SEO_PLUGIN_IDENTIFIER, $plugins_menu_registries['help']['label'] . ' - ' . AI4SEO_PLUGIN_NAME, $plugins_menu_registries['help']['label'], 'edit_posts', $plugins_menu_registries['help']['slug'], 'ai4seo_include_menu_frame_file' ); } // =========================================================================================== \\ /** * Mark our top-level menu as current when any AI for SEO page is open. * * @param string|null $parent_file * @return string|null The slug of the current top-level menu (if any). */ function ai4seo_mark_parent_menu_active(?string $parent_file ): ?string { if ( ai4seo_is_user_inside_our_plugin_admin_pages() ) { $parent_file = AI4SEO_PLUGIN_IDENTIFIER; } return $parent_file; } // =========================================================================================== \\ /** * Mark the correct submenu entry as current. * * @param string|null $submenu_file * @return string|null The slug of the current submenu entry (if any). */ function ai4seo_mark_submenu_active(?string $submenu_file): ?string { if ( ai4seo_is_user_inside_our_plugin_admin_pages() ) { // Central registry for labels and slugs. $plugins_menu_registries = ai4seo_get_plugins_menu_registry(); if ($active_post_type = ai4seo_get_active_post_type_subpage()) { $submenu_file = $plugins_menu_registries['post_types'][$active_post_type]['slug'] ?? $submenu_file; } elseif ( $active_subpage = ai4seo_get_active_subpage() ) { $submenu_file = $plugins_menu_registries[$active_subpage]['slug'] ?? $submenu_file; } else { $submenu_file = AI4SEO_PLUGIN_IDENTIFIER; } } return $submenu_file; } // === FUNCTION TO DISPLAY MENU FRAME ===================================================== \\ /** * Function to display the menu frame * @return void */ function ai4seo_include_menu_frame_file() { include_once(ai4seo_get_plugin_dir_path("includes/menu-frame.php")); } // =========================================================================================== \\ /** * Function to add modal schemas to the footer * @return void */ function ai4seo_include_modal_schemas_file() { include_once(ai4seo_get_includes_modal_schemas_path("autoload-modal-schemas.php")); } // =========================================================================================== \\ function ai4seo_enqueue_frontend_scripts() { global $ai4seo_scripts_version_number; // prevent multiple calls of this function if (!ai4seo_singleton(__FUNCTION__)) { return; } // check if we are outside the admin area if (is_admin()) { return; } // Enqueue ai-for-seo-alt-text-injection $is_render_level_alt_text_enabled = ai4seo_get_setting(AI4SEO_SETTING_ENABLE_RENDER_LEVEL_ALT_TEXT_INJECTION); $is_js_alt_text_enabled = ai4seo_get_setting(AI4SEO_SETTING_ENABLE_JS_ALT_TEXT_INJECTION); if ($is_render_level_alt_text_enabled && $is_js_alt_text_enabled) { wp_enqueue_script(AI4SEO_INJECTION_SCRIPTS_HANDLE, ai4seo_get_assets_js_path("ai-for-seo-alt-text-injection.js"), array("jquery"), $ai4seo_scripts_version_number, true); } } // === FUNCTION TO ENQUEUE JAVASCRIPT- AND CSS-FILES ========================================= \\ /** * Function to enqueue javascript- and css-files * @return void */ function ai4seo_enqueue_admin_scripts() { global $ai4seo_scripts_version_number; // prevent multiple calls of this function if (!ai4seo_singleton(__FUNCTION__)) { return; } wp_enqueue_script("wp-i18n"); // Register and enqueue stylesheet wp_register_style(AI4SEO_STYLES_HANDLE, ai4seo_get_assets_css_path("ai-for-seo-styles.css"), "", $ai4seo_scripts_version_number); wp_enqueue_style(AI4SEO_STYLES_HANDLE); // Enqueue javascript-file wp_enqueue_script(AI4SEO_SCRIPTS_HANDLE, ai4seo_get_assets_js_path("ai-for-seo-scripts.js"), array("jquery", "wp-i18n"), $ai4seo_scripts_version_number, true); // load translations load_plugin_textdomain("ai-for-seo"); // Set localization parameters ai4seo_set_localization_parameters(); /** * Prevent optimizers from combining/caching the main script which contains a localized nonce. */ add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { if ( $handle === AI4SEO_SCRIPTS_HANDLE ) { // LiteSpeed/Autoptimize respect data-no-optimize. $tag = str_replace( '<script ', '<script data-no-optimize="1" ', $tag ); } return $tag; }, 10, 3 ); } // =========================================================================================== \\ /** * Function to set localization parameters * * @return void */ function ai4seo_set_localization_parameters() { global $ai4seo_scripts_version_number; // === INITIALISATIONS ====================================================== \\ $current_post_id = ai4seo_get_post_id(); $ajax_nonce = wp_create_nonce( AI4SEO_GLOBAL_NONCE_IDENTIFIER ); $site_url = site_url(); $admin_url = admin_url(); $admin_ajax_url = admin_url( 'admin-ajax.php' ); $includes_url = includes_url(); $content_url = content_url(); $plugin_url = plugins_url(); $plugin_directory_url = plugins_url( '', __FILE__ ); $uploads_directory_url = wp_upload_dir(); $assets_directory_url = ai4seo_get_plugins_url( 'assets' ); $does_user_need_to_accept_tos_toc_and_pp = ai4seo_does_user_need_to_accept_tos_toc_and_pp(); $active_subpage = ai4seo_get_active_subpage(); $active_post_type_subpage = ai4seo_get_active_post_type_subpage(); $active_meta_tags = ai4seo_get_active_meta_tags(); $active_attachment_attributes = ai4seo_get_active_attachment_attributes(); $bypass_incognito_mode = ( isset( $_REQUEST['ai4seo_debug_bypass_incognito_mode'] ) && $_REQUEST['ai4seo_debug_bypass_incognito_mode'] ); $metadata_price_table = ai4seo_get_metadata_price_table(); $attachment_attributes_price_table = ai4seo_get_attachment_attributes_price_table(); // === LOCALIZATION PARAMETERS ============================================== \\ $localization_parameters = array( 'ai4seo_site_url' => $site_url, 'ai4seo_admin_url' => $admin_url, 'ai4seo_admin_ajax_url' => $admin_ajax_url, 'ai4seo_includes_url' => $includes_url, 'ai4seo_content_url' => $content_url, 'ai4seo_plugin_url' => $plugin_url, 'ai4seo_plugin_directory_url' => $plugin_directory_url, 'ai4seo_uploads_directory_url' => $uploads_directory_url, 'ai4seo_assets_directory_url' => $assets_directory_url, 'ai4seo_does_user_need_to_accepted_tos_toc_and_pp' => $does_user_need_to_accept_tos_toc_and_pp, 'ai4seo_plugin_version_number' => AI4SEO_PLUGIN_VERSION_NUMBER, 'ai4seo_admin_scripts_version_number' => $ai4seo_scripts_version_number, 'ai4seo_current_post_id' => $current_post_id, AI4SEO_GLOBAL_NONCE_IDENTIFIER => $ajax_nonce, 'ai4seo_bypass_incognito_mode' => $bypass_incognito_mode, 'ai4seo_active_subpage' => $active_subpage, 'ai4seo_active_post_type_subpage' => $active_post_type_subpage, 'ai4seo_active_meta_tags' => $active_meta_tags, 'ai4seo_active_attachment_attributes' => $active_attachment_attributes, 'ai4seo_max_editor_input_lengths' => AI4SEO_MAX_EDITOR_INPUT_LENGTHS, 'ai4seo_metadata_price_table' => $metadata_price_table, 'ai4seo_attachment_attributes_price_table' => $attachment_attributes_price_table, ); // === REGISTER SCRIPT LOCALIZATION ========================================= \\ wp_localize_script( AI4SEO_SCRIPTS_HANDLE, 'ai4seo_localization', $localization_parameters ); wp_set_script_translations( AI4SEO_SCRIPTS_HANDLE, 'ai-for-seo' ); } // =========================================================================================== \\ /** * Function to add new column to page- and post-table * @param array $columns * @return array */ function ai4seo_add_metadata_editor_column_to_posts_table(array $columns): array { // Make sure that this function is only called once if (!ai4seo_singleton(__FUNCTION__)) { return $columns; } $ai4seo_icon = "<img class='ai4seo-icon ai4seo-24x24-icon' src='" . esc_url(ai4seo_get_ai_for_seo_logo_url("32x32")) . "' alt='" . esc_attr(AI4SEO_PLUGIN_NAME) . "' /><span style='display: none'>" . esc_html(AI4SEO_PLUGIN_NAME) . "</span>"; return array_merge($columns, [AI4SEO_PLUGIN_IDENTIFIER => $ai4seo_icon]); } // =========================================================================================== \\ /** * Function to add content to new page- and post-table column * @param string $column_name * @param int $post_id * @return void */ function ai4seo_add_metadata_editor_button_to_posts_table(string $column_name, int $post_id) { if ($column_name == AI4SEO_PLUGIN_IDENTIFIER) { echo ai4seo_wp_kses(ai4seo_get_edit_metadata_button($post_id)); } } // =========================================================================================== \\ /** * Function to add plugin links (in the plugin directory) * @return array $links - array with links that will be displayed in the plugin directory near the plugin name */ function ai4seo_add_links_to_the_plugin_directory($links): array { // Check for function get_current_user_id() if (!function_exists("get_current_user_id")) { return array(); } // check if we loaded plugins already if (!did_action("load-plugins.php")) { return $links; // avoid running in unexpected contexts } // double check if we are in the plugin directory $this_plugin_basename = sanitize_text_field(ai4seo_get_plugin_basename()); if (current_filter() !== "plugin_action_links_{$this_plugin_basename}") { return $links; } // Make sure that this function is only called once if (!ai4seo_singleton(__FUNCTION__)) { return $links; } // remove everything from $links, except the deactivate link $links = array_filter($links, function($link) { return strpos($link, 'deactivate') !== false; }); // Define variables for the incognito-setting $ai4seo_setting_enable_incognito_mode = ai4seo_is_incognito_mode_enabled(); $ai4seo_setting_incognito_mode_user_id = ai4seo_get_setting(AI4SEO_SETTING_INCOGNITO_MODE_USER_ID); $current_user_id = get_current_user_id(); // Check incognito-setting and incognito user-id if ($ai4seo_setting_enable_incognito_mode && $ai4seo_setting_incognito_mode_user_id != $current_user_id) { return array(); } $dashboard_link_url = ai4seo_get_subpage_url("dashboard"); // only show help and upgrade links if the user has not accepted the TOS yet if (ai4seo_does_user_need_to_accept_tos_toc_and_pp()) { // add accept terms of service link (by going to the plugin's dashboard) $tos_link_tag = "<a href='" . esc_url($dashboard_link_url) . "'>> " . esc_html__("Accept Terms of Service", "ai-for-seo") . " <</a>"; array_unshift($links, $tos_link_tag); } else { // Add Settings Link $settings_link_url = ai4seo_get_subpage_url("settings"); if ($settings_link_url) { $settings_link_tag = "<a href='" . esc_url($settings_link_url) . "'>" . esc_html__("Settings", "ai-for-seo") . "</a>"; array_unshift($links, $settings_link_tag); } // add Help link $help_link_url = ai4seo_get_subpage_url("help"); if ($help_link_url) { $help_link_tag = "<a href='" . esc_url($help_link_url) . "'>" . esc_html__("Help", "ai-for-seo") . "</a>"; array_unshift($links, $help_link_tag); } # todo: add get more credits link with ajax modal // add dashboard link at the front of the links $dashboard_link_tag = "<a href='" . esc_url($dashboard_link_url) . "'>" . esc_html__("Dashboard", "ai-for-seo") . "</a>"; array_unshift($links, $dashboard_link_tag); } return $links; } // =========================================================================================== \\ /** * Function to add menu-item to admin-bar * @return void */ function ai4seo_add_admin_menu_item($wp_admin_bar) { if (!ai4seo_singleton(__FUNCTION__)) { return; } // Stop function if called outside of page or post etc. if (!is_singular()) { return; } // Prepare arguments for admin-bar menu-item $args = array( "id" => "ai4seo-edit", "title" => "<div class='ai4seo-main-menu-icon'></div> " . esc_html__("Metadata Editor", "ai-for-seo"), "meta" => array( "onclick" => "ai4seo_open_metadata_editor_modal();return false;", ), ); // Add node $wp_admin_bar->add_node($args); // Add node for mobile version $wp_admin_bar->add_menu( array( "parent" => "appearance", "id" => "ai4seo-edit-mobile", "title" => esc_html__("AI for SEO - Metadata Editor", "ai-for-seo"), "meta" => array( "onclick" => "ai4seo_open_metadata_editor_modal();return false;", ), )); } // =========================================================================================== \\ /*function ai4seo_init_meta_tags_output() { // read setting AI4SEO_SETTING_META_TAG_OUTPUT_MODE $meta_tag_output_mode = ai4seo_get_setting(AI4SEO_SETTING_META_TAG_OUTPUT_MODE); // Stop function if meta tag output is disabled if ($meta_tag_output_mode == "disable") { return; } if (ai4seo_is_plugin_or_theme_active(AI4SEO_THIRD_PARTY_PLUGIN_SQUIRRLY_SEO)) { // Squirrly SEO workaround, as they use their own buffer add_action("sq_buffer", "ai4seo_inject_our_meta_tags_into_the_html_head", 20); } else { ob_start('ai4seo_inject_our_meta_tags_into_the_html_head'); } }*/ // =========================================================================================== \\ /** * Function modify and add meta tags to the html header * @param string $full_html_buffer - the full html buffer * @return string $full_html_buffer - the modified html buffer */ function ai4seo_inject_our_meta_tags_into_the_html_head(string $full_html_buffer): string { // check if we are on a singular if (!is_singular()) { return $full_html_buffer; // stop function if we are not on a singular page or post } // Define variable for the page- or post-id $post_id = ai4seo_get_post_id(); // Stop function if no page- or post-id is defined if (!$post_id) { return $full_html_buffer; } if (!defined('AI4SEO_METADATA_DETAILS')) { return $full_html_buffer; } // read setting AI4SEO_SETTING_META_TAG_OUTPUT_MODE $meta_tag_output_mode = ai4seo_get_setting(AI4SEO_SETTING_META_TAG_OUTPUT_MODE); if ($meta_tag_output_mode == "disable") { return $full_html_buffer; // stop function if meta tag output is disabled } // read settings AI4SEO_SETTING_VISIBLE_META_TAGS $active_meta_tags = ai4seo_get_active_meta_tags(); if (!$active_meta_tags) { return $full_html_buffer; } // Extract the content between <head> and </head> $head_start_position = strpos($full_html_buffer, '<head>'); if ($head_start_position === false) { return $full_html_buffer; } // start position right after <head> $head_start_position += 6; $head_end_position = strpos($full_html_buffer, '</head>'); if ($head_end_position === false) { $head_end_position = strlen($full_html_buffer); // if no closing head tag is found, set end position to the end of the buffer } $head_html = substr($full_html_buffer, $head_start_position, $head_end_position - $head_start_position); // analyse head html $found_third_party_meta_tags = ai4seo_get_meta_tags_from_html($head_html); // read OUR metadata values for this post $our_metadata = ai4seo_read_available_metadata_by_post_ids(array($post_id), false); if ($our_metadata) { $our_metadata = $our_metadata[$post_id] ?? array(); } // check post type $supported_post_types = ai4seo_get_supported_post_types(); $current_post_type = get_post_type($post_id); if (!in_array($current_post_type, $supported_post_types, true)) { return $full_html_buffer; } $current_product_price_for_placeholders = ''; $current_product_name_for_placeholders = ''; $current_post_title_for_placeholders = ''; $current_post_title_raw = get_the_title($post_id); if (is_string($current_post_title_raw)) { $current_post_title_for_placeholders = trim(wp_strip_all_tags($current_post_title_raw)); } if ($current_post_type === 'product' && ai4seo_is_plugin_or_theme_active(AI4SEO_THIRD_PARTY_PLUGIN_WOOCOMMERCE) && function_exists('wc_get_product') && ai4seo_is_function_usable('wc_get_product') && function_exists('wc_price') && ai4seo_is_function_usable('wc_price') && class_exists('WC_Product') ) { $current_wc_product = wc_get_product($post_id); if ($current_wc_product instanceof WC_Product) { $current_product_name_for_placeholders = wp_strip_all_tags($current_wc_product->get_name()); $current_wc_product_price_raw = $current_wc_product->get_price(); if ($current_wc_product_price_raw !== '' && $current_wc_product_price_raw !== null) { $current_wc_product_price = wc_price($current_wc_product_price_raw); $current_wc_product_price = strip_tags($current_wc_product_price); $current_wc_product_price = html_entity_decode($current_wc_product_price, ENT_QUOTES | ENT_HTML5, 'UTF-8'); $current_wc_product_price = str_replace("\xC2\xA0", ' ', $current_wc_product_price); $current_product_price_for_placeholders = trim($current_wc_product_price); } } } // go through each meta tag and decide what to do with it $add_this_metadata = array(); $remove_this_third_party_meta_tags = array(); $metadata_placeholder_replacements = ai4seo_get_metadata_placeholder_replacements( $post_id, $current_product_price_for_placeholders, $current_product_name_for_placeholders ); if ($current_post_title_for_placeholders !== '') { $metadata_placeholder_replacements['TITLE'] = $current_post_title_for_placeholders; } foreach (AI4SEO_METADATA_DETAILS as $this_metadata_identifier => $this_metadata_field_details) { $this_found_third_party_meta_tags = $found_third_party_meta_tags[$this_metadata_identifier] ?? array(); $this_our_metadata = $our_metadata[$this_metadata_identifier] ?? ""; // exclude this meta tag if not active if (!in_array($this_metadata_identifier, $active_meta_tags)) { $this_our_metadata = ""; $our_metadata[$this_metadata_identifier] = ""; } // find a fallback if neither we nor a third party have a value for this meta tag if (empty($this_our_metadata) && empty($this_found_third_party_meta_tags)) { ai4seo_apply_possible_fallbacks($post_id, $this_metadata_identifier, $our_metadata); $this_our_metadata = $our_metadata[$this_metadata_identifier] ?? ""; } // leave this meta tag alone if we do not have a value for it or we exclude this meta tag if (!$this_our_metadata) { continue; } switch ($meta_tag_output_mode) { case "force": $add_this_metadata[$this_metadata_identifier] = $this_our_metadata; break; case "replace": $add_this_metadata[$this_metadata_identifier] = $this_our_metadata; // remove found third party meta tags if ($this_found_third_party_meta_tags) { foreach ($this_found_third_party_meta_tags AS $this_found_third_party_meta_tag) { if ($this_found_third_party_meta_tag) { $remove_this_third_party_meta_tags[] = $this_found_third_party_meta_tag["raw-html"]; } } } break; case "complement": if (!$this_found_third_party_meta_tags) { $add_this_metadata[$this_metadata_identifier] = $this_our_metadata; } else { // workaround: if all the found meta tags are empty -> add ours anyway and remove their empty ones $this_found_third_party_meta_tag_got_content = false; $this_found_third_party_meta_tag_no_content_raw_html = array(); foreach ($this_found_third_party_meta_tags AS $this_found_third_party_meta_tag) { if ($this_found_third_party_meta_tag["content"]) { $this_found_third_party_meta_tag_got_content = true; break; } else { $this_found_third_party_meta_tag_no_content_raw_html[] = $this_found_third_party_meta_tag["raw-html"]; } } if (!$this_found_third_party_meta_tag_got_content) { $add_this_metadata[$this_metadata_identifier] = $this_our_metadata; $remove_this_third_party_meta_tags = array_merge($remove_this_third_party_meta_tags, $this_found_third_party_meta_tag_no_content_raw_html); } } break; } } // Remove any third-party meta tags and surrounding non-visible characters if ($remove_this_third_party_meta_tags) { foreach ($remove_this_third_party_meta_tags AS $this_remove_this_meta_tag) { // Use preg_replace to match the tag and any surrounding whitespace or line breaks $full_html_buffer = preg_replace( '/' . preg_quote($this_remove_this_meta_tag, '/') . '\s*/s', '', $full_html_buffer ); } } // add our tags to the head, finding position first if ($add_this_metadata) { $add_this_meta_tags = array(); // Read prefix- and suffix-settings $ai4seo_metadata_prefixes = ai4seo_get_setting(AI4SEO_SETTING_METADATA_PREFIXES); $ai4seo_metadata_suffixes = ai4seo_get_setting(AI4SEO_SETTING_METADATA_SUFFIXES); // prepare our meta tags foreach ($add_this_metadata as $this_metadata_identifier => $this_metadata_content) { $this_metadata_field_details = AI4SEO_METADATA_DETAILS[$this_metadata_identifier] ?? array(); $this_metadata_prefix_raw = $ai4seo_metadata_prefixes[$this_metadata_identifier] ?? ""; $this_metadata_suffix_raw = $ai4seo_metadata_suffixes[$this_metadata_identifier] ?? ""; $this_metadata_prefix = trim(sanitize_text_field($this_metadata_prefix_raw)); $this_metadata_suffix = trim(sanitize_text_field($this_metadata_suffix_raw)); if ($current_post_type !== 'product' && ai4seo_text_contains_product_placeholder($this_metadata_prefix_raw) ) { $this_metadata_prefix = ''; } else { $this_metadata_prefix = ai4seo_replace_text_placeholders( $this_metadata_prefix, $metadata_placeholder_replacements ); } if ($current_post_type !== 'product' && ai4seo_text_contains_product_placeholder($this_metadata_suffix_raw) ) { $this_metadata_suffix = ''; } else { $this_metadata_suffix = ai4seo_replace_text_placeholders( $this_metadata_suffix, $metadata_placeholder_replacements ); } $this_metadata_prefix = ai4seo_replace_metadata_title_placeholder( $this_metadata_prefix, $current_post_title_for_placeholders ); $this_metadata_suffix = ai4seo_replace_metadata_title_placeholder( $this_metadata_suffix, $current_post_title_for_placeholders ); if (!$this_metadata_field_details) { continue; } if (false !== strpos($this_metadata_content, '{WC_PRICE=')) { $this_metadata_content = preg_replace_callback( '/\{WC_PRICE=([^}]+)\}/', function ($matches) use ($current_product_price_for_placeholders) { $fallback_price = html_entity_decode(wp_strip_all_tags($matches[1]), ENT_QUOTES | ENT_HTML5, 'UTF-8'); $fallback_price = str_replace("\xC2\xA0", ' ', $fallback_price); $fallback_price = trim($fallback_price); if ($current_product_price_for_placeholders !== '') { return $current_product_price_for_placeholders; } return $fallback_price; }, $this_metadata_content ); } // Add prefix and suffix $this_metadata_content = trim($this_metadata_prefix . " " . $this_metadata_content . " " . $this_metadata_suffix); // Prepare variables $this_output_tag_type = $this_metadata_field_details["output-tag-type"] ?? ""; $this_output_tag_identifier = $this_metadata_field_details["output-tag-identifier"] ?? ""; // Handle output for output-tag-type "title" if ($this_output_tag_type == "title") { $add_this_meta_tags[] = "<title>" . esc_attr($this_metadata_content) . ""; } // Handle output for output-tag-type "meta name" elseif ($this_output_tag_type == "meta name") { $add_this_meta_tags[] = ""; } // Handle output for output-tag-type "meta property" elseif ($this_output_tag_type == "meta property") { $add_this_meta_tags[] = ""; } } // output our meta tags if ($add_this_meta_tags) { // find a suitable position for our meta tags $our_meta_tags_position = $head_start_position; // consider the charset meta tag position, if it's near the head start if (isset($found_third_party_meta_tags["charset"])) { $charset_meta_tags_position = strpos($full_html_buffer, $found_third_party_meta_tags["charset"]["raw-html"]) + strlen($found_third_party_meta_tags["charset"]["raw-html"]); // set $charset_meta_tags_position as our meta tags position if it's not further away than 100 characters if ($charset_meta_tags_position - $head_start_position < 100) { $our_meta_tags_position = $charset_meta_tags_position; } } // consider the viewport meta tag position, if it's near the head start if (isset($found_third_party_meta_tags["viewport"])) { $viewport_meta_tags_position = strpos($full_html_buffer, $found_third_party_meta_tags["viewport"]["raw-html"]) + strlen($found_third_party_meta_tags["viewport"]["raw-html"]); // set $viewport_meta_tags_position as our meta tags position if it's not further away than 200 characters if ($viewport_meta_tags_position - $head_start_position < 200) { $our_meta_tags_position = $viewport_meta_tags_position; } } // Read start- and end-settings for generator hints $add_generator_hints = ai4seo_get_setting(AI4SEO_SETTING_ADD_GENERATOR_HINTS); if ($add_generator_hints) { $source_code_notes_start = ai4seo_get_setting(AI4SEO_SETTING_META_TAGS_BLOCK_STARTING_HINT); $source_code_notes_end = ai4seo_get_setting(AI4SEO_SETTING_META_TAGS_BLOCK_ENDING_HINT); // Replace placeholders in source-code-notes $source_code_notes_start = ai4seo_replace_white_label_placeholders($source_code_notes_start); $source_code_notes_end = ai4seo_replace_white_label_placeholders($source_code_notes_end); // Make sure that $source_code_notes_start and $source_code_notes_end don't exceed the max. length // decode \" to " $source_code_notes_start = str_replace('\"', '"', $source_code_notes_start); $source_code_notes_end = str_replace('\"', '"', $source_code_notes_end); $source_code_notes_start = ai4seo_mb_substr($source_code_notes_start, 0, 250); $source_code_notes_end = ai4seo_mb_substr($source_code_notes_end, 0, 250); // add plugin information to the meta tags block array_unshift($add_this_meta_tags, ""); $add_this_meta_tags[] = ""; } $add_this_meta_tags = ai4seo_deep_sanitize($add_this_meta_tags, 'ai4seo_wp_kses'); // add our meta tags to the head $full_html_buffer = substr_replace($full_html_buffer, "\n\n\t" . implode("\n\t", $add_this_meta_tags) . "\n", $our_meta_tags_position, 0); } } return $full_html_buffer; } // =========================================================================================== \\ function ai4seo_inject_image_attributes_for_gutenberg( $content, $block ) { // Skip admin, feeds, REST API and AJAX requests if ( is_admin() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { return $content; } return ai4seo_inject_image_attributes_into_html( $content ); } // =========================================================================================== \\ /** * Function to inject image attributes (alt text and title) into images * Sets up output buffering to inject attributes at render level when enabled */ function ai4seo_inject_image_attributes_into_html($content) { $alt_enabled = ai4seo_get_setting( AI4SEO_SETTING_ENABLE_RENDER_LEVEL_ALT_TEXT_INJECTION ); $title_injection_mode = ai4seo_get_setting( AI4SEO_SETTING_IMAGE_TITLE_INJECTION_MODE ); if ( ! $alt_enabled && $title_injection_mode === 'disabled' ) { return $content; } static $cache = []; return preg_replace_callback( '/]*?)>/i', function( $matches ) use ( &$cache, $alt_enabled, $title_injection_mode ) { $this_full_tag = $matches[0]; $this_attr_str = $matches[1]; // find src → attachment ID if ( ! preg_match( '/\bsrc=["\']([^"\']+)["\']/', $this_attr_str, $this_src_matches ) ) { return $this_full_tag; } $this_post_id = ai4seo_get_attachment_id_from_src( $this_src_matches[1] ); if ( ! $this_post_id ) { return $this_full_tag; } // make sure our plugin generated alt text for this entry // check if we have a wp_postmeta entry AI4SEO_POST_META_GENERATED_DATA_META_KEY for this post id -> skip if not if (!get_post_meta($this_post_id, AI4SEO_POST_META_GENERATED_DATA_META_KEY, true)) { return $this_full_tag; } $this_needs_mod = false; $this_to_add = []; // ——— ALT logic ——— if ( $alt_enabled ) { // grab existing (might be empty) preg_match( '/\balt\s*=\s*["\']([^"\']*)["\']/', $this_attr_str, $this_alt_matches ); $this_existing_alt = $this_alt_matches[1] ?? null; // get DB value (once) if ( ! isset( $cache[ $this_post_id ]['alt'] ) ) { $cache[ $this_post_id ]['alt'] = get_post_meta( $this_post_id, '_wp_attachment_image_alt', true ); } $this_db_alt = $cache[ $this_post_id ]['alt']; if ( $this_db_alt && $this_existing_alt !== $this_db_alt ) { $this_to_add['alt'] = $this_db_alt; } } // ——— TITLE logic ——— if ( $title_injection_mode !== 'disabled' ) { preg_match( '/\btitle\s*=\s*["\']([^"\']*)["\']/', $this_attr_str, $this_title_matches ); $this_existing_title = $this_title_matches[1] ?? null; if ( ! isset( $cache[ $this_post_id ][ $title_injection_mode ] ) ) { $cache[ $this_post_id ][ $title_injection_mode ] = ai4seo_get_title_attribute_value( $this_post_id, $title_injection_mode, $cache ); } $this_db_title = $cache[ $this_post_id ][ $title_injection_mode ]; if ( $this_db_title && $this_existing_title !== $this_db_title ) { $this_to_add['title'] = $this_db_title; } } if ( ! $this_to_add ) { return $this_full_tag; } // strip out any old alt="" or title="" if (isset($this_to_add['alt'])) { $this_attr_str = preg_replace( '/\s*(?:alt)\s*=\s*["\'][^"\']*["\']/', '', $this_attr_str ); } if (isset($this_to_add['title'])) { $this_attr_str = preg_replace( '/\s*(?:title)\s*=\s*["\'][^"\']*["\']/', '', $this_attr_str ); } // remove trailing slash $this_attr_str = preg_replace( '/\s*\/$/', '', rtrim( $this_attr_str ) ); // rebuild $this_self_closed = substr( rtrim( $this_full_tag ), -2 ) === '/>'; $this_tag_ending = $this_self_closed ? ' />' : '>'; $this_new_tag = ' $val ) { $this_new_tag .= ' ' . $name . '="' . esc_attr( $val ) . '"'; } $this_full_tag = $this_new_tag . $this_tag_ending; return $this_full_tag; }, $content ); } // =========================================================================================== \\ /** * Helper function to get the appropriate title attribute value based on setting * @param int $attachment_id The attachment ID * @param string $setting_value The title injection setting value * @param array &$cache Reference to the cache array * @return string|false The title attribute value or false if none found */ function ai4seo_get_title_attribute_value(int $attachment_id, string $setting_value, array &$cache ) { $cache_key = $setting_value; if ( isset( $cache[ $attachment_id ][ $cache_key ] ) ) { return $cache[ $attachment_id ][ $cache_key ]; } $value = false; switch ( $setting_value ) { case 'inject_title': $value = get_the_title( $attachment_id ); break; case 'inject_alt_text': $value = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); break; case 'inject_caption': $attachment = get_post( $attachment_id ); if ( $attachment ) { $value = $attachment->post_excerpt; } break; case 'inject_description': $attachment = get_post( $attachment_id ); if ( $attachment ) { $value = $attachment->post_content; } break; } $cache[ $attachment_id ][ $cache_key ] = $value; return $value; } // =========================================================================================== \\ /** * Function to get attachment ID from image src URL * @param string $ai4seo_img_src - the image src URL * @return int|false - attachment ID or false if not found */ function ai4seo_get_attachment_id_from_src(string $ai4seo_img_src) { global $wpdb; // Remove query parameters and fragments from URL $ai4seo_img_src = strtok($ai4seo_img_src, '?'); $ai4seo_img_src = strtok($ai4seo_img_src, '#'); // First try WordPress built-in function $ai4seo_attachment_id = attachment_url_to_postid($ai4seo_img_src); if ($ai4seo_attachment_id) { return $ai4seo_attachment_id; } // If that fails, try to match by filename in case of different sizes $ai4seo_filename = basename($ai4seo_img_src); // Remove size suffixes like -150x150, -300x200, etc. $ai4seo_filename_without_size = preg_replace('/-\d+x\d+(?=\.[^.]*$)/', '', $ai4seo_filename); if ($ai4seo_filename_without_size !== $ai4seo_filename) { // Try to find by the original filename $ai4seo_original_url = str_replace($ai4seo_filename, $ai4seo_filename_without_size, $ai4seo_img_src); $ai4seo_attachment_id = attachment_url_to_postid($ai4seo_original_url); if ($ai4seo_attachment_id) { return $ai4seo_attachment_id; } } // As last resort, search in postmeta for the URL $ai4seo_query = $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s LIMIT 1", '%' . $wpdb->esc_like($ai4seo_filename) . '%' ); $ai4seo_attachment_id = $wpdb->get_var($ai4seo_query); return $ai4seo_attachment_id ? (int) $ai4seo_attachment_id : false; } // =========================================================================================== \\ function ai4seo_filter_wp_image_attrs( $attr, $attachment, $size ) { if ( empty( $attr['alt'] ) ) { $alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ); if ( $alt ) { $attr['alt'] = sanitize_text_field( $alt ); } } return $attr; } // =========================================================================================== \\ /** * Populate missing metadata values by applying configured fallbacks. * * @param int $post_id The current post ID. * @param string $metadata_identifier Metadata identifier to resolve. * @param array $our_metadata Reference to metadata collection for this post. * @param array $visited_metadata_identifiers Optional stack to avoid circular fallbacks. * * @return void */ function ai4seo_apply_possible_fallbacks(int $post_id, string $metadata_identifier, array &$our_metadata, array $visited_metadata_identifiers = array()): void { if (isset($our_metadata[$metadata_identifier]) && $our_metadata[$metadata_identifier]) { return; } if (in_array($metadata_identifier, $visited_metadata_identifiers, true)) { return; } $active_meta_tags = ai4seo_get_active_meta_tags(); $visited_metadata_identifiers[] = $metadata_identifier; $fallback_setting_name = ai4seo_get_metadata_fallback_setting_name($metadata_identifier); if (!$fallback_setting_name) { return; } $fallback_preference = ai4seo_get_setting($fallback_setting_name); $allowed_fallback_values = ai4seo_get_metadata_fallback_allowed_values($metadata_identifier); if (!is_string($fallback_preference) || $fallback_preference === '' || $fallback_preference === 'no-fallback' || !array_key_exists($fallback_preference, $allowed_fallback_values)) { return; } $fallback_value = ''; switch ($fallback_preference) { case 'post-title': $fallback_value = ai4seo_get_metadata_fallback_post_title($post_id); break; case 'post-excerpt': $fallback_value = ai4seo_get_metadata_fallback_post_excerpt($post_id); break; case 'content': $fallback_value = ai4seo_get_metadata_fallback_post_content($post_id); break; default: $fallback_metadata_identifier = $fallback_preference; // if the fallback metadata identifier is not active, stop here if (!in_array($fallback_metadata_identifier, $active_meta_tags, true)) { return; } if (in_array($fallback_metadata_identifier, $visited_metadata_identifiers, true)) { return; } if (!isset($our_metadata[$fallback_metadata_identifier]) || !$our_metadata[$fallback_metadata_identifier]) { ai4seo_apply_possible_fallbacks($post_id, $fallback_metadata_identifier, $our_metadata, $visited_metadata_identifiers); } $fallback_value = $our_metadata[$fallback_metadata_identifier] ?? ''; break; } if (!is_string($fallback_value)) { if (is_scalar($fallback_value)) { $fallback_value = (string) $fallback_value; } else { return; } } $fallback_value = trim($fallback_value); if ($fallback_value === '') { return; } $our_metadata[$metadata_identifier] = $fallback_value; } // =========================================================================================== \\ /** * Retrieve the setting name that stores the fallback preference for a metadata identifier. * * @param string $metadata_identifier Metadata identifier. * * @return string|null The related setting constant or null when unsupported. */ function ai4seo_get_metadata_fallback_setting_name(string $metadata_identifier): ?string { switch ($metadata_identifier) { case 'meta-title': return AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE; case 'meta-description': return AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION; case 'facebook-title': return AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE; case 'facebook-description': return AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION; case 'twitter-title': return AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE; case 'twitter-description': return AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION; } return null; } // =========================================================================================== \\ /** * Retrieve the metadata identifier mapped to a fallback setting name. * * @param string $setting_name Setting identifier. * * @return string|null Metadata identifier or null if not supported. */ function ai4seo_get_fallback_metadata_identifier_by_setting_name(string $setting_name): ?string { switch ($setting_name) { case AI4SEO_SETTING_METADATA_FALLBACK_META_TITLE: return 'meta-title'; case AI4SEO_SETTING_METADATA_FALLBACK_META_DESCRIPTION: return 'meta-description'; case AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_TITLE: return 'facebook-title'; case AI4SEO_SETTING_METADATA_FALLBACK_FACEBOOK_DESCRIPTION: return 'facebook-description'; case AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_TITLE: return 'twitter-title'; case AI4SEO_SETTING_METADATA_FALLBACK_TWITTER_DESCRIPTION: return 'twitter-description'; } return null; } // =========================================================================================== \\ /** * Return the available fallback options for a metadata identifier. * * @param string $metadata_identifier Metadata identifier. * * @return array Allowed fallback options. */ function ai4seo_get_metadata_fallback_allowed_values(string $metadata_identifier): array { switch ($metadata_identifier) { case 'meta-title': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-title' => esc_html__('Use post title', 'ai-for-seo'), 'facebook-title' => esc_html__('Use Facebook title', 'ai-for-seo'), 'twitter-title' => esc_html__('Use Twitter title', 'ai-for-seo'), ); case 'meta-description': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-excerpt' => esc_html__('Use post excerpt', 'ai-for-seo'), 'content' => esc_html__('Use post content', 'ai-for-seo'), 'facebook-description' => esc_html__('Use Facebook description', 'ai-for-seo'), 'twitter-description' => esc_html__('Use Twitter description', 'ai-for-seo'), ); case 'facebook-title': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-title' => esc_html__('Use post title', 'ai-for-seo'), 'meta-title' => esc_html__('Use meta title', 'ai-for-seo'), 'twitter-title' => esc_html__('Use Twitter title', 'ai-for-seo'), ); case 'facebook-description': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-excerpt' => esc_html__('Use post excerpt', 'ai-for-seo'), 'content' => esc_html__('Use post content', 'ai-for-seo'), 'meta-description' => esc_html__('Use meta description', 'ai-for-seo'), 'twitter-description' => esc_html__('Use Twitter description', 'ai-for-seo'), ); case 'twitter-title': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-title' => esc_html__('Use post title', 'ai-for-seo'), 'meta-title' => esc_html__('Use meta title', 'ai-for-seo'), 'facebook-title' => esc_html__('Use Facebook title', 'ai-for-seo'), ); case 'twitter-description': return array( 'no-fallback' => esc_html__('No fallback', 'ai-for-seo'), 'post-excerpt' => esc_html__('Use post excerpt', 'ai-for-seo'), 'content' => esc_html__('Use post content', 'ai-for-seo'), 'meta-description' => esc_html__('Use meta description', 'ai-for-seo'), 'facebook-description' => esc_html__('Use Facebook description', 'ai-for-seo'), ); } return array(); } // =========================================================================================== \\ /** * Get a shortened fallback text from the post title. * * @param int $post_id Current post ID. * * @return string Prepared fallback text. */ function ai4seo_get_metadata_fallback_post_title(int $post_id): string { $post_title = get_the_title($post_id); $post_title = ai4seo_prepare_metadata_fallback_text($post_title); if ($post_title === '') { return ''; } return ai4seo_limit_metadata_fallback_text($post_title, 100); } // =========================================================================================== \\ /** * Get a shortened fallback text from the post excerpt. * * @param int $post_id Current post ID. * * @return string Prepared fallback text. */ function ai4seo_get_metadata_fallback_post_excerpt(int $post_id): string { $post_excerpt = get_the_excerpt($post_id); $post_excerpt = ai4seo_prepare_metadata_fallback_text($post_excerpt); if ($post_excerpt === '') { return ''; } return ai4seo_limit_metadata_fallback_text($post_excerpt, 150); } // =========================================================================================== \\ /** * Get a shortened fallback text from the post content. * * @param int $post_id Current post ID. * * @return string Prepared fallback text. */ function ai4seo_get_metadata_fallback_post_content(int $post_id): string { $post_content = get_post_field('post_content', $post_id, 'raw'); $post_content = ai4seo_prepare_metadata_fallback_text($post_content); if ($post_content === '') { return ''; } return ai4seo_limit_metadata_fallback_text($post_content, 150); } // =========================================================================================== \\ /** * Prepare a string for fallback usage by removing markup and normalising whitespace. * * @param mixed $text Input text. * * @return string Cleaned text. */ function ai4seo_prepare_metadata_fallback_text($text): string { if (!is_string($text)) { return ''; } $text = wp_strip_all_tags($text); $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'); $text = preg_replace('/\s+/u', ' ', $text); if (!is_string($text)) { $text = ''; } return trim($text); } // =========================================================================================== \\ /** * Limit fallback text length while keeping current words intact where possible. * * @param string $text Prepared text. * @param int $base_length Hard character limit before soft extension. * * @return string Shortened text. */ function ai4seo_limit_metadata_fallback_text(string $text, int $base_length): string { if ($text === '') { return ''; } if (ai4seo_mb_strlen($text) <= $base_length) { return $text; } $base_snippet = ai4seo_mb_substr($text, 0, $base_length); $remaining_segment = ai4seo_mb_substr($text, $base_length, 20); $append = ''; if ($remaining_segment !== '') { $remaining_segment_trimmed = ltrim($remaining_segment); $leading_whitespace_removed = ai4seo_mb_strlen($remaining_segment_trimmed) !== ai4seo_mb_strlen($remaining_segment); if ($remaining_segment_trimmed !== '' && preg_match('/^\S{0,20}/u', $remaining_segment_trimmed, $match) && isset($match[0])) { $append_segment = $match[0]; if ($leading_whitespace_removed && $append_segment !== '' && !preg_match('/\s$/u', $base_snippet)) { $append = ' ' . $append_segment; } else { $append = $append_segment; } } } $result = $base_snippet . $append; return trim($result); } // =========================================================================================== \\ /** * Function to replace white-label-placeholders * @param string $text string with text containing placeholders * @return string $text with placeholders replaced */ function ai4seo_replace_white_label_placeholders($text) { $text = str_replace( ["{NAME}", "{VERSION}", "{WEBSITE}"], [AI4SEO_PLUGIN_NAME, AI4SEO_PLUGIN_VERSION_NUMBER, AI4SEO_OFFICIAL_WEBSITE], $text); return $text; } // =========================================================================================== \\ /** * Returns common placeholder replacements shared across metadata and attachments. * * @return array */ function ai4seo_get_common_placeholder_replacements(): array { $website_url = untrailingslashit(home_url()); $website_url = $website_url ? trim(esc_url_raw($website_url)) : ''; $website_name = get_bloginfo('name'); $website_name = is_string($website_name) ? trim(wp_strip_all_tags($website_name)) : ''; return array( 'WEBSITE_URL' => $website_url, 'WEBSITE_NAME' => $website_name, ); } // =========================================================================================== \\ /** * Returns placeholder replacements for metadata prefixes and suffixes. * * @param int $post_id The current post ID. * @param string $product_price The WooCommerce product price if available. * @param string $product_name The WooCommerce product name if available. * * @return array */ function ai4seo_get_metadata_placeholder_replacements(int $post_id, string $product_price = '', string $product_name = ''): array { $replacements = ai4seo_get_common_placeholder_replacements(); $replacements['POST_ID'] = (string) absint($post_id); $post_type = get_post_type($post_id); $product_name_value = ''; $product_price_value = ''; if ($post_type === 'product') { if ($product_name === '') { $product_name = get_the_title($post_id); } $product_name_value = is_string($product_name) ? trim(wp_strip_all_tags($product_name)) : ''; if ($product_price !== '') { $product_price_value = trim(wp_strip_all_tags($product_price)); } } $replacements['PRODUCT_NAME'] = $product_name_value; $replacements['PRODUCT_PRICE'] = $product_price_value; return $replacements; } // =========================================================================================== \\ /** * Returns placeholder replacements for attachment prefixes and suffixes. * * @param int $attachment_post_id The attachment post ID. * * @return array */ function ai4seo_get_attachment_placeholder_replacements(int $attachment_post_id): array { $replacements = ai4seo_get_common_placeholder_replacements(); $replacements['POST_ID'] = (string) absint($attachment_post_id); $replacements['FILE_NAME'] = ''; $replacements['FILE_TYPE'] = ''; $replacements['FILE_SIZE'] = ''; $replacements['IMAGE_DIMENSIONS'] = ''; $attached_file_path = get_attached_file($attachment_post_id); $pathinfo = array(); if ($attached_file_path) { $pathinfo = pathinfo($attached_file_path); } else { $attachment_url = wp_get_attachment_url($attachment_post_id); if ($attachment_url) { $url_path = wp_parse_url($attachment_url, PHP_URL_PATH); if ($url_path) { $pathinfo = pathinfo($url_path); } } } if (!empty($pathinfo['filename'])) { $replacements['FILE_NAME'] = trim(sanitize_text_field($pathinfo['filename'])); } if (!empty($pathinfo['extension'])) { $replacements['FILE_TYPE'] = strtolower(trim(sanitize_text_field($pathinfo['extension']))); } if ($attached_file_path && file_exists($attached_file_path)) { $file_size_bytes = @filesize($attached_file_path); if (is_int($file_size_bytes) || is_float($file_size_bytes)) { $file_size_kb = $file_size_bytes / 1024; if ($file_size_kb > 0) { if ($file_size_kb < 10) { $formatted_file_size = number_format_i18n(round($file_size_kb, 2), 2); } else { $formatted_file_size = number_format_i18n(round($file_size_kb)); } } else { $formatted_file_size = '0'; } $replacements['FILE_SIZE'] = trim($formatted_file_size . ' KB'); } } $attachment_metadata = wp_get_attachment_metadata($attachment_post_id); if (is_array($attachment_metadata) && !empty($attachment_metadata['width']) && !empty($attachment_metadata['height']) ) { $width = (int) $attachment_metadata['width']; $height = (int) $attachment_metadata['height']; if ($width > 0 && $height > 0) { $replacements['IMAGE_DIMENSIONS'] = $width . 'x' . $height; } } elseif ($attached_file_path && file_exists($attached_file_path)) { $image_size = @getimagesize($attached_file_path); if (is_array($image_size) && isset($image_size[0], $image_size[1])) { $width = (int) $image_size[0]; $height = (int) $image_size[1]; if ($width > 0 && $height > 0) { $replacements['IMAGE_DIMENSIONS'] = $width . 'x' . $height; } } } return $replacements; } // =========================================================================================== \\ /** * Replaces supported placeholders in the provided text. * * @param string $text The text that may contain placeholders. * @param array $replacements Map of placeholder => replacement value. * * @return string */ function ai4seo_replace_text_placeholders(string $text, array $replacements): string { if ($text === '' || (strpos($text, '{') === false && strpos($text, '[') === false && strpos($text, '%%') === false) ) { return $text; } return (string) preg_replace_callback( '/\{([A-Z0-9_]+)\}|\[([A-Z0-9_]+)\]|%%([A-Z0-9_]+)%%/i', static function ($matches) use ($replacements) { $placeholder = ''; if (!empty($matches[1])) { $placeholder = $matches[1]; } elseif (!empty($matches[2])) { $placeholder = $matches[2]; } elseif (!empty($matches[3])) { $placeholder = $matches[3]; } if ($placeholder !== '') { $key = strtoupper($placeholder); if (array_key_exists($key, $replacements)) { return (string) $replacements[$key]; } } return $matches[0]; }, $text ); } // =========================================================================================== \\ /** * Replaces the [TITLE] placeholder in metadata prefixes or suffixes. * * @param string $text Text that may contain the [TITLE] placeholder. * @param string $post_title The current post title used as replacement. * * @return string */ function ai4seo_replace_metadata_title_placeholder(string $text, string $post_title): string { if ($text === '' || $post_title === '') { return $text; } $contains_title_placeholder = ( stripos($text, '{title}') !== false || stripos($text, '[title]') !== false || stripos($text, '%%title%%') !== false ); if (!$contains_title_placeholder) { return $text; } return str_ireplace( array('{TITLE}', '[TITLE]', '%%TITLE%%'), $post_title, $text ); } // =========================================================================================== \\ /** * Checks whether the provided text contains WooCommerce product placeholders. * * @param string $text The text to inspect. * * @return bool */ function ai4seo_text_contains_product_placeholder(string $text): bool { if ($text === '') { return false; } return (bool) preg_match( '/\{PRODUCT_(?:NAME|PRICE)\}|\[PRODUCT_(?:NAME|PRICE)\]|%%PRODUCT_(?:NAME|PRICE)%%/i', $text ); } // =========================================================================================== \\ /** * Remove TranslatePress tags and wrappers from a string. * * Example input: * "#!trpst#trp-gettext#Metadata Editor#!trpen#Manage metadata for Stuffed peppers (#35432)#!trpst#" * Output: * "Metadata Editor Manage metadata for Stuffed peppers (#35432)" * * @param string $input * @return string */ function ai4seo_remove_translatepress_tags(string $input ): string { // Replace TranslatePress wrapped text with its inner content $clean = preg_replace_callback( '/#!trpst#trp-gettext#(.*?)#!trpen#/us', function ( $m ) { return ' ' . $m[1] . ' '; }, $input ); // Handle inline variant like #trp-gettext data-trpgettextoriginal=157#!trpen# $clean = preg_replace( '/#trp-gettext[^#]*#!trpen#/us', ' ', $clean ); // Remove any remaining TranslatePress markers $clean = preg_replace( '/#!?trp[a-zA-Z0-9_\-\s="]+#?/', ' ', $clean ); // Normalize spaces and decode entities $clean = html_entity_decode( $clean, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $clean = trim( preg_replace( '/\s+/', ' ', $clean ) ); return $clean; } // =========================================================================================== \\ /** * Function to modify plugin-details for white-label-settings * @param array $all_plugins array with all plugins * @return array $all_plugins edited array with all plugins */ function ai4seo_modify_plugin_details_for_white_label(array $all_plugins): array { // Define variable for the plugin-file $plugin_file = ai4seo_get_plugin_basename(); if (!isset($all_plugins[$plugin_file])) { // If the plugin-file is not found in $all_plugins, return the original array return $all_plugins; } // APPLYING WHITE-LABEL SETTINGS $setting_enable_white_label = ai4seo_get_setting(AI4SEO_SETTING_ENABLE_WHITE_LABEL); if ($setting_enable_white_label) { // Define variables for plugin-name and plugin-description based on settings $new_plugin_name = ai4seo_get_setting(AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_NAME); $new_plugin_description = ai4seo_get_setting(AI4SEO_SETTING_INSTALLED_PLUGINS_PLUGIN_DESCRIPTION); // Make sure that plugin-name and plugin-description could be found and have content if ($new_plugin_name && $new_plugin_description) { // Replace plugin-name and plugin-description based on settings $all_plugins[$plugin_file]["Name"] = stripslashes(ai4seo_mb_substr($new_plugin_name, 0, 100)); $all_plugins[$plugin_file]["Description"] = stripslashes(ai4seo_mb_substr($new_plugin_description, 0, 140)); } } // APPLYING INCOGNITO SETTINGS // check for function get_current_user_id() if (!function_exists("get_current_user_id")) { return $all_plugins; } $current_user_id = get_current_user_id(); // Define variables for the incognito-setting $setting_enable_incognito_mode = ai4seo_is_incognito_mode_enabled(); $setting_incognito_mode_user_id = ai4seo_get_setting(AI4SEO_SETTING_INCOGNITO_MODE_USER_ID); $visible_to_anyone = !$setting_enable_incognito_mode || ($setting_incognito_mode_user_id == AI4SEO_DEFAULT_SETTINGS[AI4SEO_SETTING_INCOGNITO_MODE_USER_ID]); $only_visible_to_current_user = $setting_enable_incognito_mode && !$visible_to_anyone && $setting_incognito_mode_user_id == $current_user_id; // Check incognito-setting and incognito user-id if ($only_visible_to_current_user) { // Add a note about the incognito mode plugin meta add_filter("plugin_row_meta", "ai4seo_add_incognito_note_to_plugin_meta", 10, 4); } else if (!$visible_to_anyone || $setting_enable_white_label) { // Remove plugin-meta from plugin details add_filter("plugin_row_meta", "ai4seo_remove_plugin_meta", 10, 4); } // Return array with all plugins return $all_plugins; } // =========================================================================================== \\ /** * Function to remove plugin meta from plugins-list * @param array $plugin_meta An array of the plugin’s metadata, including the version, author, author URI, and plugin URI. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. * @param string $status Status filter currently applied to the plugin list. * @return array $plugin_meta - an array with the found meta tags */ function ai4seo_remove_plugin_meta(array $plugin_meta, string $plugin_file, array $plugin_data, string $status): array { // Check if slug could be found and if it matches the plugin if (isset($plugin_data["slug"]) && $plugin_data["slug"] == AI4SEO_PLUGIN_IDENTIFIER) { $plugin_meta[] = esc_html__("Version", "ai-for-seo") . ": " . AI4SEO_PLUGIN_VERSION_NUMBER; } return $plugin_meta; } // =========================================================================================== \\ /** * Function to add a note about the incognito mode plugin meta * @param array $plugin_meta An array of the plugin’s metadata, including the version, author, author URI, and plugin URI. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. * @param string $status Status filter currently applied to the plugin list. * @return array $plugin_meta - an array with the found meta tags */ function ai4seo_add_incognito_note_to_plugin_meta(array $plugin_meta, string $plugin_file, array $plugin_data, string $status): array { // Check if slug could be found and if it matches the plugin if (isset($plugin_data["slug"]) && $plugin_data["slug"] == AI4SEO_PLUGIN_IDENTIFIER) { $plugin_meta[] = esc_html__("(Incognito Mode: This info is only visible to you)", "ai-for-seo"); } return $plugin_meta; } // =========================================================================================== \\ /** * Function to retrieve specific meta tags from html * @param string $head_html the html content of the head * @return array $found_meta_tags - an array with the found meta tags */ function ai4seo_get_meta_tags_from_html(string $head_html): array { if (!defined('AI4SEO_METADATA_DETAILS')) { return array(); } // Remove " . __("I - General Definitions", "ai-for-seo") . ""; $html .= "
    "; $html .= "
  1. " . sprintf(__("This plugin was created and is maintained, including all updates and support, by %s, a German SEO agency (hereinafter referred to as '%s').", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_NAME, AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  2. "; $html .= "
  3. " . __("These Terms of Service outline your rights and responsibilities when using the AI for SEO plugin. Please read them carefully.", "ai-for-seo") . "
  4. "; $html .= "
  5. " . __("These Terms of Service are governed by the laws of Germany, and any disputes shall be resolved under German jurisdiction.", "ai-for-seo") . "
  6. "; $html .= "
"; $html .= "

" . __("II - General Acknowledgements", "ai-for-seo") . "

"; $html .= "
    "; $html .= "
  1. " . sprintf(__("I have read and accept the Terms and Conditions and Privacy Policy of %s.", "ai-for-seo"), AI4SEO_TERMS_AND_CONDITIONS_URL, AI4SEO_PRIVACY_POLICY_URL, AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  2. "; $html .= "
  3. " . sprintf(__("%s will not be liable for any direct, indirect, incidental, or consequential damages arising from the use of the plugin or generated content.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  4. "; $html .= "
"; $html .= "

" . __("III - User Responsibilities", "ai-for-seo") . "

"; $html .= "
    "; $html .= "
  1. " . __("I confirm that my content will be free from references to illegal drugs, violence, explicit material or otherwise illegal material.", "ai-for-seo") . "
  2. "; $html .= "
  3. " . __("I understand that AI may make errors, and I am responsible for reviewing all generated results to ensure accuracy and compliance with applicable laws.", "ai-for-seo") . "
  4. "; $html .= "
  5. " . sprintf(__("I acknowledge that I am solely responsible for how the generated data is used on my website, and %s is not liable for any misuse or improper application of the data.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  6. "; $html .= "
  7. " . __("I will ensure that my use of the plugin complies with all applicable laws and regulations in my jurisdiction.", "ai-for-seo") . "
  8. "; $html .= "
  9. " . sprintf(__("I understand that using certain features within the plugin will consume Credits based on the specific feature. If higher-than-expected credit consumption occurs due to user actions, whether intentional or unintentional, Credits cannot be refunded or reversed unless %s determines the user was not responsible. However, the right to a 100%% refund within the 14-day money-back guarantee period still applies under these circumstances.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  10. "; $html .= "
  11. " . __("I may request a full refund within 14 days of the initial purchase if not satisfied with the plugin’s performance, as outlined in our money-back guarantee policy. This refund policy applies only to monthly and yearly renewable subscriptions and does not cover Custom Credits Packs or Pay-as-you-go purchases.", "ai-for-seo") . "
  12. "; $html .= "
"; $html .= "

" . __("IV - Data Ownership, Handling and Lifetime", "ai-for-seo") . "

"; $html .= "
    "; $html .= "
  1. " . sprintf(__("All data generated through the AI for SEO plugin remains the intellectual property of the user, provided it does not violate the terms of service. %s holds no claims to ownership of user-generated content.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  2. "; $html .= "
  3. " . sprintf(__("%s complies with applicable data protection regulations, including the GDPR and DSGVO.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  4. "; $html .= "
  5. " . sprintf(__("I agree that, in order to execute certain functions, data will be sent to %s's servers. This content will only be used and stored for purposes stated in the Terms and Conditions and Privacy Policy.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION, AI4SEO_TERMS_AND_CONDITIONS_URL, AI4SEO_PRIVACY_POLICY_URL) . "
  6. "; $html .= "
  7. " . sprintf(__("When accepting these Terms of Service, %s may collect and store certain information, including the user’s website URL, website name, email address, IP address, the version of the Terms accepted, and the timestamp of acceptance. This data is collected solely for compliance purposes and will be retained securely for the period necessary to fulfill legal obligations or until account deletion, as outlined in our Privacy Policy.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION, AI4SEO_PRIVACY_POLICY_URL) . "
  8. "; $html .= "
  9. " . sprintf(__("Data will be stored only for as long as necessary to fulfill the stated purpose and will be deleted in accordance with the data retention policy outlined in the Privacy Policy.", "ai-for-seo"), AI4SEO_PRIVACY_POLICY_URL) . "
  10. "; $html .= "
  11. " . sprintf(__("I may request the deletion of my data at any time, and %s will comply unless the data is required for fulfilling contractual or legal obligations. Requests can be sent to %s.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION, AI4SEO_SUPPORT_EMAIL, AI4SEO_SUPPORT_EMAIL) . "
  12. "; $html .= "
"; $html .= "

" . __("V - Third-parties and partners", "ai-for-seo") . "

"; $html .= "
    "; $html .= "
  1. " . sprintf(__("I agree that, in order to execute certain functions, data from my website and its content may be sent to third-party services, including OpenAI.", "ai-for-seo"), AI4SEO_OPENAI_URL) . "
  2. "; $html .= "
  3. " . sprintf(__("I will adhere to OpenAI's Terms of Use at all times.", "ai-for-seo"), AI4SEO_OPENAI_TERMS_OF_USE_URL) . "
  4. "; $html .= "
  5. " . __("I specifically confirm that my content will be free from references to illegal drugs, extreme violence, or explicit material.", "ai-for-seo") . "
  6. "; $html .= "
"; $html .= "

" . __("VI - Rights and Modifications", "ai-for-seo") . "

"; $html .= "
    "; $html .= "
  1. " . sprintf(__("%s reserves the right to terminate access to the plugin or revoke usage rights at any time if the terms are violated. In the event of termination, I will no longer have access to the plugin and any associated services.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  2. "; $html .= "
  3. " . sprintf(__("%s reserves the right to modify these terms at any time. Users will be notified of any significant changes.", "ai-for-seo"), AI4SEO_PLUGIN_AUTHOR_COMPANY_ABBREVIATION) . "
  4. "; $html .= "
"; return $html; } // =========================================================================================== \\ /** * Called via AJAX - On reject of the terms of service -> deactivate plugin * @return void */ function ai4seo_reject_tos() { // Make sure that this function is only called once if (!ai4seo_singleton(__FUNCTION__)) { return; } // check if we are in the admin area of WordPress if (!is_admin()) { return; } // perform the reject terms call ai4seo_robhub_api()->perform_reject_terms_call(AI4SEO_TOS_VERSION_TIMESTAMP); // uninstall the plugin ai4seo_deactivate_plugin(); ai4seo_send_json_success(); } // =========================================================================================== \\ /** * Called via AJAX - On accept of the terms of service -> save the timestamp * @return void */ function ai4seo_accept_tos() { // Make sure that this function is only called once if (!ai4seo_singleton(__FUNCTION__)) { return; } // check if we are in the admin area of WordPress if (!is_admin()) { return; } // check if we accepted tos, toc and pp before $tos_toc_and_pp_accepted_time = (int) ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_TOC_AND_PP_ACCEPTED_TIME); // check if we accepted enhanced reporting before $enhanced_reporting_accepted = (bool) ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED); ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_TOS_TOC_AND_PP_ACCEPTED_TIME, time()); // handle enhanced reporting -> only save changes if we see the tos for the first time or the user has not accepted it before // not handling the save here only because the user did not see the checkbox in the modal if (!$tos_toc_and_pp_accepted_time || !$enhanced_reporting_accepted) { // check for $_POST["accepted_enhanced_reporting"] $enhanced_reporting_accepted = isset($_POST["accepted_enhanced_reporting"]) && $_POST["accepted_enhanced_reporting"] == "true"; if ($enhanced_reporting_accepted) { ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED, true); ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_ENHANCED_REPORTING_ACCEPTED_TIME, time()); } } // set tos accept details to database to share it with the maker of the plugin ai4seo_set_tos_accept_details($enhanced_reporting_accepted, "accepted tos, toc and pp"); ai4seo_send_json_success(); } // =========================================================================================== \\ /** * Set the ToS Acceptance details to the database * @param $accepted_enhanced_reporting bool Whether the user agreed to the extended data collection * @param $action string The action that was performed * @return void */ function ai4seo_set_tos_accept_details(bool $accepted_enhanced_reporting, string $action = "unknown") { // collect additional data and put it into the wp_option "AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS" $additional_tos_accept_details = array( "action" => sanitize_text_field($action), "website_url" => sanitize_text_field(get_site_url()), "website_name" => sanitize_text_field(get_bloginfo("name")), "email_address" => sanitize_email(ai4seo_get_option("admin_email")), "client_ip_address" => ai4seo_get_client_ip(), "server_ip_address" => ai4seo_get_server_ip(), "user_agent" => ai4seo_get_client_user_agent(), "tos_version" => AI4SEO_TOS_VERSION_TIMESTAMP, "timestamp" => time(), "accepted_extended_data_collection" => $accepted_enhanced_reporting ? "1" : "0" ); $additional_tos_accept_details = ai4seo_deep_sanitize($additional_tos_accept_details); ai4seo_update_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_OPTION_NAME, $additional_tos_accept_details); } // =========================================================================================== \\ /** * Function to send the additional tos accept details, if available in the database * @return void */ function ai4seo_send_additional_tos_accept_details() { // Make sure that the user is allowed to use this plugin if (!ai4seo_can_manage_this_plugin()) { return; } // check in wp_options if we have additional tos accept details $additional_tos_accept_details = ai4seo_get_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_OPTION_NAME); $additional_tos_accept_details = ai4seo_deep_sanitize($additional_tos_accept_details); if (!$additional_tos_accept_details) { return; } $new_tos_details_checksum = ai4seo_get_array_checksum($additional_tos_accept_details); $last_tos_details_checksum = ai4seo_read_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_TOS_DETAILS_CHECKSUM); // prevent re-sending the same data if ($new_tos_details_checksum === $last_tos_details_checksum) { // delete the additional tos accept details from the database ai4seo_delete_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_OPTION_NAME); return; } // prevent re-sending the same data using a timestamp of the last try // only allow to send this data once every 1 hour $tried_to_send_this_data_before_timestamp = (int) ai4seo_get_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_LAST_TRY_TIMESTAMP_OPTION_NAME); if ($tried_to_send_this_data_before_timestamp && $tried_to_send_this_data_before_timestamp > (time() - 3600)) { return; } ai4seo_update_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_LAST_TRY_TIMESTAMP_OPTION_NAME, time()); // call robhub api endpoint "accept-terms" with the additional tos accept details $response = ai4seo_robhub_api()->call("client/accept-terms", $additional_tos_accept_details); //check response if (!ai4seo_robhub_api()->was_call_successful($response)) { error_log("AI4SEO: Invalid response from RobHub API. #1712121224"); return; } // on success... // remove the additional tos accept details from the database ai4seo_delete_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_OPTION_NAME); ai4seo_delete_option(AI4SEO_ADDITIONAL_TOS_ACCEPT_DETAILS_LAST_TRY_TIMESTAMP_OPTION_NAME); // save the checksum of the new tos details ai4seo_update_environmental_variable(AI4SEO_ENVIRONMENTAL_VARIABLE_LAST_TOS_DETAILS_CHECKSUM, $new_tos_details_checksum); } // ___________________________________________________________________________________________ \\ // === LATEST ACTIVITY ======================================================================= \\ // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ \\ /** * Function to add an entry to the latest activity log * @param int $post_id The post id this entry refers to * @param string $status The status of the action (success, error) * @param string $action The action that was performed ("metadata-manually-generated", "metadata-bulk-generated", "attachment-attributes-manually-generated", "attachment-attributes-bulk-generated") * @param int $cost The cost of the action in credits * @param string $details The details of the action * @return bool */ function ai4seo_add_latest_activity_entry(int $post_id, string $status, string $action, int $cost = 0, string $details = ""): bool { $new_entry["timestamp"] = time(); // check if the post_id is a valid post id if ($post_id < 0) { error_log("AI4SEO: Invalid post id in latest activity log. #231410125"); return false; } // check if the status is one of the allowed statuses (success, error) $status = sanitize_text_field($status); if (!in_array($status, array("success", "error"))) { return false; } $action = sanitize_text_field($action); if (!in_array($action, array("metadata-manually-generated", "metadata-bulk-generated", "attachment-attributes-manually-generated", "attachment-attributes-bulk-generated"))) { error_log("AI4SEO: Invalid action in latest activity log. #241410125"); return false; } // check if the cost is valid if ($cost < 0) { error_log("AI4SEO: Invalid cost in latest activity log. #251410125"); return false; } // read additional post data $post_type = get_post_type($post_id); // check post type (alphanumeric, - and _ allowed) $post_type = sanitize_text_field($post_type); if (!preg_match("/^[a-zA-Z0-9_-]+$/", $post_type)) { return false; } // check title $title = sanitize_text_field(get_the_title($post_id)); $title = ai4seo_mb_substr($title, 0 , 50); $title = sanitize_text_field($title); if ($post_type == "attachment") { $url = get_edit_post_link($post_id); } else { $url = get_permalink($post_id); } if (!$url) { $url = ""; } // check url $url = sanitize_url($url); if ($url) { $url = esc_url($url); } // check details $details = sanitize_text_field($details); // build the new entry $new_entry = array( "timestamp" => time(), "post_id" => $post_id, "post_type" => $post_type, "status" => $status, "action" => $action, "cost" => $cost, "title" => $title, "url" => $url, "details" => $details ); // read the latest activity logs $latest_activity = ai4seo_get_option(AI4SEO_LATEST_ACTIVITY_OPTION_NAME, array()); // add the new entry array_unshift($latest_activity, $new_entry); // remove the oldest entry if necessary if (count($latest_activity) >= AI4SEO_MAX_LATEST_ACTIVITY_LOGS) { array_pop($latest_activity); } // save the new latest activity logs ai4seo_update_option(AI4SEO_LATEST_ACTIVITY_OPTION_NAME, $latest_activity); return true; } // ___________________________________________________________________________________________ \\ // === PAY AS YOU GO ========================================================================= \\ // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ \\ function ai4seo_send_pay_as_you_go_settings() { // call robhub api endpoint "payg-settings" with current payg settings $robhub_endpoint = "client/payg-settings"; $payg_settings = array(); $payg_settings[AI4SEO_SETTING_PAYG_ENABLED] = (bool) ai4seo_get_setting(AI4SEO_SETTING_PAYG_ENABLED); $payg_settings[AI4SEO_SETTING_PAYG_STRIPE_PRICE_ID] = ai4seo_get_setting(AI4SEO_SETTING_PAYG_STRIPE_PRICE_ID); $payg_settings[AI4SEO_SETTING_PAYG_DAILY_BUDGET] = (int) ai4seo_get_setting(AI4SEO_SETTING_PAYG_DAILY_BUDGET); $payg_settings[AI4SEO_SETTING_PAYG_MONTHLY_BUDGET] = (int) ai4seo_get_setting(AI4SEO_SETTING_PAYG_MONTHLY_BUDGET); $payg_settings = ai4seo_deep_sanitize($payg_settings); $response = ai4seo_robhub_api()->call($robhub_endpoint, $payg_settings); // check response if (!ai4seo_robhub_api()->was_call_successful($response)) { error_log("AI4SEO: Invalid response from RobHub API. #361217325"); return false; } // remove potential previous error notification ai4seo_remove_notification("payg-status-error"); return true; }