1, 'language' => 'auto', 'post_types' => array( 'post' ), 'level_adsense' => 1, 'level_managers' => 1, 'google_all' => 1, 'block_incontent' => 1, 'block_multiplex' => 1, 'block_side_rail' => 1, 'block_anchor' => 1, 'block_vignette' => 1, 'block_ad_intents' => 1, 'block_builtin_inserter' => 1, 'block_ad_inserter' => 1, 'block_ezoic' => 0, 'block_custom_networks' => 0, 'custom_ad_domains' => '', 'devices' => array( 'desktop', 'mobile' ), 'rules' => array(), ); } private function block_defaults() { return array( 'enabled' => 1, 'name' => 'New Ad Block', 'code' => '', 'position' => 'after_paragraph', 'paragraph' => 3, 'every' => 4, 'post_types' => array( 'post' ), 'devices' => array( 'desktop', 'mobile' ), 'alignment' => 'center', ); } private function available_languages() { return array( 'auto' => 'Automatic — Site language', 'en' => 'English', 'it' => 'Italiano', 'es' => 'Español', 'fr' => 'Français', 'de' => 'Deutsch', 'pt' => 'Português', ); } private function current_admin_language() { $settings = $this->get_settings(); $choice = isset( $settings['language'] ) ? $settings['language'] : 'auto'; if ( 'auto' !== $choice && in_array( $choice, array( 'en','it','es','fr','de','pt' ), true ) ) return $choice; $site_locale = (string) get_option( 'WPLANG', '' ); $locale = strtolower( '' !== $site_locale ? $site_locale : 'en_US' ); $base = substr( str_replace( '-', '_', $locale ), 0, 2 ); return in_array( $base, array( 'en','it','es','fr','de','pt' ), true ) ? $base : 'en'; } private function t( $text ) { $lang = $this->current_admin_language(); if ( 'en' === $lang ) return $text; $tr = array( 'it' => array( 'Dashboard'=>'Dashboard','Exclusion Rules'=>'Regole di esclusione','Ad Inserter'=>'Inserter annunci','Settings'=>'Impostazioni', 'One plugin, two simple actions: decide where ads are allowed and where they should appear.'=>'Un solo plugin, due azioni semplici: decidi dove gli annunci sono consentiti e dove devono apparire.', 'Create smart rules based on words, phrases or URLs found in the content, and automatically prevent ads on matching posts or pages.'=>'Crea regole intelligenti basate su parole, frasi o URL presenti nel contenuto e impedisci automaticamente gli annunci nei post o nelle pagine corrispondenti.', 'Manage exclusions'=>'Gestisci esclusioni','Create ad blocks and place them before/after content, around a paragraph, or every X paragraphs.'=>'Crea blocchi pubblicitari e posizionali prima/dopo il contenuto, vicino a un paragrafo o ogni X paragrafi.', 'Manage ad blocks'=>'Gestisci blocchi annunci','Exclusion rules'=>'Regole di esclusione','Ad blocks'=>'Blocchi annunci','Active ad blocks'=>'Blocchi annunci attivi', 'Priority:'=>'Priorità:','Exclusion Rules always win. If a page matches a rule, AdPermit Rules will not output any block created by the built-in Inserter on that page.'=>'Le Regole di esclusione hanno sempre la priorità. Se una pagina corrisponde a una regola, AdPermit Rules non inserirà alcun blocco creato con l’Inserter integrato.', 'Exclusion Rules — decide when ads must not be shown.'=>'Regole di esclusione — decidi quando gli annunci non devono essere mostrati.','Rules'=>'Regole','If at least one rule matches, the page becomes ad-excluded.'=>'Se almeno una regola corrisponde, la pagina viene esclusa dagli annunci.','+ Add rule'=>'+ Aggiungi regola','Example:'=>'Esempio:','Content contains'=>'Il contenuto contiene','URL contains'=>'URL contiene','Content ID equals'=>'ID contenuto =','Word or phrase'=>'Parola o frase','URL or URL fragment'=>'URL o parte di URL','Numeric post/page ID'=>'ID numerico post/pagina','Matching is case-insensitive.'=>'La corrispondenza non distingue maiuscole e minuscole.','Save exclusion rules'=>'Salva regole di esclusione','Blocking options'=>'Opzioni di blocco', 'Ad Inserter — create and position your ad blocks.'=>'Inserter annunci — crea e posiziona i tuoi blocchi pubblicitari.','Ad Blocks'=>'Blocchi annunci','Paste AdSense, HTML or other ad code. Exclusion Rules are applied automatically.'=>'Incolla codice AdSense, HTML o altro codice pubblicitario. Le Regole di esclusione vengono applicate automaticamente.','No ad blocks yet. Click “Add ad block” to create your first one.'=>'Non ci sono ancora blocchi annunci. Fai clic su “Aggiungi blocco annunci” per creare il primo.','+ Add ad block'=>'+ Aggiungi blocco annunci','Safe priority:'=>'Priorità sicura:','if an Exclusion Rule matches the current post/page, these blocks are not inserted.'=>'se una Regola di esclusione corrisponde al post/pagina corrente, questi blocchi non vengono inseriti.','Save ad blocks'=>'Salva blocchi annunci', 'Settings — choose what the exclusion engine blocks and on which devices.'=>'Impostazioni — scegli cosa blocca il motore di esclusione e su quali dispositivi.','General'=>'Generale','AdPermit Rules enabled'=>'AdPermit Rules attivo','Turn the exclusion engine on/off without deleting rules.'=>'Attiva o disattiva il motore di esclusione senza eliminare le regole.','Interface language'=>'Lingua interfaccia','Automatic — Site language'=>'Automatico — Lingua del sito','Uses the WordPress site language when available. Unsupported languages fall back to English.'=>'Usa la lingua del sito WordPress quando disponibile. Le lingue non supportate usano automaticamente l’inglese.', 'Where exclusions apply'=>'Dove si applicano le esclusioni','Content types'=>'Tipi di contenuto','Posts'=>'Post','Pages'=>'Pagine','Devices'=>'Dispositivi','Desktop'=>'Computer / Desktop','Mobile / Tablet'=>'Mobile / Tablet', 'What to block when a rule matches'=>'Cosa bloccare quando una regola corrisponde','What can be excluded?'=>'Cosa può essere escluso?','Exclusion Rules can block Google AdSense and Auto Ads. If the External Ad Managers compatibility layer is enabled, Ad Inserter output can also be blocked. Other ad networks are not automatically covered unless their code is handled by one of these options.'=>'Le Regole di esclusione possono bloccare Google AdSense e Auto Ads, inclusi gli annunci inseriti con l’Inserter integrato o Ad Inserter. Le altre reti pubblicitarie non sono coperte automaticamente.', 'Google Ads are handled by format. Other providers are handled separately so the choices remain clear.'=>'Le Regole di esclusione possono bloccare Google AdSense e Auto Ads, inclusi gli annunci inseriti con l’Inserter integrato o Ad Inserter. Le altre reti pubblicitarie non sono coperte automaticamente.','Ads inside content'=>'Annunci nel contenuto','Standard in-content AdSense units.'=>'Unità AdSense standard all’interno del contenuto.','Side Rail'=>'Side Rail','Floating side ads during scroll.'=>'Annunci laterali fluttuanti durante lo scorrimento.','Anchor / Overlay'=>'Anchor / Overlay','Top/bottom anchor and overlay formats.'=>'Formati anchor superiore/inferiore e overlay.','Block all Google Auto Ads'=>'Blocca tutti i Google Auto Ads','Strongest mode: blocks the Google ad script globally on matched pages.'=>'Modalità più forte: blocca globalmente lo script pubblicitario Google nelle pagine corrispondenti.','If Block all Google Auto Ads is enabled, it overrides the more selective Google format choices.'=>'Se “Blocca tutti i Google Auto Ads” è attivo, ha priorità sulle scelte selettive dei singoli formati Google.', 'When Block all Google Auto Ads is enabled, the three selective options are enabled automatically. Turning the global option off does not change the individual selections.'=>'Quando attivi “Blocca tutti i Google Auto Ads”, vengono attivate automaticamente anche le tre opzioni selettive. Se disattivi l’opzione globale, le selezioni individuali restano invariate.', 'Google Ads'=>'Google Ads','Select all Google Ads'=>'Seleziona tutti Google Ads','Turn this on to select every Google ad format below. Turning it off does not change the individual selections.'=>'Attivando questa opzione vengono selezionati tutti i formati Google sottostanti. Disattivandola, le selezioni individuali non vengono modificate.','In-page / Banner ads'=>'Annunci In-page / Banner','Standard display or native ads shown within the page content.'=>'Annunci display o nativi mostrati all’interno del contenuto della pagina.','Multiplex ads'=>'Annunci Multiplex','Native grid-style ad units with multiple ads.'=>'Unità native a griglia che mostrano più annunci.','Anchor ads'=>'Annunci Anchor','Ads fixed to the top or bottom edge of the screen.'=>'Annunci fissati al bordo superiore o inferiore dello schermo.','Vignette ads'=>'Annunci Vignette','Full-screen ads shown between page loads.'=>'Annunci a schermo intero mostrati tra un caricamento di pagina e l’altro.','Ad Intents'=>'Ad Intents','Google intent-based links, anchors and chips added to page content.'=>'Link, anchor e chip basati sull’intento aggiunti da Google al contenuto.','Other ad sources'=>'Altre sorgenti pubblicitarie','Built-in Ad Inserter'=>'Inserter annunci integrato','Blocks ad blocks created inside AdPermit Rules when a rule matches.'=>'Blocca i blocchi annunci creati dentro AdPermit Rules quando una regola corrisponde.','Ad Inserter plugin'=>'Plugin Ad Inserter','Blocks output generated by the external Ad Inserter WordPress plugin.'=>'Blocca l’output generato dal plugin WordPress esterno Ad Inserter.','Ezoic'=>'Ezoic','Blocks recognizable Ezoic ad scripts and placeholders on matched pages.'=>'Blocca script pubblicitari e placeholder Ezoic riconoscibili nelle pagine corrispondenti.','Other networks / custom domains'=>'Altre reti / domini personalizzati','Block scripts and iframes whose source contains one of the domains below.'=>'Blocca script e iframe la cui sorgente contiene uno dei domini indicati sotto.','Ad network domains'=>'Domini delle reti pubblicitarie','One domain per line, for example: ads.example.com'=>'Un dominio per riga, ad esempio: ads.example.com','Google ad formats'=>'Formati Google Ads','Google Ads are handled by format. Other providers are handled separately so the choices remain clear.'=>'Gli annunci Google sono gestiti per formato. Gli altri provider sono gestiti separatamente, così le scelte restano chiare.', 'Compatibility layers'=>'Livelli di compatibilità','Level 1 — Google AdSense / Auto Ads'=>'Livello 1 — Google AdSense / Auto Ads','Handles Google scripts, in-content units and dynamic Auto Ads.'=>'Gestisce script Google, unità nel contenuto e Auto Ads dinamici.','Level 2 — External Ad Managers'=>'Livello 2 — Gestori annunci esterni','Blocks Ad Inserter output/shortcodes when a rule matches.'=>'Blocca output e shortcode di Ad Inserter quando una regola corrisponde.','Save settings'=>'Salva impostazioni', 'Word, phrase or URL'=>'Parola, frase o URL','Remove'=>'Rimuovi','Active'=>'Attivo','Duplicate'=>'Duplica','Delete'=>'Elimina','Delete this ad block?'=>'Eliminare questo blocco annunci?','Block name'=>'Nome blocco','Status'=>'Stato','Enabled'=>'Attivo','Inactive'=>'Inattivo','Ad code / HTML'=>'Codice annuncio / HTML','Paste your AdSense, HTML or other ad code here...'=>'Incolla qui il codice AdSense, HTML o altro codice pubblicitario...','AdSense loader is managed automatically'=>'Il loader AdSense viene gestito automaticamente','If this block contains Google AdSense code, AdPermit Rules loads adsbygoogle.js once in the page head. You can remove the global AdSense script from your theme.'=>'Se questo blocco contiene codice Google AdSense, AdPermit Rules carica adsbygoogle.js una sola volta nell’head della pagina. Puoi rimuovere lo script AdSense globale dal tema.','JavaScript is preserved for administrators with the WordPress unfiltered_html capability.'=>'JavaScript viene mantenuto per gli amministratori con la capability WordPress unfiltered_html.','Position'=>'Posizione','Before content'=>'Prima del contenuto','After content'=>'Dopo il contenuto','Before paragraph'=>'Prima del paragrafo','After paragraph'=>'Dopo il paragrafo','Every X paragraphs'=>'Ogni X paragrafi','Paragraph number / interval'=>'Numero paragrafo / intervallo','For “Every X paragraphs”, this number is used as the interval.'=>'Per “Ogni X paragrafi”, questo numero viene usato come intervallo.','Alignment'=>'Allineamento','Left'=>'Sinistra','Center'=>'Centro','Right'=>'Destra','No action'=>'Nessuna azione','Exclusion'=>'Esclusione','Partial exclusion'=>'Esclusione parziale','Exclude this page?'=>'Escludi questa pagina?','Matched rule'=>'Regola corrispondente','AdSense loader'=>'Loader AdSense','Loaded'=>'Caricato','Not loaded'=>'Non caricato','No Inserter block was added to this page.'=>'Nessun blocco Inserter è stato aggiunto a questa pagina.','Open Exclusion Rules'=>'Apri Regole di esclusione','Open Ad Inserter'=>'Apri Inserter annunci' ), 'es' => array('Dashboard'=>'Panel','Exclusion Rules'=>'Reglas de exclusión','Ad Inserter'=>'Insertor de anuncios','Settings'=>'Ajustes','Interface language'=>'Idioma de la interfaz','Automatic — Site language'=>'Automático — Idioma del sitio','Save settings'=>'Guardar ajustes','Content contains'=>'El contenido contiene','URL contains'=>'La URL contiene','Content ID equals'=>'ID de contenido =','Word or phrase'=>'Palabra o frase','URL or URL fragment'=>'URL o fragmento de URL','Numeric post/page ID'=>'ID numérico de entrada/página','Word, phrase or URL'=>'Palabra, frase o URL','Posts'=>'Entradas','Pages'=>'Páginas','Devices'=>'Dispositivos','Desktop'=>'Escritorio','Mobile / Tablet'=>'Móvil / Tablet','Enabled'=>'Activado','Delete'=>'Eliminar','Duplicate'=>'Duplicar','Active'=>'Activo','Inactive'=>'Inactivo','Alignment'=>'Alineación','Left'=>'Izquierda','Center'=>'Centro','Right'=>'Derecha','No action'=>'Sin acción','Exclusion'=>'Exclusión','Partial exclusion'=>'Exclusión parcial','Exclude this page?'=>'¿Excluir esta página?','Matched rule'=>'Regla coincidente','AdSense loader'=>'Cargador de AdSense','Loaded'=>'Cargado','Not loaded'=>'No cargado','Open Exclusion Rules'=>'Abrir reglas de exclusión','Open Ad Inserter'=>'Abrir insertor de anuncios'), 'fr' => array('Dashboard'=>'Tableau de bord','Exclusion Rules'=>'Règles d’exclusion','Ad Inserter'=>'Insertion d’annonces','Settings'=>'Réglages','Interface language'=>'Langue de l’interface','Automatic — Site language'=>'Automatique — Langue du site','Save settings'=>'Enregistrer les réglages','Content contains'=>'Le contenu contient','URL contains'=>'L’URL contient','Content ID equals'=>'ID du contenu =','Word or phrase'=>'Mot ou expression','URL or URL fragment'=>'URL ou fragment d’URL','Numeric post/page ID'=>'ID numérique article/page','Word, phrase or URL'=>'Mot, expression ou URL','Posts'=>'Articles','Pages'=>'Pages','Devices'=>'Appareils','Desktop'=>'Ordinateur','Mobile / Tablet'=>'Mobile / Tablette','Enabled'=>'Activé','Delete'=>'Supprimer','Duplicate'=>'Dupliquer','Active'=>'Actif','Inactive'=>'Inactif','Alignment'=>'Alignement','Left'=>'Gauche','Center'=>'Centre','Right'=>'Droite','No action'=>'Aucune action','Exclusion'=>'Exclusion','Partial exclusion'=>'Exclusion partielle','Exclude this page?'=>'Exclure cette page ?','Matched rule'=>'Règle correspondante','AdSense loader'=>'Chargeur AdSense','Loaded'=>'Chargé','Not loaded'=>'Non chargé','Open Exclusion Rules'=>'Ouvrir les règles d’exclusion','Open Ad Inserter'=>'Ouvrir l’insertion d’annonces'), 'de' => array('Dashboard'=>'Dashboard','Exclusion Rules'=>'Ausschlussregeln','Ad Inserter'=>'Anzeigen-Inserter','Settings'=>'Einstellungen','Interface language'=>'Sprache der Oberfläche','Automatic — Site language'=>'Automatisch — Website-Sprache','Save settings'=>'Einstellungen speichern','Content contains'=>'Inhalt enthält','URL contains'=>'URL enthält','Content ID equals'=>'Inhalts-ID =','Word or phrase'=>'Wort oder Ausdruck','URL or URL fragment'=>'URL oder URL-Teil','Numeric post/page ID'=>'Numerische Beitrags-/Seiten-ID','Word, phrase or URL'=>'Wort, Ausdruck oder URL','Posts'=>'Beiträge','Pages'=>'Seiten','Devices'=>'Geräte','Desktop'=>'Desktop','Mobile / Tablet'=>'Mobil / Tablet','Enabled'=>'Aktiviert','Delete'=>'Löschen','Duplicate'=>'Duplizieren','Active'=>'Aktiv','Inactive'=>'Inaktiv','Alignment'=>'Ausrichtung','Left'=>'Links','Center'=>'Zentriert','Right'=>'Rechts','No action'=>'Keine Aktion','Exclusion'=>'Ausschluss','Partial exclusion'=>'Teilweiser Ausschluss','Exclude this page?'=>'Diese Seite ausschließen?','Matched rule'=>'Passende Regel','AdSense loader'=>'AdSense-Loader','Loaded'=>'Geladen','Not loaded'=>'Nicht geladen','Open Exclusion Rules'=>'Ausschlussregeln öffnen','Open Ad Inserter'=>'Anzeigen-Inserter öffnen'), 'pt' => array('Dashboard'=>'Painel','Exclusion Rules'=>'Regras de exclusão','Ad Inserter'=>'Inseridor de anúncios','Settings'=>'Definições','Interface language'=>'Idioma da interface','Automatic — Site language'=>'Automático — Idioma do site','Save settings'=>'Guardar definições','Content contains'=>'O conteúdo contém','URL contains'=>'URL contém','Content ID equals'=>'ID do conteúdo =','Word or phrase'=>'Palavra ou frase','URL or URL fragment'=>'URL ou parte da URL','Numeric post/page ID'=>'ID numérico do artigo/página','Word, phrase or URL'=>'Palavra, frase ou URL','Posts'=>'Artigos','Pages'=>'Páginas','Devices'=>'Dispositivos','Desktop'=>'Computador','Mobile / Tablet'=>'Mobile / Tablet','Enabled'=>'Ativo','Delete'=>'Eliminar','Duplicate'=>'Duplicar','Active'=>'Ativo','Inactive'=>'Inativo','Alignment'=>'Alinhamento','Left'=>'Esquerda','Center'=>'Centro','Right'=>'Direita','No action'=>'Nenhuma ação','Exclusion'=>'Exclusão','Partial exclusion'=>'Exclusão parcial','Exclude this page?'=>'Excluir esta página?','Matched rule'=>'Regra correspondente','AdSense loader'=>'Carregador AdSense','Loaded'=>'Carregado','Not loaded'=>'Não carregado','Open Exclusion Rules'=>'Abrir regras de exclusão','Open Ad Inserter'=>'Abrir inseridor de anúncios'), ); $extra = array( 'it' => array('Blocked'=>'Bloccato','Allowed'=>'Consentito','blocked'=>'bloccati','Other ad networks'=>'Altre reti pubblicitarie','Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.'=>'Attiva solo le reti che utilizzi realmente. Un interruttore blu indica che quella sorgente verrà bloccata quando una regola di esclusione corrisponde.','Ezoic Ads'=>'Annunci Ezoic','Automatically block recognizable Ezoic ad scripts and placeholders.'=>'Blocca automaticamente gli script pubblicitari e i placeholder Ezoic riconoscibili.','Custom ad domains'=>'Domini pubblicitari personalizzati','Block ad scripts and iframes loaded from domains you specify.'=>'Blocca script pubblicitari e iframe caricati dai domini specificati.','Domains to block'=>'Domini da bloccare','Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.'=>'Inserisci un dominio per riga. Puoi incollare anche un URL completo: AdPermit Rules salverà solo il nome host.','Google Ads allowed'=>'Google Ads consentiti','All formats blocked'=>'Tutti i formati bloccati','%d formats allowed'=>'%d formati consentiti','In-page / Banner'=>'In-page / Banner','Multiplex'=>'Multiplex','Anchor'=>'Anchor','Vignette'=>'Vignette'), 'es' => array('Blocked'=>'Bloqueado','Allowed'=>'Permitido','blocked'=>'bloqueados','Other ad networks'=>'Otras redes publicitarias','Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.'=>'Activa solo las redes que realmente utilizas. Un interruptor azul indica que esa fuente se bloqueará cuando coincida una regla de exclusión.','Ezoic Ads'=>'Anuncios Ezoic','Automatically block recognizable Ezoic ad scripts and placeholders.'=>'Bloquea automáticamente scripts publicitarios y marcadores Ezoic reconocibles.','Custom ad domains'=>'Dominios publicitarios personalizados','Block ad scripts and iframes loaded from domains you specify.'=>'Bloquea scripts publicitarios e iframes cargados desde los dominios indicados.','Domains to block'=>'Dominios a bloquear','Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.'=>'Introduce un dominio por línea. También puedes pegar una URL completa: AdPermit Rules guardará solo el nombre de host.','Google Ads allowed'=>'Google Ads permitidos','All formats blocked'=>'Todos los formatos bloqueados','%d formats allowed'=>'%d formatos permitidos'), 'fr' => array('Blocked'=>'Bloqué','Allowed'=>'Autorisé','blocked'=>'bloqués','Other ad networks'=>'Autres réseaux publicitaires','Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.'=>'Activez uniquement les réseaux que vous utilisez. Un interrupteur bleu signifie que cette source sera bloquée lorsqu’une règle d’exclusion correspond.','Ezoic Ads'=>'Annonces Ezoic','Automatically block recognizable Ezoic ad scripts and placeholders.'=>'Bloque automatiquement les scripts publicitaires et espaces réservés Ezoic reconnaissables.','Custom ad domains'=>'Domaines publicitaires personnalisés','Block ad scripts and iframes loaded from domains you specify.'=>'Bloque les scripts publicitaires et iframes chargés depuis les domaines indiqués.','Domains to block'=>'Domaines à bloquer','Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.'=>'Saisissez un domaine par ligne. Vous pouvez coller une URL complète : AdPermit Rules ne conservera que le nom d’hôte.','Google Ads allowed'=>'Google Ads autorisées','All formats blocked'=>'Tous les formats bloqués','%d formats allowed'=>'%d formats autorisés'), 'de' => array('Blocked'=>'Blockiert','Allowed'=>'Erlaubt','blocked'=>'blockiert','Other ad networks'=>'Andere Werbenetzwerke','Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.'=>'Aktivieren Sie nur Netzwerke, die Sie tatsächlich verwenden. Ein blauer Schalter bedeutet, dass diese Quelle bei einer passenden Ausschlussregel blockiert wird.','Ezoic Ads'=>'Ezoic-Anzeigen','Automatically block recognizable Ezoic ad scripts and placeholders.'=>'Erkennbare Ezoic-Werbeskripte und Platzhalter automatisch blockieren.','Custom ad domains'=>'Benutzerdefinierte Werbedomains','Block ad scripts and iframes loaded from domains you specify.'=>'Werbeskripte und Iframes von angegebenen Domains blockieren.','Domains to block'=>'Zu blockierende Domains','Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.'=>'Eine Domain pro Zeile eingeben. Sie können auch eine vollständige URL einfügen; AdPermit Rules speichert nur den Hostnamen.','Google Ads allowed'=>'Erlaubte Google Ads','All formats blocked'=>'Alle Formate blockiert','%d formats allowed'=>'%d Formate erlaubt'), 'pt' => array('Blocked'=>'Bloqueado','Allowed'=>'Permitido','blocked'=>'bloqueados','Other ad networks'=>'Outras redes de anúncios','Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.'=>'Ative apenas as redes que realmente utiliza. Um interruptor azul significa que essa origem será bloqueada quando uma regra de exclusão corresponder.','Ezoic Ads'=>'Anúncios Ezoic','Automatically block recognizable Ezoic ad scripts and placeholders.'=>'Bloqueia automaticamente scripts de anúncios e placeholders Ezoic reconhecíveis.','Custom ad domains'=>'Domínios de anúncios personalizados','Block ad scripts and iframes loaded from domains you specify.'=>'Bloqueia scripts de anúncios e iframes carregados a partir dos domínios indicados.','Domains to block'=>'Domínios a bloquear','Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.'=>'Introduza um domínio por linha. Pode colar um URL completo: o AdPermit Rules guarda apenas o nome do host.','Google Ads allowed'=>'Google Ads permitidos','All formats blocked'=>'Todos os formatos bloqueados','%d formats allowed'=>'%d formatos permitidos'), ); if(isset($extra[$lang][$text])) return $extra[$lang][$text]; return isset( $tr[$lang][$text] ) ? $tr[$lang][$text] : $text; } public function admin_menu() { add_menu_page( 'AdPermit Rules', 'AdPermit Rules', 'manage_options', 'adpermit-rules', array( $this, 'dashboard_page' ), 'dashicons-shield-alt', 80 ); add_submenu_page( 'adpermit-rules', $this->t('Dashboard'), $this->t('Dashboard'), 'manage_options', 'adpermit-rules', array( $this, 'dashboard_page' ) ); add_submenu_page( 'adpermit-rules', $this->t('Exclusion Rules'), $this->t('Exclusion Rules'), 'manage_options', 'adpermit-rules-exclusions', array( $this, 'exclusions_page' ) ); add_submenu_page( 'adpermit-rules', $this->t('Ad Inserter'), $this->t('Ad Inserter'), 'manage_options', 'adpermit-rules-inserter', array( $this, 'inserter_page' ) ); } public function register_settings() { register_setting( 'adpermitrules_rules_group', self::OPTION_NAME, array( 'type'=>'array', 'sanitize_callback'=>array($this,'sanitize_settings'), 'default'=>$this->defaults() ) ); register_setting( 'adpermitrules_blocks_group', self::BLOCKS_OPTION, array( 'type'=>'array', 'sanitize_callback'=>array($this,'sanitize_blocks'), 'default'=>array() ) ); } private function get_settings() { $settings = get_option( self::OPTION_NAME, array() ); $settings = is_array( $settings ) ? $settings : array(); return wp_parse_args( $settings, $this->defaults() ); } private function get_blocks() { $blocks = get_option( self::BLOCKS_OPTION, array() ); return is_array( $blocks ) ? $blocks : array(); } public function sanitize_settings( $input ) { $clean=$this->defaults(); $input=is_array($input)?$input:array(); foreach(array('enabled','google_all','block_incontent','block_multiplex','block_side_rail','block_anchor','block_vignette','block_ad_intents','block_ezoic','block_custom_networks') as $key){$clean[$key]=!empty($input[$key])?1:0;} // Internal compatibility is automatic and intentionally hidden from the UI. // A matched exclusion always suppresses AdPermit's own Inserter and Ad Inserter output. $clean['block_builtin_inserter']=1; $clean['block_ad_inserter']=1; $clean['level_adsense']=1; $clean['level_managers']=1; $domains=isset($input['custom_ad_domains'])?wp_unslash($input['custom_ad_domains']):''; $rows=preg_split('/\R/u',(string)$domains); $safe=array(); foreach($rows as $row){$row=strtolower(trim($row));$row=preg_replace('#^https?://#','',$row);$row=preg_replace('#/.*$#','',$row);if($row!==''&&preg_match('/^[a-z0-9.-]+$/',$row))$safe[$row]=1;} $clean['custom_ad_domains']=implode("\n",array_keys($safe)); $clean['google_all']=(!empty($clean['block_incontent'])&&!empty($clean['block_multiplex'])&&!empty($clean['block_side_rail'])&&!empty($clean['block_anchor'])&&!empty($clean['block_vignette'])&&!empty($clean['block_ad_intents']))?1:0; $lang=isset($input['language'])?sanitize_key($input['language']):'auto'; $clean['language']=in_array($lang,array('auto','en','it','es','fr','de','pt'),true)?$lang:'auto'; $clean['devices']=$this->sanitize_choice_array($input,'devices',array('desktop','mobile'),array('desktop','mobile')); $clean['post_types']=$this->sanitize_choice_array($input,'post_types',array('post','page'),array('post')); $clean['rules']=array(); $seen=array(); foreach((isset($input['rules'])&&is_array($input['rules'])?$input['rules']:array()) as $rule){ if(!is_array($rule)) continue; $condition=isset($rule['condition'])?sanitize_key($rule['condition']):'content_contains'; if(!in_array($condition,array('content_contains','url_contains','content_id'),true))$condition='content_contains'; $value=isset($rule['value'])?trim(wp_strip_all_tags(wp_unslash($rule['value']))):''; if($value==='')continue; if('content_id'===$condition){$value=(string)absint($value); if('0'===$value)continue;} $dedupe=$condition.'|'.strtolower($value); if(isset($seen[$dedupe]))continue; $seen[$dedupe]=true; $clean['rules'][]=array('condition'=>$condition,'value'=>$value); } return $clean; } public function sanitize_blocks( $input ) { $clean=array(); $input=is_array($input)?$input:array(); $allowed_positions=array('before_content','after_content','before_paragraph','after_paragraph','every_paragraphs'); $allowed_align=array('left','center','right'); foreach($input as $row){ if(!is_array($row))continue; $block=$this->block_defaults(); $block['enabled']=!empty($row['enabled'])?1:0; $block['name']=isset($row['name'])?sanitize_text_field(wp_unslash($row['name'])):'Ad Block'; $raw=isset($row['code'])?wp_unslash($row['code']):''; $block['code']=$this->sanitize_ad_code($raw); $pos=isset($row['position'])?sanitize_key($row['position']):'after_paragraph'; $block['position']=in_array($pos,$allowed_positions,true)?$pos:'after_paragraph'; $block['paragraph']=max(1,min(100,intval(isset($row['paragraph'])?$row['paragraph']:3))); $block['every']=max(1,min(100,intval(isset($row['every'])?$row['every']:4))); $block['post_types']=$this->sanitize_choice_array($row,'post_types',array('post','page'),array('post')); $block['devices']=$this->sanitize_choice_array($row,'devices',array('desktop','mobile'),array('desktop','mobile')); $align=isset($row['alignment'])?sanitize_key($row['alignment']):'center'; $block['alignment']=in_array($align,$allowed_align,true)?$align:'center'; $clean[]=$block; } return $clean; } private function allowed_ad_html(){ $global=array( 'id'=>true,'class'=>true,'style'=>true,'title'=>true,'role'=>true, 'aria-*'=>true,'data-*'=>true, ); return array( 'div'=>$global,'span'=>$global,'p'=>$global,'br'=>array(), 'ins'=>array_merge($global,array('data-ad-client'=>true,'data-ad-slot'=>true,'data-ad-format'=>true,'data-full-width-responsive'=>true,'data-ad-layout'=>true,'data-ad-layout-key'=>true)), 'script'=>array('src'=>true,'type'=>true,'async'=>true,'defer'=>true,'crossorigin'=>true,'referrerpolicy'=>true,'data-*'=>true), 'iframe'=>array_merge($global,array('src'=>true,'width'=>true,'height'=>true,'frameborder'=>true,'allow'=>true,'allowfullscreen'=>true,'loading'=>true,'referrerpolicy'=>true,'sandbox'=>true)), 'a'=>array_merge($global,array('href'=>true,'target'=>true,'rel'=>true)), 'img'=>array_merge($global,array('src'=>true,'srcset'=>true,'sizes'=>true,'alt'=>true,'width'=>true,'height'=>true,'loading'=>true)), 'noscript'=>$global, ); } private function sanitize_ad_code($code){ return wp_kses((string)$code,$this->allowed_ad_html()); } private function sanitize_choice_array($input,$key,$allowed,$fallback){ $values=isset($input[$key])&&is_array($input[$key])?$input[$key]:array(); $values=array_values(array_intersect($allowed,array_map('sanitize_key',$values))); return empty($values)?$fallback:$values; } public function admin_assets($hook){ if(strpos($hook,'adpermit-rules')===false)return; wp_enqueue_style('adpermitrules-admin',plugin_dir_url(__FILE__).'assets/admin.css',array(),self::VERSION); wp_enqueue_script('adpermitrules-admin',plugin_dir_url(__FILE__).'assets/admin.js',array(),self::VERSION,true); wp_localize_script('adpermitrules-admin','AdPermitRulesAdmin',array( 'deleteConfirm'=>$this->t('Delete this ad block?'), 'blocked'=>$this->t('blocked'), 'allowed'=>$this->t('Allowed'), )); } private function admin_header($subtitle=''){ echo '

AdPermit Rules

'.esc_html($subtitle).'

v'.esc_html(self::VERSION).'
'; } public function dashboard_page(){ if(!current_user_can('manage_options'))return; $s=$this->get_settings(); $b=$this->get_blocks(); $active=0; foreach($b as $x) if(!empty($x['enabled']))$active++; ?>
admin_header($this->t('One plugin, two simple actions: decide where ads are allowed and where they should appear.')); ?>

t('Exclusion Rules')); ?>

