Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
47.90% covered (danger)
47.90%
228 / 476
21.43% covered (danger)
21.43%
6 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 3
sharing_register_post_for_share_counts
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
sharing_maybe_enqueue_scripts
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
90
sharing_add_footer
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
110
sharing_add_header
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
sharing_process_requests
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
56
get_sharing_buttons_customisation_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
sharing_display
67.97% covered (warning)
67.97%
87 / 128
0.00% covered (danger)
0.00%
0 / 1
183.29
get_base_recaptcha_lang_code
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
Sharing_Service
51.18% covered (warning)
51.18%
130 / 254
25.00% covered (danger)
25.00%
4 / 16
1099.31
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_all_services_blog
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 get_all_services
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
6.02
 new_service
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
42
 delete_service
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 set_blog_services
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
2
 get_blog_services
94.87% covered (success)
94.87%
37 / 39
0.00% covered (danger)
0.00%
0 / 1
19.05
 get_service
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
4.12
 set_global_options
76.19% covered (warning)
76.19%
32 / 42
0.00% covered (danger)
0.00%
0 / 1
19.46
 get_global_options
52.38% covered (warning)
52.38%
11 / 21
0.00% covered (danger)
0.00%
0 / 1
31.25
 set_service
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 get_total
33.33% covered (danger)
33.33%
5 / 15
0.00% covered (danger)
0.00%
0 / 1
16.67
 get_site_totals_by_service
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 get_services_total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 get_posts_total
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
Sharing_Service_Total
88.89% covered (warning)
88.89%
8 / 9
50.00% covered (danger)
50.00%
1 / 2
4.02
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 cmp
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
Sharing_Post_Total
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 2
12
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 cmp
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Utilities to register and interact with a sharing service.
4 *
5 * Sharing_Service gets info about a service.
6 * Sharing_Service_Total and Sharing_Post_Total get stats data.
7 *
8 * @package automattic/jetpack
9 *
10 * phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
11 */
12
13// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move classes to appropriately-named class files.
14
15use Automattic\Jetpack\Assets;
16use Automattic\Jetpack\Sync\Settings;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit( 0 );
20}
21
22require_once __DIR__ . '/sharing-sources.php';
23
24define( 'WP_SHARING_PLUGIN_VERSION', JETPACK__VERSION );
25
26/**
27 * Interact with a sharing service.
28 */
29class Sharing_Service {
30    /**
31     * Should the service be available globally?
32     *
33     * @var bool
34     */
35    private $global = false;
36
37    /**
38     * Default sharing label.
39     *
40     * @var string
41     */
42    public $default_sharing_label = '';
43
44    /**
45     * Initialize the sharing service.
46     * Only run this method once upon module loading.
47     *
48     * @return void
49     */
50    public static function init() {
51        add_filter( 'the_content', 'sharing_display', 19 );
52        add_filter( 'the_excerpt', 'sharing_display', 19 );
53    }
54
55    /**
56     * Constructor.
57     */
58    public function __construct() {
59        $this->default_sharing_label = __( 'Share this:', 'jetpack' );
60    }
61
62    /**
63     * Gets a generic list of all services, without any config
64     *
65     * @return array
66     */
67    public function get_all_services_blog() {
68        $options  = get_option( 'sharing-options' );
69        $all      = $this->get_all_services();
70        $services = array();
71
72        foreach ( $all as $id => $name ) {
73            if ( isset( $all[ $id ] ) ) {
74                $config = array();
75
76                // Pre-load custom modules otherwise they won't know who they are
77                if ( str_starts_with( $id, 'custom-' ) && is_array( $options[ $id ] ) ) {
78                    $config = $options[ $id ];
79                }
80
81                $services[ $id ] = new $all[ $id ]( $id, $config );
82            }
83        }
84
85        return $services;
86    }
87
88    /**
89     * Gets a list of all available service names and classes
90     *
91     * @param bool $include_custom Include custom sharing services.
92     *
93     * @return array
94     */
95    public function get_all_services( $include_custom = true ) {
96        // Default services
97        // if you update this list, please update the REST API tests
98        // in bin/tests/api/suites/SharingTest.php
99        $services = array(
100            'print'            => 'Share_Print',
101            'email'            => 'Share_Email',
102            'facebook'         => 'Share_Facebook',
103            'linkedin'         => 'Share_LinkedIn',
104            'reddit'           => 'Share_Reddit',
105            'twitter'          => 'Share_Twitter',
106            'tumblr'           => 'Share_Tumblr',
107            'pinterest'        => 'Share_Pinterest',
108            'telegram'         => 'Share_Telegram',
109            'threads'          => 'Share_Threads',
110            'jetpack-whatsapp' => 'Jetpack_Share_WhatsApp',
111            'mastodon'         => 'Share_Mastodon',
112            'nextdoor'         => 'Share_Nextdoor',
113            'x'                => 'Share_X',
114            'bluesky'          => 'Share_Bluesky',
115        );
116
117        if ( is_multisite() && is_plugin_active( 'press-this/press-this-plugin.php' ) ) {
118            $services['press-this'] = 'Share_PressThis';
119        }
120
121        if ( $include_custom ) {
122            // Add any custom services in
123            $options = $this->get_global_options();
124            if ( isset( $options['custom'] ) ) {
125                foreach ( $options['custom'] as $custom_id ) {
126                    $services[ $custom_id ] = 'Share_Custom';
127                }
128            }
129        }
130
131        /**
132         * Filters the list of available Sharing Services.
133         *
134         * @module sharedaddy
135         *
136         * @since 1.1.0
137         *
138         * @param array $services Array of all available Sharing Services.
139         */
140        return apply_filters( 'sharing_services', $services );
141    }
142
143    /**
144     * Save a new custom sharing service.
145     *
146     * @param string $label Service name.
147     * @param string $url   Service sharing URL.
148     * @param string $icon  Service icon.
149     *
150     * @return bool|Share_Custom
151     */
152    public function new_service( $label, $url, $icon ) {
153        // Validate.
154        $label = trim( wp_html_excerpt( wp_kses( $label, array() ), 30 ) );
155        $url   = trim( esc_url_raw( $url ) );
156        $icon  = trim( esc_url_raw( $icon ) );
157
158        if ( $label && $url && $icon ) {
159            $options = get_option( 'sharing-options' );
160            if ( ! is_array( $options ) ) {
161                $options = array();
162            }
163
164            $service_id = 'custom-' . time();
165
166            // Add a new custom service
167            $options['global']['custom'][] = $service_id;
168            if ( false !== $this->global ) {
169                $this->global['custom'][] = $service_id;
170            }
171
172            update_option( 'sharing-options', $options );
173
174            // Create a custom service and set the options for it
175            $service = new Share_Custom(
176                $service_id,
177                array(
178                    'name' => $label,
179                    'url'  => $url,
180                    'icon' => $icon,
181                )
182            );
183            $this->set_service( $service_id, $service );
184
185            // Return the service
186            return $service;
187        }
188
189        return false;
190    }
191
192    /**
193     * Delete a sharing service.
194     *
195     * @param string $service_id Service ID.
196     *
197     * @return bool
198     */
199    public function delete_service( $service_id ) {
200        $options = get_option( 'sharing-options' );
201        if ( isset( $options[ $service_id ] ) ) {
202            unset( $options[ $service_id ] );
203        }
204
205        $key = array_search( $service_id, $options['global']['custom'], true );
206        if ( $key !== false ) {
207            unset( $options['global']['custom'][ $key ] );
208        }
209
210        update_option( 'sharing-options', $options );
211        return true;
212    }
213
214    /**
215     * Save enabled sharing services.
216     *
217     * @param array $visible Visible sharing services.
218     * @param array $hidden  Hidden sharing services (available under a dropdown).
219     *
220     * @return bool
221     */
222    public function set_blog_services( array $visible, array $hidden ) {
223        $services = $this->get_all_services();
224        // Validate the services
225        $available = array_keys( $services );
226
227        // Only allow services that we have defined
228        $hidden  = array_intersect( $hidden, $available );
229        $visible = array_intersect( $visible, $available );
230
231        // Ensure we don't have the same ones in hidden and visible
232        $hidden = array_diff( $hidden, $visible );
233
234        /**
235         * Control the state of the list of sharing services.
236         *
237         * @module sharedaddy
238         *
239         * @since 1.1.0
240         *
241         * @param array $args {
242         *  Array of options describing the state of the sharing services.
243         *
244         *  @type array $services List of all available service names and classes.
245         *  @type array $available Validated list of all available service names and classes.
246         *  @type array $hidden List of services hidden behind a "More" button.
247         *  @type array $visible List of visible services.
248         *  @type array $this->get_blog_services() Array of Sharing Services currently enabled.
249         * }
250         */
251        do_action(
252            'sharing_get_services_state',
253            array(
254                'services'          => $services,
255                'available'         => $available,
256                'hidden'            => $hidden,
257                'visible'           => $visible,
258                'currently_enabled' => $this->get_blog_services(),
259            )
260        );
261
262        return update_option(
263            'sharing-services',
264            array(
265                'visible' => $visible,
266                'hidden'  => $hidden,
267            )
268        );
269    }
270
271    /**
272     * Get information about enabled sharing services on the site.
273     *
274     * @return array
275     */
276    public function get_blog_services() {
277        $options  = get_option( 'sharing-options' );
278        $enabled  = get_option( 'sharing-services' );
279        $services = $this->get_all_services();
280
281        /**
282         * Check if options exist and are well formatted.
283         * This avoids issues on sites with corrupted options.
284         *
285         * @see https://github.com/Automattic/jetpack/issues/6121
286         */
287        if ( ! is_array( $options ) || ! isset( $options['button_style'] ) || ! isset( $options['global'] ) ) {
288            $global_options = array( 'global' => $this->get_global_options() );
289            $options        = is_array( $options )
290                ? array_merge( $options, $global_options )
291                : $global_options;
292        }
293
294        $global = $options['global'];
295
296        // Default services
297        if ( ! is_array( $enabled ) ) {
298            $enabled = array(
299                'visible' => array(
300                    'facebook',
301                    'x',
302                ),
303                'hidden'  => array(),
304            );
305
306            /**
307             * Filters the list of default Sharing Services.
308             *
309             * @module sharedaddy
310             *
311             * @since 1.1.0
312             *
313             * @param array $enabled Array of default Sharing Services.
314             */
315            $enabled = apply_filters( 'sharing_default_services', $enabled );
316        }
317
318        // Cleanup after any filters that may have produced duplicate services
319        if ( isset( $enabled['visible'] ) && is_array( $enabled['visible'] ) ) {
320            $enabled['visible'] = array_unique( $enabled['visible'] );
321        } else {
322            $enabled['visible'] = array();
323        }
324
325        if ( isset( $enabled['hidden'] ) && is_array( $enabled['hidden'] ) ) {
326            $enabled['hidden'] = array_unique( $enabled['hidden'] );
327        } else {
328            $enabled['hidden'] = array();
329        }
330
331        // Form the enabled services
332        $blog = array(
333            'visible' => array(),
334            'hidden'  => array(),
335        );
336
337        foreach ( $blog as $area => $stuff ) {
338            foreach ( (array) $enabled[ $area ] as $service ) {
339                if ( isset( $services[ $service ] ) ) {
340                    if ( ! isset( $options[ $service ] ) || ! is_array( $options[ $service ] ) ) {
341                        $options[ $service ] = array();
342                    }
343                    $blog[ $area ][ $service ] = new $services[ $service ]( $service, array_merge( $global, $options[ $service ] ) );
344                }
345            }
346        }
347
348        /**
349         * Filters the list of enabled Sharing Services.
350         *
351         * @module sharedaddy
352         *
353         * @since 1.1.0
354         *
355         * @param array $blog Array of enabled Sharing Services.
356         */
357        $blog = apply_filters( 'sharing_services_enabled', $blog );
358
359        // Add CSS for NASCAR
360        if ( ( is_countable( $blog['visible'] ) && count( $blog['visible'] ) ) || ( is_countable( $blog['hidden'] ) && count( $blog['hidden'] ) ) ) {
361            add_filter( 'post_flair_block_css', 'post_flair_service_enabled_sharing' );
362        }
363
364        // Convenience for checking if a service is present
365        $blog['all'] = array_flip( array_merge( array_keys( $blog['visible'] ), array_keys( $blog['hidden'] ) ) );
366        return $blog;
367    }
368
369    /**
370     * Get information about a specific enabled sharing service.
371     *
372     * @param string $service_name Service name.
373     *
374     * @return bool|Sharing_Source
375     */
376    public function get_service( $service_name ) {
377        $services = $this->get_blog_services();
378
379        if ( isset( $services['visible'][ $service_name ] ) ) {
380            return $services['visible'][ $service_name ];
381        }
382
383        if ( isset( $services['hidden'][ $service_name ] ) ) {
384            return $services['hidden'][ $service_name ];
385        }
386
387        return false;
388    }
389
390    /**
391     * Update global sharing options.
392     *
393     * @param array $data Array of new sharing options to save.
394     */
395    public function set_global_options( $data ) {
396        $options = get_option( 'sharing-options' );
397
398        // No options yet.
399        if ( ! is_array( $options ) ) {
400            $options = array();
401        }
402
403        $placement_saved = isset( $options['global']['show'] );
404
405        // Defaults.
406        $options['global'] = array(
407            'button_style'  => 'icon-text',
408            'sharing_label' => $this->default_sharing_label,
409            'open_links'    => 'same',
410            'show'          => $placement_saved ? array() : array( 'post', 'page' ),
411            'custom'        => $options['global']['custom'] ?? array(),
412        );
413
414        /**
415         * Filters global sharing settings.
416         *
417         * @module sharedaddy
418         *
419         * @since 1.1.0
420         *
421         * @param array $options['global'] Array of global sharing settings.
422         */
423        $options['global'] = apply_filters( 'sharing_default_global', $options['global'] );
424
425        // Validate options and set from our data
426        if (
427            isset( $data['button_style'] )
428            && in_array( $data['button_style'], array( 'icon-text', 'icon', 'text', 'official' ), true )
429        ) {
430            $options['global']['button_style'] = $data['button_style'];
431        }
432
433        if ( isset( $data['sharing_label'] ) ) {
434            if ( $this->default_sharing_label === $data['sharing_label'] ) {
435                $options['global']['sharing_label'] = false;
436            } else {
437                $options['global']['sharing_label'] = trim( wp_kses( stripslashes( $data['sharing_label'] ), array() ) );
438            }
439        }
440
441        if (
442            isset( $data['open_links'] )
443            && in_array( $data['open_links'], array( 'new', 'same' ), true )
444        ) {
445            $options['global']['open_links'] = $data['open_links'];
446        }
447
448        $shows   = array_values( get_post_types( array( 'public' => true ) ) );
449        $shows[] = 'index';
450        if ( isset( $data['show'] ) ) {
451            if ( is_scalar( $data['show'] ) ) {
452                switch ( $data['show'] ) {
453                    case 'posts':
454                        $data['show'] = array( 'post', 'page' );
455                        break;
456                    case 'index':
457                        $data['show'] = array( 'index' );
458                        break;
459                    case 'posts-index':
460                        $data['show'] = array( 'post', 'page', 'index' );
461                        break;
462                }
463            }
464
465            $options['global']['show'] = array_intersect( $data['show'], $shows );
466            $placement_saved           = true;
467        }
468
469        // Store no placement until one is chosen, so Likes keeps its own default; get_global_options() falls back to posts and pages.
470        if ( ! $placement_saved && array( 'post', 'page' ) === ( $options['global']['show'] ?? null ) ) {
471            unset( $options['global']['show'] );
472        }
473
474        update_option( 'sharing-options', $options );
475        return $options['global'];
476    }
477
478    /**
479     * Get global sharing options for the site.
480     *
481     * @return array
482     */
483    public function get_global_options() {
484        if ( $this->global === false ) {
485            $options = get_option( 'sharing-options' );
486
487            if ( is_array( $options ) && isset( $options['global'] ) && is_array( $options['global'] ) ) {
488                $this->global = $options['global'];
489            } else {
490                $this->global = $this->set_global_options( $options );
491            }
492        }
493
494        if ( ! isset( $this->global['show'] ) ) {
495            $this->global['show'] = array( 'post', 'page' );
496        } elseif ( is_scalar( $this->global['show'] ) ) {
497            switch ( $this->global['show'] ) {
498                case 'posts':
499                    $this->global['show'] = array( 'post', 'page' );
500                    break;
501                case 'index':
502                    $this->global['show'] = array( 'index' );
503                    break;
504                case 'posts-index':
505                    $this->global['show'] = array( 'post', 'page', 'index' );
506                    break;
507            }
508        }
509
510        if ( ! isset( $this->global['sharing_label'] ) || false === $this->global['sharing_label'] || $this->global['sharing_label'] === 'Share this:' ) {
511            $this->global['sharing_label'] = $this->default_sharing_label;
512        }
513
514        return $this->global;
515    }
516
517    /**
518     * Save a sharing service for use.
519     *
520     * @param string                  $id Sharing unique ID.
521     * @param Sharing_Advanced_Source $service Sharing service.
522     *
523     * @return void
524     */
525    public function set_service( $id, Sharing_Advanced_Source $service ) {
526        // Update the options for this service
527        $options = get_option( 'sharing-options' );
528
529        // No options yet
530        if ( ! is_array( $options ) ) {
531            $options = array();
532        }
533
534        /**
535         * Get the state of a sharing button.
536         *
537         * @module sharedaddy
538         *
539         * @since 1.1.0
540         *
541         * @param array $args {
542         *  State of a sharing button.
543         *
544         *  @type string $id Service ID.
545         *  @type array $options Array of all sharing options.
546         *  @type array $service Details about a service.
547         * }
548         */
549        do_action(
550            'sharing_get_button_state',
551            array(
552                'id'      => $id,
553                'options' => $options,
554                'service' => $service,
555            )
556        );
557
558        $options[ $id ] = $service->get_options();
559
560        update_option( 'sharing-options', array_filter( $options ) );
561    }
562
563    /**
564     * Get stats for a site, a post, or a sharing service.
565     * Soon to come to a .org plugin near you!
566     *
567     * @param string|bool $service_name Service name.
568     * @param int|bool    $post_id      Post ID.
569     * @param int|bool    $_blog_id     Blog ID.
570     *
571     * @return int
572     */
573    public function get_total( $service_name = false, $post_id = false, $_blog_id = false ) {
574        global $wpdb, $blog_id;
575        if ( ! $_blog_id ) {
576            $_blog_id = $blog_id;
577        }
578        if ( ! ( $post_id > 0 ) ) {
579            $totals = $this->get_site_totals_by_service( $_blog_id );
580            return false === $service_name ? array_sum( $totals ) : ( $totals[ $service_name ] ?? 0 );
581        }
582        if ( $service_name === false ) {
583            // total number of shares for this post
584            $sql       = $wpdb->prepare( 'SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND post_id = %d', $_blog_id, $post_id );
585            $cache_key = "sharing_service_get_total_b{$_blog_id}_p{$post_id}";
586        } else {
587            $sql       = $wpdb->prepare( 'SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND post_id = %d AND share_service = %s', $_blog_id, $post_id, $service_name );
588            $cache_key = "sharing_service_get_total_b{$_blog_id}_p{$post_id}_s{$service_name}";
589        }
590
591        $ret = wp_cache_get( $cache_key, 'sharing' );
592        if ( $ret === false ) {
593            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery -- Prepared above.
594            $ret = (int) $wpdb->get_var( $sql );
595            wp_cache_set( $cache_key, $ret, 'sharing', 5 * MINUTE_IN_SECONDS );
596        }
597        return $ret;
598    }
599
600    /**
601     * Share counts for the whole site, per service.
602     *
603     * A site-wide read of sharing_stats scans all of the site's rows, so all services are read in one query and cached for an hour.
604     *
605     * @param int $blog_id Blog ID.
606     * @return int[] Service ID => shares.
607     */
608    private function get_site_totals_by_service( $blog_id ) {
609        global $wpdb;
610
611        $cache_key = "sharing_service_get_site_totals_by_service_b{$blog_id}";
612        $totals    = wp_cache_get( $cache_key, 'sharing' );
613        if ( false === $totals ) {
614            $totals = array();
615            $rows   = $wpdb->get_results( $wpdb->prepare( 'SELECT share_service, SUM( count ) AS total FROM sharing_stats WHERE blog_id = %d GROUP BY share_service', $blog_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Cached in the sharing group.
616            foreach ( (array) $rows as $row ) {
617                $totals[ $row->share_service ] = (int) $row->total;
618            }
619            wp_cache_set( $cache_key, $totals, 'sharing', HOUR_IN_SECONDS );
620        }
621        return $totals;
622    }
623
624    /**
625     * Get total stats for a site, for all sharing services.
626     *
627     * @param int|bool $post_id Post ID.
628     *
629     * @return array
630     */
631    public function get_services_total( $post_id = false ) {
632        $totals   = array();
633        $services = $this->get_blog_services();
634
635        if ( ! empty( $services ) && isset( $services['all'] ) ) {
636            foreach ( $services['all'] as $key => $value ) {
637                $totals[ $key ] = new Sharing_Service_Total( $key, $this->get_total( $key, $post_id ) );
638            }
639        }
640        usort( $totals, array( 'Sharing_Service_Total', 'cmp' ) );
641
642        return $totals;
643    }
644
645    /**
646     * Get sharing stats for all posts on the site.
647     *
648     * @return array
649     */
650    public function get_posts_total() {
651        $totals = array();
652        global $wpdb, $blog_id;
653
654        $cache_key = "sharing_service_get_posts_total_{$blog_id}";
655        $my_data   = wp_cache_get( $cache_key, 'sharing' );
656        if ( $my_data === false ) {
657            $my_data = $wpdb->get_results( $wpdb->prepare( 'SELECT post_id as id, SUM( count ) as total FROM sharing_stats WHERE blog_id = %d GROUP BY post_id ORDER BY count DESC ', $blog_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
658            wp_cache_set( $cache_key, $my_data, 'sharing', 5 * MINUTE_IN_SECONDS );
659        }
660
661        if ( ! empty( $my_data ) ) {
662            foreach ( $my_data as $row ) {
663                $totals[] = new Sharing_Post_Total( $row->id, $row->total );
664            }
665        }
666
667        usort( $totals, array( 'Sharing_Post_Total', 'cmp' ) );
668
669        return $totals;
670    }
671}
672
673/**
674 * Get stats for a specific sharing service.
675 */
676class Sharing_Service_Total {
677    /**
678     * Sharing service ID.
679     *
680     * @var int
681     */
682    public $id = '';
683
684    /**
685     * Service name.
686     *
687     * @var string
688     */
689    public $name = '';
690
691    /**
692     * Sharing service name.
693     *
694     * @var string
695     */
696    public $service = '';
697
698    /**
699     * Total number of shares for this service.
700     *
701     * @var string
702     */
703    public $total = 0;
704
705    /**
706     * Constructor.
707     *
708     * @param int $id      Service ID.
709     * @param int $total   Total shares.
710     */
711    public function __construct( $id, $total ) {
712        $services      = new Sharing_Service();
713        $this->id      = esc_html( $id );
714        $this->service = $services->get_service( $id );
715        $this->total   = (int) $total;
716
717        if ( $this->service instanceof Sharing_Source ) {
718            $this->name = $this->service->get_name();
719        }
720    }
721
722    /**
723     * Compare total shares between 2 posts.
724     *
725     * @param object $a Sharing_Service_Total object.
726     * @param object $b Sharing_Service_Total object.
727     *
728     * @return int -1, 0, or 1 if $a is <, =, or > $b
729     */
730    public static function cmp( $a, $b ) {
731        if ( $a->total === $b->total ) {
732            return $b->name <=> $a->name;
733        }
734        return $b->total <=> $a->total;
735    }
736}
737
738/**
739 * Get sharing stats for a specific post.
740 */
741class Sharing_Post_Total {
742    /**
743     * Sharing service ID.
744     *
745     * @var int
746     */
747    public $id = 0;
748
749    /**
750     * Total shares.
751     *
752     * @var int
753     */
754    public $total = 0;
755
756    /**
757     * Post title.
758     *
759     * @var string
760     */
761    public $title = '';
762
763    /**
764     * Post permalink.
765     *
766     * @var string
767     */
768    public $url = '';
769
770    /**
771     * Constructor.
772     *
773     * @param int $id      Service ID.
774     * @param int $total   Total shares.
775     */
776    public function __construct( $id, $total ) {
777        $this->id    = (int) $id;
778        $this->total = (int) $total;
779        $this->title = get_the_title( $this->id );
780        $this->url   = get_permalink( $this->id );
781    }
782
783    /**
784     * Compare total shares between 2 posts.
785     *
786     * @param object $a Sharing_Post_Total object.
787     * @param object $b Sharing_Post_Total object.
788     *
789     * @return int -1, 0, or 1 if $a is <, =, or > $b
790     */
791    public static function cmp( $a, $b ) {
792        if ( $a->total === $b->total ) {
793            return $b->id <=> $a->id;
794        }
795        return $b->total <=> $a->total;
796    }
797}
798
799/**
800 * Populate sharing counts global with a post we want to count shares for.
801 *
802 * @param int $post_id Post ID.
803 *
804 * @return void
805 */
806function sharing_register_post_for_share_counts( $post_id ) {
807    global $jetpack_sharing_counts;
808
809    if ( ! isset( $jetpack_sharing_counts ) || ! is_array( $jetpack_sharing_counts ) ) {
810        $jetpack_sharing_counts = array();
811    }
812
813    $jetpack_sharing_counts[ (int) $post_id ] = get_permalink( $post_id );
814}
815
816/**
817 * Determine whether we should load sharing scripts or not.
818 *
819 * @return bool
820 */
821function sharing_maybe_enqueue_scripts() {
822    $sharer         = new Sharing_Service();
823    $global_options = $sharer->get_global_options();
824
825    $enqueue = false;
826    if ( is_singular() && in_array( get_post_type(), $global_options['show'], true ) ) {
827        $enqueue = true;
828    } elseif (
829        in_array( 'index', $global_options['show'], true )
830        && (
831            is_home()
832            || is_front_page()
833            || is_archive()
834            || is_search()
835            || in_array( get_post_type(), $global_options['show'], true )
836        )
837    ) {
838        $enqueue = true;
839    }
840
841    /**
842     * Filter to decide when sharing scripts should be enqueued.
843     *
844     * @module sharedaddy
845     *
846     * @since 3.2.0
847     *
848     * @param bool $enqueue Decide if the sharing scripts should be enqueued.
849     */
850    return (bool) apply_filters( 'sharing_enqueue_scripts', $enqueue );
851}
852
853/**
854 * Add sharing JavaScript to the footer of a page.
855 *
856 * @return void
857 */
858function sharing_add_footer() {
859    if (
860        class_exists( 'Jetpack_AMP_Support' )
861        && Jetpack_AMP_Support::is_amp_request()
862    ) {
863        return;
864    }
865
866    global $jetpack_sharing_counts;
867
868    if (
869        /**
870         * Filter all JavaScript output by the sharing module.
871         *
872         * @module sharedaddy
873         *
874         * @since 1.1.0
875         *
876         * @param bool true Control whether the sharing module should add any JavaScript to the site. Default to true.
877         */
878        apply_filters( 'sharing_js', true )
879        && sharing_maybe_enqueue_scripts()
880    ) {
881        if (
882            /**
883             * Filter the display of sharing counts next to the sharing buttons.
884             *
885             * @module sharedaddy
886             *
887             * @since 3.2.0
888             *
889             * @param bool true Control the display of counters next to the sharing buttons. Default to true.
890             */
891            apply_filters( 'jetpack_sharing_counts', true )
892            && is_array( $jetpack_sharing_counts )
893            && count( $jetpack_sharing_counts )
894        ) :
895            $sharing_post_urls = array_filter( $jetpack_sharing_counts );
896            if ( $sharing_post_urls ) :
897                ?>
898
899    <script type="text/javascript">
900        window.WPCOM_sharing_counts = <?php echo wp_json_encode( array_flip( $sharing_post_urls ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
901    </script>
902                <?php
903            endif;
904        endif;
905
906        wp_enqueue_script( 'sharing-js' );
907        $sharing_js_options = array(
908            'lang'            => get_base_recaptcha_lang_code(),
909            /** This filter is documented in modules/sharedaddy/sharing-service.php */
910            'counts'          => apply_filters( 'jetpack_sharing_counts', true ),
911            'is_stats_active' => Jetpack::is_module_active( 'stats' ),
912        );
913        wp_localize_script( 'sharing-js', 'sharing_js_options', $sharing_js_options );
914    }
915    $sharer  = new Sharing_Service();
916    $enabled = $sharer->get_blog_services();
917    foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) as $service ) {
918        $service->display_footer();
919    }
920}
921
922/**
923 * Enqueue sharing CSS in head.
924 *
925 * @return void
926 */
927function sharing_add_header() {
928    $sharer  = new Sharing_Service();
929    $enabled = $sharer->get_blog_services();
930
931    foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) as $service ) {
932        $service->display_header();
933    }
934
935    if ( is_countable( $enabled['all'] ) && ( count( $enabled['all'] ) > 0 ) && sharing_maybe_enqueue_scripts() ) {
936        wp_enqueue_style( 'sharedaddy', plugin_dir_url( __FILE__ ) . 'sharing.css', array(), JETPACK__VERSION );
937        wp_enqueue_style( 'social-logos' );
938    }
939}
940add_action( 'wp_head', 'sharing_add_header', 1 );
941
942/**
943 * Launch sharing requests on page load when a specific query string is used.
944 *
945 * @return void
946 */
947function sharing_process_requests() {
948    global $post;
949
950    // Only process if: single post and share=X defined
951    if ( $post instanceof WP_Post && ( is_page() || is_single() ) && isset( $_GET['share'] ) && is_string( $_GET['share'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
952        $sharer = new Sharing_Service();
953
954        $service = $sharer->get_service( sanitize_text_field( wp_unslash( $_GET['share'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
955        if ( $service ) {
956            $service->process_request( $post, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
957        }
958    }
959}
960
961// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking for the data being present.
962if ( isset( $_GET['share'] ) ) {
963    add_action( 'template_redirect', 'sharing_process_requests', 9 );
964}
965
966/**
967 * Gets the url to customise the sharing buttons in WP-Admin.
968 *
969 * @return string the customisation URL.
970 */
971function get_sharing_buttons_customisation_url() {
972    return admin_url( 'options-general.php?page=sharing' );
973}
974
975/**
976 * Append sharing links to text.
977 *
978 * @param string $text The original text to append sharing links onto.
979 * @param bool   $echo Where to echo the text or return.
980 *
981 * @return string The original $text with, if conditions are met, the sharing links.
982 */
983function sharing_display( $text = '', $echo = false ) {
984    global $post, $wp_current_filter;
985
986    if ( Settings::is_syncing() ) {
987        return $text;
988    }
989
990    // We require the post to not be empty and be an actual WordPress post object. If it's not - we just return.
991    if ( empty( $post ) || ! $post instanceof \WP_Post ) {
992        return $text;
993    }
994
995    if ( ( is_preview() || is_admin() ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
996        return $text;
997    }
998
999    // Prevent from rendering sharing buttons in block which is fetched from REST endpoint by editor
1000    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
1001        return $text;
1002    }
1003
1004    // Do not output sharing buttons for ActivityPub requests.
1005    if (
1006        function_exists( '\Activitypub\is_activitypub_request' )
1007        && \Activitypub\is_activitypub_request()
1008    ) {
1009        return $text;
1010    }
1011
1012    // Don't output flair on excerpts.
1013    if ( in_array( 'get_the_excerpt', (array) $wp_current_filter, true ) ) {
1014        return $text;
1015    }
1016
1017    // Ensure we don't display sharing buttons on post excerpts that are hooked inside the post content
1018    if ( in_array( 'the_excerpt', (array) $wp_current_filter, true ) &&
1019        in_array( 'the_content', (array) $wp_current_filter, true ) ) {
1020        return $text;
1021    }
1022
1023    // Don't allow flair to be added to the_content more than once (prevent infinite loops).
1024    $done = false;
1025    foreach ( $wp_current_filter as $filter ) {
1026        if ( 'the_content' === $filter ) {
1027            if ( $done ) {
1028                return $text;
1029            } else {
1030                $done = true;
1031            }
1032        }
1033    }
1034
1035    // check whether we are viewing the front page and whether the front page option is checked.
1036    $options         = get_option( 'sharing-options' );
1037    $display_options = null;
1038
1039    if ( is_array( $options ) ) {
1040        $display_options = $options['global']['show'] ?? array( 'post', 'page' );
1041    }
1042
1043    if ( is_front_page() && ( is_array( $display_options ) && ! in_array( 'index', $display_options, true ) ) ) {
1044        return $text;
1045    }
1046
1047    if ( is_attachment() && in_array( 'the_excerpt', (array) $wp_current_filter, true ) ) {
1048        // Many themes run the_excerpt() conditionally on an attachment page, then run the_content().
1049        // We only want to output the sharing buttons once.  Let's stick with the_content().
1050        return $text;
1051    }
1052
1053    $sharer = new Sharing_Service();
1054    $global = $sharer->get_global_options();
1055
1056    $show = false;
1057    if ( ! is_feed() ) {
1058        if ( is_singular() && in_array( get_post_type(), $global['show'], true ) ) {
1059            $show = true;
1060        } elseif ( in_array( 'index', $global['show'], true ) && ( is_home() || is_front_page() || is_archive() || is_search() || in_array( get_post_type(), $global['show'], true ) ) ) {
1061            $show = true;
1062        }
1063    }
1064
1065    /**
1066     * Filter to decide if sharing buttons should be displayed.
1067     *
1068     * @module sharedaddy
1069     *
1070     * @since 1.1.0
1071     *
1072     * @param bool $show Should the sharing buttons be displayed.
1073     * @param WP_Post $post The post to share.
1074     */
1075    $show = apply_filters( 'sharing_show', $show, $post );
1076
1077    // Disabled for this post?
1078    $switched_status = get_post_meta( $post->ID, 'sharing_disabled', false );
1079
1080    if ( ! empty( $switched_status ) ) {
1081        $show = false;
1082    }
1083
1084    // Is the post private?
1085    $post_status = get_post_status( $post->ID );
1086
1087    if ( 'private' === $post_status ) {
1088        $show = false;
1089    }
1090
1091    // Hide on password protected posts unless password is provided.
1092    if ( post_password_required( $post->ID ) ) {
1093            $show = false;
1094    }
1095
1096    /**
1097     * Filter the Sharing buttons' Ajax action name Jetpack checks for.
1098     * This allows the use of the buttons with your own Ajax implementation.
1099     *
1100     * @module sharedaddy
1101     *
1102     * @since 7.3.0
1103     *
1104     * @param string $sharing_ajax_action_name Name of the Sharing buttons' Ajax action.
1105     */
1106    $ajax_action = apply_filters( 'sharing_ajax_action', 'get_latest_posts' );
1107
1108    // Allow to be used in ajax requests for latest posts.
1109    if (
1110        defined( 'DOING_AJAX' )
1111        && DOING_AJAX
1112        && isset( $_REQUEST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce handling happens within each custom implementation.
1113        && $ajax_action === $_REQUEST['action'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce handling happens within each custom implementation.
1114    ) {
1115        $show = true;
1116    }
1117
1118    $sharing_content = '';
1119    $enabled         = false;
1120
1121    if ( $show ) {
1122        /**
1123         * Filters the list of enabled Sharing Services.
1124         *
1125         * @module sharedaddy
1126         *
1127         * @since 2.2.3
1128         *
1129         * @param array $sharer->get_blog_services() Array of Sharing Services currently enabled.
1130         */
1131        $enabled = apply_filters( 'sharing_enabled', $sharer->get_blog_services() );
1132
1133        if ( ! empty( $enabled['all'] ) ) {
1134            $dir = get_option( 'text_direction' );
1135
1136            // Wrapper.
1137            $sharing_content .= '<div class="sharedaddy sd-sharing-enabled"><div class="robots-nocontent sd-block sd-social sd-social-' . ( $global['button_style'] ?? 'icon-text' ) . ' sd-sharing">';
1138            if ( '' !== $global['sharing_label'] ) {
1139                $sharing_content .= sprintf(
1140                    /**
1141                     * Filter the sharing buttons' headline structure.
1142                     *
1143                     * @module sharedaddy
1144                     *
1145                     * @since 4.4.0
1146                     *
1147                     * @param string $sharing_headline Sharing headline structure.
1148                     * @param string $global['sharing_label'] Sharing title.
1149                     * @param string $sharing Module name.
1150                     */
1151                    apply_filters( 'jetpack_sharing_headline_html', '<h3 class="sd-title">%s</h3>', $global['sharing_label'], 'sharing' ),
1152                    esc_html( $global['sharing_label'] )
1153                );
1154            }
1155            $sharing_content .= '<div class="sd-content"><ul>';
1156
1157            // Visible items.
1158            $visible = '';
1159            foreach ( $enabled['visible'] as $service ) {
1160                $klasses = array( 'share-' . $service->get_class() );
1161                if ( $service->is_deprecated() ) {
1162                    if ( ! current_user_can( 'manage_options' ) ) {
1163                        continue;
1164                    }
1165                    $klasses[] = 'share-deprecated';
1166                }
1167                // Individual HTML for sharing service.
1168                $visible .= '<li class="' . implode( ' ', $klasses ) . '">' . $service->get_display( $post ) . '</li>';
1169            }
1170
1171            $parts         = array();
1172            $parts[]       = $visible;
1173            $count_hidden  = is_countable( $enabled['hidden'] ) ? count( $enabled['hidden'] ) : 0;
1174            $count_visible = is_countable( $enabled['visible'] ) ? count( $enabled['visible'] ) : 0;
1175            if ( $count_hidden > 0 ) {
1176                if ( $count_visible > 0 ) {
1177                    $expand = __( 'More', 'jetpack' );
1178                } else {
1179                    $expand = __( 'Share', 'jetpack' );
1180                }
1181                $parts[] = '<li><a href="#" class="sharing-anchor sd-button share-more"><span>' . $expand . '</span></a></li>';
1182            }
1183
1184            if ( 'rtl' === $dir ) {
1185                $parts = array_reverse( $parts );
1186            }
1187
1188            $sharing_content .= implode( '', $parts );
1189            $sharing_content .= '<li class="share-end"></li></ul>';
1190
1191            // Link to customization options if user can manage them.
1192            if ( current_user_can( 'manage_options' ) ) {
1193                $link_url = get_sharing_buttons_customisation_url();
1194                if ( ! empty( $link_url ) ) {
1195                    $link_text        = __( 'Customize buttons', 'jetpack' );
1196                    $sharing_content .= '<p class="share-customize-link"><a href="' . esc_url( $link_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $link_text ) . '</a></p>';
1197                }
1198            }
1199
1200            if ( $count_hidden > 0 ) {
1201                $sharing_content .= '<div class="sharing-hidden"><div class="inner" style="display: none;';
1202
1203                if ( $count_hidden === 1 ) {
1204                    $sharing_content .= 'width:150px;';
1205                }
1206
1207                $sharing_content .= '">';
1208
1209                if ( $count_hidden === 1 ) {
1210                    $sharing_content .= '<ul style="background-image:none;">';
1211                } else {
1212                    $sharing_content .= '<ul>';
1213                }
1214
1215                foreach ( $enabled['hidden'] as $service ) {
1216                    // Individual HTML for sharing service.
1217                    $klasses = array( 'share-' . $service->get_class() );
1218                    if ( $service->is_deprecated() ) {
1219                        if ( ! current_user_can( 'manage_options' ) ) {
1220                            continue;
1221                        }
1222                        $klasses[] = 'share-deprecated';
1223                    }
1224                    $sharing_content .= '<li class="' . implode( ' ', $klasses ) . '">';
1225                    $sharing_content .= $service->get_display( $post );
1226                    $sharing_content .= '</li>';
1227                }
1228
1229                // End of wrapper.
1230                $sharing_content .= '<li class="share-end"></li></ul></div></div>';
1231            }
1232
1233            $sharing_content .= '</div></div></div>';
1234
1235            // Register our JS.
1236            if ( defined( 'JETPACK__VERSION' ) ) {
1237                $ver = JETPACK__VERSION;
1238            } else {
1239                $ver = '20211226';
1240            }
1241
1242            // @todo: Investigate if we can load this JS in the footer instead.
1243            wp_register_script(
1244                'sharing-js',
1245                Assets::get_file_url_for_environment(
1246                    '_inc/build/sharedaddy/sharing.min.js',
1247                    'modules/sharedaddy/sharing.js'
1248                ),
1249                array(),
1250                $ver,
1251                false
1252            );
1253
1254            // Enqueue scripts for the footer.
1255            add_action( 'wp_footer', 'sharing_add_footer' );
1256        }
1257    }
1258
1259    /**
1260     * Filters the content markup of the Jetpack sharing links
1261     *
1262     * @module sharedaddy
1263     *
1264     * @since 3.8.0
1265     * @since 6.2.0 Started sending $enabled as a second parameter.
1266     *
1267     * @param string $sharing_content Content markup of the Jetpack sharing links
1268     * @param array  $enabled         Array of Sharing Services currently enabled.
1269     */
1270    $sharing_markup = apply_filters( 'jetpack_sharing_display_markup', $sharing_content, $enabled );
1271
1272    if ( $echo ) {
1273        echo $text . $sharing_markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1274    } else {
1275        return $text . $sharing_markup;
1276    }
1277}
1278
1279/**
1280 * Get reCAPTCHA language code based off the language code of the site.
1281 *
1282 * @return string
1283 */
1284function get_base_recaptcha_lang_code() {
1285    $base_recaptcha_lang_code_mapping = array(
1286        'en'    => 'en',
1287        'nl'    => 'nl',
1288        'fr'    => 'fr',
1289        'fr-be' => 'fr',
1290        'fr-ca' => 'fr',
1291        'fr-ch' => 'fr',
1292        'de'    => 'de',
1293        'pt'    => 'pt',
1294        'pt-br' => 'pt',
1295        'ru'    => 'ru',
1296        'es'    => 'es',
1297        'tr'    => 'tr',
1298    );
1299
1300    $blog_lang_code = get_bloginfo( 'language' );
1301    if ( isset( $base_recaptcha_lang_code_mapping[ $blog_lang_code ] ) ) {
1302        return $base_recaptcha_lang_code_mapping[ $blog_lang_code ];
1303    }
1304
1305    // if no base mapping is found return default 'en'
1306    return 'en';
1307}
1308
1309Sharing_Service::init();