Make WordPress Core

Changeset 31107


Ignore:
Timestamp:
01/09/2015 04:42:48 AM (9 years ago)
Author:
pento
Message:

Add get_avatar_url(), for retrieving just the URL of an avatar, rather than the entire <img> tag that get_avatar() produces.

Unlike get_avatar(), get_avatar_url() is not pluggable. It can be extended/or modified through the new filters included.

Fixes #21195.

Props mdawaffe, pento, pathawks, DrewAPicture

Location:
trunk
Files:
1 added
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/link-template.php

    r31071 r31107  
    33253325    }
    33263326}
     3327
     3328
     3329/**
     3330 * Retrieve the avatar URL.
     3331 *
     3332 * @since 4.2.0
     3333 *
     3334 * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash,
     3335 *                           user email, WP_User object, WP_Post object, or comment object.
     3336 * @param array $args        {
     3337 *     Optional. Arguments to return instead of the default arguments.
     3338 *
     3339 *     @type int    $size           Height and width of the avatar in pixels. Default 96.
     3340 *     @type string $default        URL for the default image or a default type. Accepts '404' (return
     3341 *                                  a 404 instead of a default image), 'retro' (8bit), 'monsterid' (monster),
     3342 *                                  'wavatar' (cartoon face), 'indenticon' (the "quilt"), 'mystery', 'mm',
     3343 *                                  or 'mysterman' (The Oyster Man), 'blank' (transparent GIF), or
     3344 *                                  'gravatar_default' (the Gravatar logo). Default is the value of the
     3345 *                                  'avatar_default' option, with a fallback of 'mystery'.
     3346 *     @type bool   $force_default  Whether to always show the default image, never the Gravatar. Default false.
     3347 *     @type string $rating         What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
     3348 *                                  judged in that order. Default is the value of the 'avatar_rating' option.
     3349 *     @type string $scheme         URL scheme to use. See {@see set_url_scheme()} for accepted values.
     3350 *                                  Default null.
     3351 *     @type array  $processed_args When the function returns, the value will be the processed/sanitized $args
     3352 *                                  plus a "found_avatar" guess. Pass as a reference. Default null.
     3353 * }
     3354 *
     3355 * @return false|string The URL of the avatar we found, or false if we couldn't find an avatar.
     3356 */
     3357function get_avatar_url( $id_or_email, $args = null ) {
     3358    $args = get_avatar_data( $id_or_email, $args );
     3359    return $args['url'];
     3360}
     3361
     3362/**
     3363 * Retrieve default data about the avatar.
     3364 *
     3365 * @since 4.2.0
     3366 *
     3367 * @param mixed $id_or_email The Gravatar to check the data against. Accepts a user_id, gravatar md5 hash,
     3368 *                           user email, WP_User object, WP_Post object, or comment object.
     3369 * @param array $args        {
     3370 *     Optional. Arguments to return instead of the default arguments.
     3371 *
     3372 *     @type int    $size           Height and width of the avatar in pixels. Default 96.
     3373 *     @type string $default        URL for the default image or a default type. Accepts '404' (return
     3374 *                                  a 404 instead of a default image), 'retro' (8bit), 'monsterid' (monster),
     3375 *                                  'wavatar' (cartoon face), 'indenticon' (the "quilt"), 'mystery', 'mm',
     3376 *                                  or 'mysterman' (The Oyster Man), 'blank' (transparent GIF), or
     3377 *                                  'gravatar_default' (the Gravatar logo). Default is the value of the
     3378 *                                  'avatar_default' option, with a fallback of 'mystery'.
     3379 *     @type bool   $force_default  Whether to always show the default image, never the Gravatar. Default false.
     3380 *     @type string $rating         What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
     3381 *                                  judged in that order. Default is the value of the 'avatar_rating' option.
     3382 *     @type string $scheme         URL scheme to use. See {@see set_url_scheme()} for accepted values.
     3383 *                                  Default null.
     3384 *     @type array  $processed_args When the function returns, the value will be the processed/sanitized $args
     3385 *                                  plus a "found_avatar" guess. Pass as a reference. Default null.
     3386 * }
     3387 *
     3388 * @return array $processed_args {
     3389 *     Along with the arguments passed in $args, this will contain a couple of extra arguments.
     3390 *
     3391 *     @type bool         $found_avatar True if we were able to find an avatar for this user,
     3392 *                                      false or not set if we couldn't.
     3393 *     @type false|string $url          The URL of the avatar we found, or false if we couldn't find an avatar.
     3394 * }
     3395 */
     3396function get_avatar_data( $id_or_email, $args = null ) {
     3397    $args = wp_parse_args( $args, array(
     3398        'size'           => 96,
     3399        'default'        => get_option( 'avatar_default', 'mystery' ),
     3400        'force_default'  => false,
     3401        'rating'         => get_option( 'avatar_rating' ),
     3402        'scheme'         => null,
     3403        'processed_args' => null, // if used, should be a reference
     3404    ) );
     3405
     3406    if ( is_numeric( $args['size'] ) ) {
     3407        $args['size'] = absint( $args['size'] );
     3408        if ( ! $args['size'] ) {
     3409            $args['size'] = 96;
     3410        }
     3411    } else {
     3412        $args['size'] = 96;
     3413    }
     3414
     3415    if ( empty( $args['default'] ) ) {
     3416        $args['default'] = 'mystery';
     3417    }
     3418
     3419    switch ( $args['default'] ) {
     3420        case 'mm' :
     3421        case 'mystery' :
     3422        case 'mysteryman' :
     3423            $args['default'] = 'mm';
     3424            break;
     3425        case 'gravatar_default' :
     3426            $args['default'] = false;
     3427            break;
     3428    }
     3429
     3430    $args['force_default'] = (bool) $args['force_default'];
     3431
     3432    $args['rating'] = strtolower( $args['rating'] );
     3433
     3434    $args['found_avatar'] = false;
     3435
     3436    /**
     3437     * Filter whether to retrieve the avatar URL early.
     3438     *
     3439     * Passing a non-null value in the 'url' member of the return array will
     3440     * effectively short circuit {@see get_avatar_data()}, passing the value
     3441     * through the 'get_avatar_data' filter and returning early.
     3442     *
     3443     * @since 4.2.0
     3444     *
     3445     * @param array             $args          Arguments passed to get_avatar_data(), after processing.
     3446     * @param int|object|string $id_or_email   A user ID, email address, or comment object.
     3447     */
     3448    $args = apply_filters( 'pre_get_avatar_data', $args, $id_or_email );
     3449
     3450    if ( isset( $args['url'] ) && ! is_null( $args['url'] ) ) {
     3451        /** This filter is documented in src/wp-includes/link-template.php */
     3452        return apply_filters( 'get_avatar_data', $args, $id_or_email );
     3453    }
     3454
     3455    $email_hash = '';
     3456    $user = $email = false;
     3457
     3458    // Process the user identifier.
     3459    if ( is_numeric( $id_or_email ) ) {
     3460        $user = get_user_by( 'id', absint( $id_or_email ) );
     3461    } elseif ( is_string( $id_or_email ) ) {
     3462        if ( strpos( $id_or_email, '@md5.gravatar.com' ) ) {
     3463            // md5 hash
     3464            list( $email_hash ) = explode( '@', $id_or_email );
     3465        } else {
     3466            // email address
     3467            $email = $id_or_email;
     3468        }
     3469    } elseif ( $id_or_email instanceof WP_User ) {
     3470        // User Object
     3471        $user = $id_or_email;
     3472    } elseif ( $id_or_email instanceof WP_Post ) {
     3473        // Post Object
     3474        $user = get_user_by( 'id', (int) $id_or_email->post_author );
     3475    } elseif ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
     3476        // Comment Object
     3477
     3478        /**
     3479         * Filter the list of allowed comment types for retrieving avatars.
     3480         *
     3481         * @since 3.0.0
     3482         *
     3483         * @param array $types An array of content types. Default only contains 'comment'.
     3484         */
     3485        $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
     3486        if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) {
     3487            $args['url'] = false;
     3488            /** This filter is documented in src/wp-includes/link-template.php */
     3489            return apply_filters( 'get_avatar_data', $args, $id_or_email );
     3490        }
     3491
     3492        if ( ! empty( $id_or_email->user_id ) ) {
     3493            $user = get_user_by( 'id', (int) $id_or_email->user_id );
     3494        }
     3495        if ( ( ! $user || is_wp_error( $user ) ) && ! empty( $id_or_email->comment_author_email ) ) {
     3496            $email = $id_or_email->comment_author_email;
     3497        }
     3498    }
     3499
     3500    if ( ! $email_hash ) {
     3501        if ( $user ) {
     3502            $email = $user->user_email;
     3503        }
     3504
     3505        if ( $email ) {
     3506            $email_hash = md5( strtolower( trim( $email ) ) );
     3507        }
     3508    }
     3509
     3510    if ( $email_hash ) {
     3511        $args['found_avatar'] = true;
     3512        $gravatar_server = hexdec( $email_hash[0] ) % 3;
     3513    } else {
     3514        $gravatar_server = rand( 0, 2 );
     3515    }
     3516
     3517    $url_args = array(
     3518        's' => $args['size'],
     3519        'd' => $args['default'],
     3520        'f' => $args['force_default'] ? 'y' : false,
     3521        'r' => $args['rating'],
     3522    );
     3523
     3524    $url = sprintf( 'http://%d.gravatar.com/avatar/%s', $gravatar_server, $email_hash );
     3525
     3526    $url = add_query_arg(
     3527        rawurlencode_deep( array_filter( $url_args ) ),
     3528        set_url_scheme( $url, $args['scheme'] )
     3529    );
     3530
     3531    /**
     3532     * Filter the avatar URL.
     3533     *
     3534     * @since 4.2.0
     3535     *
     3536     * @param string            $url           The URL of the avatar.
     3537     * @param int|object|string $id_or_email   A user ID, email address, or comment object.
     3538     * @param array             $args          Arguments passed to get_avatar_data(), after processing.
     3539     */
     3540    $args['url'] = apply_filters( 'get_avatar_url', $url, $id_or_email, $args );
     3541
     3542    /**
     3543     * Filter the avatar data.
     3544     *
     3545     * @since 4.2.0
     3546     *
     3547     * @param array             $args          Arguments passed to get_avatar_data(), after processing.
     3548     * @param int|object|string $id_or_email   A user ID, email address, or comment object.
     3549     */
     3550    $args = apply_filters( 'get_avatar_data', $args, $id_or_email );
     3551
     3552    // Don't return a broken URL if we couldn't find the email hash, and none of the filters returned a different URL.
     3553    if ( ! $email_hash && $url === $args['url'] ) {
     3554        $args['url'] = false;
     3555    }
     3556
     3557    return $args;
     3558}
  • trunk/src/wp-includes/pluggable.php

    r31060 r31107  
    20832083if ( !function_exists( 'get_avatar' ) ) :
    20842084/**
    2085  * Retrieve the avatar for a user who provided a user ID or email address.
     2085 * Retrieve the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post.
    20862086 *
    20872087 * @since 2.5.0
    2088  *
    2089  * @param int|string|object $id_or_email A user ID,  email address, or comment object
    2090  * @param int $size Size of the avatar image
    2091  * @param string $default URL to a default image to use if no avatar is available
    2092  * @param string $alt Alternative text to use in image tag. Defaults to blank
    2093  * @return false|string `<img>` tag for the user's avatar.
    2094 */
    2095 function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
    2096     if ( ! get_option('show_avatars') )
     2088 * @since 4.2.0 Optional $args parameter added.
     2089 *
     2090 * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
     2091 *                           user email, WP_User object, WP_Post object, or comment object.
     2092 * @param int    $size       Optional. Height and width of the avatar in pixels. Default 96.
     2093 * @param string $default    Optional. URL for the default image or a default type. Accepts '404'
     2094 *                           (return a 404 instead of a default image), 'retro' (8bit), 'monsterid'
     2095 *                           (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
     2096 *                           'mystery', 'mm', or 'mysterman' (The Oyster Man), 'blank' (transparent GIF),
     2097 *                           or 'gravatar_default' (the Gravatar logo). Default is the value of the
     2098 *                           'avatar_default' option, with a fallback of 'mystery'.
     2099 * @param string $alt        Optional. Alternative text to use in &lt;img&gt; tag. Default empty.
     2100 * @param array  $args       {
     2101 *     Optional. Extra arguments to retrieve the avatar.
     2102 *
     2103 *     @type bool         $force_default Whether to always show the default image, never the Gravatar. Default false.
     2104 *     @type string       $rating        What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
     2105 *                                       judged in that order. Default is the value of the 'avatar_rating' option.
     2106 *     @type string       $scheme        URL scheme to use. See {@see set_url_scheme()} for accepted values.
     2107 *                                       Default null.
     2108 *     @type array|string $class         Array or string of additional classes to add to the &lt;img&gt; element.
     2109 *                                       Default null.
     2110 *     @type bool         $force_display Whether to always show the avatar - ignores the show_avatars option.
     2111 *                                       Default false.
     2112 * }
     2113 *
     2114 * @return false|string `<img>` tag for the user's avatar. False on failure.
     2115 */
     2116function get_avatar( $id_or_email, $size = 96, $default = '', $alt = '', $args = null ) {
     2117    $defaults = array(
     2118        // get_avatar_data() args.
     2119        'size'          => 96,
     2120        'default'       => get_option( 'avatar_default', 'mystery' ),
     2121        'force_default' => false,
     2122        'rating'        => get_option( 'avatar_rating' ),
     2123        'scheme'        => null,
     2124        'alt'           => '',
     2125        'class'         => null,
     2126        'force_display' => false,
     2127    );
     2128
     2129    if ( empty( $args ) ) {
     2130        $args = array();
     2131    }
     2132
     2133    $args['size']    = $size;
     2134    $args['default'] = $default;
     2135    $args['alt']     = $alt;
     2136
     2137    $args = wp_parse_args( $args, $defaults );
     2138
     2139    /**
     2140     * Filter whether to retrieve the avatar URL early.
     2141     *
     2142     * Passing a non-null value will effectively short-circuit {@see get_avatar()},
     2143     * passing the value through the 'pre_get_avatar' filter and returning early.
     2144     *
     2145     * @since 4.2.0
     2146     *
     2147     * @param string            $avatar        HTML for the user's avatar. Default null.
     2148     * @param int|object|string $id_or_email   A user ID, email address, or comment object.
     2149     * @param array             $args          Arguments passed to get_avatar_url(), after processing.
     2150     */
     2151    $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
     2152    if ( ! is_null( $avatar ) ) {
     2153        /** This filter is documented in src/wp-include/pluggable.php */
     2154        return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
     2155    }
     2156
     2157    if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
    20972158        return false;
    2098 
    2099     if ( false === $alt)
    2100         $safe_alt = '';
    2101     else
    2102         $safe_alt = esc_attr( $alt );
    2103 
    2104     if ( !is_numeric($size) )
    2105         $size = '96';
    2106 
    2107     $email = '';
    2108     if ( is_numeric($id_or_email) ) {
    2109         $id = (int) $id_or_email;
    2110         $user = get_userdata($id);
    2111         if ( $user )
    2112             $email = $user->user_email;
    2113     } elseif ( is_object($id_or_email) ) {
    2114         // No avatar for pingbacks or trackbacks
    2115 
    2116         /**
    2117          * Filter the list of allowed comment types for retrieving avatars.
    2118          *
    2119          * @since 3.0.0
    2120          *
    2121          * @param array $types An array of content types. Default only contains 'comment'.
    2122          */
    2123         $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
    2124         if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
    2125             return false;
    2126 
    2127         if ( ! empty( $id_or_email->user_id ) ) {
    2128             $id = (int) $id_or_email->user_id;
    2129             $user = get_userdata($id);
    2130             if ( $user )
    2131                 $email = $user->user_email;
     2159    }
     2160
     2161    $args = get_avatar_data( $id_or_email, $args );
     2162
     2163    $url = $args['url'];
     2164
     2165    if ( ! $url || is_wp_error( $url ) ) {
     2166        return false;
     2167    }
     2168
     2169    $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
     2170
     2171    if ( ! $args['found_avatar'] || $args['force_default'] ) {
     2172        $class[] = 'avatar-default';
     2173    }
     2174
     2175    if ( $args['class'] ) {
     2176        if ( is_array( $args['class'] ) ) {
     2177            $class = array_merge( $class, $args['class'] );
     2178        } else {
     2179            $class[] = $args['class'];
    21322180        }
    2133 
    2134         if ( ! $email && ! empty( $id_or_email->comment_author_email ) )
    2135             $email = $id_or_email->comment_author_email;
    2136     } else {
    2137         $email = $id_or_email;
    2138     }
    2139 
    2140     if ( empty($default) ) {
    2141         $avatar_default = get_option('avatar_default');
    2142         if ( empty($avatar_default) )
    2143             $default = 'mystery';
    2144         else
    2145             $default = $avatar_default;
    2146     }
    2147 
    2148     if ( !empty($email) )
    2149         $email_hash = md5( strtolower( trim( $email ) ) );
    2150 
    2151     if ( is_ssl() ) {
    2152         $host = 'https://secure.gravatar.com';
    2153     } else {
    2154         if ( !empty($email) )
    2155             $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
    2156         else
    2157             $host = 'http://0.gravatar.com';
    2158     }
    2159 
    2160     if ( 'mystery' == $default )
    2161         $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
    2162     elseif ( 'blank' == $default )
    2163         $default = $email ? 'blank' : includes_url( 'images/blank.gif' );
    2164     elseif ( !empty($email) && 'gravatar_default' == $default )
    2165         $default = '';
    2166     elseif ( 'gravatar_default' == $default )
    2167         $default = "$host/avatar/?s={$size}";
    2168     elseif ( empty($email) )
    2169         $default = "$host/avatar/?d=$default&amp;s={$size}";
    2170     elseif ( strpos($default, 'http://') === 0 )
    2171         $default = add_query_arg( 's', $size, $default );
    2172 
    2173     if ( !empty($email) ) {
    2174         $out = "$host/avatar/";
    2175         $out .= $email_hash;
    2176         $out .= '?s='.$size;
    2177         $out .= '&amp;d=' . urlencode( $default );
    2178 
    2179         $rating = get_option('avatar_rating');
    2180         if ( !empty( $rating ) )
    2181             $out .= "&amp;r={$rating}";
    2182 
    2183         $out = str_replace( '&#038;', '&amp;', esc_url( $out ) );
    2184         $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
    2185     } else {
    2186         $out = esc_url( $default );
    2187         $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
    2188     }
     2181    }
     2182
     2183    $avatar = sprintf(
     2184        '<img alt="%s" src="%s" class="%s" height="%d" width="%d" />',
     2185        esc_attr( $args['alt'] ),
     2186        esc_url( $url ),
     2187        esc_attr( join( ' ', $class ) ),
     2188        (int) $args['size'],
     2189        (int) $args['size']
     2190    );
    21892191
    21902192    /**
     
    21922194     *
    21932195     * @since 2.5.0
    2194      *
    2195      * @param string            $avatar      Image tag for the user's avatar.
    2196      * @param int|object|string $id_or_email A user ID, email address, or comment object.
    2197      * @param int               $size        Square avatar width and height in pixels to retrieve.
    2198      * @param string            $alt         Alternative text to use in the avatar image tag.
    2199      *                                       Default empty.
    2200      */
    2201     return apply_filters( 'get_avatar', $avatar, $id_or_email, $size, $default, $alt );
     2196     * @since 4.2.0 $args parameter added
     2197     *
     2198     * @param string            $avatar         &lt;img&gt; tag for the user's avatar.
     2199     * @param int|object|string $id_or_email    A user ID, email address, or comment object.
     2200     * @param int               $size           Square avatar width and height in pixels to retrieve.
     2201     * @param string            $alt            Alternative text to use in the avatar image tag.
     2202     *                                          Default empty.
     2203     * @param array             $args           Arguments passed to get_avatar_data(), after processing.
     2204     */
     2205    return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
    22022206}
    22032207endif;
Note: See TracChangeset for help on using the changeset viewer.