Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.62% covered (warning)
86.62%
136 / 157
64.29% covered (warning)
64.29%
9 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Author_Schema_Node
86.62% covered (warning)
86.62%
136 / 157
64.29% covered (warning)
64.29%
9 / 14
57.22
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
1
 build_person
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
9
 build_profile_page
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 render_profile_fields
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 save_profile_fields
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
6.09
 get_profile
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 update_profile
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
10
 is_wpcom_profile
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 save_job_title
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 save_same_as
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 sanitize_url_list
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_user
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 text
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 url
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Author Person / ProfilePage Schema.org node builder.
4 *
5 * @package automattic/jetpack-seo-package
6 */
7
8namespace Automattic\Jetpack\SEO;
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Status\Host;
12use WP_Error;
13use WP_User;
14
15/**
16 * Builds author Person / ProfilePage nodes and owns the extra author profile meta.
17 */
18class Author_Schema_Node {
19
20    /**
21     * User meta key for the author's job title.
22     */
23    const META_JOB_TITLE = 'jetpack_seo_job_title';
24
25    /**
26     * User meta key for profile links emitted as Person `sameAs`.
27     */
28    const META_SAME_AS = 'jetpack_seo_same_as';
29
30    /**
31     * Wire the WP user-profile fields.
32     *
33     * @return void
34     */
35    public static function init() {
36        register_meta(
37            'user',
38            self::META_JOB_TITLE,
39            array(
40                'type'              => 'string',
41                'single'            => true,
42                'default'           => '',
43                'sanitize_callback' => 'sanitize_text_field',
44                'show_in_rest'      => true,
45            )
46        );
47        register_meta(
48            'user',
49            self::META_SAME_AS,
50            array(
51                'type'              => 'array',
52                'single'            => true,
53                'default'           => array(),
54                'sanitize_callback' => array( __CLASS__, 'sanitize_url_list' ),
55                'show_in_rest'      => array(
56                    'schema' => array(
57                        'type'  => 'array',
58                        'items' => array(
59                            'type'   => 'string',
60                            'format' => 'uri',
61                        ),
62                    ),
63                ),
64            )
65        );
66
67        add_action( 'show_user_profile', array( __CLASS__, 'render_profile_fields' ) );
68        add_action( 'edit_user_profile', array( __CLASS__, 'render_profile_fields' ) );
69        add_action( 'personal_options_update', array( __CLASS__, 'save_profile_fields' ) );
70        add_action( 'edit_user_profile_update', array( __CLASS__, 'save_profile_fields' ) );
71    }
72
73    /**
74     * Build a Person node for a WP user.
75     *
76     * @param WP_User|int|null $user User object or ID.
77     * @return array|null
78     */
79    public static function build_person( $user ) {
80        $user = self::get_user( $user );
81        if ( ! $user ) {
82            return null;
83        }
84
85        $name = self::text( $user->display_name );
86        if ( '' === $name ) {
87            return null;
88        }
89
90        $node = array(
91            '@type' => 'Person',
92            '@id'   => Schema_Node_Ids::person( $user->ID, $user->user_nicename ),
93            'name'  => $name,
94        );
95
96        $image = get_avatar_url( $user->ID, array( 'size' => 512 ) );
97        if ( is_string( $image ) && '' !== $image ) {
98            $node['image'] = $image;
99        }
100
101        $description = self::text( get_the_author_meta( 'description', $user->ID ) );
102        if ( '' !== $description ) {
103            $node['description'] = $description;
104        }
105
106        // Prefer the user's Website field; fall back to the author archive so the
107        // Person always carries a URL identifying the author.
108        $url         = self::url( $user->user_url );
109        $node['url'] = '' !== $url ? $url : get_author_posts_url( $user->ID, $user->user_nicename );
110
111        $job_title = self::text( get_user_meta( $user->ID, self::META_JOB_TITLE, true ) );
112        if ( '' !== $job_title ) {
113            $node['jobTitle'] = $job_title;
114        }
115
116        $same_as = self::sanitize_url_list( get_user_meta( $user->ID, self::META_SAME_AS, true ) );
117        if ( ! empty( $same_as ) ) {
118            $node['sameAs'] = $same_as;
119        }
120
121        return $node;
122    }
123
124    /**
125     * Build a ProfilePage node for an author archive.
126     *
127     * @param WP_User|int|null $user User object or ID.
128     * @return array|null
129     */
130    public static function build_profile_page( $user ) {
131        $user = self::get_user( $user );
132        if ( ! $user || '' === self::text( $user->display_name ) ) {
133            return null;
134        }
135
136        return array(
137            '@type'      => 'ProfilePage',
138            '@id'        => Schema_Node_Ids::profile_page( $user->ID, $user->user_nicename ),
139            'url'        => get_author_posts_url( $user->ID, $user->user_nicename ),
140            'mainEntity' => array( '@id' => Schema_Node_Ids::person( $user->ID, $user->user_nicename ) ),
141        );
142    }
143
144    /**
145     * Render the Jetpack SEO author profile fields.
146     *
147     * @param WP_User $user User being edited.
148     * @return void
149     */
150    public static function render_profile_fields( WP_User $user ) {
151        $job_field   = self::META_JOB_TITLE;
152        $links_field = self::META_SAME_AS;
153        $job_title   = get_user_meta( $user->ID, $job_field, true );
154        $same_as     = self::sanitize_url_list( get_user_meta( $user->ID, $links_field, true ) );
155
156        printf(
157            '<h2>%1$s</h2>
158            <table class="form-table" role="presentation">
159                <tr>
160                    <th><label for="%2$s">%3$s</label></th>
161                    <td><input type="text" class="regular-text" name="%2$s" id="%2$s" value="%4$s" /></td>
162                </tr>
163                <tr>
164                    <th><label for="%5$s">%6$s</label></th>
165                    <td>
166                        <textarea class="large-text code" rows="5" name="%5$s" id="%5$s">%7$s</textarea>
167                        <p class="description">%8$s</p>
168                    </td>
169                </tr>
170            </table>',
171            esc_html__( 'Jetpack SEO author schema', 'jetpack-seo' ),
172            esc_attr( $job_field ),
173            esc_html__( 'Job title', 'jetpack-seo' ),
174            esc_attr( $job_title ),
175            esc_attr( $links_field ),
176            esc_html__( 'Profile links', 'jetpack-seo' ),
177            esc_textarea( implode( "\n", $same_as ) ),
178            esc_html__( 'One public profile URL per line.', 'jetpack-seo' )
179        );
180    }
181
182    /**
183     * Save the Jetpack SEO author profile fields.
184     *
185     * @param int $user_id User ID.
186     * @return void
187     */
188    public static function save_profile_fields( $user_id ) {
189        if ( ! current_user_can( 'edit_user', $user_id ) ) {
190            return;
191        }
192
193        $nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
194        if ( ! wp_verify_nonce( $nonce, 'update-user_' . $user_id ) ) {
195            return;
196        }
197
198        self::save_job_title(
199            $user_id,
200            isset( $_POST[ self::META_JOB_TITLE ] ) ? sanitize_text_field( wp_unslash( $_POST[ self::META_JOB_TITLE ] ) ) : ''
201        );
202        self::save_same_as(
203            $user_id,
204            isset( $_POST[ self::META_SAME_AS ] )
205                ? preg_split( '/\r\n|\r|\n/', sanitize_textarea_field( wp_unslash( $_POST[ self::META_SAME_AS ] ) ) )
206                : array()
207        );
208    }
209
210    /**
211     * The author profile of a user, as the Settings Author profile card edits it.
212     * `accountProfileUrl` is where name, bio and website are edited when WordPress.com owns them.
213     *
214     * @param int $user_id User ID.
215     * @return array{name: string, description: string, url: string, jobTitle: string, sameAs: array<int, string>, avatarUrl: string, accountProfileUrl: string}
216     */
217    public static function get_profile( $user_id ) {
218        $user = get_userdata( $user_id );
219        return array(
220            'name'              => $user ? (string) $user->display_name : '',
221            'description'       => $user ? (string) $user->description : '',
222            'url'               => $user ? (string) $user->user_url : '',
223            'jobTitle'          => (string) get_user_meta( $user_id, self::META_JOB_TITLE, true ),
224            'sameAs'            => self::sanitize_url_list( get_user_meta( $user_id, self::META_SAME_AS, true ) ),
225            'avatarUrl'         => (string) get_avatar_url( $user_id, array( 'size' => 96 ) ),
226            'accountProfileUrl' => self::is_wpcom_profile( $user_id ) ? 'https://my.wordpress.com/me/account' : '',
227        );
228    }
229
230    /**
231     * Update a user's author profile. Omitted fields keep their stored values, and
232     * name, bio and website are left alone where WordPress.com owns them.
233     *
234     * @param int   $user_id User ID.
235     * @param array $fields  Any of `name`, `description`, `url`, `jobTitle` and `sameAs`.
236     * @return array|WP_Error The stored profile, or the error that stopped the update.
237     */
238    public static function update_profile( $user_id, array $fields ) {
239        if ( self::is_wpcom_profile( $user_id ) ) {
240            unset( $fields['name'], $fields['description'], $fields['url'] );
241        }
242
243        $userdata = array( 'ID' => $user_id );
244        if ( isset( $fields['name'] ) ) {
245            $userdata['display_name'] = sanitize_text_field( (string) $fields['name'] );
246            if ( '' === $userdata['display_name'] ) {
247                return new WP_Error(
248                    'jetpack_seo_author_name_empty',
249                    __( 'Author name cannot be empty.', 'jetpack-seo' ),
250                    array( 'status' => 400 )
251                );
252            }
253        }
254        if ( isset( $fields['description'] ) ) {
255            $userdata['description'] = (string) $fields['description'];
256        }
257        if ( isset( $fields['url'] ) ) {
258            $userdata['user_url'] = esc_url_raw( trim( (string) $fields['url'] ) );
259        }
260        if ( count( $userdata ) > 1 ) {
261            // wp_update_user() and update_user_meta() unslash their input, so slash it as core's users route does.
262            $result = wp_update_user( wp_slash( $userdata ) );
263            if ( is_wp_error( $result ) ) {
264                return $result;
265            }
266        }
267
268        if ( isset( $fields['jobTitle'] ) ) {
269            self::save_job_title( $user_id, $fields['jobTitle'] );
270        }
271        if ( isset( $fields['sameAs'] ) ) {
272            self::save_same_as( $user_id, $fields['sameAs'] );
273        }
274
275        return self::get_profile( $user_id );
276    }
277
278    /**
279     * Whether name, bio and website belong to the user's WordPress.com account: on Simple
280     * they're shared by all the user's sites, and on Atomic WordPress.com pushes them over local edits.
281     *
282     * @param int $user_id User ID.
283     * @return bool
284     */
285    private static function is_wpcom_profile( $user_id ) {
286        $host = new Host();
287        return $host->is_wpcom_simple()
288            || ( $host->is_woa_site() && ( new Connection_Manager() )->is_user_connected( $user_id ) );
289    }
290
291    /**
292     * Store a user's job title, deleting the meta when it's empty.
293     *
294     * @param int   $user_id User ID.
295     * @param mixed $value   Raw job title.
296     * @return void
297     */
298    private static function save_job_title( $user_id, $value ) {
299        $job_title = is_scalar( $value ) ? sanitize_text_field( (string) $value ) : '';
300        if ( '' === $job_title ) {
301            delete_user_meta( $user_id, self::META_JOB_TITLE );
302        } else {
303            update_user_meta( $user_id, self::META_JOB_TITLE, wp_slash( $job_title ) );
304        }
305    }
306
307    /**
308     * Store a user's profile links, deleting the meta when none are valid.
309     *
310     * @param int   $user_id User ID.
311     * @param mixed $value   Raw list of URLs.
312     * @return void
313     */
314    private static function save_same_as( $user_id, $value ) {
315        $same_as = self::sanitize_url_list( $value );
316        if ( empty( $same_as ) ) {
317            delete_user_meta( $user_id, self::META_SAME_AS );
318        } else {
319            update_user_meta( $user_id, self::META_SAME_AS, wp_slash( $same_as ) );
320        }
321    }
322
323    /**
324     * Normalize a list of URLs: keep unique absolute http(s) URLs. Delegates to
325     * the shared {@see Schema_Settings::sanitize_url_list()} sanitizer.
326     *
327     * @param mixed $value Raw value.
328     * @return array<int, string>
329     */
330    public static function sanitize_url_list( $value ) {
331        return Schema_Settings::sanitize_url_list( $value );
332    }
333
334    /**
335     * Resolve a WP user.
336     *
337     * @param WP_User|int|null $user User object or ID.
338     * @return WP_User|null
339     */
340    private static function get_user( $user ) {
341        if ( $user instanceof WP_User ) {
342            return $user;
343        }
344
345        // Plugins such as PublishPress Authors replace the author archive's queried
346        // object with their own class; casting that to int silently yields user 1.
347        if ( ! is_numeric( $user ) ) {
348            return null;
349        }
350
351        $user = get_userdata( (int) $user );
352        return $user instanceof WP_User ? $user : null;
353    }
354
355    /**
356     * Normalize a scalar value to trimmed plain text.
357     *
358     * @param mixed $value Raw value.
359     * @return string
360     */
361    private static function text( $value ) {
362        if ( ! is_scalar( $value ) ) {
363            return '';
364        }
365        return trim( \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( (string) $value ) ) );
366    }
367
368    /**
369     * Normalize an absolute http(s) URL.
370     *
371     * @param mixed $value Raw value.
372     * @return string
373     */
374    private static function url( $value ) {
375        $list = Schema_Settings::sanitize_url_list( array( $value ) );
376        return $list[0] ?? '';
377    }
378}