Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.17% covered (warning)
75.17%
109 / 145
63.64% covered (warning)
63.64%
7 / 11
CRAP
n/a
0 / 0
Automattic\Jetpack\Extensions\Blogroll\register_block
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Blogroll\load_assets
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
Automattic\Jetpack\Extensions\Blogroll\site_recommendations_settings
97.87% covered (success)
97.87%
46 / 47
0.00% covered (danger)
0.00%
0 / 1
1
Automattic\Jetpack\Extensions\Blogroll\has_opml
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
Automattic\Jetpack\Extensions\Blogroll\get_public_blocks
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
Automattic\Jetpack\Extensions\Blogroll\get_opml_post
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\Extensions\Blogroll\get_opml_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
Automattic\Jetpack\Extensions\Blogroll\get_opml_items
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
14
Automattic\Jetpack\Extensions\Blogroll\get_opml
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\Extensions\Blogroll\serve_opml
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Blogroll\print_opml_link
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Blogroll Block.
4 *
5 * @since 12.1
6 *
7 * @package automattic/jetpack
8 */
9
10namespace Automattic\Jetpack\Extensions\Blogroll;
11
12require_once __DIR__ . '/blogroll-item/blogroll-item.php';
13
14use Automattic\Jetpack\Blocks;
15use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
16use Automattic\Jetpack\Status\Request;
17use Jetpack_Gutenberg;
18
19/**
20 * Registers the block for use in Gutenberg
21 * This is done via an action so that we can disable
22 * registration if we need to.
23 */
24function register_block() {
25    Blocks::jetpack_register_block(
26        __DIR__,
27        array(
28            'render_callback'  => __NAMESPACE__ . '\load_assets',
29            'provides_context' => array(
30                'openLinksNewWindow' => 'open_links_new_window',
31            ),
32        )
33    );
34}
35add_action( 'init', __NAMESPACE__ . '\register_block' );
36
37/**
38 * Blogroll block registration/dependency declaration.
39 *
40 * @param array  $attr    Array containing the Blogroll block attributes.
41 * @param string $content String containing the Blogroll block content.
42 *
43 * @return string
44 */
45function load_assets( $attr, $content ) {
46    global $wp;
47
48    /*
49     * Enqueue necessary scripts and styles.
50     */
51    Jetpack_Gutenberg::load_assets_as_required( __DIR__ );
52    $current_location = home_url( $wp->request );
53    $is_wpcom         = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
54
55    $form_content = <<<HTML
56        <form method="post" action="https://subscribe.wordpress.com" accept-charset="utf-8">
57            <input name="action" type="hidden" value="subscribe">
58            <input name="source" type="hidden" value="$current_location">
59            <input name="sub-type" type="hidden" value="jetpack_blogroll">
60            $content
61        </form>
62HTML;
63
64    $blogroll_content = $is_wpcom && Request::is_frontend() ? $form_content : $content;
65
66    return sprintf(
67        '<div class="%1$s">%2$s</div>',
68        esc_attr( Blocks::classes( FEATURE_NAME, $attr ) ),
69        $blogroll_content
70    );
71}
72
73/**
74 * Register site_recommendations settings
75 *
76 * @since 12.7
77 */
78function site_recommendations_settings() {
79    register_setting(
80        'general',
81        'Blogroll Recommendations', // Visible to the user see: https://github.com/WordPress/gutenberg/issues/41637
82        array(
83            'description'   => __( 'Site Recommendations', 'jetpack' ),
84            'type'          => 'array',
85            'show_in_rest'  => array(
86                'schema' => array(
87                    'items' => array(
88                        'type'       => 'object',
89                        'properties' => array(
90                            'id'                => array(
91                                'type'   => 'string',
92                                'format' => 'text-field',
93                            ),
94                            'name'              => array(
95                                'type'   => 'string',
96                                'format' => 'text-field',
97                            ),
98                            'icon'              => array(
99                                'type'   => 'string',
100                                'format' => 'uri',
101                            ),
102                            'url'               => array(
103                                'type'   => 'string',
104                                'format' => 'uri',
105                            ),
106                            'feed_url'          => array(
107                                'type'   => 'string',
108                                'format' => 'uri',
109                            ),
110                            'description'       => array(
111                                'type'   => 'string',
112                                'format' => 'text-field',
113                            ),
114                            'is_non_wpcom_site' => array(
115                                'type' => 'boolean',
116                            ),
117                        ),
118                    ),
119                ),
120            ),
121            'auth_callback' => function () {
122                return current_user_can( 'edit_posts' );
123            },
124        )
125    );
126}
127
128add_action( 'rest_api_init', __NAMESPACE__ . '\site_recommendations_settings' );
129
130/**
131 * Whether a post publishes its blogroll as OPML.
132 *
133 * @param \WP_Post|null $post Post object.
134 * @return bool
135 */
136function has_opml( $post ) {
137    return $post instanceof \WP_Post
138        && 'publish' === $post->post_status
139        && ! post_password_required( $post )
140        && ( has_block( 'jetpack/blogroll', $post ) || has_block( 'core/block', $post ) )
141        && get_opml_items( get_public_blocks( $post ) );
142}
143
144/**
145 * The blocks of a post that every visitor can see, so gated blogrolls stay out of the OPML.
146 *
147 * Mirrors add_paywall(): a gated post is public only above its Paywall block.
148 *
149 * @param \WP_Post $post Post object.
150 * @return array Parsed blocks.
151 */
152function get_public_blocks( $post ) {
153    $blocks = parse_blocks( $post->post_content );
154    if ( ! has_filter( 'the_content', 'Automattic\Jetpack\Extensions\Subscriptions\add_paywall' ) ) {
155        return $blocks;
156    }
157
158    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
159    if ( Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === \Jetpack_Memberships::get_post_access_level( $post->ID ) ) {
160        return $blocks;
161    }
162
163    foreach ( $blocks as $i => $block ) {
164        if ( 'jetpack/paywall' === $block['blockName'] ) {
165            return array_slice( $blocks, 0, $i );
166        }
167    }
168    return array();
169}
170
171/**
172 * The current post, if it publishes its blogroll as OPML.
173 *
174 * @return \WP_Post|null
175 */
176function get_opml_post() {
177    $post = is_singular() ? get_queried_object() : null;
178    return has_opml( $post ) ? $post : null;
179}
180
181/**
182 * An absolute http(s) URL from a block attribute, or an empty string.
183 *
184 * An OPML file has no base URL, so a relative URL cannot be resolved by a reader.
185 *
186 * @param mixed $url Attribute value.
187 * @return string
188 */
189function get_opml_url( $url ) {
190    $url   = is_string( $url ) ? esc_url_raw( $url, array( 'http', 'https' ) ) : '';
191    $parts = wp_parse_url( $url );
192    return ! empty( $parts['scheme'] ) && ! empty( $parts['host'] ) ? $url : '';
193}
194
195/**
196 * Collect the subscribable items of the blogroll blocks, including nested ones and synced patterns.
197 *
198 * Items without a feed URL cannot be subscribed to, so they are left out.
199 *
200 * @param array $blocks Parsed blocks.
201 * @param array $items  Items found so far, keyed by normalized feed URL.
202 * @param int[] $refs   Synced patterns already followed, so a pattern that includes itself ends.
203 * @return array Items with `name`, `url` and `feed_url`, keyed by normalized feed URL.
204 */
205function get_opml_items( $blocks, $items = array(), $refs = array() ) {
206    foreach ( $blocks as $block ) {
207        // Only rendered for subscribers, see render_subscriber_view_block().
208        if ( 'premium-content/subscriber-view' === $block['blockName'] ) {
209            continue;
210        }
211
212        $feed_url = 'jetpack/blogroll-item' === $block['blockName'] ? get_opml_url( $block['attrs']['feed_url'] ?? '' ) : '';
213        // The same feed with another scheme or without the trailing slash is listed once.
214        $key = untrailingslashit( set_url_scheme( $feed_url, 'https' ) );
215        if ( '' !== $feed_url && ! isset( $items[ $key ] ) ) {
216            $items[ $key ] = array(
217                'name'     => is_string( $block['attrs']['name'] ?? '' ) ? wp_strip_all_tags( $block['attrs']['name'] ?? '' ) : '',
218                'url'      => get_opml_url( $block['attrs']['url'] ?? '' ),
219                'feed_url' => $feed_url,
220            );
221        }
222
223        $ref = 'core/block' === $block['blockName'] ? (int) ( $block['attrs']['ref'] ?? 0 ) : 0;
224        if ( $ref && ! in_array( $ref, $refs, true ) ) {
225            $pattern = get_post( $ref );
226            if ( $pattern instanceof \WP_Post && 'wp_block' === $pattern->post_type && 'publish' === $pattern->post_status ) {
227                $items = get_opml_items( parse_blocks( $pattern->post_content ), $items, array_merge( $refs, array( $ref ) ) );
228            }
229        }
230
231        if ( ! empty( $block['innerBlocks'] ) ) {
232            $items = get_opml_items( $block['innerBlocks'], $items, $refs );
233        }
234    }
235
236    return $items;
237}
238
239/**
240 * The blogroll of a post as an OPML document.
241 *
242 * @param \WP_Post $post Post object.
243 * @return string OPML document.
244 */
245function get_opml( $post ) {
246    $opml  = '<?xml version="1.0" encoding="' . esc_attr( get_option( 'blog_charset' ) ) . '"?>' . "\n";
247    $opml .= '<opml version="2.0">' . "\n";
248    $opml .= "\t<head>\n";
249    $opml .= "\t\t<title>" . esc_xml( wp_strip_all_tags( get_the_title( $post ) ) ) . "</title>\n";
250    $opml .= "\t</head>\n";
251    $opml .= "\t<body>\n";
252
253    foreach ( get_opml_items( get_public_blocks( $post ) ) as $item ) {
254        $opml .= sprintf(
255            "\t\t" . '<outline type="rss" text="%1$s" xmlUrl="%2$s"%3$s />' . "\n",
256            esc_xml( $item['name'] ),
257            esc_url( $item['feed_url'] ),
258            $item['url'] ? ' htmlUrl="' . esc_url( $item['url'] ) . '"' : ''
259        );
260    }
261
262    $opml .= "\t</body>\n";
263    $opml .= '</opml>' . "\n";
264
265    return $opml;
266}
267
268/**
269 * Serve the blogroll of the current post as OPML on `?opml`.
270 *
271 * @param string $template Template to load.
272 * @return string
273 */
274function serve_opml( $template ) {
275    // Not a query var: any extra query var stops WP_Query from resolving a static front page.
276    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only, public document.
277    $post = isset( $_GET['opml'] ) ? get_opml_post() : null;
278    if ( ! $post ) {
279        return $template;
280    }
281
282    header( 'Content-Type: text/x-opml; charset=' . get_option( 'blog_charset' ) );
283    header( 'X-Robots-Tag: noindex' );
284    echo get_opml( $post ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in get_opml().
285    exit( 0 );
286}
287// Last, after redirect_canonical() and template gates like Coming Soon.
288add_filter( 'template_include', __NAMESPACE__ . '\serve_opml', PHP_INT_MAX );
289
290/**
291 * Print the rel="blogroll" discovery link on a post with a blogroll.
292 */
293function print_opml_link() {
294    $post = get_opml_post();
295    if ( ! $post ) {
296        return;
297    }
298
299    printf(
300        '<link rel="blogroll" type="text/x-opml" title="%1$s" href="%2$s" />' . "\n",
301        esc_attr( wp_strip_all_tags( get_the_title( $post ) ) ),
302        esc_url( add_query_arg( 'opml', '', get_permalink( $post ) ) )
303    );
304}
305add_action( 'wp_head', __NAMESPACE__ . '\print_opml_link' );