t('Create smart rules based on words, phrases or URLs found in the content, and automatically prevent ads on matching posts or pages.')); ?>

t('Manage exclusions')); ?>

t('Ad Inserter')); ?>

t('Create ad blocks and place them before/after content, around a paragraph, or every X paragraphs.')); ?>

t('Manage ad blocks')); ?>
t('Exclusion rules')); ?>
t('Ad blocks')); ?>
t('Active ad blocks')); ?>
t('Priority:')); ?> t('Exclusion Rules always win. If a page matches a rule, AdPermit Rules will not output any block created by the built-in Inserter on that page.')); ?>

t('Interface language')); ?>

t('Uses the WordPress site language when available. Unsupported languages fall back to English.')); ?>

hidden_rules($s['rules']); $this->hidden_settings_fields($s,array('enabled','post_types','devices','google_all','block_incontent','block_multiplex','block_side_rail','block_anchor','block_vignette','block_ad_intents','block_builtin_inserter','block_ad_inserter','block_ezoic','block_custom_networks','custom_ad_domains')); ?>
t('Save settings'),'secondary','submit',false); ?>
get_settings(); $rules=$s['rules']; $prefill_id=0; $prefill_url=''; $quick_nonce=isset($_GET['adpermitrules_nonce'])?sanitize_text_field(wp_unslash($_GET['adpermitrules_nonce'])):''; if($quick_nonce!==''&&wp_verify_nonce($quick_nonce,'adpermitrules_quick_exclude')){ $prefill_id=isset($_GET['adpermitrules_add_id'])?absint($_GET['adpermitrules_add_id']):0; $prefill_url=isset($_GET['adpermitrules_add_url'])?sanitize_text_field(wp_unslash($_GET['adpermitrules_add_url'])):''; } if($prefill_id>0){ $exists=false; foreach($rules as $rr){ if(isset($rr['condition'],$rr['value'])&&'content_id'===$rr['condition']&&absint($rr['value'])===$prefill_id){$exists=true;break;} } if(!$exists)$rules[]=array('condition'=>'content_id','value'=>(string)$prefill_id); } elseif($prefill_url!==''){ $exists=false; foreach($rules as $rr){ if(isset($rr['condition'],$rr['value'])&&'url_contains'===$rr['condition']&&trim((string)$rr['value'])===$prefill_url){$exists=true;break;} } if(!$exists)$rules[]=array('condition'=>'url_contains','value'=>$prefill_url); } ?>
admin_header($this->t('Exclusion Rules — decide when ads must not be shown.')); settings_errors(); ?>

