roles as $role_key => $role_data ) { $roles[ $role_key ] = translate_user_role( $role_data['name'] ); } return $roles; } /** * Retrieves an array of post types based on the specified arguments. * This method allows for filtering through various categories of post types, * including base types (posts, pages), WooCommerce-specific types, media attachments, * and other registered post types. * * @param array $args Optional. An array of arguments to filter post types. The following keys are supported: * 'base' - Includes default WordPress post types (post, page). * 'woocommerce' - Includes WooCommerce post types (product, shop_coupon, shop_order), * only if WooCommerce is active. * 'media' - Includes media types (attachment). * 'others' - Includes other public and UI-visible post types. * * @return array An associative array of post type keys and their corresponding labels. */ public static function get_post_types( array $args = [] ): array { $return = []; if( in_array( 'base', $args ) ) { $return['post'] = esc_html__( 'Posts', 'adminease' ); $return['page'] = esc_html__( 'Pages', 'adminease' ); } if( in_array( 'product', $args ) && class_exists( 'woocommerce' ) ) { $return['product'] = esc_html__( 'Products', 'adminease' ); } if( in_array( 'woocommerce', $args ) && class_exists( 'woocommerce' ) ) { $return['product'] = esc_html__( 'Products', 'adminease' ); $return['shop_coupon'] = esc_html__( 'Coupons', 'adminease' ); $return['shop_order'] = esc_html__( 'Orders', 'adminease' ); if( class_exists( 'WC_Subscriptions' ) ) { $return['shop_subscription'] = esc_html__( 'Subscription', 'adminease' ); } } if( in_array( 'media', $args ) ) { $return['attachment'] = esc_html__( 'Media', 'adminease' ); } if( in_array( 'others', $args ) ) { $base_and_others = array_filter( wp_list_pluck( get_post_types( [ 'public' => true, 'show_ui' => true ], 'objects' ), 'label', 'name' ), function( $key ) { return strpos( $key, 'wp_' ) === false; }, ARRAY_FILTER_USE_KEY ); unset( $base_and_others['attachment'] ); $return = array_merge( $return, $base_and_others ); } return $return; } public static function get_taxonomies( array $args = [] ): array { $return = []; if( in_array( 'base', $args ) ) { $return['category'] = esc_html__( 'Categories', 'adminease' ); $return['post_tag'] = esc_html__( 'Tags', 'adminease' ); } if( in_array( 'base_hierarchical', $args ) ) { $return['category'] = esc_html__( 'Categories', 'adminease' ); } if( in_array( 'others', $args ) ) { $return = wp_list_pluck( get_taxonomies( [ 'show_ui' => true ], 'objects' ), 'label', 'name' ); } if( in_array( 'others_hierarchical', $args ) ) { $return = wp_list_pluck( get_taxonomies( [ 'public' => true, 'hierarchical' => true, 'show_ui' => true ], 'objects' ), 'label', 'name' ); } return $return; } /** * Checks if the request is coming through Cloudflare. * @return bool Returns true if Cloudflare headers are present, otherwise false. */ public static function is_cloudflare_enabled(): bool { return !empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) || !empty( $_SERVER['HTTP_CF_IPCountry'] ) || !empty( $_SERVER['HTTP:CF-IPCountry'] ) || !empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) || !empty( $_SERVER['HTTP_CF_RAY'] ); } /** * Determines if GeoIP functionality is enabled and available. * * Checks the geolocation variables a CDN, proxy or server module injects, then the * PECL geoip extension. A GeoIP.dat file sitting on disk is deliberately *not* * treated as support: the only thing in this plugin that can read one is * geoip_country_code_by_name(), which the extension check above already covers, so * a bare file proves nothing. Accepting it made this return true on hosts that ship * the distro geoip-database package without the extension to read it - Cloudways * among them. BlockSpecificCountries then reported itself supported, rendered its * controls enabled, saved happily and blocked nobody, because get_client_country() * still had no country to resolve and the gate fails open. A security toggle that * silently does nothing is worse than one that says it cannot run here. * * The variable list must stay in step with the one get_client_country() reads, or * the two disagree: HTTP_X_FORWARDED_COUNTRY was resolved there but missing here, * so a server geolocated by that header alone reported itself unsupported while * happily returning a country - and because get_client_country()'s GeoIP branch is * itself gated on this method, the gap was self-reinforcing. * * @return bool True if GeoIP functionality is enabled and available, false otherwise. */ public static function is_geoip_enabled(): bool { $geoip_vars = [ 'GEOIP_COUNTRY_CODE', 'GEOIP_COUNTRY_NAME', 'HTTP_CF_IPCOUNTRY', 'HTTP_X_GEO_COUNTRY', 'HTTP_X_COUNTRY_CODE', 'HTTP_GEOIP_COUNTRY_CODE', 'HTTP_X_FORWARDED_COUNTRY', ]; foreach( $geoip_vars as $var ) { if( !empty( $_SERVER[ $var ] ) || getenv( $var ) ) { return true; } } return function_exists( 'geoip_country_code_by_name' ); } /** * Determines whether the current server reads .htaccess files. * * True for Apache, and for LiteSpeed running in Apache-compatibility mode, which is * the only mode in which it exposes apache_get_modules(). Nginx, native-mode LiteSpeed * and IIS ignore .htaccess entirely, so a feature that hardens the site through rewrite * rules has to fall back to a PHP layer instead of writing a file nothing will read. * * @return bool True when .htaccess rules are honoured, false otherwise. */ public static function is_apache_compatible(): bool { if( !isset( $_SERVER['SERVER_SOFTWARE'] ) ) { return false; } $server = strtolower( sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) ); if( false !== strpos( $server, 'apache' ) ) { return true; } if( false !== strpos( $server, 'litespeed' ) && function_exists( 'apache_get_modules' ) ) { return true; } return false; } /** * Whether the current user may manage what every site on a network shares. * * On a single site this is everyone who reached an AdminEase handler, because * those already require manage_options. On a network, a site administrator also * holds manage_options, so the shared files and the shared debug.log need a * super admin instead. * * @return bool True on a single site, or for a super admin on a network. */ public static function is_network_admin_user(): bool { return !is_multisite() || current_user_can( 'manage_network_options' ); } /** * Whether this request may write wp-config.php, .htaccess, .user.ini or robots.txt. * * Every site on a network reads the same copy of those files, so only the main * site writes them. If each site wrote its own settings, the last site to save * would silently undo the others. * * @return bool True on a single site, or for a super admin on the main site. */ public static function can_write_shared_files(): bool { if( !is_multisite() ) { return true; } return is_main_site() && self::is_network_admin_user(); } /** * Returns the note shown under a setting that would normally be enforced through * .htaccess, telling the user it is being enforced in PHP instead. * * Returns an empty string on servers that do read .htaccess, so callers can test it * before deciding whether to show anything. Without it the feature looks identical on * both server types while only working on one of them. * * @return string Note text, or an empty string on Apache-compatible servers. */ public static function get_php_enforcement_notice(): string { if( self::is_apache_compatible() ) { return ''; } return __( 'Your server does not read .htaccess files (Nginx or similar), so AdminEase enforces this in PHP instead. Nothing needs to be configured on the server.', 'adminease' ); } /** * Retrieve the client's IP address. * * Forwarding headers (CF-Connecting-IP, X-Forwarded-For, X-Real-IP) are set by the * client, not the server: on a site reachable straight from the internet, any visitor * can send whatever address they please and the site will believe it. Anything built on * top - the exclusion list, country blocking, rate limiting, the audit trail - is only * as trustworthy as this function. * * So the headers are read only where there is evidence a proxy genuinely sits in front * of the site: * - REMOTE_ADDR is a private or reserved address, meaning the request reached PHP over * the local network rather than off the public internet; * - REMOTE_ADDR belongs to a known CDN edge (Cloudflare's published ranges ship by * default) or to the adminease_trusted_proxies list; * - the site owner enabled "My site is behind a proxy or CDN". * * Each candidate is validated on its own, so a malformed header no longer short-circuits * the chain and hands the caller an empty string. * * @return string The IP address of the client, or an empty string if none is valid. */ public static function get_client_ip(): string { $remote_addr = isset( $_SERVER['REMOTE_ADDR'] ) ? trim( sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) ) : ''; if( self::should_trust_proxy_headers( $remote_addr ) ) { /** * Filters the forwarding headers consulted, in priority order. * * @param array $headers $_SERVER keys to read. */ $headers = apply_filters( 'adminease_client_ip_headers', [ 'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP' ] ); foreach( $headers as $header ) { if( empty( $_SERVER[ $header ] ) ) { continue; } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Sanitised here, then validated by extract_client_ip(). $ip = self::extract_client_ip( sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ) ); if( '' !== $ip ) { return $ip; } } } return filter_var( $remote_addr, FILTER_VALIDATE_IP ) ? $remote_addr : ''; } /** * Picks the originating client address out of a forwarding header value. * * X-Forwarded-For is a chain - "client, proxy1, proxy2" - that each hop appends to. The * left-most entry is the only one a client can write, so it is read right to left and * the first hop that is not itself a proxy is returned: behind a real proxy that is the * address the proxy observed. If every hop looks like a proxy (an all-internal chain), * the left-most valid address is used instead. * * @param string $value Raw header value. * * @return string A valid IP address, or an empty string when the header holds none. */ private static function extract_client_ip( string $value ): string { $candidates = array_map( 'trim', explode( ',', $value ) ); $candidates = array_values( array_filter( $candidates, static function( $candidate ) { return (bool) filter_var( $candidate, FILTER_VALIDATE_IP ); } ) ); if( empty( $candidates ) ) { return ''; } foreach( array_reverse( $candidates ) as $candidate ) { if( !self::is_proxy_address( $candidate ) ) { return $candidate; } } return $candidates[0]; } /** * Decides whether forwarding headers may be believed for the current request. * * @param string $remote_addr The address PHP actually accepted the connection from. * * @return bool True when a proxy is known or declared to sit in front of the site. */ private static function should_trust_proxy_headers( string $remote_addr ): bool { $settings = Plugin::get_settings( 'debug' ); $trusted = !empty( $settings['network_viewer_trust_proxy'] ); if( !$trusted && '' !== $remote_addr ) { $trusted = self::is_proxy_address( $remote_addr ); } /** * Filters whether the forwarding headers are trusted for this request. * * @param bool $trusted Whether a proxy is believed to be in front of the site. * @param string $remote_addr The connecting address. */ return (bool) apply_filters( 'adminease_trust_proxy_headers', $trusted, $remote_addr ); } /** * Checks whether an address is one a proxy would connect from, rather than a real visitor. * That means a private or otherwise reserved address, a known CDN edge, or anything the * site has added to the trusted proxy list. * * @param string $ip The address to test. * * @return bool True when the address represents an infrastructure hop. */ private static function is_proxy_address( string $ip ): bool { if( !filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } if( !filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { return true; } return self::ip_in_allowlist( $ip, implode( PHP_EOL, self::get_trusted_proxies() ) ); } /** * Returns the proxy ranges whose forwarding headers are believed. * * Cloudflare's published ranges are included by default so sites behind it keep * resolving real visitor IPs without any configuration, while a spoofed CF-Connecting-IP * sent straight to the origin is ignored. Other CDNs and load balancers can be added * through the filter; entries may be exact addresses, CIDR ranges or wildcards. * * Cloudflare's current list lives at https://www.cloudflare.com/ips/. * * @return array List of trusted proxy addresses or ranges. */ public static function get_trusted_proxies(): array { $cloudflare = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ]; /** * Filters the trusted proxy ranges. * * @param array $proxies Exact IPs, CIDR ranges or wildcard patterns. */ return (array) apply_filters( 'adminease_trusted_proxies', $cloudflare ); } /** * Checks whether the given IP address matches any entry in a newline-separated allowlist. * Each line may be an exact IP, a CIDR range (e.g. 192.168.1.0/24), or a wildcard (e.g. 192.168.1.*). * * @param string $ip The client IP address to check. * @param string $allowlist Newline-separated list of allowed IPs, CIDR ranges, or wildcards. * * @return bool True if the IP matches an entry in the allowlist, false otherwise. */ public static function ip_in_allowlist( string $ip, string $allowlist ): bool { if( empty( $ip ) || empty( $allowlist ) ) { return false; } $lines = preg_split( '/[\r\n]+/', $allowlist ); foreach( $lines as $line ) { $entry = trim( $line ); if( '' === $entry ) { continue; } if( self::ip_matches( $ip, $entry ) ) { return true; } } return false; } /** * Checks whether the given IP address matches a single allowlist entry, which may be * an exact IP, a CIDR range, or a wildcard pattern. * * @param string $ip The client IP address to check. * @param string $entry A single allowlist entry (exact IP, CIDR, or wildcard). * * @return bool True if the IP matches the entry, false otherwise. */ public static function ip_matches( string $ip, string $entry ): bool { if( false !== strpos( $entry, '/' ) ) { return self::ip_in_cidr( $ip, $entry ); } if( false !== strpos( $entry, '*' ) ) { return fnmatch( $entry, $ip ); } return hash_equals( $entry, $ip ); } /** * Checks whether the given IP address falls within a CIDR range. Supports both IPv4 and IPv6. * * @param string $ip The client IP address to check. * @param string $cidr The CIDR range, e.g. '192.168.1.0/24'. * * @return bool True if the IP is within the CIDR range, false otherwise. */ public static function ip_in_cidr( string $ip, string $cidr ): bool { $parts = explode( '/', $cidr ); if( 2 !== count( $parts ) ) { return false; } [ $subnet, $mask_bits ] = $parts; if( !is_numeric( $mask_bits ) ) { return false; } $mask_bits = (int) $mask_bits; $ip_bin = inet_pton( $ip ); $subnet_bin = inet_pton( $subnet ); if( false === $ip_bin || false === $subnet_bin || strlen( $ip_bin ) !== strlen( $subnet_bin ) ) { return false; } $bytes = strlen( $ip_bin ); if( $mask_bits < 0 || $mask_bits > $bytes * 8 ) { return false; } $full_bytes = intdiv( $mask_bits, 8 ); $rem_bits = $mask_bits % 8; if( $full_bytes > 0 && substr( $ip_bin, 0, $full_bytes ) !== substr( $subnet_bin, 0, $full_bytes ) ) { return false; } if( $rem_bits > 0 ) { $mask = chr( ( 0xFF << ( 8 - $rem_bits ) ) & 0xFF ); $ip_byte = substr( $ip_bin, $full_bytes, 1 ); $subnet_byte = substr( $subnet_bin, $full_bytes, 1 ); if( ( $ip_byte & $mask ) !== ( $subnet_byte & $mask ) ) { return false; } } return true; } /** * Retrieves the client's country code based on available server variables and services. * The method attempts to determine the country of the client by checking Cloudflare headers, * GeoIP server variables, and performing a GeoIP lookup if necessary. It returns a validated * two-letter ISO country code or an empty string if the country cannot be determined. * @return string Returns a two-letter ISO country code (uppercase) if successfully determined, * or an empty string if the country could not be identified. */ public static function get_client_country(): string { $country_code = ''; if( self::is_cloudflare_enabled() ) { if( !empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) { $country_code = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ); } else if( !empty( $_SERVER['HTTP_CF_IPCountry'] ) ) { $country_code = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_IPCountry'] ) ); } } if( empty( $country_code ) && self::is_geoip_enabled() ) { if( !empty( $_SERVER['GEOIP_COUNTRY_CODE'] ) ) { $country_code = sanitize_text_field( wp_unslash( $_SERVER['GEOIP_COUNTRY_CODE'] ) ); } else if( !empty( $_SERVER['HTTP_X_FORWARDED_COUNTRY'] ) ) { $country_code = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_COUNTRY'] ) ); } } if( empty( $country_code ) && function_exists( 'geoip_country_code_by_name' ) ) { $ip = self::get_client_ip(); if( !empty( $ip ) ) { $country_code = geoip_country_code_by_name( $ip ); } } if( !empty( $country_code ) ) { if( strlen( $country_code ) === 2 && preg_match( '/^[A-Z]{2}$/', $country_code ) ) { $countries = self::get_countries_iso(); if( isset( $countries[ $country_code ] ) ) { return $country_code; } } else if( strlen( $country_code ) > 2 ) { $countries = array_values( self::get_countries_iso() ); $index = array_search( $country_code, $countries, true ); if( false !== $index ) { $iso_codes = array_keys( self::get_countries_iso() ); return $iso_codes[ $index ]; } } } return ''; } /** * Returns a list of countries with their ISO 3166-1 alpha-2 codes as keys and their corresponding country names as values. * @return array An associative array where the keys are ISO 3166-1 alpha-2 country codes and the values are the respective country names. */ public static function get_countries_iso(): array { return [ 'AF' => 'Afghanistan', 'AX' => 'Aland Islands', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AS' => 'American Samoa', 'AD' => 'Andorra', 'AO' => 'Angola', 'AI' => 'Anguilla', 'AQ' => 'Antarctica', 'AG' => 'Antigua and Barbuda', 'AR' => 'Argentina', 'AM' => 'Armenia', 'AW' => 'Aruba', 'AU' => 'Australia', 'AT' => 'Austria', 'AZ' => 'Azerbaijan', 'BS' => 'Bahamas', 'BH' => 'Bahrain', 'BD' => 'Bangladesh', 'BB' => 'Barbados', 'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin', 'BM' => 'Bermuda', 'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BQ' => 'Bonaire, Sint Eustatius and Saba', 'BA' => 'Bosnia and Herzegovina', 'BW' => 'Botswana', 'BV' => 'Bouvet Island', 'BR' => 'Brazil', 'IO' => 'British Indian Ocean Territory', 'BN' => 'Brunei Darussalam', 'BG' => 'Bulgaria', 'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'KH' => 'Cambodia', 'CM' => 'Cameroon', 'CA' => 'Canada', 'CV' => 'Cape Verde', 'KY' => 'Cayman Islands', 'CF' => 'Central African Republic', 'TD' => 'Chad', 'CL' => 'Chile', 'CN' => 'China', 'CX' => 'Christmas Island', 'CC' => 'Cocos (Keeling) Islands', 'CO' => 'Colombia', 'KM' => 'Comoros', 'CG' => 'Congo', 'CD' => 'Congo, Democratic Republic of the', 'CK' => 'Cook Islands', 'CR' => 'Costa Rica', 'CI' => 'Côte d\'Ivoire', 'HR' => 'Croatia', 'CU' => 'Cuba', 'CW' => 'Curaçao', 'CY' => 'Cyprus', 'CZ' => 'Czechia', 'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DM' => 'Dominica', 'DO' => 'Dominican Republic', 'EC' => 'Ecuador', 'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'EE' => 'Estonia', 'ET' => 'Ethiopia', 'FK' => 'Falkland Islands (Malvinas)', 'FO' => 'Faroe Islands', 'FJ' => 'Fiji', 'FI' => 'Finland', 'FR' => 'France', 'GF' => 'French Guiana', 'PF' => 'French Polynesia', 'TF' => 'French Southern Territories', 'GA' => 'Gabon', 'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana', 'GI' => 'Gibraltar', 'GR' => 'Greece', 'GL' => 'Greenland', 'GD' => 'Grenada', 'GP' => 'Guadeloupe', 'GU' => 'Guam', 'GT' => 'Guatemala', 'GG' => 'Guernsey', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau', 'GY' => 'Guyana', 'HT' => 'Haiti', 'HM' => 'Heard Island and McDonald Islands', 'VA' => 'Holy See', 'HN' => 'Honduras', 'HK' => 'Hong Kong', 'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia', 'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IM' => 'Isle of Man', 'IL' => 'Israel', 'IT' => 'Italy', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JE' => 'Jersey', 'JO' => 'Jordan', 'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'KP' => 'Korea (Democratic People\'s Republic of)', 'KR' => 'Korea (Republic of)', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan', 'LA' => 'Lao People\'s Democratic Republic', 'LV' => 'Latvia', 'LB' => 'Lebanon', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania', 'LU' => 'Luxembourg', 'MO' => 'Macao', 'MG' => 'Madagascar', 'MW' => 'Malawi', 'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta', 'MH' => 'Marshall Islands', 'MQ' => 'Martinique', 'MR' => 'Mauritania', 'MU' => 'Mauritius', 'YT' => 'Mayotte', 'MX' => 'Mexico', 'FM' => 'Micronesia (Federated States of)', 'MD' => 'Moldova', 'MC' => 'Monaco', 'MN' => 'Mongolia', 'ME' => 'Montenegro', 'MS' => 'Montserrat', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'MM' => 'Myanmar', 'NA' => 'Namibia', 'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands', 'NC' => 'New Caledonia', 'NZ' => 'New Zealand', 'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria', 'NU' => 'Niue', 'NF' => 'Norfolk Island', 'MK' => 'North Macedonia', 'MP' => 'Northern Mariana Islands', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan', 'PW' => 'Palau', 'PS' => 'Palestine, State of', 'PA' => 'Panama', 'PG' => 'Papua New Guinea', 'PY' => 'Paraguay', 'PE' => 'Peru', 'PH' => 'Philippines', 'PN' => 'Pitcairn', 'PL' => 'Poland', 'PT' => 'Portugal', 'PR' => 'Puerto Rico', 'QA' => 'Qatar', 'RE' => 'Réunion', 'RO' => 'Romania', 'RU' => 'Russian Federation', 'RW' => 'Rwanda', 'BL' => 'Saint Barthélemy', 'SH' => 'Saint Helena, Ascension and Tristan da Cunha', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia', 'MF' => 'Saint Martin (French part)', 'PM' => 'Saint Pierre and Miquelon', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa', 'SM' => 'San Marino', 'ST' => 'Sao Tome and Principe', 'SA' => 'Saudi Arabia', 'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone', 'SG' => 'Singapore', 'SX' => 'Sint Maarten (Dutch part)', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'SB' => 'Solomon Islands', 'SO' => 'Somalia', 'ZA' => 'South Africa', 'GS' => 'South Georgia and the South Sandwich Islands', 'SS' => 'South Sudan', 'ES' => 'Spain', 'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'SJ' => 'Svalbard and Jan Mayen', 'SE' => 'Sweden', 'CH' => 'Switzerland', 'SY' => 'Syrian Arab Republic', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan', 'TZ' => 'Tanzania, United Republic of', 'TH' => 'Thailand', 'TL' => 'Timor-Leste', 'TG' => 'Togo', 'TK' => 'Tokelau', 'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Turkey', 'TM' => 'Turkmenistan', 'TC' => 'Turks and Caicos Islands', 'TV' => 'Tuvalu', 'UG' => 'Uganda', 'UA' => 'Ukraine', 'AE' => 'United Arab Emirates', 'GB' => 'United Kingdom', 'US' => 'United States', 'UM' => 'United States Minor Outlying Islands', 'UY' => 'Uruguay', 'UZ' => 'Uzbekistan', 'VU' => 'Vanuatu', 'VE' => 'Venezuela', 'VN' => 'Viet Nam', 'VG' => 'Virgin Islands (British)', 'VI' => 'Virgin Islands (U.S.)', 'WF' => 'Wallis and Futuna', 'EH' => 'Western Sahara', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe', ]; } /** * Retrieves the ISO code of a country based on its name. * * @param string $country_name The name of the country to retrieve the ISO code for. * The input is case-insensitive and will be trimmed and converted to lowercase. * * @return string Returns the ISO code of the country if found. * Returns an empty string if the country name does not match any in the list. */ public static function get_country_code_by_name( string $country_name ): string { $countries = self::get_countries_iso(); $country_name = trim( strtolower( $country_name ) ); foreach( $countries as $iso => $name ) { if( strtolower( $name ) === $country_name ) { return $iso; } } return ''; } /** * Get list of common bots * @return array */ public static function get_bots_list(): array { $categorized = self::get_categorized_bots(); $optgroups = []; foreach( $categorized as $category => $data ) { $optgroups[ $data['label'] ] = $data['bots']; } return $optgroups; } /** * Get categorized bot lists * @return array */ public static function get_categorized_bots(): array { return [ 'search_engines' => [ 'label' => 'Search Engines', 'bots' => [ 'Googlebot' => 'Googlebot', 'Bingbot' => 'Bingbot', 'YandexBot' => 'YandexBot', 'Baiduspider' => 'Baiduspider', 'DuckDuckBot' => 'DuckDuckBot', 'Slurp' => 'Yahoo! Slurp', 'Sogou' => 'Sogou Spider', 'Yeti' => 'Naver Yeti', 'Applebot' => 'Applebot', 'ia_archiver' => 'Alexa Crawler', ], ], 'social_media' => [ 'label' => 'Social Media', 'bots' => [ 'facebookexternalhit' => 'Facebook Bot', 'Facebot' => 'Facebook Facebot', 'Twitterbot' => 'Twitterbot', 'LinkedInBot' => 'LinkedIn Bot', 'Pinterestbot' => 'Pinterestbot', 'WhatsApp' => 'WhatsApp Bot', 'TelegramBot' => 'Telegram Bot', 'SkypeUriPreview' => 'Skype URI Preview', 'Discordbot' => 'Discord Bot', 'redditbot' => 'Reddit Bot', 'Slackbot' => 'Slack Bot', 'InstagramBot' => 'Instagram Bot', 'snapchat-proxy' => 'Snapchat Bot', 'TikTokBot' => 'TikTok Bot', 'LinkedInFeedBot' => 'LinkedIn Feed Bot', 'TikTok' => 'TikTok Crawler', 'YelpBot' => 'Yelp Bot', 'MastodonBot' => 'Mastodon Bot', 'BlueSkyBot' => 'BlueSky Bot', 'ThreadsBot' => 'Meta Threads Bot', ], ], 'ai_research' => [ 'label' => 'AI & Research', 'bots' => [ 'GPTBot' => 'OpenAI GPTBot', 'ChatGPT-User' => 'ChatGPT User Agent', 'CCBot' => 'Common Crawl Bot', 'anthropic-ai' => 'Anthropic AI Bot', 'ClaudeBot' => 'Claude AI Bot', 'Google-Extended' => 'Google Bard/Gemini Bot', 'PerplexityBot' => 'Perplexity AI Bot', 'YouBot' => 'You.com AI Bot', 'AI2Bot' => 'Allen Institute AI Bot', 'FacebookBot' => 'Meta AI Bot', 'Bytespider' => 'ByteDance AI Bot', 'ImagesiftBot' => 'ImageSift AI Bot', 'Omgilibot' => 'Omgili AI Bot', 'Diffbot' => 'Diffbot AI Crawler', 'DataMinr' => 'DataMinr AI Bot', 'WebzBot' => 'Webz.io AI Bot', 'ChatGPT' => 'ChatGPT Bot', 'BingAI' => 'Bing AI Chat Bot', 'PaLM' => 'Google PaLM Bot', 'LaMDA' => 'Google LaMDA Bot', 'Cohere' => 'Cohere AI Bot', 'HuggingFace' => 'Hugging Face Bot', 'Anthropic' => 'Anthropic Bot', 'OpenAI' => 'OpenAI Bot', ], ], 'seo_tools' => [ 'label' => 'SEO Tools', 'bots' => [ 'AhrefsBot' => 'AhrefsBot', 'SemrushBot' => 'SEMrushBot', 'MJ12bot' => 'Majestic MJ12bot', 'DotBot' => 'DotBot', 'Rogerbot' => 'Moz Rogerbot (Deprecated)', 'SerpstatBot' => 'Serpstat Bot', 'DataForSeoBot' => 'DataForSEO Bot', 'Screaming Frog SEO Spider' => 'Screaming Frog', 'Sitebulb' => 'Sitebulb Crawler', 'Lumar' => 'Lumar (DeepCrawl)', 'DeepCrawl' => 'DeepCrawl', 'OnCrawl' => 'OnCrawl', 'Botify' => 'Botify', 'JetOctopus' => 'JetOctopus', 'NetpeakSpider' => 'Netpeak Spider', 'ContentKing' => 'ContentKing', 'BLEXBot' => 'BLEXBot', 'MegaIndex' => 'MegaIndex Bot', 'CognitiveSEO' => 'CognitiveSEO Bot', 'BrandVerity' => 'BrandVerity Bot', 'LinkpadBot' => 'Linkpad Bot', 'PageFreezer' => 'PageFreezer Bot', ], ], 'monitoring' => [ 'label' => 'Monitoring & Uptime', 'bots' => [ 'UptimeRobot' => 'UptimeRobot', 'StatusCake' => 'StatusCake Bot', 'Pingdom' => 'Pingdom Bot', 'Site24x7' => 'Site24x7 Bot', 'GTmetrix' => 'GTmetrix Bot', 'NodePing' => 'NodePing Bot', 'Monitis' => 'Monitis Bot', 'WebGazer' => 'WebGazer Bot', 'AlertSite' => 'AlertSite Bot', 'Keynote' => 'Keynote Bot', 'ThousandEyes' => 'ThousandEyes Bot', 'NewRelic' => 'New Relic Bot', 'DatadogSynthetics' => 'Datadog Synthetics', 'AppDynamics' => 'AppDynamics Bot', 'Dynatrace' => 'Dynatrace Bot', 'SolarWinds' => 'SolarWinds Bot', 'LogicMonitor' => 'LogicMonitor Bot', 'Catchpoint' => 'Catchpoint Bot', ], ], 'ecommerce' => [ 'label' => 'E-commerce', 'bots' => [ 'Shopify-Partner' => 'Shopify Partner Bot', 'WooRank' => 'WooRank Bot', 'PriceGrabber' => 'PriceGrabber Bot', 'Shopping.com' => 'Shopping.com Bot', 'Nextag' => 'Nextag Bot', 'Bizrate' => 'Bizrate Bot', 'ShopWiki' => 'ShopWiki Bot', 'TheFind' => 'TheFind Bot', 'Amazon' => 'Amazon Bot', 'eBayBot' => 'eBay Bot', 'EtsyBot' => 'Etsy Bot', 'WalmartBot' => 'Walmart Bot', 'TargetBot' => 'Target Bot', 'BestBuyBot' => 'Best Buy Bot', 'HomeDepotBot' => 'Home Depot Bot', 'WayfairBot' => 'Wayfair Bot', 'AliExpressBot' => 'AliExpress Bot', 'WishBot' => 'Wish Bot', 'OverstockBot' => 'Overstock Bot', 'NeweggBot' => 'Newegg Bot', 'ShopifyBot' => 'Shopify Bot', 'BigCommerceBot' => 'BigCommerce Bot', 'WooCommerceBot' => 'WooCommerce Bot', 'MagentoBot' => 'Magento Bot', 'PrestaShopBot' => 'PrestaShop Bot', 'OpenCartBot' => 'OpenCart Bot', 'SquareBot' => 'Square Bot', 'StripeBot' => 'Stripe Bot', 'PayPalBot' => 'PayPal Bot', 'KlarnaBot' => 'Klarna Bot', 'AfterPayBot' => 'AfterPay Bot', 'ShipStationBot' => 'ShipStation Bot', ], ], 'news_media' => [ 'label' => 'News & Media', 'bots' => [ 'Flipboard' => 'Flipboard Bot', 'Pocket' => 'Pocket Bot', 'NewsBlur' => 'NewsBlur Bot', 'Apple News' => 'Apple News Bot', 'Google News' => 'Google News Bot', 'Yahoo News' => 'Yahoo News Bot', 'MSN Bot' => 'MSN News Bot', 'Bing News' => 'Bing News Bot', 'Reuters' => 'Reuters Bot', 'Associated Press' => 'AP News Bot', 'CNN' => 'CNN Bot', 'BBC' => 'BBC Bot', 'NPR' => 'NPR Bot', 'Medium' => 'Medium Bot', 'Substack' => 'Substack Bot', 'NewsAPI' => 'News API Bot', 'AllSides' => 'AllSides Bot', 'Ground News' => 'Ground News Bot', 'SmartNews' => 'SmartNews Bot', 'Inoreader' => 'Inoreader Bot', 'Feedly' => 'Feedly Bot', 'The Old Reader' => 'The Old Reader Bot', ], ], 'archive' => [ 'label' => 'Archive & Backup', 'bots' => [ 'archive.org_bot' => 'Internet Archive Bot', 'Wayback' => 'Wayback Machine', 'BacklinkCrawler' => 'Backlink Crawler', ], ], ]; } /** * Checks if the Pro version of the plugin is active. * @return bool Returns true if the Pro version of the plugin is active, otherwise false. */ public static function is_pro_plugin_active(): bool { return defined( 'ADMINEASE_PRO_VERSION' ); } /** * Settings keys that are hidden on this site and must keep their stored value, by tab. * * @var array */ private static array $hidden_settings = []; /** * Checks if the site runs at least the given WordPress version. * * @param string $version The WordPress version to compare against, e.g. '5.8'. * * @return bool True when the site runs that version or newer. */ public static function wp_at_least( string $version ): bool { return version_compare( get_bloginfo( 'version' ), $version, '>=' ); } /** * Checks if the active theme is a block theme. False on WordPress versions without block themes. * * @return bool True when the active theme is a block theme. */ public static function is_block_theme(): bool { if( !function_exists( 'wp_is_block_theme' ) ) { return false; } return wp_is_block_theme(); } /** * Takes the RSS feed links out of the page head. Safe to call more than once. * * @return void */ public static function remove_feed_links(): void { remove_action( 'wp_head', 'feed_links', 2 ); remove_action( 'wp_head', 'feed_links_extra', 3 ); } /** * Turns the current front end request into a 404 and empties the main query, * so the theme shows its 404 page and none of the requested posts. * * @return void */ public static function send_404(): void { global $wp_query; $wp_query->set_404(); $wp_query->posts = []; $wp_query->post_count = 0; $wp_query->found_posts = 0; $wp_query->max_num_pages = 0; $wp_query->post = null; status_header( 404 ); nocache_headers(); } /** * Lists which of the given plugins are active, on a single site or network wide. * * @param array $plugins Plugin file => display name, e.g. 'jetpack/jetpack.php' => 'Jetpack'. * * @return array The display names of the plugins that are active. */ public static function active_conflicts( array $plugins ): array { if( ! function_exists( 'is_plugin_active' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $found = []; foreach( $plugins as $file => $name ) { if( is_plugin_active( (string) $file ) || is_plugin_active_for_network( (string) $file ) ) { $found[] = (string) $name; } } return array_values( array_unique( $found ) ); } /** * Checks if WooCommerce is active. * * @return bool True when WooCommerce is loaded. */ public static function woocommerce_active(): bool { return class_exists( 'WooCommerce' ); } /** * Gets the REST route the current request is for, in the spelling WordPress will serve it. * * Reads the resolved route, so /wp-json/... and ?rest_route=... give the same answer. * The route is lowercased, and trailing slashes, backslashes and whitespace are removed, * because WordPress serves /WP/V2/Users/, ?rest_route=0/ and a route ending in a line * break as the route (or the index) they look like. A guard that compares the raw text * can be walked around with any of them. * * @return string The route with a leading slash, '/' for the REST index, or '' when this is not a REST request. */ public static function current_rest_route(): string { if( !isset( $GLOBALS['wp']->query_vars['rest_route'] ) ) { return ''; } $route = $GLOBALS['wp']->query_vars['rest_route']; if( !is_string( $route ) || '' === trim( $route ) ) { return ''; } $route = strtolower( rtrim( ltrim( $route ), "/\\ \t\n\r\0\x0B" ) ); if( empty( $route ) ) { return '/'; } if( '/' !== $route[0] ) { $route = '/' . $route; } return $route; } /** * Checks if a REST route is the given prefix or sits underneath it, on a path boundary. * 'wc/store' matches '/wc/store/v1/cart' but not '/wc/storefoo'. * * @param string $route The route to test, usually from current_rest_route(). * @param string $prefix The prefix, with or without surrounding slashes. * * @return bool True when the route is the prefix or below it. False for an empty route or prefix. */ public static function rest_route_is_under( string $route, string $prefix ): bool { $route = strtolower( trim( $route, "/ \t\n\r\0\x0B" ) ); $prefix = strtolower( trim( $prefix, "/ \t\n\r\0\x0B" ) ); if( '' === $route || '' === $prefix ) { return false; } return $route === $prefix || 0 === strpos( $route, $prefix . '/' ); } /** * Keeps the stored value of settings that are hidden on this site. * A hidden field is not posted by the form, and a save replaces the whole option, so * without this its stored value would be wiped and would not come back if the site changes. * * @param string $tab The settings tab the keys belong to. * @param array $keys The setting keys hidden on this site. * * @return void */ public static function keep_hidden_settings( string $tab, array $keys ) { if( empty( $keys ) ) { return; } if( false === has_filter( 'adminease_validate_settings', [ self::class, 'restore_hidden_settings' ] ) ) { add_filter( 'adminease_validate_settings', [ self::class, 'restore_hidden_settings' ], 20 ); } self::$hidden_settings[ $tab ] = array_values( array_unique( array_merge( self::$hidden_settings[ $tab ] ?? [], $keys ) ) ); } /** * Copies the stored value of every hidden setting into the settings about to be saved. * * @param mixed $sanitized_settings The settings about to be saved. * * @return mixed The settings, with hidden values restored. */ public static function restore_hidden_settings( $sanitized_settings ) { if( !is_array( $sanitized_settings ) ) { return $sanitized_settings; } $stored_settings = get_option( 'adminease_settings', [] ); if( !is_array( $stored_settings ) ) { return $sanitized_settings; } foreach( self::$hidden_settings as $tab => $keys ) { if( isset( $sanitized_settings[ $tab ] ) && !is_array( $sanitized_settings[ $tab ] ) ) { continue; } foreach( $keys as $key ) { if( isset( $stored_settings[ $tab ][ $key ] ) && !isset( $sanitized_settings[ $tab ][ $key ] ) ) { $sanitized_settings[ $tab ][ $key ] = $stored_settings[ $tab ][ $key ]; } } } return $sanitized_settings; } }