Plugin Directory

Changeset 3832004


Ignore:
Timestamp:
11/28/2026 06:47:01 PM (less than one hour ago)
Author:
razorfrog
Message:

Release 2.3.0: last 7 days panel, visitor sources (?from=instagram), editor notice, SMTP hint, Elementor/Divi/WPBakery support

Location:
link-in-bio-report
Files:
6 edited
1 copied

Legend:

Unmodified
Added
Removed
  • link-in-bio-report/tags/2.3.0/assets/admin.css

    r3831037 r3832004  
    241241.lbr-advanced > .form-table { margin-top: 0; }
    242242.lbr-advanced + h2.title { margin-top: 24px; padding-top: 18px; border-top: 1px solid #dcdcde; max-width: 960px; }
     243
     244/* 2.3: "Last 7 days" box and per-app bio addresses. */
     245
     246.lbr-recent h3 {
     247        font-size: 13px;
     248        margin: 16px 0 6px;
     249}
     250
     251.lbr-recent h3 span {
     252        font-weight: 400;
     253        color: #646970;
     254        margin-left: 6px;
     255}
     256
     257.lbr-recent-totals {
     258        font-size: 14px;
     259        margin: 0 0 10px;
     260}
     261
     262.lbr-recent-table {
     263        max-width: 560px;
     264}
     265
     266.lbr-recent-table .num {
     267        text-align: right;
     268        width: 70px;
     269        font-variant-numeric: tabular-nums;
     270}
     271
     272.lbr-recent-sources {
     273        margin: 6px 0 0;
     274        color: #50575e;
     275}
     276
     277.lbr-apps {
     278        margin: -4px 0 12px;
     279}
     280
     281.lbr-apps summary {
     282        cursor: pointer;
     283        color: #2271b1;
     284}
     285
     286.lbr-apps .lbr-app {
     287        display: flex;
     288        flex-wrap: wrap;
     289        align-items: center;
     290        gap: 6px;
     291        margin: 6px 0;
     292}
     293
     294.lbr-apps .lbr-app label {
     295        margin: 0;
     296        min-width: 80px;
     297        font-weight: 400;
     298}
     299
     300.lbr-apps .lbr-app input {
     301        flex: 1 1 14em;
     302        min-width: 0;
     303        max-width: 24em;
     304}
     305
     306.lbr-apps .lbr-app .button {
     307        margin-left: 0;
     308}
  • link-in-bio-report/tags/2.3.0/link-in-bio-report.php

    r3831063 r3832004  
    44 * Plugin URI:        https://razorfrog.com/link-in-bio-report/
    55 * Description:       Counts taps on your link-in-bio pages without cookies and emails you a weekly or monthly report, with a section for each page. Works with any theme or page builder.
    6  * Version:           2.2.2
     6 * Version:           2.3.0
    77 * Requires at least: 6.2
    88 * Requires PHP:      7.2
    … …  
    3434        const OPTION     = 'link_in_bio_report_settings';
    3535        const CRON_HOOK  = 'link_in_bio_report_send_report';
    36         const VERSION    = '2.2.2';
    37         const DB_VERSION = '2';
     36        const VERSION    = '2.3.0';
     37        const DB_VERSION = '3'; // 3 added the source column.
    3838
    3939        /** Rows older than this are deleted when a report runs. */
    … …  
    5252         */
    5353        const SETTINGS_VERSION = '6';
     54
     55        /**
     56         * Where a visit came from, for the source breakdown: hosts in a referrer, and the short names
     57         * people put in a bio address (/links/?from=ig), mapped to one key each.
     58         */
     59        const SOURCE_HOSTS = array(
     60                'instagram' => array( 'instagram.com', 'ig.me' ),
     61                'tiktok'    => array( 'tiktok.com' ),
     62                'facebook'  => array( 'facebook.com', 'fb.com', 'fb.me', 'messenger.com' ),
     63                'threads'   => array( 'threads.net', 'threads.com' ),
     64                'x'         => array( 'x.com', 'twitter.com', 't.co' ),
     65                'linkedin'  => array( 'linkedin.com', 'lnkd.in' ),
     66                'youtube'   => array( 'youtube.com', 'youtu.be' ),
     67                'pinterest' => array( 'pinterest.com', 'pin.it' ),
     68                'snapchat'  => array( 'snapchat.com' ),
     69                'google'    => array( 'google.com' ),
     70        );
     71
     72        /** Short names for the same sources. */
     73        const SOURCE_ALIASES = array(
     74                'ig'        => 'instagram',
     75                'insta'     => 'instagram',
     76                'tt'        => 'tiktok',
     77                'fb'        => 'facebook',
     78                'twitter'   => 'x',
     79                'yt'        => 'youtube',
     80                'li'        => 'linkedin',
     81                'pin'       => 'pinterest',
     82                'snap'      => 'snapchat',
     83        );
    5484
    5585        /** Auto-found links that left the page drop out of the report after this many days (unless clicked). */
    … …  
    80110        private $notice = null;
    81111
     112        /**
     113         * Why the last report email failed, from WordPress's wp_mail_failed hook ('' if it didn't say).
     114         *
     115         * @var string
     116         */
     117        private $mail_error = '';
     118
    82119        /** Hooks everything up. */
    83120        public function __construct() {
    … …  
    118155                add_action( 'admin_init', array( $this, 'privacy_policy_content' ) );
    119156                add_action( 'wp_after_insert_post', array( $this, 'scan_on_save' ), 10, 2 );
     157                add_action( 'enqueue_block_editor_assets', array( $this, 'editor_notice' ) );
     158                add_action( 'admin_notices', array( $this, 'classic_editor_notice' ) );
    120159
    121160                // Starter links page layout, offered when a new page is created in the block editor.
    … …  
    164203                if ( get_option( 'link_in_bio_report_db_version' ) !== self::DB_VERSION ) {
    165204                        $this->create_table();
    166                         update_option( 'link_in_bio_report_db_version', self::DB_VERSION );
     205                        // Only mark the upgrade done once the new column is there; otherwise try again next load.
     206                        if ( $this->has_source_column() ) {
     207                                update_option( 'link_in_bio_report_db_version', self::DB_VERSION );
     208                        }
    167209                }
    168210                if ( get_option( 'link_in_bio_report_settings_version' ) !== self::SETTINGS_VERSION ) {
    … …  
    256298        }
    257299
     300        /**
     301         * Whether the clicks table has the source column (added in 2.3).
     302         *
     303         * @return bool
     304         */
     305        private function has_source_column() {
     306                global $wpdb;
     307                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Checking the plugin's own table during an upgrade.
     308                $columns = $wpdb->get_col( $wpdb->prepare( 'DESCRIBE %i', $this->table ) );
     309                return in_array( 'source', (array) $columns, true );
     310        }
     311
    258312        /** Creates or updates the clicks table. */
    259313        private function create_table() {
    … …  
    265319                        slug VARCHAR(191) NOT NULL DEFAULT '',
    266320                        visitor CHAR(16) NOT NULL DEFAULT '',
     321                        source VARCHAR(20) NOT NULL DEFAULT '',
    267322                        created_at DATETIME NOT NULL,
    268323                        PRIMARY KEY (id),
    … …  
    331386                // and link scanners that fetch /go/ URLs directly send no Referer.
    332387                if ( ! $this->is_bot() && $this->is_from_site() && ! current_user_can( 'edit_posts' ) ) {
    333                         $this->log( 'click', $slug, MINUTE_IN_SECONDS );
     388                        $this->log( 'click', $slug, MINUTE_IN_SECONDS, $this->click_source() );
    334389                }
    335390
    … …  
    373428                        }
    374429                        // A refresh or back-button return within 30 min counts as one visit.
    375                         $this->log( 'view', $this->view_slug( $page_id ), 30 * MINUTE_IN_SECONDS );
     430                        $this->log( 'view', $this->view_slug( $page_id ), 30 * MINUTE_IN_SECONDS, $this->normalize_source( $this->string_param( $request, 'from' ), $this->string_param( $request, 'ref' ) ) );
    376431                }
    377432                return new WP_REST_Response( array( 'ok' => true ), 200 );
     433        }
     434
     435        /**
     436         * A request parameter as a string ('' when it's missing or not a string).
     437         *
     438         * @param WP_REST_Request $request Request.
     439         * @param string          $name    Parameter.
     440         * @return string
     441         */
     442        private function string_param( $request, $name ) {
     443                $value = $request->get_param( $name );
     444                return is_string( $value ) ? $value : '';
    378445        }
    379446
    … …  
    384451                        return; // Only real visitors to a published links page.
    385452                }
    386                 $url = add_query_arg( 'page', $page_id, rest_url( 'link-in-bio-report/v1/view' ) );
    387                 $js  = '(function(){var u=' . wp_json_encode( esc_url_raw( $url ) ) . ';'
     453                $url     = add_query_arg( 'page', $page_id, rest_url( 'link-in-bio-report/v1/view' ) );
     454                $go_path = (string) wp_parse_url( home_url( '/go/' ), PHP_URL_PATH );
     455                // Where the visit came from: the bio address's ?from= (or a utm_source the app added), else
     456                // the referring site. It goes with the visit, and onto the page's /go/ links so taps carry it too.
     457                $js = '(function(){var u=' . wp_json_encode( esc_url_raw( $url ) ) . ',q,f="",r="";'
     458                        . "try{q=new URLSearchParams(location.search);f=(q.get('from')||q.get('utm_source')||'').slice(0,40);}catch(e){}"
     459                        . "try{if(document.referrer){r=new URL(document.referrer).hostname;if(r===location.hostname){r='';}}}catch(e){}"
     460                        . "u+='&from='+encodeURIComponent(f)+'&ref='+encodeURIComponent(r);"
     461                        . "var s=f||r;try{if(s){document.querySelectorAll('a[href*=\"/go/\"]').forEach(function(a){try{var l=new URL(a.href);"
     462                        . 'if(l.hostname===location.hostname&&l.pathname.indexOf(' . wp_json_encode( $go_path ) . ')===0){l.searchParams.set("from",s);a.href=l.toString();}}catch(e){}});}}catch(e){}'
    388463                        . 'try{if(navigator.sendBeacon){navigator.sendBeacon(u);}'
    389464                        . "else{fetch(u,{method:'POST',keepalive:true,credentials:'same-origin'});}}catch(e){}})();";
    … …  
    409484         * @param string $slug   Link slug, or the page path for a view.
    410485         * @param int    $dedupe Seconds.
    411          */
    412         private function log( $type, $slug, $dedupe = 0 ) {
     486         * @param string $source Where the visit came from (see normalize_source()), or ''.
     487         */
     488        private function log( $type, $slug, $dedupe = 0, $source = '' ) {
    413489                global $wpdb;
    414490                $visitor = $this->visitor_id();
    … …  
    438514                                'slug'       => $slug,
    439515                                'visitor'    => $visitor,
     516                                'source'     => substr( (string) $source, 0, 20 ),
    440517                                'created_at' => current_time( 'mysql' ),
    441518                        ),
    442                         array( '%s', '%s', '%s', '%s' )
     519                        array( '%s', '%s', '%s', '%s', '%s' )
    443520                );
    444521        }
    … …  
    465542                $filtered = apply_filters( 'link_in_bio_report_client_ip', $ip );
    466543                return is_string( $filtered ) && filter_var( $filtered, FILTER_VALIDATE_IP ) ? $filtered : $ip;
     544        }
     545
     546        /**
     547         * Turns a bio address's ?from= value (or utm_source) and a referring host into one source key:
     548         * "instagram", "tiktok" and so on, "web" for any other site, or "" when there's no sign of one.
     549         *
     550         * @param string $from     The from= or utm_source value.
     551         * @param string $referrer The referring host (or URL).
     552         * @return string
     553         */
     554        public function normalize_source( $from, $referrer = '' ) {
     555                $from = strtolower( trim( sanitize_text_field( $from ) ) );
     556                if ( '' !== $from ) {
     557                        if ( false !== strpos( $from, '.' ) ) {
     558                                // A host: the beacon passes on the referring site this way, or someone put a domain in from=.
     559                                $host = false !== strpos( $from, '/' ) ? (string) wp_parse_url( $from, PHP_URL_HOST ) : $from;
     560                                if ( '' === $host || $this->same_host( 'https://' . $host . '/' ) ) {
     561                                        return '';
     562                                }
     563                                $known = $this->source_for_host( $host );
     564                                return '' !== $known ? $known : 'web';
     565                        } else {
     566                                $from = substr( sanitize_key( $from ), 0, 20 );
     567                                $from = isset( self::SOURCE_ALIASES[ $from ] ) ? self::SOURCE_ALIASES[ $from ] : $from;
     568                        }
     569                        if ( '' !== $from ) {
     570                                return $from;
     571                        }
     572                }
     573                $referrer = strtolower( trim( sanitize_text_field( $referrer ) ) );
     574                if ( '' === $referrer ) {
     575                        return '';
     576                }
     577                $host = false !== strpos( $referrer, '/' ) ? (string) wp_parse_url( $referrer, PHP_URL_HOST ) : $referrer;
     578                if ( '' === $host || $this->same_host( 'https://' . $host . '/' ) ) {
     579                        return '';
     580                }
     581                $known = $this->source_for_host( $host );
     582                return '' !== $known ? $known : 'web';
     583        }
     584
     585        /**
     586         * The source key for a host (l.instagram.com is "instagram"), or "" when it isn't a known one.
     587         *
     588         * @param string $host Host name.
     589         * @return string
     590         */
     591        private function source_for_host( $host ) {
     592                $host = preg_replace( '/^www\./', '', strtolower( (string) $host ) );
     593                foreach ( self::SOURCE_HOSTS as $key => $domains ) {
     594                        foreach ( $domains as $domain ) {
     595                                if ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) {
     596                                        return $key;
     597                                }
     598                        }
     599                }
     600                // Google search on country domains (google.de, google.co.uk).
     601                return preg_match( '/(^|\.)google\.[a-z.]+$/', $host ) ? 'google' : '';
     602        }
     603
     604        /**
     605         * Where a tap on a /go/ link came from: the from= the beacon added to the link, or else the
     606         * from= or utm_source on the links page address it was tapped on (the Referer).
     607         *
     608         * @return string
     609         */
     610        private function click_source() {
     611                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A public redirect link; the value is only matched to a known key.
     612                $from = isset( $_GET['from'] ) && is_string( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : '';
     613                if ( '' === $from ) {
     614                        $query = (string) wp_parse_url( (string) wp_get_raw_referer(), PHP_URL_QUERY );
     615                        parse_str( $query, $args );
     616                        foreach ( array( 'from', 'utm_source' ) as $key ) {
     617                                if ( ! empty( $args[ $key ] ) && is_string( $args[ $key ] ) ) {
     618                                        $from = $args[ $key ];
     619                                        break;
     620                                }
     621                        }
     622                }
     623                return $this->normalize_source( $from );
     624        }
     625
     626        /**
     627         * A source key's name for the report: "Instagram", "TikTok", "Other websites".
     628         *
     629         * @param string $key Source key.
     630         * @return string
     631         */
     632        private function source_label( $key ) {
     633                $names = array(
     634                        ''          => __( 'Direct or unknown', 'link-in-bio-report' ),
     635                        'web'       => __( 'Other websites', 'link-in-bio-report' ),
     636                        'instagram' => 'Instagram',
     637                        'tiktok'    => 'TikTok',
     638                        'facebook'  => 'Facebook',
     639                        'threads'   => 'Threads',
     640                        'x'         => 'X',
     641                        'linkedin'  => 'LinkedIn',
     642                        'youtube'   => 'YouTube',
     643                        'pinterest' => 'Pinterest',
     644                        'snapchat'  => 'Snapchat',
     645                        'google'    => 'Google',
     646                );
     647                return isset( $names[ $key ] ) ? $names[ $key ] : ucwords( str_replace( array( '-', '_' ), ' ', $key ) );
    467648        }
    468649
    … …  
    639820                $taken   = array(); // Slug => url, to keep two different links from sharing a slug.
    640821                $pattern = '#<h([23])\b[^>]*>(.*?)</h\1>|<a\b([^>]*)>(.*?)</a>#is';
     822                $saved   = get_option( self::AUTO_OPTION, array() );
     823                $saved   = is_array( $saved ) ? $saved : array();
    641824
    642825                return preg_replace_callback(
    643826                        $pattern,
    644                         function ( $m ) use ( &$section, &$taken, &$found, $prefix ) {
     827                        function ( $m ) use ( &$section, &$taken, &$found, $prefix, $saved ) {
    645828                                if ( '' !== $m[1] ) {
    646829                                        $section = $this->clean_text( $m[2] );
    … …  
    656839                                }
    657840
     841                                $host  = (string) wp_parse_url( $url, PHP_URL_HOST );
    658842                                $label = $this->clean_text( $m[4] );
    659                                 if ( '' === $label && preg_match( '#\baria-label\s*=\s*(["\'])(.*?)\1#is', $attrs, $am ) ) {
     843                                if ( '' === $label && preg_match( '#(?<![\w-])aria-label\s*=\s*(["\'])(.*?)\1#is', $attrs, $am ) ) {
    660844                                        $label = $this->clean_text( $am[2] );
    661845                                }
     846                                // Before 2.3, a link with no text or aria-label was named after its host. 2.3 tries its
     847                                // title and the image's alt text first, but a link already counted keeps its old slug.
     848                                $by_host = '' === $label;
     849                                foreach ( array( array( $attrs, 'title' ), array( $m[4], 'alt' ) ) as $try ) {
     850                                        if ( '' === $label && preg_match( '#(?<![\w-])' . $try[1] . '\s*=\s*(["\'])(.*?)\1#is', $try[0], $am ) ) {
     851                                                $label = $this->clean_text( $am[2] );
     852                                        }
     853                                }
    662854                                if ( '' === $label ) {
    663                                         $label = (string) wp_parse_url( $url, PHP_URL_HOST );
     855                                        $label = $host;
    664856                                }
    665857                                $full = '' !== $section ? $section . ' · ' . $label : $label;
    666858
    667859                                // Slug from the plain words only: sanitize_title() would keep the "·" as %c2%b7.
    668                                 $base = substr( sanitize_title( remove_accents( $section . ' ' . $label ) ), 0, 60 );
    669                                 $base = trim( $base, '-' );
     860                                $base = $this->slug_base( $section, $label, $prefix );
     861                                if ( $by_host && $label !== $host ) {
     862                                        $old = $this->slug_base( $section, $host, $prefix );
     863                                        if ( '' !== $old && isset( $saved[ $old ] ) && $saved[ $old ]['url'] === $url ) {
     864                                                $base = $old;
     865                                        }
     866                                }
    670867                                if ( '' === $base ) {
    671868                                        return $m[0];
    672                                 }
    673                                 if ( '' !== $prefix ) {
    674                                         $base = trim( substr( $prefix . '-' . $base, 0, 90 ), '-' );
    675869                                }
    676870                                $slug = $base;
    … …  
    690884                        $html
    691885                );
     886        }
     887
     888        /**
     889         * The /go/ slug for a link: its section and label in plain words, after the page's prefix.
     890         *
     891         * @param string $section Nearest heading.
     892         * @param string $label   Link label.
     893         * @param string $prefix  Slug prefix for the page.
     894         * @return string '' when there are no usable words.
     895         */
     896        private function slug_base( $section, $label, $prefix ) {
     897                $base = trim( substr( sanitize_title( remove_accents( $section . ' ' . $label ) ), 0, 60 ), '-' );
     898                if ( '' !== $base && '' !== $prefix ) {
     899                        $base = trim( substr( $prefix . '-' . $base, 0, 90 ), '-' );
     900                }
     901                return $base;
    692902        }
    693903
    … …  
    755965                }
    756966
     967                $this->load_builder_shortcodes();
    757968                global $post;
    758969                $previous = $post;
    … …  
    774985        }
    775986
     987        /**
     988         * Page builders that only register their shortcodes on the front end (WPBakery, Divi) are loaded
     989         * here, so a links page saved from the editor is scanned the same way it's shown to visitors.
     990         */
     991        private function load_builder_shortcodes() {
     992                try {
     993                        $this->load_builders();
     994                } catch ( Throwable $e ) {
     995                        return; // The page is still saved; its links are found on the first visit instead.
     996                }
     997                /**
     998                 * Fires before a links page is rendered to find its links, for loading other builders' shortcodes.
     999                 */
     1000                do_action( 'link_in_bio_report_before_scan' );
     1001        }
     1002
     1003        /** Loads WPBakery's and Divi's shortcodes when they aren't loaded yet. */
     1004        private function load_builders() {
     1005                if ( class_exists( 'WPBMap' ) && method_exists( 'WPBMap', 'addAllMappedShortcodes' ) && ! shortcode_exists( 'vc_row' ) ) {
     1006                        WPBMap::addAllMappedShortcodes();
     1007                }
     1008                if ( function_exists( 'et_builder_add_main_elements' ) && function_exists( 'et_builder_should_load_framework' ) && ! did_action( 'et_builder_ready' ) && et_builder_should_load_framework() ) {
     1009                        if ( function_exists( 'et_builder_init_global_settings' ) ) {
     1010                                et_builder_init_global_settings();
     1011                        }
     1012                        et_builder_add_main_elements();
     1013                }
     1014        }
     1015
    7761016        /** Suggested text for the site's privacy policy (Settings → Privacy → Policy Guide). */
    7771017        public function privacy_policy_content() {
    … …  
    7811021                $text = '<p class="privacy-policy-tutorial">' . esc_html__( 'Link in Bio Report counts visits to the links pages and taps on their links. It sets no cookies and sends nothing to outside services.', 'link-in-bio-report' ) . '</p>'
    7821022                        . '<p><strong class="privacy-policy-tutorial">' . esc_html__( 'Suggested text:', 'link-in-bio-report' ) . ' </strong>'
    783                         . esc_html__( 'When you visit our links page or tap a link on it, we record the page or link and the time, with an anonymous visitor code. The code is a one-way, salted hash of your IP address and browser details, so it can’t be turned back into either; your IP address itself is never stored. This lets us count how many different people visited without using cookies. These records stay on our website, are used only for our own visit and tap counts, and are deleted after two years.', 'link-in-bio-report' )
     1023                        . esc_html__( 'When you visit our links page or tap a link on it, we record the page or link, the time and, when known, the app or website you came from (such as Instagram), with an anonymous visitor code. The code is a one-way, salted hash of your IP address and browser details, so it can’t be turned back into either; your IP address itself is never stored. This lets us count how many different people visited without using cookies. These records stay on our website, are used only for our own visit and tap counts, and are deleted after two years.', 'link-in-bio-report' )
    7841024                        . '</p>';
    7851025                wp_add_privacy_policy_content( 'Link in Bio Report', wp_kses_post( $text ) );
     1026        }
     1027
     1028        /**
     1029         * How many buttons or links on a page still point at "#", as each editor saves them. Block
     1030         * buttons are counted by their HTML (href="#"), and social icons by their settings, since they
     1031         * save no HTML; WPBakery, Divi and Elementor keep links in their own formats.
     1032         *
     1033         * @param int $page_id Page ID.
     1034         * @return int
     1035         */
     1036        private function placeholder_count( $page_id ) {
     1037                $elementor = get_post_meta( $page_id, '_elementor_data', true );
     1038                if ( is_string( $elementor ) && '' !== $elementor && 'builder' === get_post_meta( $page_id, '_elementor_edit_mode', true ) ) {
     1039                        return (int) preg_match_all( '/"url":"#"/', $elementor ); // Elementor's own data; post_content is only a copy.
     1040                }
     1041                $content = (string) get_post_field( 'post_content', $page_id );
     1042                $count   = (int) preg_match_all( '/href="#"/', $content ); // Block buttons and plain HTML.
     1043                $count  += (int) preg_match_all( '/<!-- wp:(?:social-link|navigation-link)\b[^>]*"url":"#"/', $content ); // Blocks without saved HTML.
     1044                $count  += (int) preg_match_all( '/(?<![\w-])link="url:%23\|/', $content ); // WPBakery.
     1045                $count  += (int) preg_match_all( '/(?<![\w-])(?:button_url|url|link_option_url)="#"/', $content ); // Divi.
     1046                return $count;
    7861047        }
    7871048
    … …  
    10001261
    10011262        /**
    1002          * Builds and sends the report email. Also used by the "send test" button.
    1003          *
    1004          * @param bool $is_test When true, the subject starts with [TEST].
    1005          * @return bool wp_mail result.
    1006          */
    1007         public function send_report( $is_test = false ) {
     1263         * The numbers for a report period, one section per links page (plus "Other links" when
     1264         * links outside the pages were tapped). Used by the email and the settings screen.
     1265         *
     1266         * @param string $start Site-time 'Y-m-d H:i:s'.
     1267         * @param string $end   Site-time 'Y-m-d H:i:s' (not included).
     1268         * @return array sections, totals (visitors, clicks, pages).
     1269         */
     1270        private function report_data( $start, $end ) {
    10081271                global $wpdb;
    1009                 $this->purge_old_rows();
    1010 
    1011                 $settings   = $this->get_settings();
    1012                 $recipients = array_filter( array_map( 'trim', explode( ',', $this->recipient( $settings ) ) ) );
    1013                 if ( empty( $recipients ) ) {
    1014                         return false;
    1015                 }
    1016 
    10171272                // Rows logged before v1.4 have no visitor key and include prefetches and
    10181273                // crawler hits, so they're left out (visitor <> '').
    1019                 $window = $this->report_window();
     1274                $settings = $this->get_settings();
    10201275
    10211276                // Clicks per slug and the visitors behind them.
    … …  
    10231278                $click_rows = $wpdb->get_results(
    10241279                        $wpdb->prepare(
    1025                                 "SELECT slug, visitor FROM %i WHERE event_type = 'click' AND visitor <> '' AND created_at >= %s AND created_at < %s",
     1280                                "SELECT slug, visitor, source FROM %i WHERE event_type = 'click' AND visitor <> '' AND created_at >= %s AND created_at < %s",
    10261281                                $this->table,
    1027                                 $window['start'],
    1028                                 $window['end']
     1282                                $start,
     1283                                $end
    10291284                        ),
    10301285                        ARRAY_A
    … …  
    10341289                $view_rows = $wpdb->get_results(
    10351290                        $wpdb->prepare(
    1036                                 "SELECT slug, visitor FROM %i WHERE event_type = 'view' AND visitor <> '' AND created_at >= %s AND created_at < %s",
     1291                                "SELECT slug, visitor, source FROM %i WHERE event_type = 'view' AND visitor <> '' AND created_at >= %s AND created_at < %s",
    10371292                                $this->table,
    1038                                 $window['start'],
    1039                                 $window['end']
     1293                                $start,
     1294                                $end
    10401295                        ),
    10411296                        ARRAY_A
    … …  
    10681323                        'views'    => 0,
    10691324                        'visitors' => array(),
     1325                        'sources'  => array(), // Source => visitors (set), clicks.
    10701326                );
    10711327                $sections = array();
    … …  
    11001356                        $sections[ $p ]['counts'][ $r['slug'] ]      = ( isset( $sections[ $p ]['counts'][ $r['slug'] ] ) ? $sections[ $p ]['counts'][ $r['slug'] ] : 0 ) + 1;
    11011357                        $sections[ $p ]['clickers'][ $r['visitor'] ] = true;
     1358                        $src = (string) $r['source'];
     1359                        if ( ! isset( $sections[ $p ]['sources'][ $src ] ) ) {
     1360                                $sections[ $p ]['sources'][ $src ] = array(
     1361                                        'visitors' => array(),
     1362                                        'clicks'   => 0,
     1363                                );
     1364                        }
     1365                        ++$sections[ $p ]['sources'][ $src ]['clicks'];
    11021366                }
    11031367                $by_view_slug = array();
    … …  
    11161380                        $sections[ $key ]['visitors'][ $r['visitor'] ] = true;
    11171381                        $all_visitors[ $r['visitor'] ]                 = true;
     1382                        $src = (string) $r['source'];
     1383                        if ( ! isset( $sections[ $key ]['sources'][ $src ] ) ) {
     1384                                $sections[ $key ]['sources'][ $src ] = array(
     1385                                        'visitors' => array(),
     1386                                        'clicks'   => 0,
     1387                                );
     1388                        }
     1389                        $sections[ $key ]['sources'][ $src ]['visitors'][ $r['visitor'] ] = true;
    11181390                }
    11191391
    … …  
    11421414                                }
    11431415                        );
     1416                        // Sources, most visitors first. Only worth showing when at least one visit had a source.
     1417                        $sources = array();
     1418                        foreach ( $sec['sources'] as $src => $info ) {
     1419                                $sources[] = array(
     1420                                        'key'      => (string) $src,
     1421                                        'label'    => $this->source_label( (string) $src ),
     1422                                        'visitors' => count( $info['visitors'] ),
     1423                                        'clicks'   => $info['clicks'],
     1424                                );
     1425                        }
     1426                        usort(
     1427                                $sources,
     1428                                function ( $a, $b ) {
     1429                                        if ( '' === $a['key'] || '' === $b['key'] ) {
     1430                                                return '' === $a['key'] ? 1 : -1; // "Direct or unknown" last.
     1431                                        }
     1432                                        $diff = $b['visitors'] - $a['visitors'];
     1433                                        return 0 !== $diff ? $diff : $b['clicks'] - $a['clicks'];
     1434                                }
     1435                        );
     1436                        if ( ! array_filter( wp_list_pluck( $sources, 'key' ) ) ) {
     1437                                $sources = array();
     1438                        }
     1439                        // Anyone can make up a from= value, so past the first 6 named sources the rest share a row.
     1440                        $named = array();
     1441                        $more  = null;
     1442                        $tail  = array();
     1443                        foreach ( $sources as $src ) {
     1444                                if ( '' === $src['key'] ) {
     1445                                        $tail[] = $src;
     1446                                } elseif ( count( $named ) < 6 ) {
     1447                                        $named[] = $src;
     1448                                } else {
     1449                                        $more = $more ? $more : array(
     1450                                                'key'      => 'more',
     1451                                                'label'    => __( 'Other sources', 'link-in-bio-report' ),
     1452                                                'visitors' => 0,
     1453                                                'clicks'   => 0,
     1454                                        );
     1455                                        $more['visitors'] += $src['visitors'];
     1456                                        $more['clicks']   += $src['clicks'];
     1457                                }
     1458                        }
     1459                        $sources = array_merge( $named, $more ? array( $more ) : array(), $tail );
    11441460                        $out[] = array(
    11451461                                'title'    => $sec['title'],
    … …  
    11521468                                'rows'     => $rows,
    11531469                                'idle'     => $idle,
     1470                                'sources'  => $sources,
    11541471                        );
    11551472                }
     1473
     1474                return array(
     1475                        'sections' => $out,
     1476                        'totals'   => array(
     1477                                'visitors' => count( $all_visitors ),
     1478                                'clicks'   => count( $click_rows ),
     1479                                'pages'    => count( array_filter( wp_list_pluck( $out, 'is_page' ) ) ),
     1480                        ),
     1481                );
     1482        }
     1483
     1484        /**
     1485         * Builds and sends the report email. Also used by the "send test" button.
     1486         *
     1487         * @param bool $is_test When true, the subject starts with [TEST].
     1488         * @return bool wp_mail result.
     1489         */
     1490        public function send_report( $is_test = false ) {
     1491                $this->purge_old_rows();
     1492
     1493                $settings   = $this->get_settings();
     1494                $recipients = array_filter( array_map( 'trim', explode( ',', $this->recipient( $settings ) ) ) );
     1495                if ( empty( $recipients ) ) {
     1496                        return false;
     1497                }
     1498
     1499                $window = $this->report_window();
     1500                $data   = $this->report_data( $window['start'], $window['end'] );
     1501                $out    = $data['sections'];
     1502                $totals = $data['totals'];
    11561503
    11571504                // Decode entities so the subject line shows a plain apostrophe, not &#039;.
    … …  
    11671514                        $subject = '[' . __( 'TEST', 'link-in-bio-report' ) . '] ' . $subject;
    11681515                }
    1169 
    1170                 $totals = array(
    1171                         'visitors' => count( $all_visitors ),
    1172                         'clicks'   => count( $click_rows ),
    1173                         'pages'    => count( array_filter( wp_list_pluck( $out, 'is_page' ) ) ),
    1174                 );
    11751516
    11761517                $html     = $this->render_email( $site, $window, $out, $totals, $settings['footer_text'] );
    … …  
    11871528                        return $from_name;
    11881529                };
     1530                $catch = function ( $error ) {
     1531                        $this->mail_error = is_wp_error( $error ) ? $error->get_error_message() : '';
     1532                };
    11891533                add_filter( 'wp_mail_from_name', $set_from, 20 );
     1534                add_action( 'wp_mail_failed', $catch );
    11901535                $sent = wp_mail( $recipients, $subject, $html, $headers );
     1536                remove_action( 'wp_mail_failed', $catch );
    11911537                remove_filter( 'wp_mail_from_name', $set_from, 20 );
    11921538                return $sent;
    … …  
    13351681                                <?php endif; ?>
    13361682
     1683                                <?php if ( $sec['sources'] ) : ?>
     1684                                        <table style="width:100%;border-collapse:collapse;font-size:13px;margin:14px 0 0;">
     1685                                                <thead>
     1686                                                        <tr>
     1687                                                                <th style="text-align:left;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'Came from', 'link-in-bio-report' ); ?></th>
     1688                                                                <th style="text-align:right;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'People', 'link-in-bio-report' ); ?></th>
     1689                                                                <th style="text-align:right;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'Clicks', 'link-in-bio-report' ); ?></th>
     1690                                                        </tr>
     1691                                                </thead>
     1692                                                <tbody>
     1693                                                <?php foreach ( $sec['sources'] as $src ) : ?>
     1694                                                        <tr>
     1695                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;"><?php echo esc_html( $src['label'] ); ?></td>
     1696                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;text-align:right;font-variant-numeric:tabular-nums;"><?php echo esc_html( number_format_i18n( $src['visitors'] ) ); ?></td>
     1697                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;text-align:right;font-variant-numeric:tabular-nums;"><?php echo esc_html( number_format_i18n( $src['clicks'] ) ); ?></td>
     1698                                                        </tr>
     1699                                                <?php endforeach; ?>
     1700                                                </tbody>
     1701                                        </table>
     1702                                <?php endif; ?>
     1703
    13371704                                <?php if ( $block ) : ?>
    13381705                                                </td>
    … …  
    13901757                        . "if(navigator.clipboard){navigator.clipboard.writeText(f.value).then(done,legacy);}else{legacy();}});"
    13911758                );
     1759        }
     1760
     1761        /**
     1762         * The links page being edited on this screen, or 0.
     1763         *
     1764         * @return int
     1765         */
     1766        private function edited_links_page() {
     1767                $post = get_post();
     1768                return ( $post && 'page' === $post->post_type && in_array( (int) $post->ID, $this->page_ids(), true ) ) ? (int) $post->ID : 0;
     1769        }
     1770
     1771        /**
     1772         * The editor notice's text for a links page: that it's counted, and its bio address.
     1773         *
     1774         * @param int $page_id Page ID.
     1775         * @return string Plain text.
     1776         */
     1777        private function editor_notice_text( $page_id ) {
     1778                if ( 'publish' !== get_post_status( $page_id ) ) {
     1779                        return __( 'This is a links page for Link in Bio Report. Once it’s published, visits and taps on its buttons are counted. Point the buttons at their real addresses.', 'link-in-bio-report' );
     1780                }
     1781                return sprintf(
     1782                        /* translators: %s: the page's address. */
     1783                        __( 'This is a links page for Link in Bio Report: visits and taps on its buttons are counted. Its bio address is %s', 'link-in-bio-report' ),
     1784                        get_permalink( $page_id )
     1785                );
     1786        }
     1787
     1788        /**
     1789         * In the block editor, on a links page: a notice that the page is counted, with its bio
     1790         * address, and a warning while any button still links to "#".
     1791         */
     1792        public function editor_notice() {
     1793                $page_id = $this->edited_links_page();
     1794                if ( ! $page_id || ! current_user_can( 'edit_post', $page_id ) ) {
     1795                        return;
     1796                }
     1797                $data = array(
     1798                        'text'     => $this->editor_notice_text( $page_id ),
     1799                        'settings' => current_user_can( 'manage_options' ) ? admin_url( 'options-general.php?page=link-in-bio-report' ) : '',
     1800                        'label'    => __( 'Link in Bio Report settings', 'link-in-bio-report' ),
     1801                        /* translators: %d: number of buttons. */
     1802                        'one'      => __( '%d button or icon on this page still links to “#”. Give it a real address so its taps are counted.', 'link-in-bio-report' ),
     1803                        /* translators: %d: number of buttons. */
     1804                        'many'     => __( '%d buttons or icons on this page still link to “#”. Give them real addresses so their taps are counted.', 'link-in-bio-report' ),
     1805                );
     1806                wp_register_script( 'link-in-bio-report-editor', false, array( 'wp-data', 'wp-dom-ready', 'wp-notices', 'wp-editor' ), self::VERSION, true );
     1807                wp_enqueue_script( 'link-in-bio-report-editor' );
     1808                wp_add_inline_script(
     1809                        'link-in-bio-report-editor',
     1810                        '(function(d){var n=wp.data.dispatch("core/notices"),last=-1,timer=0;'
     1811                        . 'wp.domReady(function(){n.createNotice("info",d.text,{id:"lbr-links-page",isDismissible:true,'
     1812                        . 'actions:d.settings?[{label:d.label,url:d.settings}]:[]});'
     1813                        . 'var check=function(){var c=wp.data.select("core/editor").getEditedPostContent()||"",'
     1814                        . 'm=function(r){return(c.match(r)||[]).length;},k=m(/href="#"/g)+m(/<!-- wp:(?:social-link|navigation-link)\\b[^>]*"url":"#"/g)+m(/(^|[^\\w-])link="url:%23\\|/g)+m(/(^|[^\\w-])(?:button_url|url|link_option_url)="#"/g);if(k===last){return;}last=k;'
     1815                        . 'if(k){n.createNotice("warning",(k===1?d.one:d.many).replace("%d",k),{id:"lbr-placeholders",isDismissible:false});}'
     1816                        . 'else{n.removeNotice("lbr-placeholders");}};'
     1817                        . 'check();wp.data.subscribe(function(){clearTimeout(timer);timer=setTimeout(check,800);});});'
     1818                        . '})(' . wp_json_encode( $data ) . ');'
     1819                );
     1820        }
     1821
     1822        /**
     1823         * The same notice on the classic editor screen (and page builders that use it), read from the saved page.
     1824         */
     1825        public function classic_editor_notice() {
     1826                $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
     1827                if ( ! $screen || 'post' !== $screen->base || ( method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor() ) ) {
     1828                        return;
     1829                }
     1830                $page_id = $this->edited_links_page();
     1831                if ( ! $page_id || ! current_user_can( 'edit_post', $page_id ) ) {
     1832                        return;
     1833                }
     1834                echo '<div class="notice notice-info"><p>' . esc_html( $this->editor_notice_text( $page_id ) ) . '</p></div>';
     1835                $count = $this->placeholder_count( $page_id );
     1836                if ( $count ) {
     1837                        echo '<div class="notice notice-warning"><p>' . esc_html(
     1838                                sprintf(
     1839                                        /* translators: %d: number of buttons. */
     1840                                        _n( '%d button or icon on this page still links to “#”. Give it a real address so its taps are counted.', '%d buttons or icons on this page still link to “#”. Give them real addresses so their taps are counted.', $count, 'link-in-bio-report' ),
     1841                                        $count
     1842                                )
     1843                        ) . '</p></div>';
     1844                }
    13921845        }
    13931846
    … …  
    15251978                                : array(
    15261979                                        'type' => 'error',
    1527                                         'msg'  => __( 'Could not send. Check the recipient and your site’s email setup.', 'link-in-bio-report' ),
     1980                                        'msg'  => $this->send_failed_message(),
     1981                                        'html' => true,
    15281982                                );
    15291983                } else {
    … …  
    15331987                        );
    15341988                }
     1989        }
     1990
     1991        /**
     1992         * The error shown when the test report couldn't be sent: what WordPress said, and what usually fixes it.
     1993         *
     1994         * @return string HTML (links and code only).
     1995         */
     1996        private function send_failed_message() {
     1997                $msg = esc_html__( 'Could not send the test report.', 'link-in-bio-report' );
     1998                if ( '' !== $this->mail_error ) {
     1999                        /* translators: %s: the error from WordPress's mailer. */
     2000                        $msg .= ' ' . sprintf( esc_html__( 'WordPress said: %s', 'link-in-bio-report' ), '<code>' . esc_html( $this->mail_error ) . '</code>' );
     2001                }
     2002                if ( $this->has_smtp_plugin() ) {
     2003                        $msg .= ' ' . esc_html__( 'Check the settings of your email (SMTP) plugin, and the recipient address.', 'link-in-bio-report' );
     2004                } else {
     2005                        $msg .= ' ' . esc_html__( 'Many hosts don’t deliver email sent by WordPress itself. An SMTP plugin, which sends through a real mail service, usually fixes it.', 'link-in-bio-report' );
     2006                        if ( current_user_can( 'install_plugins' ) ) {
     2007                                $msg .= ' <a href="' . esc_url( admin_url( 'plugin-install.php?s=smtp&tab=search&type=term' ) ) . '">' . esc_html__( 'Find an SMTP plugin', 'link-in-bio-report' ) . '</a>';
     2008                        }
     2009                }
     2010                return $msg;
     2011        }
     2012
     2013        /**
     2014         * Whether a plugin that sends WordPress email through SMTP or a mail service is active.
     2015         *
     2016         * @return bool
     2017         */
     2018        private function has_smtp_plugin() {
     2019                // SMTP plugins either hook into PHPMailer, take over wp_mail() before it sends, or replace it.
     2020                $found = defined( 'WPMS_PLUGIN_VER' ) || defined( 'FLUENTMAIL' ) || defined( 'POST_SMTP_VER' )
     2021                        || has_action( 'phpmailer_init' ) || has_filter( 'pre_wp_mail' );
     2022                if ( ! $found && function_exists( 'wp_mail' ) ) {
     2023                        try {
     2024                                $file  = wp_normalize_path( (string) ( new ReflectionFunction( 'wp_mail' ) )->getFileName() );
     2025                                $found = '' !== $file && wp_normalize_path( ABSPATH . WPINC . '/pluggable.php' ) !== $file;
     2026                        } catch ( ReflectionException $e ) {
     2027                                $found = false;
     2028                        }
     2029                }
     2030                /**
     2031                 * Filters whether the site sends email through an SMTP plugin or mail service.
     2032                 *
     2033                 * @param bool $found Whether a known one is active.
     2034                 */
     2035                return (bool) apply_filters( 'link_in_bio_report_has_smtp_plugin', $found );
     2036        }
     2037
     2038        /**
     2039         * The "Last 7 days" box on the settings screen: visits, taps and the top links of each
     2040         * page, so it's clear the counting works before the first report arrives.
     2041         */
     2042        private function recent_panel() {
     2043                if ( ! $this->published_page_ids() ) {
     2044                        return;
     2045                }
     2046                $now  = new DateTimeImmutable( 'now', wp_timezone() );
     2047                $data = $this->report_data( $now->modify( '-7 days' )->format( 'Y-m-d H:i:s' ), $now->modify( '+1 minute' )->format( 'Y-m-d H:i:s' ) );
     2048                $secs = $data['sections'];
     2049                ?>
     2050                <div class="lbr-box lbr-recent">
     2051                        <h2><?php esc_html_e( 'Last 7 days', 'link-in-bio-report' ); ?></h2>
     2052                        <p class="lbr-recent-totals">
     2053                                <?php
     2054                                echo wp_kses(
     2055                                        sprintf(
     2056                                                /* translators: 1: people who visited, 2: link clicks. */
     2057                                                __( '%1$s visited, %2$s.', 'link-in-bio-report' ),
     2058                                                sprintf(
     2059                                                        /* translators: %s: number of people, in bold. */
     2060                                                        _n( '<strong>%s</strong> person', '<strong>%s</strong> people', $data['totals']['visitors'], 'link-in-bio-report' ),
     2061                                                        esc_html( number_format_i18n( $data['totals']['visitors'] ) )
     2062                                                ),
     2063                                                sprintf(
     2064                                                        /* translators: %s: number of clicks, in bold. */
     2065                                                        _n( '<strong>%s</strong> link click', '<strong>%s</strong> link clicks', $data['totals']['clicks'], 'link-in-bio-report' ),
     2066                                                        esc_html( number_format_i18n( $data['totals']['clicks'] ) )
     2067                                                )
     2068                                        ),
     2069                                        array( 'strong' => array() )
     2070                                );
     2071                                ?>
     2072                        </p>
     2073                        <?php foreach ( $secs as $sec ) : ?>
     2074                                <?php if ( count( $secs ) > 1 ) : ?>
     2075                                        <h3><?php echo esc_html( $sec['title'] ); ?>
     2076                                                <?php if ( $sec['is_page'] ) : ?>
     2077                                                        <span><?php echo esc_html( sprintf( /* translators: 1: people, 2: clicks. */ __( '%1$s people · %2$s clicks', 'link-in-bio-report' ), number_format_i18n( $sec['visitors'] ), number_format_i18n( $sec['clicks'] ) ) ); ?></span>
     2078                                                <?php endif; ?>
     2079                                        </h3>
     2080                                <?php endif; ?>
     2081                                <?php if ( $sec['rows'] ) : ?>
     2082                                        <table class="widefat striped lbr-recent-table">
     2083                                                <thead><tr><th><?php esc_html_e( 'Top links', 'link-in-bio-report' ); ?></th><th class="num"><?php esc_html_e( 'Clicks', 'link-in-bio-report' ); ?></th></tr></thead>
     2084                                                <tbody>
     2085                                                <?php foreach ( array_slice( $sec['rows'], 0, 5 ) as $row ) : ?>
     2086                                                        <tr><td><?php echo esc_html( $row['label'] ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( $row['clicks'] ) ); ?></td></tr>
     2087                                                <?php endforeach; ?>
     2088                                                </tbody>
     2089                                        </table>
     2090                                <?php else : ?>
     2091                                        <p class="description"><?php esc_html_e( 'No link clicks yet.', 'link-in-bio-report' ); ?></p>
     2092                                <?php endif; ?>
     2093                                <?php if ( $sec['sources'] ) : ?>
     2094                                        <p class="lbr-recent-sources">
     2095                                                <?php
     2096                                                $parts = array();
     2097                                                foreach ( $sec['sources'] as $src ) {
     2098                                                        $parts[] = $src['label'] . ' ' . number_format_i18n( $src['visitors'] );
     2099                                                }
     2100                                                /* translators: %s: sources and their visitor counts, like "Instagram 12 · TikTok 4". */
     2101                                                echo esc_html( sprintf( __( 'Came from: %s', 'link-in-bio-report' ), implode( ' · ', $parts ) ) );
     2102                                                ?>
     2103                                        </p>
     2104                                <?php endif; ?>
     2105                        <?php endforeach; ?>
     2106                        <p class="description"><?php esc_html_e( 'Your own visits and taps while logged in aren’t counted. To check that counting works, open the page in a private window.', 'link-in-bio-report' ); ?></p>
     2107                </div>
     2108                <?php
    15352109        }
    15362110
    … …  
    15712145                        </div>
    15722146                        <?php if ( $this->notice ) : ?>
    1573                                 <div class="notice notice-<?php echo 'error' === $this->notice['type'] ? 'error' : 'success'; ?> is-dismissible"><p><?php echo esc_html( $this->notice['msg'] ); ?></p></div>
     2147                                <div class="notice notice-<?php echo 'error' === $this->notice['type'] ? 'error' : 'success'; ?> is-dismissible"><p><?php echo empty( $this->notice['html'] ) ? esc_html( $this->notice['msg'] ) : wp_kses( $this->notice['msg'], array( 'a' => array( 'href' => array() ), 'code' => array() ) ); ?></p></div>
    15742148                        <?php endif; ?>
    15752149
    … …  
    15792153                        <div class="lbr-main">
    15802154                        <?php $this->getting_started( $s, $next_str ); ?>
     2155                        <?php $this->recent_panel(); ?>
    15812156                        <form method="post">
    15822157                                <?php wp_nonce_field( 'link_in_bio_report_save' ); ?>
    … …  
    17842359                                );
    17852360                        }
    1786                         $placeholders = preg_match_all( '/href="#"|"url":"#"/', $post->post_content );
     2361                        $placeholders = $this->placeholder_count( $id );
    17872362                        if ( $placeholders ) {
    17882363                                $problems[] = sprintf(
    … …  
    18362411                                                <a href="<?php echo esc_url( get_permalink( $id ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'View', 'link-in-bio-report' ); ?></a>
    18372412                                        </p>
     2413                                        <details class="lbr-apps">
     2414                                                <summary><?php esc_html_e( 'In more than one app’s bio?', 'link-in-bio-report' ); ?></summary>
     2415                                                <p class="description"><?php esc_html_e( 'Give each app its own address, and the report shows how many people came from each. Visits from other sites are sorted by where they came from on their own.', 'link-in-bio-report' ); ?></p>
     2416                                                <?php foreach ( array( 'instagram', 'tiktok', 'facebook' ) as $app ) : ?>
     2417                                                        <?php $app_field = $field . '-' . $app; ?>
     2418                                                        <p class="lbr-bio lbr-app">
     2419                                                                <label for="<?php echo esc_attr( $app_field ); ?>"><?php echo esc_html( $this->source_label( $app ) ); ?></label>
     2420                                                                <input type="text" readonly class="regular-text code" id="<?php echo esc_attr( $app_field ); ?>" value="<?php echo esc_attr( add_query_arg( 'from', $app, get_permalink( $id ) ) ); ?>" />
     2421                                                                <button type="button" class="button lbr-copy" data-target="<?php echo esc_attr( $app_field ); ?>" data-done="<?php esc_attr_e( 'Copied', 'link-in-bio-report' ); ?>"><?php esc_html_e( 'Copy', 'link-in-bio-report' ); ?></button>
     2422                                                        </p>
     2423                                                <?php endforeach; ?>
     2424                                                <p class="description">
     2425                                                        <?php
     2426                                                        printf(
     2427                                                                /* translators: %s: example address ending. */
     2428                                                                esc_html__( 'For any other app, add %s with its name.', 'link-in-bio-report' ),
     2429                                                                '<code>?from=</code>'
     2430                                                        );
     2431                                                        ?>
     2432                                                </p>
     2433                                        </details>
    18382434                                <?php endforeach; ?>
    18392435                        <?php endif; ?>
  • link-in-bio-report/tags/2.3.0/readme.txt

    r3831063 r3832004  
    55Tested up to: 7.1
    66Requires PHP: 7.2
    7 Stable tag: 2.2.2
     7Stable tag: 2.3.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    1616
    1717* **Works with the page you already have.** Build the links page with the block editor, any theme or any page builder. Every outbound link on it is tracked automatically, including buttons you add later.
     18* **Instagram, TikTok or somewhere else.** Give each app its own bio address (`/links/?from=tiktok`) and the report shows how many people came from each. Visits from other sites are sorted by where they came from on their own.
     19* **Numbers right in WordPress.** The settings screen shows the last 7 days (visits, taps and the top links), so you can see it working before the first email arrives.
    1820* **Several links pages, one report.** One page per Instagram account or per location, say. The email has a colored section for each page plus a total.
    1921* **Weekly or monthly.** Pick the day and time, or have it sent on the 1st for the month before.
    … …  
    29312. When a links page is shown, each `http(s)` link on it is pointed at `/go/{slug}` on your site. The page itself keeps its real URLs, so you edit it as usual.
    30323. A tap on `/go/{slug}` is counted, then the visitor is sent on to the real destination.
    31 4. The report lists, for each page, how many people visited, how many visits and taps there were, the share of visitors who tapped a link, and every link by taps.
     334. The report lists, for each page, how many people visited, how many visits and taps there were, the share of visitors who tapped a link, every link by taps, and where visitors came from.
    3234
    3335The slug and the label in the report come from the nearest heading plus the button text, so "Order online" under two different locations is counted separately.
    … …  
    8284Yes. **Show the links pages on their own** (on by default) shows only the page content, with your theme's fonts and colors but without its header, footer and page title. Turn it off to show the page like any other. Developers can decide per page with the `link_in_bio_report_own_page` filter.
    8385
     86= How do I tell Instagram and TikTok visitors apart? =
     87
     88Put a different address in each bio: `example.com/links/?from=instagram` in Instagram and `example.com/links/?from=tiktok` in TikTok. The settings screen has these ready to copy under **In more than one app's bio?**. Any name works after `from=`. Visits that come from another website are counted under that site (Google, Facebook, "Other websites") without any setup, and the rest are "Direct or unknown".
     89
     90= Does it work with Elementor, Divi and WPBakery? =
     91
     92Yes. Buttons, icons and image links made with Elementor, Divi or WPBakery are counted like any other link, and "Show the links pages on their own" keeps the builder's styles.
     93
    8494= What are the /go/ addresses in the Tracked links table? =
    8595
    … …  
    92102== Privacy ==
    93103
    94 The plugin sets no cookies and uses no outside services. For each visit or tap it stores the time, the page or link, and a 16-character visitor key: a salted one-way hash of the IP address and user agent that can't be turned back into either. IP addresses are never stored. A short-lived counter keyed by a hash of the IP address limits visits counted from one address to 30 an hour.
     104The plugin sets no cookies and uses no outside services. For each visit or tap it stores the time, the page or link, where the visit came from when that's known (such as "instagram", from the bio address or the referring site's name; never the full referring address), and a 16-character visitor key: a salted one-way hash of the IP address and user agent that can't be turned back into either. IP addresses are never stored. A short-lived counter keyed by a hash of the IP address limits visits counted from one address to 30 an hour.
    95105
    96106The plugin adds suggested text to **Settings → Privacy → Policy Guide** for your privacy policy.
    … …  
    103113
    104114== Changelog ==
     115
     116= 2.3.0 =
     117* A "Last 7 days" box on the settings screen: visits, taps and the top links on each page.
     118* Where visitors came from: give each app its own bio address (`/links/?from=instagram`, `?from=tiktok`) and the report shows people and clicks for each. Visits from other sites are sorted by the referring site (Google, Facebook and others) on their own.
     119* In the editor, a links page says it's being counted and shows its bio address, and warns while a button or icon still links to "#". Works in the block editor and the classic editor, and spots "#" links in Elementor, Divi and WPBakery pages.
     120* Saving a WPBakery or Divi links page now fills in Tracked links right away (before, it waited for the first visit).
     121* Icon and image links with no text are named from their title or image description instead of the site they link to. Links already being counted keep their /go/ address, so their numbers carry on.
     122* When the test report can't be sent, the message shows WordPress's reason and suggests an SMTP plugin.
     123* Fixed: a block button linking to "#" was counted twice in the "Getting started" warning.
    105124
    106125= 2.2.2 =
  • link-in-bio-report/trunk/assets/admin.css

    r3831037 r3832004  
    241241.lbr-advanced > .form-table { margin-top: 0; }
    242242.lbr-advanced + h2.title { margin-top: 24px; padding-top: 18px; border-top: 1px solid #dcdcde; max-width: 960px; }
     243
     244/* 2.3: "Last 7 days" box and per-app bio addresses. */
     245
     246.lbr-recent h3 {
     247        font-size: 13px;
     248        margin: 16px 0 6px;
     249}
     250
     251.lbr-recent h3 span {
     252        font-weight: 400;
     253        color: #646970;
     254        margin-left: 6px;
     255}
     256
     257.lbr-recent-totals {
     258        font-size: 14px;
     259        margin: 0 0 10px;
     260}
     261
     262.lbr-recent-table {
     263        max-width: 560px;
     264}
     265
     266.lbr-recent-table .num {
     267        text-align: right;
     268        width: 70px;
     269        font-variant-numeric: tabular-nums;
     270}
     271
     272.lbr-recent-sources {
     273        margin: 6px 0 0;
     274        color: #50575e;
     275}
     276
     277.lbr-apps {
     278        margin: -4px 0 12px;
     279}
     280
     281.lbr-apps summary {
     282        cursor: pointer;
     283        color: #2271b1;
     284}
     285
     286.lbr-apps .lbr-app {
     287        display: flex;
     288        flex-wrap: wrap;
     289        align-items: center;
     290        gap: 6px;
     291        margin: 6px 0;
     292}
     293
     294.lbr-apps .lbr-app label {
     295        margin: 0;
     296        min-width: 80px;
     297        font-weight: 400;
     298}
     299
     300.lbr-apps .lbr-app input {
     301        flex: 1 1 14em;
     302        min-width: 0;
     303        max-width: 24em;
     304}
     305
     306.lbr-apps .lbr-app .button {
     307        margin-left: 0;
     308}
  • link-in-bio-report/trunk/link-in-bio-report.php

    r3831063 r3832004  
    44 * Plugin URI:        https://razorfrog.com/link-in-bio-report/
    55 * Description:       Counts taps on your link-in-bio pages without cookies and emails you a weekly or monthly report, with a section for each page. Works with any theme or page builder.
    6  * Version:           2.2.2
     6 * Version:           2.3.0
    77 * Requires at least: 6.2
    88 * Requires PHP:      7.2
    … …  
    3434        const OPTION     = 'link_in_bio_report_settings';
    3535        const CRON_HOOK  = 'link_in_bio_report_send_report';
    36         const VERSION    = '2.2.2';
    37         const DB_VERSION = '2';
     36        const VERSION    = '2.3.0';
     37        const DB_VERSION = '3'; // 3 added the source column.
    3838
    3939        /** Rows older than this are deleted when a report runs. */
    … …  
    5252         */
    5353        const SETTINGS_VERSION = '6';
     54
     55        /**
     56         * Where a visit came from, for the source breakdown: hosts in a referrer, and the short names
     57         * people put in a bio address (/links/?from=ig), mapped to one key each.
     58         */
     59        const SOURCE_HOSTS = array(
     60                'instagram' => array( 'instagram.com', 'ig.me' ),
     61                'tiktok'    => array( 'tiktok.com' ),
     62                'facebook'  => array( 'facebook.com', 'fb.com', 'fb.me', 'messenger.com' ),
     63                'threads'   => array( 'threads.net', 'threads.com' ),
     64                'x'         => array( 'x.com', 'twitter.com', 't.co' ),
     65                'linkedin'  => array( 'linkedin.com', 'lnkd.in' ),
     66                'youtube'   => array( 'youtube.com', 'youtu.be' ),
     67                'pinterest' => array( 'pinterest.com', 'pin.it' ),
     68                'snapchat'  => array( 'snapchat.com' ),
     69                'google'    => array( 'google.com' ),
     70        );
     71
     72        /** Short names for the same sources. */
     73        const SOURCE_ALIASES = array(
     74                'ig'        => 'instagram',
     75                'insta'     => 'instagram',
     76                'tt'        => 'tiktok',
     77                'fb'        => 'facebook',
     78                'twitter'   => 'x',
     79                'yt'        => 'youtube',
     80                'li'        => 'linkedin',
     81                'pin'       => 'pinterest',
     82                'snap'      => 'snapchat',
     83        );
    5484
    5585        /** Auto-found links that left the page drop out of the report after this many days (unless clicked). */
    … …  
    80110        private $notice = null;
    81111
     112        /**
     113         * Why the last report email failed, from WordPress's wp_mail_failed hook ('' if it didn't say).
     114         *
     115         * @var string
     116         */
     117        private $mail_error = '';
     118
    82119        /** Hooks everything up. */
    83120        public function __construct() {
    … …  
    118155                add_action( 'admin_init', array( $this, 'privacy_policy_content' ) );
    119156                add_action( 'wp_after_insert_post', array( $this, 'scan_on_save' ), 10, 2 );
     157                add_action( 'enqueue_block_editor_assets', array( $this, 'editor_notice' ) );
     158                add_action( 'admin_notices', array( $this, 'classic_editor_notice' ) );
    120159
    121160                // Starter links page layout, offered when a new page is created in the block editor.
    … …  
    164203                if ( get_option( 'link_in_bio_report_db_version' ) !== self::DB_VERSION ) {
    165204                        $this->create_table();
    166                         update_option( 'link_in_bio_report_db_version', self::DB_VERSION );
     205                        // Only mark the upgrade done once the new column is there; otherwise try again next load.
     206                        if ( $this->has_source_column() ) {
     207                                update_option( 'link_in_bio_report_db_version', self::DB_VERSION );
     208                        }
    167209                }
    168210                if ( get_option( 'link_in_bio_report_settings_version' ) !== self::SETTINGS_VERSION ) {
    … …  
    256298        }
    257299
     300        /**
     301         * Whether the clicks table has the source column (added in 2.3).
     302         *
     303         * @return bool
     304         */
     305        private function has_source_column() {
     306                global $wpdb;
     307                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Checking the plugin's own table during an upgrade.
     308                $columns = $wpdb->get_col( $wpdb->prepare( 'DESCRIBE %i', $this->table ) );
     309                return in_array( 'source', (array) $columns, true );
     310        }
     311
    258312        /** Creates or updates the clicks table. */
    259313        private function create_table() {
    … …  
    265319                        slug VARCHAR(191) NOT NULL DEFAULT '',
    266320                        visitor CHAR(16) NOT NULL DEFAULT '',
     321                        source VARCHAR(20) NOT NULL DEFAULT '',
    267322                        created_at DATETIME NOT NULL,
    268323                        PRIMARY KEY (id),
    … …  
    331386                // and link scanners that fetch /go/ URLs directly send no Referer.
    332387                if ( ! $this->is_bot() && $this->is_from_site() && ! current_user_can( 'edit_posts' ) ) {
    333                         $this->log( 'click', $slug, MINUTE_IN_SECONDS );
     388                        $this->log( 'click', $slug, MINUTE_IN_SECONDS, $this->click_source() );
    334389                }
    335390
    … …  
    373428                        }
    374429                        // A refresh or back-button return within 30 min counts as one visit.
    375                         $this->log( 'view', $this->view_slug( $page_id ), 30 * MINUTE_IN_SECONDS );
     430                        $this->log( 'view', $this->view_slug( $page_id ), 30 * MINUTE_IN_SECONDS, $this->normalize_source( $this->string_param( $request, 'from' ), $this->string_param( $request, 'ref' ) ) );
    376431                }
    377432                return new WP_REST_Response( array( 'ok' => true ), 200 );
     433        }
     434
     435        /**
     436         * A request parameter as a string ('' when it's missing or not a string).
     437         *
     438         * @param WP_REST_Request $request Request.
     439         * @param string          $name    Parameter.
     440         * @return string
     441         */
     442        private function string_param( $request, $name ) {
     443                $value = $request->get_param( $name );
     444                return is_string( $value ) ? $value : '';
    378445        }
    379446
    … …  
    384451                        return; // Only real visitors to a published links page.
    385452                }
    386                 $url = add_query_arg( 'page', $page_id, rest_url( 'link-in-bio-report/v1/view' ) );
    387                 $js  = '(function(){var u=' . wp_json_encode( esc_url_raw( $url ) ) . ';'
     453                $url     = add_query_arg( 'page', $page_id, rest_url( 'link-in-bio-report/v1/view' ) );
     454                $go_path = (string) wp_parse_url( home_url( '/go/' ), PHP_URL_PATH );
     455                // Where the visit came from: the bio address's ?from= (or a utm_source the app added), else
     456                // the referring site. It goes with the visit, and onto the page's /go/ links so taps carry it too.
     457                $js = '(function(){var u=' . wp_json_encode( esc_url_raw( $url ) ) . ',q,f="",r="";'
     458                        . "try{q=new URLSearchParams(location.search);f=(q.get('from')||q.get('utm_source')||'').slice(0,40);}catch(e){}"
     459                        . "try{if(document.referrer){r=new URL(document.referrer).hostname;if(r===location.hostname){r='';}}}catch(e){}"
     460                        . "u+='&from='+encodeURIComponent(f)+'&ref='+encodeURIComponent(r);"
     461                        . "var s=f||r;try{if(s){document.querySelectorAll('a[href*=\"/go/\"]').forEach(function(a){try{var l=new URL(a.href);"
     462                        . 'if(l.hostname===location.hostname&&l.pathname.indexOf(' . wp_json_encode( $go_path ) . ')===0){l.searchParams.set("from",s);a.href=l.toString();}}catch(e){}});}}catch(e){}'
    388463                        . 'try{if(navigator.sendBeacon){navigator.sendBeacon(u);}'
    389464                        . "else{fetch(u,{method:'POST',keepalive:true,credentials:'same-origin'});}}catch(e){}})();";
    … …  
    409484         * @param string $slug   Link slug, or the page path for a view.
    410485         * @param int    $dedupe Seconds.
    411          */
    412         private function log( $type, $slug, $dedupe = 0 ) {
     486         * @param string $source Where the visit came from (see normalize_source()), or ''.
     487         */
     488        private function log( $type, $slug, $dedupe = 0, $source = '' ) {
    413489                global $wpdb;
    414490                $visitor = $this->visitor_id();
    … …  
    438514                                'slug'       => $slug,
    439515                                'visitor'    => $visitor,
     516                                'source'     => substr( (string) $source, 0, 20 ),
    440517                                'created_at' => current_time( 'mysql' ),
    441518                        ),
    442                         array( '%s', '%s', '%s', '%s' )
     519                        array( '%s', '%s', '%s', '%s', '%s' )
    443520                );
    444521        }
    … …  
    465542                $filtered = apply_filters( 'link_in_bio_report_client_ip', $ip );
    466543                return is_string( $filtered ) && filter_var( $filtered, FILTER_VALIDATE_IP ) ? $filtered : $ip;
     544        }
     545
     546        /**
     547         * Turns a bio address's ?from= value (or utm_source) and a referring host into one source key:
     548         * "instagram", "tiktok" and so on, "web" for any other site, or "" when there's no sign of one.
     549         *
     550         * @param string $from     The from= or utm_source value.
     551         * @param string $referrer The referring host (or URL).
     552         * @return string
     553         */
     554        public function normalize_source( $from, $referrer = '' ) {
     555                $from = strtolower( trim( sanitize_text_field( $from ) ) );
     556                if ( '' !== $from ) {
     557                        if ( false !== strpos( $from, '.' ) ) {
     558                                // A host: the beacon passes on the referring site this way, or someone put a domain in from=.
     559                                $host = false !== strpos( $from, '/' ) ? (string) wp_parse_url( $from, PHP_URL_HOST ) : $from;
     560                                if ( '' === $host || $this->same_host( 'https://' . $host . '/' ) ) {
     561                                        return '';
     562                                }
     563                                $known = $this->source_for_host( $host );
     564                                return '' !== $known ? $known : 'web';
     565                        } else {
     566                                $from = substr( sanitize_key( $from ), 0, 20 );
     567                                $from = isset( self::SOURCE_ALIASES[ $from ] ) ? self::SOURCE_ALIASES[ $from ] : $from;
     568                        }
     569                        if ( '' !== $from ) {
     570                                return $from;
     571                        }
     572                }
     573                $referrer = strtolower( trim( sanitize_text_field( $referrer ) ) );
     574                if ( '' === $referrer ) {
     575                        return '';
     576                }
     577                $host = false !== strpos( $referrer, '/' ) ? (string) wp_parse_url( $referrer, PHP_URL_HOST ) : $referrer;
     578                if ( '' === $host || $this->same_host( 'https://' . $host . '/' ) ) {
     579                        return '';
     580                }
     581                $known = $this->source_for_host( $host );
     582                return '' !== $known ? $known : 'web';
     583        }
     584
     585        /**
     586         * The source key for a host (l.instagram.com is "instagram"), or "" when it isn't a known one.
     587         *
     588         * @param string $host Host name.
     589         * @return string
     590         */
     591        private function source_for_host( $host ) {
     592                $host = preg_replace( '/^www\./', '', strtolower( (string) $host ) );
     593                foreach ( self::SOURCE_HOSTS as $key => $domains ) {
     594                        foreach ( $domains as $domain ) {
     595                                if ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) {
     596                                        return $key;
     597                                }
     598                        }
     599                }
     600                // Google search on country domains (google.de, google.co.uk).
     601                return preg_match( '/(^|\.)google\.[a-z.]+$/', $host ) ? 'google' : '';
     602        }
     603
     604        /**
     605         * Where a tap on a /go/ link came from: the from= the beacon added to the link, or else the
     606         * from= or utm_source on the links page address it was tapped on (the Referer).
     607         *
     608         * @return string
     609         */
     610        private function click_source() {
     611                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A public redirect link; the value is only matched to a known key.
     612                $from = isset( $_GET['from'] ) && is_string( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : '';
     613                if ( '' === $from ) {
     614                        $query = (string) wp_parse_url( (string) wp_get_raw_referer(), PHP_URL_QUERY );
     615                        parse_str( $query, $args );
     616                        foreach ( array( 'from', 'utm_source' ) as $key ) {
     617                                if ( ! empty( $args[ $key ] ) && is_string( $args[ $key ] ) ) {
     618                                        $from = $args[ $key ];
     619                                        break;
     620                                }
     621                        }
     622                }
     623                return $this->normalize_source( $from );
     624        }
     625
     626        /**
     627         * A source key's name for the report: "Instagram", "TikTok", "Other websites".
     628         *
     629         * @param string $key Source key.
     630         * @return string
     631         */
     632        private function source_label( $key ) {
     633                $names = array(
     634                        ''          => __( 'Direct or unknown', 'link-in-bio-report' ),
     635                        'web'       => __( 'Other websites', 'link-in-bio-report' ),
     636                        'instagram' => 'Instagram',
     637                        'tiktok'    => 'TikTok',
     638                        'facebook'  => 'Facebook',
     639                        'threads'   => 'Threads',
     640                        'x'         => 'X',
     641                        'linkedin'  => 'LinkedIn',
     642                        'youtube'   => 'YouTube',
     643                        'pinterest' => 'Pinterest',
     644                        'snapchat'  => 'Snapchat',
     645                        'google'    => 'Google',
     646                );
     647                return isset( $names[ $key ] ) ? $names[ $key ] : ucwords( str_replace( array( '-', '_' ), ' ', $key ) );
    467648        }
    468649
    … …  
    639820                $taken   = array(); // Slug => url, to keep two different links from sharing a slug.
    640821                $pattern = '#<h([23])\b[^>]*>(.*?)</h\1>|<a\b([^>]*)>(.*?)</a>#is';
     822                $saved   = get_option( self::AUTO_OPTION, array() );
     823                $saved   = is_array( $saved ) ? $saved : array();
    641824
    642825                return preg_replace_callback(
    643826                        $pattern,
    644                         function ( $m ) use ( &$section, &$taken, &$found, $prefix ) {
     827                        function ( $m ) use ( &$section, &$taken, &$found, $prefix, $saved ) {
    645828                                if ( '' !== $m[1] ) {
    646829                                        $section = $this->clean_text( $m[2] );
    … …  
    656839                                }
    657840
     841                                $host  = (string) wp_parse_url( $url, PHP_URL_HOST );
    658842                                $label = $this->clean_text( $m[4] );
    659                                 if ( '' === $label && preg_match( '#\baria-label\s*=\s*(["\'])(.*?)\1#is', $attrs, $am ) ) {
     843                                if ( '' === $label && preg_match( '#(?<![\w-])aria-label\s*=\s*(["\'])(.*?)\1#is', $attrs, $am ) ) {
    660844                                        $label = $this->clean_text( $am[2] );
    661845                                }
     846                                // Before 2.3, a link with no text or aria-label was named after its host. 2.3 tries its
     847                                // title and the image's alt text first, but a link already counted keeps its old slug.
     848                                $by_host = '' === $label;
     849                                foreach ( array( array( $attrs, 'title' ), array( $m[4], 'alt' ) ) as $try ) {
     850                                        if ( '' === $label && preg_match( '#(?<![\w-])' . $try[1] . '\s*=\s*(["\'])(.*?)\1#is', $try[0], $am ) ) {
     851                                                $label = $this->clean_text( $am[2] );
     852                                        }
     853                                }
    662854                                if ( '' === $label ) {
    663                                         $label = (string) wp_parse_url( $url, PHP_URL_HOST );
     855                                        $label = $host;
    664856                                }
    665857                                $full = '' !== $section ? $section . ' · ' . $label : $label;
    666858
    667859                                // Slug from the plain words only: sanitize_title() would keep the "·" as %c2%b7.
    668                                 $base = substr( sanitize_title( remove_accents( $section . ' ' . $label ) ), 0, 60 );
    669                                 $base = trim( $base, '-' );
     860                                $base = $this->slug_base( $section, $label, $prefix );
     861                                if ( $by_host && $label !== $host ) {
     862                                        $old = $this->slug_base( $section, $host, $prefix );
     863                                        if ( '' !== $old && isset( $saved[ $old ] ) && $saved[ $old ]['url'] === $url ) {
     864                                                $base = $old;
     865                                        }
     866                                }
    670867                                if ( '' === $base ) {
    671868                                        return $m[0];
    672                                 }
    673                                 if ( '' !== $prefix ) {
    674                                         $base = trim( substr( $prefix . '-' . $base, 0, 90 ), '-' );
    675869                                }
    676870                                $slug = $base;
    … …  
    690884                        $html
    691885                );
     886        }
     887
     888        /**
     889         * The /go/ slug for a link: its section and label in plain words, after the page's prefix.
     890         *
     891         * @param string $section Nearest heading.
     892         * @param string $label   Link label.
     893         * @param string $prefix  Slug prefix for the page.
     894         * @return string '' when there are no usable words.
     895         */
     896        private function slug_base( $section, $label, $prefix ) {
     897                $base = trim( substr( sanitize_title( remove_accents( $section . ' ' . $label ) ), 0, 60 ), '-' );
     898                if ( '' !== $base && '' !== $prefix ) {
     899                        $base = trim( substr( $prefix . '-' . $base, 0, 90 ), '-' );
     900                }
     901                return $base;
    692902        }
    693903
    … …  
    755965                }
    756966
     967                $this->load_builder_shortcodes();
    757968                global $post;
    758969                $previous = $post;
    … …  
    774985        }
    775986
     987        /**
     988         * Page builders that only register their shortcodes on the front end (WPBakery, Divi) are loaded
     989         * here, so a links page saved from the editor is scanned the same way it's shown to visitors.
     990         */
     991        private function load_builder_shortcodes() {
     992                try {
     993                        $this->load_builders();
     994                } catch ( Throwable $e ) {
     995                        return; // The page is still saved; its links are found on the first visit instead.
     996                }
     997                /**
     998                 * Fires before a links page is rendered to find its links, for loading other builders' shortcodes.
     999                 */
     1000                do_action( 'link_in_bio_report_before_scan' );
     1001        }
     1002
     1003        /** Loads WPBakery's and Divi's shortcodes when they aren't loaded yet. */
     1004        private function load_builders() {
     1005                if ( class_exists( 'WPBMap' ) && method_exists( 'WPBMap', 'addAllMappedShortcodes' ) && ! shortcode_exists( 'vc_row' ) ) {
     1006                        WPBMap::addAllMappedShortcodes();
     1007                }
     1008                if ( function_exists( 'et_builder_add_main_elements' ) && function_exists( 'et_builder_should_load_framework' ) && ! did_action( 'et_builder_ready' ) && et_builder_should_load_framework() ) {
     1009                        if ( function_exists( 'et_builder_init_global_settings' ) ) {
     1010                                et_builder_init_global_settings();
     1011                        }
     1012                        et_builder_add_main_elements();
     1013                }
     1014        }
     1015
    7761016        /** Suggested text for the site's privacy policy (Settings → Privacy → Policy Guide). */
    7771017        public function privacy_policy_content() {
    … …  
    7811021                $text = '<p class="privacy-policy-tutorial">' . esc_html__( 'Link in Bio Report counts visits to the links pages and taps on their links. It sets no cookies and sends nothing to outside services.', 'link-in-bio-report' ) . '</p>'
    7821022                        . '<p><strong class="privacy-policy-tutorial">' . esc_html__( 'Suggested text:', 'link-in-bio-report' ) . ' </strong>'
    783                         . esc_html__( 'When you visit our links page or tap a link on it, we record the page or link and the time, with an anonymous visitor code. The code is a one-way, salted hash of your IP address and browser details, so it can’t be turned back into either; your IP address itself is never stored. This lets us count how many different people visited without using cookies. These records stay on our website, are used only for our own visit and tap counts, and are deleted after two years.', 'link-in-bio-report' )
     1023                        . esc_html__( 'When you visit our links page or tap a link on it, we record the page or link, the time and, when known, the app or website you came from (such as Instagram), with an anonymous visitor code. The code is a one-way, salted hash of your IP address and browser details, so it can’t be turned back into either; your IP address itself is never stored. This lets us count how many different people visited without using cookies. These records stay on our website, are used only for our own visit and tap counts, and are deleted after two years.', 'link-in-bio-report' )
    7841024                        . '</p>';
    7851025                wp_add_privacy_policy_content( 'Link in Bio Report', wp_kses_post( $text ) );
     1026        }
     1027
     1028        /**
     1029         * How many buttons or links on a page still point at "#", as each editor saves them. Block
     1030         * buttons are counted by their HTML (href="#"), and social icons by their settings, since they
     1031         * save no HTML; WPBakery, Divi and Elementor keep links in their own formats.
     1032         *
     1033         * @param int $page_id Page ID.
     1034         * @return int
     1035         */
     1036        private function placeholder_count( $page_id ) {
     1037                $elementor = get_post_meta( $page_id, '_elementor_data', true );
     1038                if ( is_string( $elementor ) && '' !== $elementor && 'builder' === get_post_meta( $page_id, '_elementor_edit_mode', true ) ) {
     1039                        return (int) preg_match_all( '/"url":"#"/', $elementor ); // Elementor's own data; post_content is only a copy.
     1040                }
     1041                $content = (string) get_post_field( 'post_content', $page_id );
     1042                $count   = (int) preg_match_all( '/href="#"/', $content ); // Block buttons and plain HTML.
     1043                $count  += (int) preg_match_all( '/<!-- wp:(?:social-link|navigation-link)\b[^>]*"url":"#"/', $content ); // Blocks without saved HTML.
     1044                $count  += (int) preg_match_all( '/(?<![\w-])link="url:%23\|/', $content ); // WPBakery.
     1045                $count  += (int) preg_match_all( '/(?<![\w-])(?:button_url|url|link_option_url)="#"/', $content ); // Divi.
     1046                return $count;
    7861047        }
    7871048
    … …  
    10001261
    10011262        /**
    1002          * Builds and sends the report email. Also used by the "send test" button.
    1003          *
    1004          * @param bool $is_test When true, the subject starts with [TEST].
    1005          * @return bool wp_mail result.
    1006          */
    1007         public function send_report( $is_test = false ) {
     1263         * The numbers for a report period, one section per links page (plus "Other links" when
     1264         * links outside the pages were tapped). Used by the email and the settings screen.
     1265         *
     1266         * @param string $start Site-time 'Y-m-d H:i:s'.
     1267         * @param string $end   Site-time 'Y-m-d H:i:s' (not included).
     1268         * @return array sections, totals (visitors, clicks, pages).
     1269         */
     1270        private function report_data( $start, $end ) {
    10081271                global $wpdb;
    1009                 $this->purge_old_rows();
    1010 
    1011                 $settings   = $this->get_settings();
    1012                 $recipients = array_filter( array_map( 'trim', explode( ',', $this->recipient( $settings ) ) ) );
    1013                 if ( empty( $recipients ) ) {
    1014                         return false;
    1015                 }
    1016 
    10171272                // Rows logged before v1.4 have no visitor key and include prefetches and
    10181273                // crawler hits, so they're left out (visitor <> '').
    1019                 $window = $this->report_window();
     1274                $settings = $this->get_settings();
    10201275
    10211276                // Clicks per slug and the visitors behind them.
    … …  
    10231278                $click_rows = $wpdb->get_results(
    10241279                        $wpdb->prepare(
    1025                                 "SELECT slug, visitor FROM %i WHERE event_type = 'click' AND visitor <> '' AND created_at >= %s AND created_at < %s",
     1280                                "SELECT slug, visitor, source FROM %i WHERE event_type = 'click' AND visitor <> '' AND created_at >= %s AND created_at < %s",
    10261281                                $this->table,
    1027                                 $window['start'],
    1028                                 $window['end']
     1282                                $start,
     1283                                $end
    10291284                        ),
    10301285                        ARRAY_A
    … …  
    10341289                $view_rows = $wpdb->get_results(
    10351290                        $wpdb->prepare(
    1036                                 "SELECT slug, visitor FROM %i WHERE event_type = 'view' AND visitor <> '' AND created_at >= %s AND created_at < %s",
     1291                                "SELECT slug, visitor, source FROM %i WHERE event_type = 'view' AND visitor <> '' AND created_at >= %s AND created_at < %s",
    10371292                                $this->table,
    1038                                 $window['start'],
    1039                                 $window['end']
     1293                                $start,
     1294                                $end
    10401295                        ),
    10411296                        ARRAY_A
    … …  
    10681323                        'views'    => 0,
    10691324                        'visitors' => array(),
     1325                        'sources'  => array(), // Source => visitors (set), clicks.
    10701326                );
    10711327                $sections = array();
    … …  
    11001356                        $sections[ $p ]['counts'][ $r['slug'] ]      = ( isset( $sections[ $p ]['counts'][ $r['slug'] ] ) ? $sections[ $p ]['counts'][ $r['slug'] ] : 0 ) + 1;
    11011357                        $sections[ $p ]['clickers'][ $r['visitor'] ] = true;
     1358                        $src = (string) $r['source'];
     1359                        if ( ! isset( $sections[ $p ]['sources'][ $src ] ) ) {
     1360                                $sections[ $p ]['sources'][ $src ] = array(
     1361                                        'visitors' => array(),
     1362                                        'clicks'   => 0,
     1363                                );
     1364                        }
     1365                        ++$sections[ $p ]['sources'][ $src ]['clicks'];
    11021366                }
    11031367                $by_view_slug = array();
    … …  
    11161380                        $sections[ $key ]['visitors'][ $r['visitor'] ] = true;
    11171381                        $all_visitors[ $r['visitor'] ]                 = true;
     1382                        $src = (string) $r['source'];
     1383                        if ( ! isset( $sections[ $key ]['sources'][ $src ] ) ) {
     1384                                $sections[ $key ]['sources'][ $src ] = array(
     1385                                        'visitors' => array(),
     1386                                        'clicks'   => 0,
     1387                                );
     1388                        }
     1389                        $sections[ $key ]['sources'][ $src ]['visitors'][ $r['visitor'] ] = true;
    11181390                }
    11191391
    … …  
    11421414                                }
    11431415                        );
     1416                        // Sources, most visitors first. Only worth showing when at least one visit had a source.
     1417                        $sources = array();
     1418                        foreach ( $sec['sources'] as $src => $info ) {
     1419                                $sources[] = array(
     1420                                        'key'      => (string) $src,
     1421                                        'label'    => $this->source_label( (string) $src ),
     1422                                        'visitors' => count( $info['visitors'] ),
     1423                                        'clicks'   => $info['clicks'],
     1424                                );
     1425                        }
     1426                        usort(
     1427                                $sources,
     1428                                function ( $a, $b ) {
     1429                                        if ( '' === $a['key'] || '' === $b['key'] ) {
     1430                                                return '' === $a['key'] ? 1 : -1; // "Direct or unknown" last.
     1431                                        }
     1432                                        $diff = $b['visitors'] - $a['visitors'];
     1433                                        return 0 !== $diff ? $diff : $b['clicks'] - $a['clicks'];
     1434                                }
     1435                        );
     1436                        if ( ! array_filter( wp_list_pluck( $sources, 'key' ) ) ) {
     1437                                $sources = array();
     1438                        }
     1439                        // Anyone can make up a from= value, so past the first 6 named sources the rest share a row.
     1440                        $named = array();
     1441                        $more  = null;
     1442                        $tail  = array();
     1443                        foreach ( $sources as $src ) {
     1444                                if ( '' === $src['key'] ) {
     1445                                        $tail[] = $src;
     1446                                } elseif ( count( $named ) < 6 ) {
     1447                                        $named[] = $src;
     1448                                } else {
     1449                                        $more = $more ? $more : array(
     1450                                                'key'      => 'more',
     1451                                                'label'    => __( 'Other sources', 'link-in-bio-report' ),
     1452                                                'visitors' => 0,
     1453                                                'clicks'   => 0,
     1454                                        );
     1455                                        $more['visitors'] += $src['visitors'];
     1456                                        $more['clicks']   += $src['clicks'];
     1457                                }
     1458                        }
     1459                        $sources = array_merge( $named, $more ? array( $more ) : array(), $tail );
    11441460                        $out[] = array(
    11451461                                'title'    => $sec['title'],
    … …  
    11521468                                'rows'     => $rows,
    11531469                                'idle'     => $idle,
     1470                                'sources'  => $sources,
    11541471                        );
    11551472                }
     1473
     1474                return array(
     1475                        'sections' => $out,
     1476                        'totals'   => array(
     1477                                'visitors' => count( $all_visitors ),
     1478                                'clicks'   => count( $click_rows ),
     1479                                'pages'    => count( array_filter( wp_list_pluck( $out, 'is_page' ) ) ),
     1480                        ),
     1481                );
     1482        }
     1483
     1484        /**
     1485         * Builds and sends the report email. Also used by the "send test" button.
     1486         *
     1487         * @param bool $is_test When true, the subject starts with [TEST].
     1488         * @return bool wp_mail result.
     1489         */
     1490        public function send_report( $is_test = false ) {
     1491                $this->purge_old_rows();
     1492
     1493                $settings   = $this->get_settings();
     1494                $recipients = array_filter( array_map( 'trim', explode( ',', $this->recipient( $settings ) ) ) );
     1495                if ( empty( $recipients ) ) {
     1496                        return false;
     1497                }
     1498
     1499                $window = $this->report_window();
     1500                $data   = $this->report_data( $window['start'], $window['end'] );
     1501                $out    = $data['sections'];
     1502                $totals = $data['totals'];
    11561503
    11571504                // Decode entities so the subject line shows a plain apostrophe, not &#039;.
    … …  
    11671514                        $subject = '[' . __( 'TEST', 'link-in-bio-report' ) . '] ' . $subject;
    11681515                }
    1169 
    1170                 $totals = array(
    1171                         'visitors' => count( $all_visitors ),
    1172                         'clicks'   => count( $click_rows ),
    1173                         'pages'    => count( array_filter( wp_list_pluck( $out, 'is_page' ) ) ),
    1174                 );
    11751516
    11761517                $html     = $this->render_email( $site, $window, $out, $totals, $settings['footer_text'] );
    … …  
    11871528                        return $from_name;
    11881529                };
     1530                $catch = function ( $error ) {
     1531                        $this->mail_error = is_wp_error( $error ) ? $error->get_error_message() : '';
     1532                };
    11891533                add_filter( 'wp_mail_from_name', $set_from, 20 );
     1534                add_action( 'wp_mail_failed', $catch );
    11901535                $sent = wp_mail( $recipients, $subject, $html, $headers );
     1536                remove_action( 'wp_mail_failed', $catch );
    11911537                remove_filter( 'wp_mail_from_name', $set_from, 20 );
    11921538                return $sent;
    … …  
    13351681                                <?php endif; ?>
    13361682
     1683                                <?php if ( $sec['sources'] ) : ?>
     1684                                        <table style="width:100%;border-collapse:collapse;font-size:13px;margin:14px 0 0;">
     1685                                                <thead>
     1686                                                        <tr>
     1687                                                                <th style="text-align:left;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'Came from', 'link-in-bio-report' ); ?></th>
     1688                                                                <th style="text-align:right;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'People', 'link-in-bio-report' ); ?></th>
     1689                                                                <th style="text-align:right;padding:6px 0;border-bottom:2px solid <?php echo esc_attr( $head_border ); ?>;"><?php esc_html_e( 'Clicks', 'link-in-bio-report' ); ?></th>
     1690                                                        </tr>
     1691                                                </thead>
     1692                                                <tbody>
     1693                                                <?php foreach ( $sec['sources'] as $src ) : ?>
     1694                                                        <tr>
     1695                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;"><?php echo esc_html( $src['label'] ); ?></td>
     1696                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;text-align:right;font-variant-numeric:tabular-nums;"><?php echo esc_html( number_format_i18n( $src['visitors'] ) ); ?></td>
     1697                                                                <td style="<?php echo esc_attr( $row_td ); ?>padding:6px 0;text-align:right;font-variant-numeric:tabular-nums;"><?php echo esc_html( number_format_i18n( $src['clicks'] ) ); ?></td>
     1698                                                        </tr>
     1699                                                <?php endforeach; ?>
     1700                                                </tbody>
     1701                                        </table>
     1702                                <?php endif; ?>
     1703
    13371704                                <?php if ( $block ) : ?>
    13381705                                                </td>
    … …  
    13901757                        . "if(navigator.clipboard){navigator.clipboard.writeText(f.value).then(done,legacy);}else{legacy();}});"
    13911758                );
     1759        }
     1760
     1761        /**
     1762         * The links page being edited on this screen, or 0.
     1763         *
     1764         * @return int
     1765         */
     1766        private function edited_links_page() {
     1767                $post = get_post();
     1768                return ( $post && 'page' === $post->post_type && in_array( (int) $post->ID, $this->page_ids(), true ) ) ? (int) $post->ID : 0;
     1769        }
     1770
     1771        /**
     1772         * The editor notice's text for a links page: that it's counted, and its bio address.
     1773         *
     1774         * @param int $page_id Page ID.
     1775         * @return string Plain text.
     1776         */
     1777        private function editor_notice_text( $page_id ) {
     1778                if ( 'publish' !== get_post_status( $page_id ) ) {
     1779                        return __( 'This is a links page for Link in Bio Report. Once it’s published, visits and taps on its buttons are counted. Point the buttons at their real addresses.', 'link-in-bio-report' );
     1780                }
     1781                return sprintf(
     1782                        /* translators: %s: the page's address. */
     1783                        __( 'This is a links page for Link in Bio Report: visits and taps on its buttons are counted. Its bio address is %s', 'link-in-bio-report' ),
     1784                        get_permalink( $page_id )
     1785                );
     1786        }
     1787
     1788        /**
     1789         * In the block editor, on a links page: a notice that the page is counted, with its bio
     1790         * address, and a warning while any button still links to "#".
     1791         */
     1792        public function editor_notice() {
     1793                $page_id = $this->edited_links_page();
     1794                if ( ! $page_id || ! current_user_can( 'edit_post', $page_id ) ) {
     1795                        return;
     1796                }
     1797                $data = array(
     1798                        'text'     => $this->editor_notice_text( $page_id ),
     1799                        'settings' => current_user_can( 'manage_options' ) ? admin_url( 'options-general.php?page=link-in-bio-report' ) : '',
     1800                        'label'    => __( 'Link in Bio Report settings', 'link-in-bio-report' ),
     1801                        /* translators: %d: number of buttons. */
     1802                        'one'      => __( '%d button or icon on this page still links to “#”. Give it a real address so its taps are counted.', 'link-in-bio-report' ),
     1803                        /* translators: %d: number of buttons. */
     1804                        'many'     => __( '%d buttons or icons on this page still link to “#”. Give them real addresses so their taps are counted.', 'link-in-bio-report' ),
     1805                );
     1806                wp_register_script( 'link-in-bio-report-editor', false, array( 'wp-data', 'wp-dom-ready', 'wp-notices', 'wp-editor' ), self::VERSION, true );
     1807                wp_enqueue_script( 'link-in-bio-report-editor' );
     1808                wp_add_inline_script(
     1809                        'link-in-bio-report-editor',
     1810                        '(function(d){var n=wp.data.dispatch("core/notices"),last=-1,timer=0;'
     1811                        . 'wp.domReady(function(){n.createNotice("info",d.text,{id:"lbr-links-page",isDismissible:true,'
     1812                        . 'actions:d.settings?[{label:d.label,url:d.settings}]:[]});'
     1813                        . 'var check=function(){var c=wp.data.select("core/editor").getEditedPostContent()||"",'
     1814                        . 'm=function(r){return(c.match(r)||[]).length;},k=m(/href="#"/g)+m(/<!-- wp:(?:social-link|navigation-link)\\b[^>]*"url":"#"/g)+m(/(^|[^\\w-])link="url:%23\\|/g)+m(/(^|[^\\w-])(?:button_url|url|link_option_url)="#"/g);if(k===last){return;}last=k;'
     1815                        . 'if(k){n.createNotice("warning",(k===1?d.one:d.many).replace("%d",k),{id:"lbr-placeholders",isDismissible:false});}'
     1816                        . 'else{n.removeNotice("lbr-placeholders");}};'
     1817                        . 'check();wp.data.subscribe(function(){clearTimeout(timer);timer=setTimeout(check,800);});});'
     1818                        . '})(' . wp_json_encode( $data ) . ');'
     1819                );
     1820        }
     1821
     1822        /**
     1823         * The same notice on the classic editor screen (and page builders that use it), read from the saved page.
     1824         */
     1825        public function classic_editor_notice() {
     1826                $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
     1827                if ( ! $screen || 'post' !== $screen->base || ( method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor() ) ) {
     1828                        return;
     1829                }
     1830                $page_id = $this->edited_links_page();
     1831                if ( ! $page_id || ! current_user_can( 'edit_post', $page_id ) ) {
     1832                        return;
     1833                }
     1834                echo '<div class="notice notice-info"><p>' . esc_html( $this->editor_notice_text( $page_id ) ) . '</p></div>';
     1835                $count = $this->placeholder_count( $page_id );
     1836                if ( $count ) {
     1837                        echo '<div class="notice notice-warning"><p>' . esc_html(
     1838                                sprintf(
     1839                                        /* translators: %d: number of buttons. */
     1840                                        _n( '%d button or icon on this page still links to “#”. Give it a real address so its taps are counted.', '%d buttons or icons on this page still link to “#”. Give them real addresses so their taps are counted.', $count, 'link-in-bio-report' ),
     1841                                        $count
     1842                                )
     1843                        ) . '</p></div>';
     1844                }
    13921845        }
    13931846
    … …  
    15251978                                : array(
    15261979                                        'type' => 'error',
    1527                                         'msg'  => __( 'Could not send. Check the recipient and your site’s email setup.', 'link-in-bio-report' ),
     1980                                        'msg'  => $this->send_failed_message(),
     1981                                        'html' => true,
    15281982                                );
    15291983                } else {
    … …  
    15331987                        );
    15341988                }
     1989        }
     1990
     1991        /**
     1992         * The error shown when the test report couldn't be sent: what WordPress said, and what usually fixes it.
     1993         *
     1994         * @return string HTML (links and code only).
     1995         */
     1996        private function send_failed_message() {
     1997                $msg = esc_html__( 'Could not send the test report.', 'link-in-bio-report' );
     1998                if ( '' !== $this->mail_error ) {
     1999                        /* translators: %s: the error from WordPress's mailer. */
     2000                        $msg .= ' ' . sprintf( esc_html__( 'WordPress said: %s', 'link-in-bio-report' ), '<code>' . esc_html( $this->mail_error ) . '</code>' );
     2001                }
     2002                if ( $this->has_smtp_plugin() ) {
     2003                        $msg .= ' ' . esc_html__( 'Check the settings of your email (SMTP) plugin, and the recipient address.', 'link-in-bio-report' );
     2004                } else {
     2005                        $msg .= ' ' . esc_html__( 'Many hosts don’t deliver email sent by WordPress itself. An SMTP plugin, which sends through a real mail service, usually fixes it.', 'link-in-bio-report' );
     2006                        if ( current_user_can( 'install_plugins' ) ) {
     2007                                $msg .= ' <a href="' . esc_url( admin_url( 'plugin-install.php?s=smtp&tab=search&type=term' ) ) . '">' . esc_html__( 'Find an SMTP plugin', 'link-in-bio-report' ) . '</a>';
     2008                        }
     2009                }
     2010                return $msg;
     2011        }
     2012
     2013        /**
     2014         * Whether a plugin that sends WordPress email through SMTP or a mail service is active.
     2015         *
     2016         * @return bool
     2017         */
     2018        private function has_smtp_plugin() {
     2019                // SMTP plugins either hook into PHPMailer, take over wp_mail() before it sends, or replace it.
     2020                $found = defined( 'WPMS_PLUGIN_VER' ) || defined( 'FLUENTMAIL' ) || defined( 'POST_SMTP_VER' )
     2021                        || has_action( 'phpmailer_init' ) || has_filter( 'pre_wp_mail' );
     2022                if ( ! $found && function_exists( 'wp_mail' ) ) {
     2023                        try {
     2024                                $file  = wp_normalize_path( (string) ( new ReflectionFunction( 'wp_mail' ) )->getFileName() );
     2025                                $found = '' !== $file && wp_normalize_path( ABSPATH . WPINC . '/pluggable.php' ) !== $file;
     2026                        } catch ( ReflectionException $e ) {
     2027                                $found = false;
     2028                        }
     2029                }
     2030                /**
     2031                 * Filters whether the site sends email through an SMTP plugin or mail service.
     2032                 *
     2033                 * @param bool $found Whether a known one is active.
     2034                 */
     2035                return (bool) apply_filters( 'link_in_bio_report_has_smtp_plugin', $found );
     2036        }
     2037
     2038        /**
     2039         * The "Last 7 days" box on the settings screen: visits, taps and the top links of each
     2040         * page, so it's clear the counting works before the first report arrives.
     2041         */
     2042        private function recent_panel() {
     2043                if ( ! $this->published_page_ids() ) {
     2044                        return;
     2045                }
     2046                $now  = new DateTimeImmutable( 'now', wp_timezone() );
     2047                $data = $this->report_data( $now->modify( '-7 days' )->format( 'Y-m-d H:i:s' ), $now->modify( '+1 minute' )->format( 'Y-m-d H:i:s' ) );
     2048                $secs = $data['sections'];
     2049                ?>
     2050                <div class="lbr-box lbr-recent">
     2051                        <h2><?php esc_html_e( 'Last 7 days', 'link-in-bio-report' ); ?></h2>
     2052                        <p class="lbr-recent-totals">
     2053                                <?php
     2054                                echo wp_kses(
     2055                                        sprintf(
     2056                                                /* translators: 1: people who visited, 2: link clicks. */
     2057                                                __( '%1$s visited, %2$s.', 'link-in-bio-report' ),
     2058                                                sprintf(
     2059                                                        /* translators: %s: number of people, in bold. */
     2060                                                        _n( '<strong>%s</strong> person', '<strong>%s</strong> people', $data['totals']['visitors'], 'link-in-bio-report' ),
     2061                                                        esc_html( number_format_i18n( $data['totals']['visitors'] ) )
     2062                                                ),
     2063                                                sprintf(
     2064                                                        /* translators: %s: number of clicks, in bold. */
     2065                                                        _n( '<strong>%s</strong> link click', '<strong>%s</strong> link clicks', $data['totals']['clicks'], 'link-in-bio-report' ),
     2066                                                        esc_html( number_format_i18n( $data['totals']['clicks'] ) )
     2067                                                )
     2068                                        ),
     2069                                        array( 'strong' => array() )
     2070                                );
     2071                                ?>
     2072                        </p>
     2073                        <?php foreach ( $secs as $sec ) : ?>
     2074                                <?php if ( count( $secs ) > 1 ) : ?>
     2075                                        <h3><?php echo esc_html( $sec['title'] ); ?>
     2076                                                <?php if ( $sec['is_page'] ) : ?>
     2077                                                        <span><?php echo esc_html( sprintf( /* translators: 1: people, 2: clicks. */ __( '%1$s people · %2$s clicks', 'link-in-bio-report' ), number_format_i18n( $sec['visitors'] ), number_format_i18n( $sec['clicks'] ) ) ); ?></span>
     2078                                                <?php endif; ?>
     2079                                        </h3>
     2080                                <?php endif; ?>
     2081                                <?php if ( $sec['rows'] ) : ?>
     2082                                        <table class="widefat striped lbr-recent-table">
     2083                                                <thead><tr><th><?php esc_html_e( 'Top links', 'link-in-bio-report' ); ?></th><th class="num"><?php esc_html_e( 'Clicks', 'link-in-bio-report' ); ?></th></tr></thead>
     2084                                                <tbody>
     2085                                                <?php foreach ( array_slice( $sec['rows'], 0, 5 ) as $row ) : ?>
     2086                                                        <tr><td><?php echo esc_html( $row['label'] ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( $row['clicks'] ) ); ?></td></tr>
     2087                                                <?php endforeach; ?>
     2088                                                </tbody>
     2089                                        </table>
     2090                                <?php else : ?>
     2091                                        <p class="description"><?php esc_html_e( 'No link clicks yet.', 'link-in-bio-report' ); ?></p>
     2092                                <?php endif; ?>
     2093                                <?php if ( $sec['sources'] ) : ?>
     2094                                        <p class="lbr-recent-sources">
     2095                                                <?php
     2096                                                $parts = array();
     2097                                                foreach ( $sec['sources'] as $src ) {
     2098                                                        $parts[] = $src['label'] . ' ' . number_format_i18n( $src['visitors'] );
     2099                                                }
     2100                                                /* translators: %s: sources and their visitor counts, like "Instagram 12 · TikTok 4". */
     2101                                                echo esc_html( sprintf( __( 'Came from: %s', 'link-in-bio-report' ), implode( ' · ', $parts ) ) );
     2102                                                ?>
     2103                                        </p>
     2104                                <?php endif; ?>
     2105                        <?php endforeach; ?>
     2106                        <p class="description"><?php esc_html_e( 'Your own visits and taps while logged in aren’t counted. To check that counting works, open the page in a private window.', 'link-in-bio-report' ); ?></p>
     2107                </div>
     2108                <?php
    15352109        }
    15362110
    … …  
    15712145                        </div>
    15722146                        <?php if ( $this->notice ) : ?>
    1573                                 <div class="notice notice-<?php echo 'error' === $this->notice['type'] ? 'error' : 'success'; ?> is-dismissible"><p><?php echo esc_html( $this->notice['msg'] ); ?></p></div>
     2147                                <div class="notice notice-<?php echo 'error' === $this->notice['type'] ? 'error' : 'success'; ?> is-dismissible"><p><?php echo empty( $this->notice['html'] ) ? esc_html( $this->notice['msg'] ) : wp_kses( $this->notice['msg'], array( 'a' => array( 'href' => array() ), 'code' => array() ) ); ?></p></div>
    15742148                        <?php endif; ?>
    15752149
    … …  
    15792153                        <div class="lbr-main">
    15802154                        <?php $this->getting_started( $s, $next_str ); ?>
     2155                        <?php $this->recent_panel(); ?>
    15812156                        <form method="post">
    15822157                                <?php wp_nonce_field( 'link_in_bio_report_save' ); ?>
    … …  
    17842359                                );
    17852360                        }
    1786                         $placeholders = preg_match_all( '/href="#"|"url":"#"/', $post->post_content );
     2361                        $placeholders = $this->placeholder_count( $id );
    17872362                        if ( $placeholders ) {
    17882363                                $problems[] = sprintf(
    … …  
    18362411                                                <a href="<?php echo esc_url( get_permalink( $id ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'View', 'link-in-bio-report' ); ?></a>
    18372412                                        </p>
     2413                                        <details class="lbr-apps">
     2414                                                <summary><?php esc_html_e( 'In more than one app’s bio?', 'link-in-bio-report' ); ?></summary>
     2415                                                <p class="description"><?php esc_html_e( 'Give each app its own address, and the report shows how many people came from each. Visits from other sites are sorted by where they came from on their own.', 'link-in-bio-report' ); ?></p>
     2416                                                <?php foreach ( array( 'instagram', 'tiktok', 'facebook' ) as $app ) : ?>
     2417                                                        <?php $app_field = $field . '-' . $app; ?>
     2418                                                        <p class="lbr-bio lbr-app">
     2419                                                                <label for="<?php echo esc_attr( $app_field ); ?>"><?php echo esc_html( $this->source_label( $app ) ); ?></label>
     2420                                                                <input type="text" readonly class="regular-text code" id="<?php echo esc_attr( $app_field ); ?>" value="<?php echo esc_attr( add_query_arg( 'from', $app, get_permalink( $id ) ) ); ?>" />
     2421                                                                <button type="button" class="button lbr-copy" data-target="<?php echo esc_attr( $app_field ); ?>" data-done="<?php esc_attr_e( 'Copied', 'link-in-bio-report' ); ?>"><?php esc_html_e( 'Copy', 'link-in-bio-report' ); ?></button>
     2422                                                        </p>
     2423                                                <?php endforeach; ?>
     2424                                                <p class="description">
     2425                                                        <?php
     2426                                                        printf(
     2427                                                                /* translators: %s: example address ending. */
     2428                                                                esc_html__( 'For any other app, add %s with its name.', 'link-in-bio-report' ),
     2429                                                                '<code>?from=</code>'
     2430                                                        );
     2431                                                        ?>
     2432                                                </p>
     2433                                        </details>
    18382434                                <?php endforeach; ?>
    18392435                        <?php endif; ?>
  • link-in-bio-report/trunk/readme.txt

    r3831063 r3832004  
    55Tested up to: 7.1
    66Requires PHP: 7.2
    7 Stable tag: 2.2.2
     7Stable tag: 2.3.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    1616
    1717* **Works with the page you already have.** Build the links page with the block editor, any theme or any page builder. Every outbound link on it is tracked automatically, including buttons you add later.
     18* **Instagram, TikTok or somewhere else.** Give each app its own bio address (`/links/?from=tiktok`) and the report shows how many people came from each. Visits from other sites are sorted by where they came from on their own.
     19* **Numbers right in WordPress.** The settings screen shows the last 7 days (visits, taps and the top links), so you can see it working before the first email arrives.
    1820* **Several links pages, one report.** One page per Instagram account or per location, say. The email has a colored section for each page plus a total.
    1921* **Weekly or monthly.** Pick the day and time, or have it sent on the 1st for the month before.
    … …  
    29312. When a links page is shown, each `http(s)` link on it is pointed at `/go/{slug}` on your site. The page itself keeps its real URLs, so you edit it as usual.
    30323. A tap on `/go/{slug}` is counted, then the visitor is sent on to the real destination.
    31 4. The report lists, for each page, how many people visited, how many visits and taps there were, the share of visitors who tapped a link, and every link by taps.
     334. The report lists, for each page, how many people visited, how many visits and taps there were, the share of visitors who tapped a link, every link by taps, and where visitors came from.
    3234
    3335The slug and the label in the report come from the nearest heading plus the button text, so "Order online" under two different locations is counted separately.
    … …  
    8284Yes. **Show the links pages on their own** (on by default) shows only the page content, with your theme's fonts and colors but without its header, footer and page title. Turn it off to show the page like any other. Developers can decide per page with the `link_in_bio_report_own_page` filter.
    8385
     86= How do I tell Instagram and TikTok visitors apart? =
     87
     88Put a different address in each bio: `example.com/links/?from=instagram` in Instagram and `example.com/links/?from=tiktok` in TikTok. The settings screen has these ready to copy under **In more than one app's bio?**. Any name works after `from=`. Visits that come from another website are counted under that site (Google, Facebook, "Other websites") without any setup, and the rest are "Direct or unknown".
     89
     90= Does it work with Elementor, Divi and WPBakery? =
     91
     92Yes. Buttons, icons and image links made with Elementor, Divi or WPBakery are counted like any other link, and "Show the links pages on their own" keeps the builder's styles.
     93
    8494= What are the /go/ addresses in the Tracked links table? =
    8595
    … …  
    92102== Privacy ==
    93103
    94 The plugin sets no cookies and uses no outside services. For each visit or tap it stores the time, the page or link, and a 16-character visitor key: a salted one-way hash of the IP address and user agent that can't be turned back into either. IP addresses are never stored. A short-lived counter keyed by a hash of the IP address limits visits counted from one address to 30 an hour.
     104The plugin sets no cookies and uses no outside services. For each visit or tap it stores the time, the page or link, where the visit came from when that's known (such as "instagram", from the bio address or the referring site's name; never the full referring address), and a 16-character visitor key: a salted one-way hash of the IP address and user agent that can't be turned back into either. IP addresses are never stored. A short-lived counter keyed by a hash of the IP address limits visits counted from one address to 30 an hour.
    95105
    96106The plugin adds suggested text to **Settings → Privacy → Policy Guide** for your privacy policy.
    … …  
    103113
    104114== Changelog ==
     115
     116= 2.3.0 =
     117* A "Last 7 days" box on the settings screen: visits, taps and the top links on each page.
     118* Where visitors came from: give each app its own bio address (`/links/?from=instagram`, `?from=tiktok`) and the report shows people and clicks for each. Visits from other sites are sorted by the referring site (Google, Facebook and others) on their own.
     119* In the editor, a links page says it's being counted and shows its bio address, and warns while a button or icon still links to "#". Works in the block editor and the classic editor, and spots "#" links in Elementor, Divi and WPBakery pages.
     120* Saving a WPBakery or Divi links page now fills in Tracked links right away (before, it waited for the first visit).
     121* Icon and image links with no text are named from their title or image description instead of the site they link to. Links already being counted keep their /go/ address, so their numbers carry on.
     122* When the test report can't be sent, the message shows WordPress's reason and suggests an SMTP plugin.
     123* Fixed: a block button linking to "#" was counted twice in the "Getting started" warning.
    105124
    106125= 2.2.2 =
Note: See TracChangeset for help on using the changeset viewer.