t('General')); ?>

t('AdPermit Rules enabled')); ?>

t('Turn the exclusion engine on/off without deleting rules.')); ?>

t('Rules')); ?>

t('If at least one rule matches, the page becomes ad-excluded.')); ?>

$r)$this->render_rule($i,$r); ?>
t('Example:')); ?> t('Content contains')); ?> → sponsored   t('URL contains')); ?> → /reviews/   t('Content ID equals')); ?> → 1234 t('Matching is case-insensitive.')); ?>
t('What can be excluded?')); ?> t('Google Ads are handled by format. Other providers are handled separately so the choices remain clear.')); ?>

t('Where exclusions apply')); ?>

t('Content types')); ?>

t('Devices')); ?>

t('What to block when a rule matches')); ?>

t('Google Ads are handled by format. Other providers are handled separately so the choices remain clear.')); ?>

t('Select all Google Ads')); ?>

t('Turn this on to select every Google ad format below. Turning it off does not change the individual selections.')); ?>

toggle_box($this->t('In-page / Banner ads'),$this->t('Standard display or native ads shown within the page content.'),'block_incontent',$s); $this->toggle_box($this->t('Multiplex ads'),$this->t('Native grid-style ad units with multiple ads.'),'block_multiplex',$s); $this->toggle_box($this->t('Side Rail'),$this->t('Floating side ads during scroll.'),'block_side_rail',$s); $this->toggle_box($this->t('Anchor ads'),$this->t('Ads fixed to the top or bottom edge of the screen.'),'block_anchor',$s); $this->toggle_box($this->t('Vignette ads'),$this->t('Full-screen ads shown between page loads.'),'block_vignette',$s); $this->toggle_box($this->t('Ad Intents'),$this->t('Google intent-based links, anchors and chips added to page content.'),'block_ad_intents',$s); ?>

