Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
41.49% covered (danger)
41.49%
195 / 470
11.11% covered (danger)
11.11%
3 / 27
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
42
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
188.33
get_base_recaptcha_lang_code
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
Sharing_Service
42.34% covered (danger)
42.34%
105 / 248
13.33% covered (danger)
13.33%
2 / 15
1642.88
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
92.31% covered (success)
92.31%
36 / 39
0.00% covered (danger)
0.00%
0 / 1
19.16
 get_service
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
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
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
 get_services_total
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 get_posts_total
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
Sharing_Service_Total
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 2
20
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 cmp
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
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 ( $service_name === false ) {
579            if ( $post_id > 0 ) {
580                // total number of shares for this post
581                $sql       = $wpdb->prepare( 'SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND post_id = %d', $_blog_id, $post_id );
582                $cache_key = "sharing_service_get_total_b{$_blog_id}_p{$post_id}";
583            } else {
584                // total number of shares for this blog
585                $sql       = $wpdb->prepare( 'SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d', $_blog_id );
586                $cache_key = "sharing_service_get_total_b{$_blog_id}";
587            }
588        } elseif ( $post_id > 0 ) {
589            $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 );
590            $cache_key = "sharing_service_get_total_b{$_blog_id}_p{$post_id}_s{$service_name}";
591        } else {
592            $sql       = $wpdb->prepare( 'SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND share_service = %s', $_blog_id, $service_name );
593            $cache_key = "sharing_service_get_total_b{$_blog_id}_s{$service_name}";
594        }
595
596        $ret = wp_cache_get( $cache_key, 'sharing' );
597        if ( $ret === false ) {
598            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery -- Prepared above.
599            $ret = (int) $wpdb->get_var( $sql );
600            wp_cache_set( $cache_key, $ret, 'sharing', 5 * MINUTE_IN_SECONDS );
601        }
602        return $ret;
603    }
604
605    /**
606     * Get total stats for a site, for all sharing services.
607     *
608     * @param int|bool $post_id Post ID.
609     *
610     * @return array
611     */
612    public function get_services_total( $post_id = false ) {
613        $totals   = array();
614        $services = $this->get_blog_services();
615
616        if ( ! empty( $services ) && isset( $services['all'] ) ) {
617            foreach ( $services['all'] as $key => $value ) {
618                $totals[ $key ] = new Sharing_Service_Total( $key, $this->get_total( $key, $post_id ) );
619            }
620        }
621        usort( $totals, array( 'Sharing_Service_Total', 'cmp' ) );
622
623        return $totals;
624    }
625
626    /**
627     * Get sharing stats for all posts on the site.
628     *
629     * @return array
630     */
631    public function get_posts_total() {
632        $totals = array();
633        global $wpdb, $blog_id;
634
635        $cache_key = "sharing_service_get_posts_total_{$blog_id}";
636        $my_data   = wp_cache_get( $cache_key, 'sharing' );
637        if ( $my_data === false ) {
638            $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
639            wp_cache_set( $cache_key, $my_data, 'sharing', 5 * MINUTE_IN_SECONDS );
640        }
641
642        if ( ! empty( $my_data ) ) {
643            foreach ( $my_data as $row ) {
644                $totals[] = new Sharing_Post_Total( $row->id, $row->total );
645            }
646        }
647
648        usort( $totals, array( 'Sharing_Post_Total', 'cmp' ) );
649
650        return $totals;
651    }
652}
653
654/**
655 * Get stats for a specific sharing service.
656 */
657class Sharing_Service_Total {
658    /**
659     * Sharing service ID.
660     *
661     * @var int
662     */
663    public $id = '';
664
665    /**
666     * Service name.
667     *
668     * @var string
669     */
670    public $name = '';
671
672    /**
673     * Sharing service name.
674     *
675     * @var string
676     */
677    public $service = '';
678
679    /**
680     * Total number of shares for this service.
681     *
682     * @var string
683     */
684    public $total = 0;
685
686    /**
687     * Constructor.
688     *
689     * @param int $id      Service ID.
690     * @param int $total   Total shares.
691     */
692    public function __construct( $id, $total ) {
693        $services      = new Sharing_Service();
694        $this->id      = esc_html( $id );
695        $this->service = $services->get_service( $id );
696        $this->total   = (int) $total;
697
698        if ( $this->service instanceof Sharing_Source ) {
699            $this->name = $this->service->get_name();
700        }
701    }
702
703    /**
704     * Compare total shares between 2 posts.
705     *
706     * @param object $a Sharing_Service_Total object.
707     * @param object $b Sharing_Service_Total object.
708     *
709     * @return int -1, 0, or 1 if $a is <, =, or > $b
710     */
711    public static function cmp( $a, $b ) {
712        if ( $a->total === $b->total ) {
713            return $b->name <=> $a->name;
714        }
715        return $b->total <=> $a->total;
716    }
717}
718
719/**
720 * Get sharing stats for a specific post.
721 */
722class Sharing_Post_Total {
723    /**
724     * Sharing service ID.
725     *
726     * @var int
727     */
728    public $id = 0;
729
730    /**
731     * Total shares.
732     *
733     * @var int
734     */
735    public $total = 0;
736
737    /**
738     * Post title.
739     *
740     * @var string
741     */
742    public $title = '';
743
744    /**
745     * Post permalink.
746     *
747     * @var string
748     */
749    public $url = '';
750
751    /**
752     * Constructor.
753     *
754     * @param int $id      Service ID.
755     * @param int $total   Total shares.
756     */
757    public function __construct( $id, $total ) {
758        $this->id    = (int) $id;
759        $this->total = (int) $total;
760        $this->title = get_the_title( $this->id );
761        $this->url   = get_permalink( $this->id );
762    }
763
764    /**
765     * Compare total shares between 2 posts.
766     *
767     * @param object $a Sharing_Post_Total object.
768     * @param object $b Sharing_Post_Total object.
769     *
770     * @return int -1, 0, or 1 if $a is <, =, or > $b
771     */
772    public static function cmp( $a, $b ) {
773        if ( $a->total === $b->total ) {
774            return $b->id <=> $a->id;
775        }
776        return $b->total <=> $a->total;
777    }
778}
779
780/**
781 * Populate sharing counts global with a post we want to count shares for.
782 *
783 * @param int $post_id Post ID.
784 *
785 * @return void
786 */
787function sharing_register_post_for_share_counts( $post_id ) {
788    global $jetpack_sharing_counts;
789
790    if ( ! isset( $jetpack_sharing_counts ) || ! is_array( $jetpack_sharing_counts ) ) {
791        $jetpack_sharing_counts = array();
792    }
793
794    $jetpack_sharing_counts[ (int) $post_id ] = get_permalink( $post_id );
795}
796
797/**
798 * Determine whether we should load sharing scripts or not.
799 *
800 * @return bool
801 */
802function sharing_maybe_enqueue_scripts() {
803    $sharer         = new Sharing_Service();
804    $global_options = $sharer->get_global_options();
805
806    $enqueue = false;
807    if ( is_singular() && in_array( get_post_type(), $global_options['show'], true ) ) {
808        $enqueue = true;
809    } elseif (
810        in_array( 'index', $global_options['show'], true )
811        && (
812            is_home()
813            || is_front_page()
814            || is_archive()
815            || is_search()
816            || in_array( get_post_type(), $global_options['show'], true )
817        )
818    ) {
819        $enqueue = true;
820    }
821
822    /**
823     * Filter to decide when sharing scripts should be enqueued.
824     *
825     * @module sharedaddy
826     *
827     * @since 3.2.0
828     *
829     * @param bool $enqueue Decide if the sharing scripts should be enqueued.
830     */
831    return (bool) apply_filters( 'sharing_enqueue_scripts', $enqueue );
832}
833
834/**
835 * Add sharing JavaScript to the footer of a page.
836 *
837 * @return void
838 */
839function sharing_add_footer() {
840    if (
841        class_exists( 'Jetpack_AMP_Support' )
842        && Jetpack_AMP_Support::is_amp_request()
843    ) {
844        return;
845    }
846
847    global $jetpack_sharing_counts;
848
849    if (
850        /**
851         * Filter all JavaScript output by the sharing module.
852         *
853         * @module sharedaddy
854         *
855         * @since 1.1.0
856         *
857         * @param bool true Control whether the sharing module should add any JavaScript to the site. Default to true.
858         */
859        apply_filters( 'sharing_js', true )
860        && sharing_maybe_enqueue_scripts()
861    ) {
862        if (
863            /**
864             * Filter the display of sharing counts next to the sharing buttons.
865             *
866             * @module sharedaddy
867             *
868             * @since 3.2.0
869             *
870             * @param bool true Control the display of counters next to the sharing buttons. Default to true.
871             */
872            apply_filters( 'jetpack_sharing_counts', true )
873            && is_array( $jetpack_sharing_counts )
874            && count( $jetpack_sharing_counts )
875        ) :
876            $sharing_post_urls = array_filter( $jetpack_sharing_counts );
877            if ( $sharing_post_urls ) :
878                ?>
879
880    <script type="text/javascript">
881        window.WPCOM_sharing_counts = <?php echo wp_json_encode( array_flip( $sharing_post_urls ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
882    </script>
883                <?php
884            endif;
885        endif;
886
887        wp_enqueue_script( 'sharing-js' );
888        $sharing_js_options = array(
889            'lang'            => get_base_recaptcha_lang_code(),
890            /** This filter is documented in modules/sharedaddy/sharing-service.php */
891            'counts'          => apply_filters( 'jetpack_sharing_counts', true ),
892            'is_stats_active' => Jetpack::is_module_active( 'stats' ),
893        );
894        wp_localize_script( 'sharing-js', 'sharing_js_options', $sharing_js_options );
895    }
896    $sharer  = new Sharing_Service();
897    $enabled = $sharer->get_blog_services();
898    foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) as $service ) {
899        $service->display_footer();
900    }
901}
902
903/**
904 * Enqueue sharing CSS in head.
905 *
906 * @return void
907 */
908function sharing_add_header() {
909    $sharer  = new Sharing_Service();
910    $enabled = $sharer->get_blog_services();
911
912    foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) as $service ) {
913        $service->display_header();
914    }
915
916    if ( is_countable( $enabled['all'] ) && ( count( $enabled['all'] ) > 0 ) && sharing_maybe_enqueue_scripts() ) {
917        wp_enqueue_style( 'sharedaddy', plugin_dir_url( __FILE__ ) . 'sharing.css', array(), JETPACK__VERSION );
918        wp_enqueue_style( 'social-logos' );
919    }
920}
921add_action( 'wp_head', 'sharing_add_header', 1 );
922
923/**
924 * Launch sharing requests on page load when a specific query string is used.
925 *
926 * @return void
927 */
928function sharing_process_requests() {
929    global $post;
930
931    // Only process if: single post and share=X defined
932    if ( ( is_page() || is_single() ) && isset( $_GET['share'] ) && is_string( $_GET['share'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
933        $sharer = new Sharing_Service();
934
935        $service = $sharer->get_service( sanitize_text_field( wp_unslash( $_GET['share'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
936        if ( $service ) {
937            $service->process_request( $post, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
938        }
939    }
940}
941
942// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking for the data being present.
943if ( isset( $_GET['share'] ) ) {
944    add_action( 'template_redirect', 'sharing_process_requests', 9 );
945}
946
947/**
948 * Gets the url to customise the sharing buttons in WP-Admin.
949 *
950 * @return string the customisation URL.
951 */
952function get_sharing_buttons_customisation_url() {
953    return admin_url( 'options-general.php?page=sharing' );
954}
955
956/**
957 * Append sharing links to text.
958 *
959 * @param string $text The original text to append sharing links onto.
960 * @param bool   $echo Where to echo the text or return.
961 *
962 * @return string The original $text with, if conditions are met, the sharing links.
963 */
964function sharing_display( $text = '', $echo = false ) {
965    global $post, $wp_current_filter;
966
967    if ( Settings::is_syncing() ) {
968        return $text;
969    }
970
971    // We require the post to not be empty and be an actual WordPress post object. If it's not - we just return.
972    if ( empty( $post ) || ! $post instanceof \WP_Post ) {
973        return $text;
974    }
975
976    if ( ( is_preview() || is_admin() ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
977        return $text;
978    }
979
980    // Prevent from rendering sharing buttons in block which is fetched from REST endpoint by editor
981    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
982        return $text;
983    }
984
985    // Do not output sharing buttons for ActivityPub requests.
986    if (
987        function_exists( '\Activitypub\is_activitypub_request' )
988        && \Activitypub\is_activitypub_request()
989    ) {
990        return $text;
991    }
992
993    // Don't output flair on excerpts.
994    if ( in_array( 'get_the_excerpt', (array) $wp_current_filter, true ) ) {
995        return $text;
996    }
997
998    // Ensure we don't display sharing buttons on post excerpts that are hooked inside the post content
999    if ( in_array( 'the_excerpt', (array) $wp_current_filter, true ) &&
1000        in_array( 'the_content', (array) $wp_current_filter, true ) ) {
1001        return $text;
1002    }
1003
1004    // Don't allow flair to be added to the_content more than once (prevent infinite loops).
1005    $done = false;
1006    foreach ( $wp_current_filter as $filter ) {
1007        if ( 'the_content' === $filter ) {
1008            if ( $done ) {
1009                return $text;
1010            } else {
1011                $done = true;
1012            }
1013        }
1014    }
1015
1016    // check whether we are viewing the front page and whether the front page option is checked.
1017    $options         = get_option( 'sharing-options' );
1018    $display_options = null;
1019
1020    if ( is_array( $options ) ) {
1021        $display_options = $options['global']['show'] ?? array( 'post', 'page' );
1022    }
1023
1024    if ( is_front_page() && ( is_array( $display_options ) && ! in_array( 'index', $display_options, true ) ) ) {
1025        return $text;
1026    }
1027
1028    if ( is_attachment() && in_array( 'the_excerpt', (array) $wp_current_filter, true ) ) {
1029        // Many themes run the_excerpt() conditionally on an attachment page, then run the_content().
1030        // We only want to output the sharing buttons once.  Let's stick with the_content().
1031        return $text;
1032    }
1033
1034    $sharer = new Sharing_Service();
1035    $global = $sharer->get_global_options();
1036
1037    $show = false;
1038    if ( ! is_feed() ) {
1039        if ( is_singular() && in_array( get_post_type(), $global['show'], true ) ) {
1040            $show = true;
1041        } elseif ( in_array( 'index', $global['show'], true ) && ( is_home() || is_front_page() || is_archive() || is_search() || in_array( get_post_type(), $global['show'], true ) ) ) {
1042            $show = true;
1043        }
1044    }
1045
1046    /**
1047     * Filter to decide if sharing buttons should be displayed.
1048     *
1049     * @module sharedaddy
1050     *
1051     * @since 1.1.0
1052     *
1053     * @param bool $show Should the sharing buttons be displayed.
1054     * @param WP_Post $post The post to share.
1055     */
1056    $show = apply_filters( 'sharing_show', $show, $post );
1057
1058    // Disabled for this post?
1059    $switched_status = get_post_meta( $post->ID, 'sharing_disabled', false );
1060
1061    if ( ! empty( $switched_status ) ) {
1062        $show = false;
1063    }
1064
1065    // Is the post private?
1066    $post_status = get_post_status( $post->ID );
1067
1068    if ( 'private' === $post_status ) {
1069        $show = false;
1070    }
1071
1072    // Hide on password protected posts unless password is provided.
1073    if ( post_password_required( $post->ID ) ) {
1074            $show = false;
1075    }
1076
1077    /**
1078     * Filter the Sharing buttons' Ajax action name Jetpack checks for.
1079     * This allows the use of the buttons with your own Ajax implementation.
1080     *
1081     * @module sharedaddy
1082     *
1083     * @since 7.3.0
1084     *
1085     * @param string $sharing_ajax_action_name Name of the Sharing buttons' Ajax action.
1086     */
1087    $ajax_action = apply_filters( 'sharing_ajax_action', 'get_latest_posts' );
1088
1089    // Allow to be used in ajax requests for latest posts.
1090    if (
1091        defined( 'DOING_AJAX' )
1092        && DOING_AJAX
1093        && isset( $_REQUEST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce handling happens within each custom implementation.
1094        && $ajax_action === $_REQUEST['action'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce handling happens within each custom implementation.
1095    ) {
1096        $show = true;
1097    }
1098
1099    $sharing_content = '';
1100    $enabled         = false;
1101
1102    if ( $show ) {
1103        /**
1104         * Filters the list of enabled Sharing Services.
1105         *
1106         * @module sharedaddy
1107         *
1108         * @since 2.2.3
1109         *
1110         * @param array $sharer->get_blog_services() Array of Sharing Services currently enabled.
1111         */
1112        $enabled = apply_filters( 'sharing_enabled', $sharer->get_blog_services() );
1113
1114        if ( is_countable( $enabled['all'] ) && ( count( $enabled['all'] ) > 0 ) ) {
1115            $dir = get_option( 'text_direction' );
1116
1117            // Wrapper.
1118            $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">';
1119            if ( '' !== $global['sharing_label'] ) {
1120                $sharing_content .= sprintf(
1121                    /**
1122                     * Filter the sharing buttons' headline structure.
1123                     *
1124                     * @module sharedaddy
1125                     *
1126                     * @since 4.4.0
1127                     *
1128                     * @param string $sharing_headline Sharing headline structure.
1129                     * @param string $global['sharing_label'] Sharing title.
1130                     * @param string $sharing Module name.
1131                     */
1132                    apply_filters( 'jetpack_sharing_headline_html', '<h3 class="sd-title">%s</h3>', $global['sharing_label'], 'sharing' ),
1133                    esc_html( $global['sharing_label'] )
1134                );
1135            }
1136            $sharing_content .= '<div class="sd-content"><ul>';
1137
1138            // Visible items.
1139            $visible = '';
1140            foreach ( $enabled['visible'] as $service ) {
1141                $klasses = array( 'share-' . $service->get_class() );
1142                if ( $service->is_deprecated() ) {
1143                    if ( ! current_user_can( 'manage_options' ) ) {
1144                        continue;
1145                    }
1146                    $klasses[] = 'share-deprecated';
1147                }
1148                // Individual HTML for sharing service.
1149                $visible .= '<li class="' . implode( ' ', $klasses ) . '">' . $service->get_display( $post ) . '</li>';
1150            }
1151
1152            $parts         = array();
1153            $parts[]       = $visible;
1154            $count_hidden  = is_countable( $enabled['hidden'] ) ? count( $enabled['hidden'] ) : 0;
1155            $count_visible = is_countable( $enabled['visible'] ) ? count( $enabled['visible'] ) : 0;
1156            if ( $count_hidden > 0 ) {
1157                if ( $count_visible > 0 ) {
1158                    $expand = __( 'More', 'jetpack' );
1159                } else {
1160                    $expand = __( 'Share', 'jetpack' );
1161                }
1162                $parts[] = '<li><a href="#" class="sharing-anchor sd-button share-more"><span>' . $expand . '</span></a></li>';
1163            }
1164
1165            if ( 'rtl' === $dir ) {
1166                $parts = array_reverse( $parts );
1167            }
1168
1169            $sharing_content .= implode( '', $parts );
1170            $sharing_content .= '<li class="share-end"></li></ul>';
1171
1172            // Link to customization options if user can manage them.
1173            if ( current_user_can( 'manage_options' ) ) {
1174                $link_url = get_sharing_buttons_customisation_url();
1175                if ( ! empty( $link_url ) ) {
1176                    $link_text        = __( 'Customize buttons', 'jetpack' );
1177                    $sharing_content .= '<p class="share-customize-link"><a href="' . esc_url( $link_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $link_text ) . '</a></p>';
1178                }
1179            }
1180
1181            if ( $count_hidden > 0 ) {
1182                $sharing_content .= '<div class="sharing-hidden"><div class="inner" style="display: none;';
1183
1184                if ( $count_hidden === 1 ) {
1185                    $sharing_content .= 'width:150px;';
1186                }
1187
1188                $sharing_content .= '">';
1189
1190                if ( $count_hidden === 1 ) {
1191                    $sharing_content .= '<ul style="background-image:none;">';
1192                } else {
1193                    $sharing_content .= '<ul>';
1194                }
1195
1196                foreach ( $enabled['hidden'] as $service ) {
1197                    // Individual HTML for sharing service.
1198                    $klasses = array( 'share-' . $service->get_class() );
1199                    if ( $service->is_deprecated() ) {
1200                        if ( ! current_user_can( 'manage_options' ) ) {
1201                            continue;
1202                        }
1203                        $klasses[] = 'share-deprecated';
1204                    }
1205                    $sharing_content .= '<li class="' . implode( ' ', $klasses ) . '">';
1206                    $sharing_content .= $service->get_display( $post );
1207                    $sharing_content .= '</li>';
1208                }
1209
1210                // End of wrapper.
1211                $sharing_content .= '<li class="share-end"></li></ul></div></div>';
1212            }
1213
1214            $sharing_content .= '</div></div></div>';
1215
1216            // Register our JS.
1217            if ( defined( 'JETPACK__VERSION' ) ) {
1218                $ver = JETPACK__VERSION;
1219            } else {
1220                $ver = '20211226';
1221            }
1222
1223            // @todo: Investigate if we can load this JS in the footer instead.
1224            wp_register_script(
1225                'sharing-js',
1226                Assets::get_file_url_for_environment(
1227                    '_inc/build/sharedaddy/sharing.min.js',
1228                    'modules/sharedaddy/sharing.js'
1229                ),
1230                array(),
1231                $ver,
1232                false
1233            );
1234
1235            // Enqueue scripts for the footer.
1236            add_action( 'wp_footer', 'sharing_add_footer' );
1237        }
1238    }
1239
1240    /**
1241     * Filters the content markup of the Jetpack sharing links
1242     *
1243     * @module sharedaddy
1244     *
1245     * @since 3.8.0
1246     * @since 6.2.0 Started sending $enabled as a second parameter.
1247     *
1248     * @param string $sharing_content Content markup of the Jetpack sharing links
1249     * @param array  $enabled         Array of Sharing Services currently enabled.
1250     */
1251    $sharing_markup = apply_filters( 'jetpack_sharing_display_markup', $sharing_content, $enabled );
1252
1253    if ( $echo ) {
1254        echo $text . $sharing_markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1255    } else {
1256        return $text . $sharing_markup;
1257    }
1258}
1259
1260/**
1261 * Get reCAPTCHA language code based off the language code of the site.
1262 *
1263 * @return string
1264 */
1265function get_base_recaptcha_lang_code() {
1266    $base_recaptcha_lang_code_mapping = array(
1267        'en'    => 'en',
1268        'nl'    => 'nl',
1269        'fr'    => 'fr',
1270        'fr-be' => 'fr',
1271        'fr-ca' => 'fr',
1272        'fr-ch' => 'fr',
1273        'de'    => 'de',
1274        'pt'    => 'pt',
1275        'pt-br' => 'pt',
1276        'ru'    => 'ru',
1277        'es'    => 'es',
1278        'tr'    => 'tr',
1279    );
1280
1281    $blog_lang_code = get_bloginfo( 'language' );
1282    if ( isset( $base_recaptcha_lang_code_mapping[ $blog_lang_code ] ) ) {
1283        return $base_recaptcha_lang_code_mapping[ $blog_lang_code ];
1284    }
1285
1286    // if no base mapping is found return default 'en'
1287    return 'en';
1288}
1289
1290Sharing_Service::init();