t('Enable only the networks you actually use. A blue switch means that source will be blocked when an exclusion rule matches.')); ?>

toggle_box($this->t('Ezoic Ads'),$this->t('Automatically block recognizable Ezoic ad scripts and placeholders.'),'block_ezoic',$s); $this->toggle_box($this->t('Custom ad domains'),$this->t('Block ad scripts and iframes loaded from domains you specify.'),'block_custom_networks',$s); ?>

t('Enter one hostname per line. You can paste a full URL: AdPermit Rules saves only the hostname.')); ?>

get_blocks(); ?>
admin_header($this->t('Ad Inserter — create and position your ad blocks.')); settings_errors(); ?>

t('Ad Blocks')); ?>

t('Paste AdSense, HTML or other ad code. Exclusion Rules are applied automatically.')); ?>

'.esc_html($this->t('No ad blocks yet. Click “Add ad block” to create your first one.')).'
'; foreach($blocks as $i=>$block)$this->render_block($i,$block); ?>

t('Safe priority:')); ?> t('if an Exclusion Rule matches the current post/page, these blocks are not inserted.')); ?>

$r){$c=isset($r['condition'])&&in_array($r['condition'],array('content_contains','url_contains','content_id'),true)?$r['condition']:'content_contains';echo '';}} private function hidden_settings_fields($s,$keys){foreach($keys as $key){if(in_array($key,array('post_types','devices'),true)){foreach($s[$key] as $v)echo '';}elseif('language'===$key){echo '';}elseif('custom_ad_domains'===$key){echo '';}else echo '';}} private function render_rule($i,$r){$base=self::OPTION_NAME.'[rules]['.$i.']';$cond=isset($r['condition'])?$r['condition']:'content_contains';?>
block_defaults());$base=self::BLOCKS_OPTION.'['.$i.']';?>
'.esc_html($this->t('Active')).''; ?>
t('Active'):$this->t('Inactive')); ?>
t('JavaScript is preserved for administrators with the WordPress unfiltered_html capability.')); ?>
t('AdSense loader is managed automatically')); ?>. t('If this block contains Google AdSense code, AdPermit Rules loads adsbygoogle.js once in the page head. You can remove the global AdSense script from your theme.')); ?>
t('For “Every X paragraphs”, this number is used as the interval.')); ?>
ID)!==intval($queried->ID))return $content; if(!is_singular())return $content; if($this->current_content_should_exclude()&&!empty($this->get_settings()['block_builtin_inserter']))return $content; $post=$queried; $device=wp_is_mobile()?'mobile':'desktop'; foreach($this->get_blocks() as $idx=>$raw){ $b=wp_parse_args($raw,$this->block_defaults()); if(empty($b['enabled'])||trim($b['code'])==='')continue; if(!in_array($post->post_type,$b['post_types'],true)||!in_array($device,$b['devices'],true))continue; // The shared AdSense loader is printed once in ; remove any copy pasted inside the block. $block_code=$this->sanitize_ad_code($this->strip_adsense_loader_from_block($b['code'])); if(trim($block_code)==='')continue; $ad='
'.$block_code.'
'; switch($b['position']){ case 'before_content': $content=$ad.$content; break; case 'after_content': $content.=$ad; break; case 'before_paragraph': $content=$this->insert_near_paragraph($content,$ad,intval($b['paragraph']),false); break; case 'every_paragraphs': $content=$this->insert_every_paragraphs($content,$ad,max(1,intval($b['paragraph']))); break; case 'after_paragraph': default: $content=$this->insert_near_paragraph($content,$ad,intval($b['paragraph']),true); break; } $this->inserted_blocks[(string)$idx] = trim((string)$b['name']) !== '' ? (string)$b['name'] : ('#'.((int)$idx+1)); } return $content; } /** * Enqueue public CSS and the selective exclusion guard using WordPress APIs. */ public function enqueue_frontend_assets(){ if(is_admin())return; wp_enqueue_style('adpermitrules-frontend',plugin_dir_url(__FILE__).'assets/frontend.css',array(),self::VERSION); if(!$this->current_content_should_exclude())return; $s=$this->get_settings(); $config=array( 'all'=>$this->all_google_formats_blocked($s), 'content'=>!empty($s['block_incontent']), 'multiplex'=>!empty($s['block_multiplex']), 'side'=>!empty($s['block_side_rail']), 'anchor'=>!empty($s['block_anchor']), 'vignette'=>!empty($s['block_vignette']), 'intent'=>!empty($s['block_ad_intents']), 'ezoic'=>!empty($s['block_ezoic']), 'custom'=>!empty($s['block_custom_networks']), 'domains'=>array_values(array_filter(array_map('trim',preg_split('/\R/u',(string)$s['custom_ad_domains'])))), ); if(!$config['all']&&!$config['content']&&!$config['multiplex']&&!$config['side']&&!$config['anchor']&&!$config['vignette']&&!$config['intent']&&!$config['ezoic']&&!$config['custom'])return; wp_enqueue_script('adpermitrules-runtime',plugin_dir_url(__FILE__).'assets/runtime.js',array(),self::VERSION,false); wp_localize_script('adpermitrules-runtime','AdPermitRulesConfig',$config); } public function enqueue_adsense_loader(){ if(is_admin()||wp_doing_ajax()||wp_doing_cron()||is_feed()||!is_singular())return; $settings=$this->get_settings(); $excluded=$this->current_content_should_exclude(); // Suppress the Google loader only when every Google format is blocked for // this exact request/device. Selective exclusions keep AdSense available. if($excluded && $this->all_google_formats_blocked($settings))return; $client=$this->current_request_adsense_client_id(); if(!$client && $excluded && !$this->all_google_formats_blocked($settings)){ $client=$this->saved_adsense_client_id(); } if(!$client)return; $src=add_query_arg('client',$client,'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'); wp_enqueue_script('adpermit-rules-adsense-loader',esc_url_raw($src),array(),null,false); $this->adsense_loader_printed = true; } private function all_google_formats_blocked($settings=null){ $settings=is_array($settings)?$settings:$this->get_settings(); foreach(array('block_incontent','block_multiplex','block_side_rail','block_anchor','block_vignette','block_ad_intents') as $key){ if(empty($settings[$key]))return false; } return true; } private function saved_adsense_client_id(){ foreach($this->get_blocks() as $raw){ $b=wp_parse_args($raw,$this->block_defaults()); if(empty($b['enabled'])||trim((string)$b['code'])==='')continue; $client=$this->extract_adsense_client_id($b['code']); if($client)return $client; } return ''; } private function current_request_adsense_client_id(){ if(!is_singular())return ''; $post=get_queried_object(); if(!($post instanceof WP_Post))return ''; $device=wp_is_mobile()?'mobile':'desktop'; foreach($this->get_blocks() as $raw){ $b=wp_parse_args($raw,$this->block_defaults()); if(empty($b['enabled'])||trim((string)$b['code'])==='')continue; if(!in_array($post->post_type,$b['post_types'],true)||!in_array($device,$b['devices'],true))continue; $client=$this->extract_adsense_client_id($b['code']); if($client)return $client; } return ''; } private function extract_adsense_client_id($code){ $code=(string)$code; $patterns=array( '/[?&]client=(ca-pub-\d{6,})/i', '/data-ad-client\s*=\s*(["\'])(ca-pub-\d{6,})\1/i', '/\b(ca-pub-\d{6,})\b/i', ); foreach($patterns as $pattern){ if(preg_match($pattern,$code,$m)){ $client=isset($m[2])?$m[2]:$m[1]; if(preg_match('/^ca-pub-\d+$/i',$client))return strtolower($client); } } return ''; } private function strip_adsense_loader_from_block($code){ $code=(string)$code; // Remove only the shared adsbygoogle.js loader. Keep the ad unit and push() call. $code=preg_replace_callback('#]*\bsrc\s*=\s*(["\'])([^"\']*pagead2\.googlesyndication\.com/pagead/js/adsbygoogle\.js[^"\']*)\1[^>]*>\s*#is',function($m){return '';},$code); return $code; } private function insert_near_paragraph($content,$ad,$number,$after=true){ $number=max(1,$number); $parts=preg_split('/(<\/p>)/i',$content,-1,PREG_SPLIT_DELIM_CAPTURE); if(count($parts)<2)return $after?$content.$ad:$ad.$content; $out=''; $p=0; for($i=0;$i'){ $p++; if(!$after&&$p===$number)$out.=$ad; $out.=$part; if($after&&$p===$number)$out.=$ad; } else $out.=$part; } if($p<$number)$out.=$ad; return $out; } private function insert_every_paragraphs($content,$ad,$interval){ $parts=preg_split('/(<\/p>)/i',$content,-1,PREG_SPLIT_DELIM_CAPTURE); if(count($parts)<2)return $content; $out='';$p=0; foreach($parts as $part){$out.=$part;if(strtolower($part)==='

'){ $p++; if($p%$interval===0)$out.=$ad; }} return $out; } private function current_request_url_path(){ $uri=isset($_SERVER['REQUEST_URI'])?sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])):''; if($uri==='')return '/'; $path=(string)wp_parse_url($uri,PHP_URL_PATH); if($path==='')$path='/'; // Normalize duplicate slashes and keep a stable relative path so rules are // independent from protocol, host, www and query strings. $path='/'.ltrim(preg_replace('#/+#','/',$path),'/'); return $path; } private function current_content_should_exclude(){ if(null!==$this->should_exclude)return $this->should_exclude; $this->should_exclude=false; if(is_admin()||wp_doing_ajax()||wp_doing_cron()||is_feed())return false; $s=$this->get_settings(); if(empty($s['enabled'])||empty($s['rules']))return false; $device=wp_is_mobile()?'mobile':'desktop'; if(!in_array($device,$s['devices'],true))return false; $is_singular_view=is_singular(); $post=$is_singular_view?get_queried_object():null; $request_path=$this->current_request_url_path(); $content_haystack=''; $permalink=$request_path; $current_id=0; if($is_singular_view){ if(!($post instanceof WP_Post))return false; if(!in_array($post->post_type,$s['post_types'],true))return false; $content_haystack=html_entity_decode(implode("\n",array((string)$post->post_title,(string)$post->post_content)),ENT_QUOTES|ENT_HTML5,'UTF-8'); $permalink=html_entity_decode((string)get_permalink($post),ENT_QUOTES|ENT_HTML5,'UTF-8'); $current_id=(int)$post->ID; } foreach($s['rules'] as $r){ $condition=isset($r['condition'])?sanitize_key($r['condition']):'content_contains'; $value=isset($r['value'])?trim((string)$r['value']):''; if($value==='')continue; $matched=false; if('content_id'===$condition){ $matched=$is_singular_view && ((int)absint($value)===$current_id); }elseif('url_contains'===$condition){ // URL rules also apply to archives, taxonomy pages and paginated views. $matched=$this->contains_ci($is_singular_view?$permalink:$request_path,$value); }else{ $matched=$is_singular_view && $this->contains_ci($content_haystack,$value); } if($matched){$this->should_exclude=true;$this->matched_rule_value=$value;break;} } return $this->should_exclude; } private function applicable_inserter_blocks(){ $out=array(); if(!is_singular())return $out; $post=get_queried_object(); if(!($post instanceof WP_Post))return $out; $device=wp_is_mobile()?'mobile':'desktop'; $settings=$this->get_settings(); $excluded=$this->current_content_should_exclude(); // Exclusion Rules always take priority over AdPermit's built-in Inserter. if($excluded)return $out; foreach($this->get_blocks() as $idx=>$raw){ $b=wp_parse_args($raw,$this->block_defaults()); if(empty($b['enabled'])||trim((string)$b['code'])==='')continue; if(!in_array($post->post_type,$b['post_types'],true)||!in_array($device,$b['devices'],true))continue; $out[(string)$idx]=trim((string)$b['name'])!==''?(string)$b['name']:('#'.((int)$idx+1)); } return $out; } private function exclusion_is_partial(){ if(!$this->current_content_should_exclude())return false; return !$this->all_google_formats_blocked($this->get_settings()); } private function allowed_google_formats($s=null){ if(null===$s)$s=$this->get_settings(); $formats=array( 'block_incontent'=>'In-page / Banner', 'block_multiplex'=>'Multiplex', 'block_side_rail'=>'Side Rail', 'block_anchor'=>'Anchor', 'block_vignette'=>'Vignette', 'block_ad_intents'=>'Ad Intents', ); $allowed=array(); foreach($formats as $key=>$label)if(empty($s[$key]))$allowed[]=$this->t($label); return $allowed; } private function adsense_loader_will_load(){ if(is_admin()||wp_doing_ajax()||wp_doing_cron()||is_feed()||!is_singular())return false; $s=$this->get_settings(); $excluded=$this->current_content_should_exclude(); if($excluded && $this->all_google_formats_blocked($s))return false; $client=$this->current_request_adsense_client_id(); if(!$client && $excluded && !$this->all_google_formats_blocked($s))$client=$this->saved_adsense_client_id(); return (bool)$client; } public function admin_bar_status($wp_admin_bar){ if(is_admin()||!is_user_logged_in()||!current_user_can('manage_options')||!is_admin_bar_showing())return; // Show AdPermit status on all front-end views, including archives and paginated // listings such as /blog/page/11/. $excluded=$this->current_content_should_exclude(); $status_blocks=$this->applicable_inserter_blocks(); $count=count($status_blocks); $partial=$excluded?$this->exclusion_is_partial():false; if($excluded){ $allowed_formats=$partial?$this->allowed_google_formats():array(); if($partial){ $allowed_short=count($allowed_formats)<=2?implode(' + ',$allowed_formats):sprintf($this->t('%d formats allowed'),count($allowed_formats)); $label='AdPermit: '.$this->t('Partial exclusion').' Google Ads — '.$this->t('Active').': '.$allowed_short; $class='adpermitrules-status-partial'; }else{ $label='AdPermit: '.$this->t('Exclusion'); $class='adpermitrules-status-exclusion'; } }elseif($count){$label='AdPermit: Inserter ('.$count.')';$class='adpermitrules-status-inserter';} else{$label='AdPermit: '.$this->t('No action');$class='adpermitrules-status-idle';} $wp_admin_bar->add_node(array('id'=>'adpermit-rules-status','title'=>esc_html($label),'href'=>admin_url('admin.php?page=adpermit-rules'),'meta'=>array('class'=>'adpermit-rules-status '.$class,'title'=>'AdPermit Rules'))); if($excluded){ $rule=$this->matched_rule_value!==''?$this->matched_rule_value:'—'; $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-match','title'=>esc_html($this->t('Matched rule').': '.$rule),'href'=>admin_url('admin.php?page=adpermit-rules-exclusions'))); if($partial){ $allowed_formats=$this->allowed_google_formats(); $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-allowed','title'=>esc_html($this->t('Google Ads allowed').': '.implode(', ',$allowed_formats)),'href'=>admin_url('admin.php?page=adpermit-rules-exclusions'))); }else{ $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-all-google-blocked','title'=>esc_html($this->t('Google Ads').': '.$this->t('All formats blocked')),'href'=>admin_url('admin.php?page=adpermit-rules-exclusions'))); } } if($count){ foreach($status_blocks as $idx=>$name){$wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-block-'.sanitize_key($idx),'title'=>esc_html('Inserter: '.$name),'href'=>admin_url('admin.php?page=adpermit-rules-inserter')));} } elseif(is_singular()) { $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-no-blocks','title'=>esc_html($this->t('No Inserter block was added to this page.')),'href'=>admin_url('admin.php?page=adpermit-rules-inserter'))); } if(is_singular()){ $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-loader','title'=>esc_html($this->t('AdSense loader').': '.($this->adsense_loader_will_load()?$this->t('Loaded'):$this->t('Not loaded'))),'href'=>admin_url('admin.php?page=adpermit-rules-inserter'))); } // Only offer the quick exclusion action when no exclusion is already active. if(!$excluded){ if(is_singular() && get_queried_object_id()>0){ $exclude_url=add_query_arg(array('page'=>'adpermit-rules-exclusions','adpermitrules_add_id'=>get_queried_object_id()),admin_url('admin.php')); } else { $exclude_url=add_query_arg(array('page'=>'adpermit-rules-exclusions','adpermitrules_add_url'=>$this->current_request_url_path()),admin_url('admin.php')); } $exclude_url=add_query_arg('adpermitrules_nonce',wp_create_nonce('adpermitrules_quick_exclude'),$exclude_url); $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-exclude-page','title'=>esc_html($this->t('Exclude this page?')),'href'=>esc_url($exclude_url))); } $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-open-exclusions','title'=>esc_html($this->t('Open Exclusion Rules')),'href'=>admin_url('admin.php?page=adpermit-rules-exclusions'))); $wp_admin_bar->add_node(array('parent'=>'adpermit-rules-status','id'=>'adpermit-rules-open-inserter','title'=>esc_html($this->t('Open Ad Inserter')),'href'=>admin_url('admin.php?page=adpermit-rules-inserter'))); } private function contains_ci($h,$n){if($n==='')return false;return function_exists('mb_stripos')?false!==mb_stripos($h,$n,0,'UTF-8'):false!==stripos($h,$n);} private function level_enabled($key){$s=$this->get_settings();return !empty($s[$key]);} public function ad_inserter_block_check($enabled,$block,$server_side_check=true){if(!$this->level_enabled('level_managers')||!$this->level_enabled('block_ad_inserter')||!$this->current_content_should_exclude())return $enabled;return 0===(int)$block?(is_array($enabled)?array():false):false;} public function maybe_block_ad_manager_shortcode($return,$tag,$attr,$m){if($this->level_enabled('level_managers')&&$this->level_enabled('block_ad_inserter')&&$this->current_content_should_exclude()&&'adinserter'===strtolower((string)$tag))return '';return $return;} public function filter_ad_manager_content($content){if(!is_string($content)||$content===''||!$this->level_enabled('level_managers')||!$this->level_enabled('block_ad_inserter')||!$this->current_content_should_exclude())return $content;return $this->strip_ad_inserter_output($content);} private function strip_ad_inserter_output($html){$html=preg_replace('#]*\bclass\s*=\s*(["\'])[^"\']*\bcode-block(?:[-_][a-z0-9_-]+)?\b[^"\']*\1)[^>]*>.*?#is','',$html);$html=preg_replace('#]*\b(?:src|data-src)\s*=\s*(["\'])[^"\']*(?:action=ai_ajax|[?&]block=\d+)[^"\']*\1[^>]*>.*?#is','',$html);return $html;} public function filter_ad_script_tag($tag,$handle,$src){ if('adpermit-rules-adsense-loader'===$handle){ $tag=str_replace('