/**
 * Generates a Photon URL.
 *
 * @see http://developer.wordpress.com/docs/photon/
 *
 * @param string $image_url URL to the publicly accessible image you want to manipulate
 * @param array|string $args An array of arguments, i.e. array( 'w' => '300', 'resize' => array( 123, 456 ) ), or in string form (w=123&h=456)
 * @return string The raw final URL. You should run this through esc_url() before displaying it.
 */
function jetpack_photon_url($image_url, $args = array(), $scheme = null)
{
    $image_url = trim($image_url);
    $image_url = apply_filters('jetpack_photon_pre_image_url', $image_url, $args, $scheme);
    $args = apply_filters('jetpack_photon_pre_args', $args, $image_url, $scheme);
    if (empty($image_url)) {
        return $image_url;
    }
    $image_url_parts = @parse_url($image_url);
    // Unable to parse
    if (!is_array($image_url_parts) || empty($image_url_parts['host']) || empty($image_url_parts['path'])) {
        return $image_url;
    }
    if (is_array($args)) {
        // Convert values that are arrays into strings
        foreach ($args as $arg => $value) {
            if (is_array($value)) {
                $args[$arg] = implode(',', $value);
            }
        }
        // Encode values
        // See http://core.trac.wordpress.org/ticket/17923
        $args = rawurlencode_deep($args);
    }
    // You can't run a Photon URL through Photon again because query strings are stripped.
    // So if the image is already a Photon URL, append the new arguments to the existing URL.
    if (in_array($image_url_parts['host'], array('i0.wp.com', 'i1.wp.com', 'i2.wp.com'))) {
        $photon_url = add_query_arg($args, $image_url);
        return jetpack_photon_url_scheme($photon_url, $scheme);
    }
    // This setting is Photon Server dependent
    if (!apply_filters('jetpack_photon_any_extension_for_domain', false, $image_url_parts['host'])) {
        // Photon doesn't support query strings so we ignore them and look only at the path.
        // However some source images are served via PHP so check the no-query-string extension.
        // For future proofing, this is a blacklist of common issues rather than a whitelist.
        $extension = pathinfo($image_url_parts['path'], PATHINFO_EXTENSION);
        if (empty($extension) || in_array($extension, array('php'))) {
            return $image_url;
        }
    }
    $image_host_path = $image_url_parts['host'] . $image_url_parts['path'];
    // Figure out which CDN subdomain to use
    srand(crc32($image_host_path));
    $subdomain = rand(0, 2);
    srand();
    $photon_url = "http://i{$subdomain}.wp.com/{$image_host_path}";
    // This setting is Photon Server dependent
    if (isset($image_url_parts['query']) && apply_filters('jetpack_photon_add_query_string_to_domain', false, $image_url_parts['host'])) {
        $photon_url .= '?q=' . rawurlencode($image_url_parts['query']);
    }
    if ($args) {
        if (is_array($args)) {
            $photon_url = add_query_arg($args, $photon_url);
        } else {
            // You can pass a query string for complicated requests but where you still want CDN subdomain help, etc.
            $photon_url .= '?' . $args;
        }
    }
    return jetpack_photon_url_scheme($photon_url, $scheme);
}
Esempio n. 2
0
/**
 * Retrieve default data about the avatar.
 *
 * @since 4.2.0
 *
 * @param mixed $id_or_email The Gravatar to check the data against. Accepts a user_id, gravatar md5 hash,
 *                           user email, WP_User object, WP_Post object, or comment object.
 * @param array $args {
 *     Optional. Arguments to return instead of the default arguments.
 *
 *     @type int    $size           Height and width of the avatar image file in pixels. Default 96.
 *     @type int    $height         Display height of the avatar in pixels. Defaults to $size.
 *     @type int    $width          Display width of the avatar in pixels. Defaults to $size.
 *     @type string $default        URL for the default image or a default type. Accepts '404' (return
 *                                  a 404 instead of a default image), 'retro' (8bit), 'monsterid' (monster),
 *                                  'wavatar' (cartoon face), 'indenticon' (the "quilt"), 'mystery', 'mm',
 *                                  or 'mysterman' (The Oyster Man), 'blank' (transparent GIF), or
 *                                  'gravatar_default' (the Gravatar logo). Default is the value of the
 *                                  'avatar_default' option, with a fallback of 'mystery'.
 *     @type bool   $force_default  Whether to always show the default image, never the Gravatar. Default false.
 *     @type string $rating         What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
 *                                  judged in that order. Default is the value of the 'avatar_rating' option.
 *     @type string $scheme         URL scheme to use. See set_url_scheme() for accepted values.
 *                                  Default null.
 *     @type array  $processed_args When the function returns, the value will be the processed/sanitized $args
 *                                  plus a "found_avatar" guess. Pass as a reference. Default null.
 *     @type string $extra_attr     HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
 * }
 * @return array $processed_args {
 *     Along with the arguments passed in `$args`, this will contain a couple of extra arguments.
 *
 *     @type bool   $found_avatar True if we were able to find an avatar for this user,
 *                                false or not set if we couldn't.
 *     @type string $url          The URL of the avatar we found.
 * }
 */
function get_avatar_data($id_or_email, $args = null)
{
    $args = wp_parse_args($args, array('size' => 96, 'height' => null, 'width' => null, 'default' => get_option('avatar_default', 'mystery'), 'force_default' => false, 'rating' => get_option('avatar_rating'), 'scheme' => null, 'processed_args' => null, 'extra_attr' => ''));
    if (is_numeric($args['size'])) {
        $args['size'] = absint($args['size']);
        if (!$args['size']) {
            $args['size'] = 96;
        }
    } else {
        $args['size'] = 96;
    }
    if (is_numeric($args['height'])) {
        $args['height'] = absint($args['height']);
        if (!$args['height']) {
            $args['height'] = $args['size'];
        }
    } else {
        $args['height'] = $args['size'];
    }
    if (is_numeric($args['width'])) {
        $args['width'] = absint($args['width']);
        if (!$args['width']) {
            $args['width'] = $args['size'];
        }
    } else {
        $args['width'] = $args['size'];
    }
    if (empty($args['default'])) {
        $args['default'] = get_option('avatar_default', 'mystery');
    }
    switch ($args['default']) {
        case 'mm':
        case 'mystery':
        case 'mysteryman':
            $args['default'] = 'mm';
            break;
        case 'gravatar_default':
            $args['default'] = false;
            break;
    }
    $args['force_default'] = (bool) $args['force_default'];
    $args['rating'] = strtolower($args['rating']);
    $args['found_avatar'] = false;
    /**
     * Filter whether to retrieve the avatar URL early.
     *
     * Passing a non-null value in the 'url' member of the return array will
     * effectively short circuit get_avatar_data(), passing the value through
     * the {@see 'get_avatar_data'} filter and returning early.
     *
     * @since 4.2.0
     *
     * @param array             $args          Arguments passed to get_avatar_data(), after processing.
     * @param int|object|string $id_or_email   A user ID, email address, or comment object.
     */
    $args = apply_filters('pre_get_avatar_data', $args, $id_or_email);
    if (isset($args['url']) && !is_null($args['url'])) {
        /** This filter is documented in wp-includes/link-template.php */
        return apply_filters('get_avatar_data', $args, $id_or_email);
    }
    $email_hash = '';
    $user = $email = false;
    // Process the user identifier.
    if (is_numeric($id_or_email)) {
        $user = get_user_by('id', absint($id_or_email));
    } elseif (is_string($id_or_email)) {
        if (strpos($id_or_email, '@md5.gravatar.com')) {
            // md5 hash
            list($email_hash) = explode('@', $id_or_email);
        } else {
            // email address
            $email = $id_or_email;
        }
    } elseif ($id_or_email instanceof WP_User) {
        // User Object
        $user = $id_or_email;
    } elseif ($id_or_email instanceof WP_Post) {
        // Post Object
        $user = get_user_by('id', (int) $id_or_email->post_author);
    } elseif (is_object($id_or_email) && isset($id_or_email->comment_ID)) {
        // Comment Object
        /**
         * Filter the list of allowed comment types for retrieving avatars.
         *
         * @since 3.0.0
         *
         * @param array $types An array of content types. Default only contains 'comment'.
         */
        $allowed_comment_types = apply_filters('get_avatar_comment_types', array('comment'));
        if (!empty($id_or_email->comment_type) && !in_array($id_or_email->comment_type, (array) $allowed_comment_types)) {
            $args['url'] = false;
            /** This filter is documented in wp-includes/link-template.php */
            return apply_filters('get_avatar_data', $args, $id_or_email);
        }
        if (!empty($id_or_email->user_id)) {
            $user = get_user_by('id', (int) $id_or_email->user_id);
        }
        if ((!$user || is_wp_error($user)) && !empty($id_or_email->comment_author_email)) {
            $email = $id_or_email->comment_author_email;
        }
    }
    if (!$email_hash) {
        if ($user) {
            $email = $user->user_email;
        }
        if ($email) {
            $email_hash = md5(strtolower(trim($email)));
        }
    }
    if ($email_hash) {
        $args['found_avatar'] = true;
        $gravatar_server = hexdec($email_hash[0]) % 3;
    } else {
        $gravatar_server = rand(0, 2);
    }
    $url_args = array('s' => $args['size'], 'd' => $args['default'], 'f' => $args['force_default'] ? 'y' : false, 'r' => $args['rating']);
    if (is_ssl()) {
        $url = 'https://secure.gravatar.com/avatar/' . $email_hash;
    } else {
        $url = sprintf('http://%d.gravatar.com/avatar/%s', $gravatar_server, $email_hash);
    }
    $url = add_query_arg(rawurlencode_deep(array_filter($url_args)), set_url_scheme($url, $args['scheme']));
    /**
     * Filter the avatar URL.
     *
     * @since 4.2.0
     *
     * @param string            $url         The URL of the avatar.
     * @param int|object|string $id_or_email A user ID, email address, or comment object.
     * @param array             $args        Arguments passed to get_avatar_data(), after processing.
     */
    $args['url'] = apply_filters('get_avatar_url', $url, $id_or_email, $args);
    /**
     * Filter the avatar data.
     *
     * @since 4.2.0
     *
     * @param array             $args        Arguments passed to get_avatar_data(), after processing.
     * @param int|object|string $id_or_email A user ID, email address, or comment object.
     */
    return apply_filters('get_avatar_data', $args, $id_or_email);
}
Esempio n. 3
0
/**
 * Get an avatar for a BuddyPress object.
 *
 * Supports avatars for users, groups, and blogs by default, but can be
 * extended to support custom components as well.
 *
 * This function gives precedence to locally-uploaded avatars. When a local
 * avatar is not found, Gravatar is queried. To disable Gravatar fallbacks
 * locally:
 *    add_filter( 'bp_core_fetch_avatar_no_grav', '__return_true' );
 *
 * @since 2.4.0 Added 'extra_attr', 'scheme', 'rating' and 'force_default' for $args.
 *              These are inherited from WordPress 4.2.0. See {@link get_avatar()}.
 *
 * @param array|string $args {
 *     An array of arguments. All arguments are technically optional; some
 *     will, if not provided, be auto-detected by bp_core_fetch_avatar(). This
 *     auto-detection is described more below, when discussing specific
 *     arguments.
 *
 *     @type int|bool    $item_id    The numeric ID of the item for which you're requesting
 *                                   an avatar (eg, a user ID). If no 'item_id' is present,
 *                                   the function attempts to infer an ID from the 'object' + the
 *                                   current context: if 'object' is 'user' and the current page is a
 *                                   user page, 'item_id' will default to the displayed user ID; if
 *                                   'group' and on a group page, to the current group ID; if 'blog',
 *                                   to the current blog's ID. If no 'item_id' can be determined in
 *                                   this way, the function returns false. Default: false.
 *     @type string      $object     The kind of object for which you're getting an
 *                                   avatar. BuddyPress natively supports three options: 'user',
 *                                   'group', 'blog'; a plugin may register more.  Default: 'user'.
 *     @type string      $type       When a new avatar is uploaded to BP, 'thumb' and
 *                                   'full' versions are saved. This parameter specifies whether you'd
 *                                   like the 'full' or smaller 'thumb' avatar. Default: 'thumb'.
 *     @type string|bool $avatar_dir The name of the subdirectory where the
 *                                   requested avatar should be found. If no value is passed,
 *                                   'avatar_dir' is inferred from 'object': 'user' becomes 'avatars',
 *                                   'group' becomes 'group-avatars', 'blog' becomes 'blog-avatars'.
 *                                   Remember that this string denotes a subdirectory of BP's main
 *                                   avatar directory (usually based on {@link wp_upload_dir()}); it's a
 *                                   string like 'group-avatars' rather than the full directory path.
 *                                   Generally, it'll only be necessary to override the default value if
 *                                   storing avatars in a non-default location. Defaults to false
 *                                   (auto-detected).
 *     @type int|bool    $width      Requested avatar width. The unit is px. This value
 *                                   is used to build the 'width' attribute for the <img> element. If
 *                                   no value is passed, BP uses the global avatar width for this
 *                                   avatar type. Default: false (auto-detected).
 *     @type int|bool    $height     Requested avatar height. The unit is px. This
 *                                   value is used to build the 'height' attribute for the <img>
 *                                   element. If no value is passed, BP uses the global avatar height
 *                                   for this avatar type. Default: false (auto-detected).
 *     @type string      $class      The CSS class for the <img> element. Note that BP
 *                                   uses the 'avatar' class fairly extensively in its default styling,
 *                                   so if you plan to pass a custom value, consider appending it to
 *                                   'avatar' (eg 'avatar foo') rather than replacing it altogether.
 *                                   Default: 'avatar'.
 *     @type string|bool $css_id     The CSS id for the <img> element.
 *                                   Default: false.
 *     @type string      $title      The title attribute for the <img> element.
 *                                   Default: false.
 *     @type string      $alt        The alt attribute for the <img> element. In BP, this
 *                                   value is generally passed by the wrapper functions, where the data
 *                                   necessary for concatenating the string is at hand; see
 *                                   {@link bp_get_activity_avatar()} for an example. Default: ''.
 *     @type string|bool $email      An email to use in Gravatar queries. Unless
 *                                   otherwise configured, BP uses Gravatar as a fallback for avatars
 *                                   that are not provided locally. Gravatar's API requires using a hash
 *                                   of the user's email address; this argument provides it. If not
 *                                   provided, the function will infer it: for users, by getting the
 *                                   user's email from the database, for groups/blogs, by concatenating
 *                                   "{$item_id}-{$object}@{bp_get_root_domain()}". The user query adds
 *                                   overhead, so it's recommended that wrapper functions provide a
 *                                   value for 'email' when querying user IDs. Default: false.
 *     @type bool       $no_grav     Whether to disable the default Gravatar fallback.
 *                                   By default, BP will fall back on Gravatar when it cannot find a
 *                                   local avatar. In some cases, this may be undesirable, in which
 *                                   case 'no_grav' should be set to true. To disable Gravatar
 *                                   fallbacks globally, see the 'bp_core_fetch_avatar_no_grav' filter.
 *                                   Default: false.
 *     @type bool       $html        Whether to return an <img> HTML element, vs a raw URL
 *                                   to an avatar. If false, <img>-specific arguments (like 'css_id')
 *                                   will be ignored. Default: true.
 *     @type string     $extra_attr  HTML attributes to insert in the IMG element. Not sanitized. Default: ''.
 *     @type string     $scheme      URL scheme to use. See set_url_scheme() for accepted values.
 *                                   Default null.
 *     @type string     $rating      What rating to display Gravatars for. Accepts 'G', 'PG', 'R', 'X'.
 *                                   Default is the value of the 'avatar_rating' option.
 *     @type bool       $force_default Used when creating the Gravatar URL. Whether to force the default
 *                                     image regardless if the Gravatar exists. Default: false.
 * }
 *
 * @return string Formatted HTML <img> element, or raw avatar URL based on $html arg.
 */
function bp_core_fetch_avatar($args = '')
{
    $bp = buddypress();
    // If avatars are disabled for the root site, obey that request and bail
    if (!$bp->avatar->show_avatars) {
        return;
    }
    global $current_blog;
    // Set the default variables array and parse it against incoming $args array.
    $params = wp_parse_args($args, array('item_id' => false, 'object' => 'user', 'type' => 'thumb', 'avatar_dir' => false, 'width' => false, 'height' => false, 'class' => 'avatar', 'css_id' => false, 'alt' => '', 'email' => false, 'no_grav' => false, 'html' => true, 'title' => '', 'extra_attr' => '', 'scheme' => null, 'rating' => get_option('avatar_rating'), 'force_default' => false));
    /** Set item_id ***********************************************************/
    if (empty($params['item_id'])) {
        switch ($params['object']) {
            case 'blog':
                $params['item_id'] = $current_blog->id;
                break;
            case 'group':
                if (bp_is_active('groups')) {
                    $params['item_id'] = $bp->groups->current_group->id;
                } else {
                    $params['item_id'] = false;
                }
                break;
            case 'user':
            default:
                $params['item_id'] = bp_displayed_user_id();
                break;
        }
        /**
         * Filters the ID of the item being requested.
         *
         * @since 1.1.0
         *
         * @param string $value  ID of avatar item being requested.
         * @param string $value  Avatar type being requested.
         * @param array  $params Array of parameters for the request.
         */
        $params['item_id'] = apply_filters('bp_core_avatar_item_id', $params['item_id'], $params['object'], $params);
        if (empty($params['item_id'])) {
            return false;
        }
    }
    /** Set avatar_dir ********************************************************/
    if (empty($params['avatar_dir'])) {
        switch ($params['object']) {
            case 'blog':
                $params['avatar_dir'] = 'blog-avatars';
                break;
            case 'group':
                if (bp_is_active('groups')) {
                    $params['avatar_dir'] = 'group-avatars';
                } else {
                    $params['avatar_dir'] = false;
                }
                break;
            case 'user':
            default:
                $params['avatar_dir'] = 'avatars';
                break;
        }
        /**
         * Filters the avatar directory to use.
         *
         * @since 1.1.0
         *
         * @param string $value  Name of the subdirectory where the requested avatar should be found.
         * @param string $value  Avatar type being requested.
         * @param array  $params Array of parameters for the request.
         */
        $params['avatar_dir'] = apply_filters('bp_core_avatar_dir', $params['avatar_dir'], $params['object'], $params);
        if (empty($params['avatar_dir'])) {
            return false;
        }
    }
    /** <img> alt *************************************************************/
    if (false !== strpos($params['alt'], '%s') || false !== strpos($params['alt'], '%1$s')) {
        switch ($params['object']) {
            case 'blog':
                $item_name = get_blog_option($params['item_id'], 'blogname');
                break;
            case 'group':
                $item_name = bp_get_group_name(groups_get_group(array('group_id' => $params['item_id'])));
                break;
            case 'user':
            default:
                $item_name = bp_core_get_user_displayname($params['item_id']);
                break;
        }
        /**
         * Filters the alt attribute value to be applied to avatar.
         *
         * @since 1.5.0
         *
         * @param string $value  alt to be applied to avatar.
         * @param string $value  ID of avatar item being requested.
         * @param string $value  Avatar type being requested.
         * @param array  $params Array of parameters for the request.
         */
        $item_name = apply_filters('bp_core_avatar_alt', $item_name, $params['item_id'], $params['object'], $params);
        $params['alt'] = sprintf($params['alt'], $item_name);
    }
    /** Sanity Checks *********************************************************/
    // Get a fallback for the 'alt' parameter, create html output.
    if (empty($params['alt'])) {
        $params['alt'] = __('Profile Photo', 'buddypress');
    }
    $html_alt = ' alt="' . esc_attr($params['alt']) . '"';
    // Filter image title and create html string.
    $html_title = '';
    /**
     * Filters the title attribute value to be applied to avatar.
     *
     * @since 1.5.0
     *
     * @param string $value  Title to be applied to avatar.
     * @param string $value  ID of avatar item being requested.
     * @param string $value  Avatar type being requested.
     * @param array  $params Array of parameters for the request.
     */
    $params['title'] = apply_filters('bp_core_avatar_title', $params['title'], $params['item_id'], $params['object'], $params);
    if (!empty($params['title'])) {
        $html_title = ' title="' . esc_attr($params['title']) . '"';
    }
    // Extra attributes
    $extra_attr = !empty($args['extra_attr']) ? ' ' . $args['extra_attr'] : '';
    // Set CSS ID and create html string.
    $html_css_id = '';
    /**
     * Filters the ID attribute to be applied to avatar.
     *
     * @since 2.2.0
     *
     * @param string $value  ID to be applied to avatar.
     * @param string $value  ID of avatar item being requested.
     * @param string $value  Avatar type being requested.
     * @param array  $params Array of parameters for the request.
     */
    $params['css_id'] = apply_filters('bp_core_css_id', $params['css_id'], $params['item_id'], $params['object'], $params);
    if (!empty($params['css_id'])) {
        $html_css_id = ' id="' . esc_attr($params['css_id']) . '"';
    }
    // Set image width
    if (false !== $params['width']) {
        // Width has been specified. No modification necessary.
    } elseif ('thumb' == $params['type']) {
        $params['width'] = bp_core_avatar_thumb_width();
    } else {
        $params['width'] = bp_core_avatar_full_width();
    }
    $html_width = ' width="' . $params['width'] . '"';
    // Set image height
    if (false !== $params['height']) {
        // Height has been specified. No modification necessary.
    } elseif ('thumb' == $params['type']) {
        $params['height'] = bp_core_avatar_thumb_height();
    } else {
        $params['height'] = bp_core_avatar_full_height();
    }
    $html_height = ' height="' . $params['height'] . '"';
    /**
     * Filters the classes to be applied to the avatar.
     *
     * @since 1.6.0
     *
     * @param array|string $value  Class(es) to be applied to the avatar.
     * @param string       $value  ID of the avatar item being requested.
     * @param string       $value  Avatar type being requested.
     * @param array        $params Array of parameters for the request.
     */
    $params['class'] = apply_filters('bp_core_avatar_class', $params['class'], $params['item_id'], $params['object'], $params);
    // Use an alias to leave the param unchanged
    $avatar_classes = $params['class'];
    if (!is_array($avatar_classes)) {
        $avatar_classes = explode(' ', $avatar_classes);
    }
    // merge classes
    $avatar_classes = array_merge($avatar_classes, array($params['object'] . '-' . $params['item_id'] . '-avatar', 'avatar-' . $params['width']));
    // Sanitize each class
    $avatar_classes = array_map('sanitize_html_class', $avatar_classes);
    // populate the class attribute
    $html_class = ' class="' . join(' ', $avatar_classes) . ' photo"';
    // Set img URL and DIR based on prepopulated constants
    $avatar_loc = new stdClass();
    $avatar_loc->path = trailingslashit(bp_core_avatar_upload_path());
    $avatar_loc->url = trailingslashit(bp_core_avatar_url());
    $avatar_loc->dir = trailingslashit($params['avatar_dir']);
    /**
     * Filters the avatar folder directory URL.
     *
     * @since 1.1.0
     *
     * @param string $value Path to the avatar folder URL.
     * @param int    $value ID of the avatar item being requested.
     * @param string $value Avatar type being requested.
     * @param string $value Subdirectory where the requested avatar should be found.
     */
    $avatar_folder_url = apply_filters('bp_core_avatar_folder_url', $avatar_loc->url . $avatar_loc->dir . $params['item_id'], $params['item_id'], $params['object'], $params['avatar_dir']);
    /**
     * Filters the avatar folder directory path.
     *
     * @since 1.1.0
     *
     * @param string $value Path to the avatar folder directory.
     * @param int    $value ID of the avatar item being requested.
     * @param string $value Avatar type being requested.
     * @param string $value Subdirectory where the requested avatar should be found.
     */
    $avatar_folder_dir = apply_filters('bp_core_avatar_folder_dir', $avatar_loc->path . $avatar_loc->dir . $params['item_id'], $params['item_id'], $params['object'], $params['avatar_dir']);
    /**
     * Look for uploaded avatar first. Use it if it exists.
     * Set the file names to search for, to select the full size
     * or thumbnail image.
     */
    $avatar_size = 'full' == $params['type'] ? '-bpfull' : '-bpthumb';
    $legacy_user_avatar_name = 'full' == $params['type'] ? '-avatar2' : '-avatar1';
    $legacy_group_avatar_name = 'full' == $params['type'] ? '-groupavatar-full' : '-groupavatar-thumb';
    // Check for directory
    if (file_exists($avatar_folder_dir)) {
        // Open directory
        if ($av_dir = opendir($avatar_folder_dir)) {
            // Stash files in an array once to check for one that matches
            $avatar_files = array();
            while (false !== ($avatar_file = readdir($av_dir))) {
                // Only add files to the array (skip directories)
                if (2 < strlen($avatar_file)) {
                    $avatar_files[] = $avatar_file;
                }
            }
            // Check for array
            if (0 < count($avatar_files)) {
                // Check for current avatar
                foreach ($avatar_files as $key => $value) {
                    if (strpos($value, $avatar_size) !== false) {
                        $avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
                    }
                }
                // Legacy avatar check
                if (!isset($avatar_url)) {
                    foreach ($avatar_files as $key => $value) {
                        if (strpos($value, $legacy_user_avatar_name) !== false) {
                            $avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
                        }
                    }
                    // Legacy group avatar check
                    if (!isset($avatar_url)) {
                        foreach ($avatar_files as $key => $value) {
                            if (strpos($value, $legacy_group_avatar_name) !== false) {
                                $avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
                            }
                        }
                    }
                }
            }
        }
        // Close the avatar directory
        closedir($av_dir);
        // If we found a locally uploaded avatar
        if (isset($avatar_url)) {
            // Support custom scheme
            $avatar_url = set_url_scheme($avatar_url, $params['scheme']);
            // Return it wrapped in an <img> element
            if (true === $params['html']) {
                /**
                 * Filters an avatar URL wrapped in an <img> element.
                 *
                 * @since 1.1.0
                 *
                 * @param string $value             Full <img> element for an avatar.
                 * @param array  $params            Array of parameters for the request.
                 * @param string $value             ID of the item requested.
                 * @param string $value             Subdirectory where the requested avatar should be found.
                 * @param string $html_css_id       ID attribute for avatar.
                 * @param string $html_width        Width attribute for avatar.
                 * @param string $html_height       Height attribtue for avatar.
                 * @param string $avatar_folder_url Avatar URL path.
                 * @param string $avatar_folder_dir Avatar dir path.
                 */
                return apply_filters('bp_core_fetch_avatar', '<img src="' . $avatar_url . '"' . $html_class . $html_css_id . $html_width . $html_height . $html_alt . $html_title . $extra_attr . ' />', $params, $params['item_id'], $params['avatar_dir'], $html_css_id, $html_width, $html_height, $avatar_folder_url, $avatar_folder_dir);
                // ...or only the URL
            } else {
                /**
                 * Filters a locally uploaded avatar URL.
                 *
                 * @since 1.2.5
                 *
                 * @param string $avatar_url URL for a locally uploaded avatar.
                 * @param array  $params     Array of parameters for the request.
                 */
                return apply_filters('bp_core_fetch_avatar_url', $avatar_url, $params);
            }
        }
    }
    /**
     * Filters whether or not to skip Gravatar check.
     *
     * @since 1.5.0
     *
     * @param bool  $value  Whether or not to skip Gravatar.
     * @param array $params Array of parameters for the avatar request.
     */
    if (!apply_filters('bp_core_fetch_avatar_no_grav', $params['no_grav'], $params)) {
        // Set gravatar type
        if (empty($bp->grav_default->{$params['object']})) {
            $default_grav = 'wavatar';
        } elseif ('mystery' == $bp->grav_default->{$params['object']}) {
            /**
             * Filters the Mystery person avatar src value.
             *
             * @since 1.2.0
             *
             * @param string $value Avatar value.
             * @param string $value Width to display avatar at.
             */
            $default_grav = apply_filters('bp_core_mysteryman_src', 'mm', $params['width']);
        } else {
            $default_grav = $bp->grav_default->{$params['object']};
        }
        // Set gravatar object
        if (empty($params['email'])) {
            if ('user' == $params['object']) {
                $params['email'] = bp_core_get_user_email($params['item_id']);
            } elseif ('group' == $params['object'] || 'blog' == $params['object']) {
                $params['email'] = $params['item_id'] . '-' . $params['object'] . '@' . bp_get_root_domain();
            }
        }
        /**
         * Filters the Gravatar email to use.
         *
         * @since 1.1.0
         *
         * @param string $value Email to use in Gravatar request.
         * @param string $value ID of the item being requested.
         * @param string $value Object type being requested.
         */
        $params['email'] = apply_filters('bp_core_gravatar_email', $params['email'], $params['item_id'], $params['object']);
        /**
         * Filters the Gravatar URL host.
         *
         * @since 1.0.2
         *
         * @param string $value Gravatar URL host.
         */
        $gravatar = apply_filters('bp_gravatar_url', '//www.gravatar.com/avatar/');
        // Append email hash to Gravatar
        $gravatar .= md5(strtolower($params['email']));
        // Main Gravatar URL args
        $url_args = array('s' => $params['width']);
        // Custom Gravatar URL args
        if (!empty($params['force_default'])) {
            $url_args['f'] = 'y';
        }
        if (!empty($params['rating'])) {
            $url_args['r'] = strtolower($params['rating']);
        }
        // Only set default image if 'Gravatar Logo' is not requested
        if ('gravatar_default' !== $default_grav) {
            $url_args['d'] = $default_grav;
        }
        // Set up the Gravatar URL
        $gravatar = esc_url(add_query_arg(rawurlencode_deep(array_filter($url_args)), $gravatar));
        // No avatar was found, and we've been told not to use a gravatar.
    } else {
        /**
         * Filters the avatar default when Gravatar is not used.
         *
         * This is a variable filter dependent on the avatar type being requested.
         *
         * @since 1.5.0
         *
         * @param string $value  Default avatar for non-gravatar requests.
         * @param array  $params Array of parameters for the avatar request.
         */
        $gravatar = apply_filters('bp_core_default_avatar_' . $params['object'], bp_core_avatar_default('local'), $params);
    }
    if (true === $params['html']) {
        /** This filter is documented in bp-core/bp-core-avatars.php */
        return apply_filters('bp_core_fetch_avatar', '<img src="' . $gravatar . '"' . $html_css_id . $html_class . $html_width . $html_height . $html_alt . $html_title . $extra_attr . ' />', $params, $params['item_id'], $params['avatar_dir'], $html_css_id, $html_width, $html_height, $avatar_folder_url, $avatar_folder_dir);
    } else {
        /** This filter is documented in bp-core/bp-core-avatars.php */
        return apply_filters('bp_core_fetch_avatar_url', $gravatar, $params);
    }
}
Esempio n. 4
0
 public function process_request($post, array $post_data)
 {
     $post_title = $this->get_share_title($post->ID);
     $post_link = $this->get_share_url($post->ID);
     if (function_exists('mb_stripos')) {
         $strlen = 'mb_strlen';
         $substr = 'mb_substr';
     } else {
         $strlen = 'strlen';
         $substr = 'substr';
     }
     $via = $this->sharing_twitter_via($post);
     $related = $this->get_related_accounts($post);
     if ($via) {
         $sig = " via @{$via}";
         if ($related === $via) {
             $related = false;
         }
     } else {
         $via = false;
         $sig = '';
     }
     $suffix_length = $this->short_url_length + $strlen($sig);
     // $sig is handled by twitter in their 'via' argument.
     // $post_link is handled by twitter in their 'url' argument.
     if (140 < $strlen($post_title) + $suffix_length) {
         // The -1 is for "\xE2\x80\xA6", a UTF-8 ellipsis.
         $text = $substr($post_title, 0, 140 - $suffix_length - 1) . "…";
     } else {
         $text = $post_title;
     }
     // Record stats
     parent::process_request($post, $post_data);
     $url = $post_link;
     $twitter_url = add_query_arg(rawurlencode_deep(array_filter(compact('via', 'related', 'text', 'url'))), 'https://twitter.com/intent/tweet');
     // Redirect to Twitter
     wp_redirect($twitter_url);
     die;
 }
Esempio n. 5
0
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
 * page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST
 * requests.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 *
 * @global WP_Rewrite $wp_rewrite
 * @global bool $is_IIS
 * @global WP_Query $wp_query
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return string|void The string of the URL, if redirect needed.
 */
function redirect_canonical($requested_url = null, $do_redirect = true)
{
    global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;
    if (isset($_SERVER['REQUEST_METHOD']) && !in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('GET', 'HEAD'))) {
        return;
    }
    // If we're not in wp-admin and the post has been published and preview nonce
    // is non-existent or invalid then no need for preview in query
    if (is_preview() && get_query_var('p') && 'publish' == get_post_status(get_query_var('p'))) {
        if (!isset($_GET['preview_id']) || !isset($_GET['preview_nonce']) || !wp_verify_nonce($_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'])) {
            $wp_query->is_preview = false;
        }
    }
    if (is_trackback() || is_search() || is_comments_popup() || is_admin() || is_preview() || is_robots() || $is_IIS && !iis7_supports_permalinks()) {
        return;
    }
    if (!$requested_url && isset($_SERVER['HTTP_HOST'])) {
        // build the URL in the address bar
        $requested_url = is_ssl() ? 'https://' : 'http://';
        $requested_url .= $_SERVER['HTTP_HOST'];
        $requested_url .= $_SERVER['REQUEST_URI'];
    }
    $original = @parse_url($requested_url);
    if (false === $original) {
        return;
    }
    $redirect = $original;
    $redirect_url = false;
    // Notice fixing
    if (!isset($redirect['path'])) {
        $redirect['path'] = '';
    }
    if (!isset($redirect['query'])) {
        $redirect['query'] = '';
    }
    // If the original URL ended with non-breaking spaces, they were almost
    // certainly inserted by accident. Let's remove them, so the reader doesn't
    // see a 404 error with no obvious cause.
    $redirect['path'] = preg_replace('|(%C2%A0)+$|i', '', $redirect['path']);
    // It's not a preview, so remove it from URL
    if (get_query_var('preview')) {
        $redirect['query'] = remove_query_arg('preview', $redirect['query']);
    }
    if (is_feed() && ($id = get_query_var('p'))) {
        if ($redirect_url = get_post_comments_feed_link($id, get_query_var('feed'))) {
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url);
            $redirect['path'] = parse_url($redirect_url, PHP_URL_PATH);
        }
    }
    if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) {
        $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id));
        if (isset($vars[0]) && ($vars = $vars[0])) {
            if ('revision' == $vars->post_type && $vars->post_parent > 0) {
                $id = $vars->post_parent;
            }
            if ($redirect_url = get_permalink($id)) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
    }
    // These tests give us a WP-generated permalink
    if (is_404()) {
        // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
        $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id'));
        if ($id && ($redirect_post = get_post($id))) {
            $post_type_obj = get_post_type_object($redirect_post->post_type);
            if ($post_type_obj->public) {
                $redirect_url = get_permalink($redirect_post);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('day') && get_query_var('monthnum') && get_query_var('year')) {
            $year = get_query_var('year');
            $month = get_query_var('monthnum');
            $day = get_query_var('day');
            $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
            if (!wp_checkdate($month, $day, $year, $date)) {
                $redirect_url = get_month_link($year, $month);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum', 'day'), $redirect_url);
            }
        } elseif (get_query_var('monthnum') && get_query_var('year') && 12 < get_query_var('monthnum')) {
            $redirect_url = get_year_link(get_query_var('year'));
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum'), $redirect_url);
        }
        if (!$redirect_url) {
            if ($redirect_url = redirect_guess_404_permalink()) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('page') && $wp_query->post && false !== strpos($wp_query->post->post_content, '<!--nextpage-->')) {
            $redirect['path'] = rtrim($redirect['path'], (int) get_query_var('page') . '/');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
            $redirect_url = get_permalink($wp_query->post->ID);
        }
    } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) {
        // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
        if (is_attachment() && !array_diff(array_keys($wp->query_vars), array('attachment', 'attachment_id')) && !$redirect_url) {
            if (!empty($_GET['attachment_id'])) {
                $redirect_url = get_attachment_link(get_query_var('attachment_id'));
                if ($redirect_url) {
                    $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
                }
            } else {
                $redirect_url = get_attachment_link();
            }
        } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('p'))) {
                $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
            }
        } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) {
            if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) {
                $redirect['query'] = remove_query_arg('name', $redirect['query']);
            }
        } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('page_id'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) {
            $redirect_url = home_url('/');
        } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) {
            if ($redirect_url = get_permalink(get_option('page_for_posts'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) {
            $m = get_query_var('m');
            switch (strlen($m)) {
                case 4:
                    // Yearly
                    $redirect_url = get_year_link($m);
                    break;
                case 6:
                    // Monthly
                    $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2));
                    break;
                case 8:
                    // Daily
                    $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
                    break;
            }
            if ($redirect_url) {
                $redirect['query'] = remove_query_arg('m', $redirect['query']);
            }
            // now moving on to non ?m=X year/month/day links
        } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) {
            if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
            }
        } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) {
            if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
            }
        } elseif (is_year() && !empty($_GET['year'])) {
            if ($redirect_url = get_year_link(get_query_var('year'))) {
                $redirect['query'] = remove_query_arg('year', $redirect['query']);
            }
        } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) {
            $author = get_userdata(get_query_var('author'));
            if (false !== $author && $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = 'publish' LIMIT 1", $author->ID))) {
                if ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename)) {
                    $redirect['query'] = remove_query_arg('author', $redirect['query']);
                }
            }
        } elseif (is_category() || is_tag() || is_tax()) {
            // Terms (Tags/categories)
            $term_count = 0;
            foreach ($wp_query->tax_query->queried_terms as $tax_query) {
                $term_count += count($tax_query['terms']);
            }
            $obj = $wp_query->get_queried_object();
            if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) {
                if (!empty($redirect['query'])) {
                    // Strip taxonomy query vars off the url.
                    $qv_remove = array('term', 'taxonomy');
                    if (is_category()) {
                        $qv_remove[] = 'category_name';
                        $qv_remove[] = 'cat';
                    } elseif (is_tag()) {
                        $qv_remove[] = 'tag';
                        $qv_remove[] = 'tag_id';
                    } else {
                        // Custom taxonomies will have a custom query var, remove those too:
                        $tax_obj = get_taxonomy($obj->taxonomy);
                        if (false !== $tax_obj->query_var) {
                            $qv_remove[] = $tax_obj->query_var;
                        }
                    }
                    $rewrite_vars = array_diff(array_keys($wp_query->query), array_keys($_GET));
                    if (!array_diff($rewrite_vars, array_keys($_GET))) {
                        // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
                        $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']);
                        //Remove all of the per-tax qv's
                        // Create the destination url for this taxonomy
                        $tax_url = parse_url($tax_url);
                        if (!empty($tax_url['query'])) {
                            // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
                            parse_str($tax_url['query'], $query_vars);
                            $redirect['query'] = add_query_arg($query_vars, $redirect['query']);
                        } else {
                            // Taxonomy is accessible via a "pretty-URL"
                            $redirect['path'] = $tax_url['path'];
                        }
                    } else {
                        // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
                        foreach ($qv_remove as $_qv) {
                            if (isset($rewrite_vars[$_qv])) {
                                $redirect['query'] = remove_query_arg($_qv, $redirect['query']);
                            }
                        }
                    }
                }
            }
        } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && ($cat = get_query_var('category_name'))) {
            $category = get_category_by_path($cat);
            $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
            if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) {
                $redirect_url = get_permalink($wp_query->get_queried_object_id());
            }
        }
        // Post Paging
        if (is_singular() && !is_front_page() && get_query_var('page')) {
            if (!$redirect_url) {
                $redirect_url = get_permalink(get_queried_object_id());
            }
            $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
        }
        // paging and feeds
        if (get_query_var('paged') || is_feed() || get_query_var('cpage')) {
            while (preg_match("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", $redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path']) || preg_match("#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?\$#", $redirect['path'])) {
                // Strip off paging and feed
                $redirect['path'] = preg_replace("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing paging
                $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']);
                // strip off feed endings
                $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing comment paging
            }
            $addl_path = '';
            if (is_feed() && in_array(get_query_var('feed'), $wp_rewrite->feeds)) {
                $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                if (!is_singular() && get_query_var('withcomments')) {
                    $addl_path .= 'comments/';
                }
                if ('rss' == get_default_feed() && 'feed' == get_query_var('feed') || 'rss' == get_query_var('feed')) {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == 'rss2' ? '' : 'rss2'), 'feed');
                } else {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed');
                }
                $redirect['query'] = remove_query_arg('feed', $redirect['query']);
            } elseif (is_feed() && 'old' == get_query_var('feed')) {
                $old_feed_files = array('wp-atom.php' => 'atom', 'wp-commentsrss2.php' => 'comments_rss2', 'wp-feed.php' => get_default_feed(), 'wp-rdf.php' => 'rdf', 'wp-rss.php' => 'rss2', 'wp-rss2.php' => 'rss2');
                if (isset($old_feed_files[basename($redirect['path'])])) {
                    $redirect_url = get_feed_link($old_feed_files[basename($redirect['path'])]);
                    wp_redirect($redirect_url, 301);
                    die;
                }
            }
            if (get_query_var('paged') > 0) {
                $paged = get_query_var('paged');
                $redirect['query'] = remove_query_arg('paged', $redirect['query']);
                if (!is_feed()) {
                    if ($paged > 1 && !is_single()) {
                        $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("{$wp_rewrite->pagination_base}/{$paged}", 'paged');
                    } elseif (!is_single()) {
                        $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                    }
                } elseif ($paged > 1) {
                    $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']);
                }
            }
            if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) {
                $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit($wp_rewrite->comments_pagination_base . '-' . get_query_var('cpage'), 'commentpaged');
                $redirect['query'] = remove_query_arg('cpage', $redirect['query']);
            }
            $redirect['path'] = user_trailingslashit(preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/?$|', '/', $redirect['path']));
            // strip off trailing /index.php/
            if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false) {
                $redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/';
            }
            if (!empty($addl_path)) {
                $redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
            }
            $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
        }
        if ('wp-register.php' == basename($redirect['path'])) {
            if (is_multisite()) {
                /** This filter is documented in wp-login.php */
                $redirect_url = apply_filters('wp_signup_location', network_site_url('wp-signup.php'));
            } else {
                $redirect_url = wp_registration_url();
            }
            wp_redirect($redirect_url, 301);
            die;
        }
    }
    // tack on any additional query vars
    $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    if ($redirect_url && !empty($redirect['query'])) {
        parse_str($redirect['query'], $_parsed_query);
        $redirect = @parse_url($redirect_url);
        if (!empty($_parsed_query['name']) && !empty($redirect['query'])) {
            parse_str($redirect['query'], $_parsed_redirect_query);
            if (empty($_parsed_redirect_query['name'])) {
                unset($_parsed_query['name']);
            }
        }
        $_parsed_query = rawurlencode_deep($_parsed_query);
        $redirect_url = add_query_arg($_parsed_query, $redirect_url);
    }
    if ($redirect_url) {
        $redirect = @parse_url($redirect_url);
    }
    // www.example.com vs example.com
    $user_home = @parse_url(home_url());
    if (!empty($user_home['host'])) {
        $redirect['host'] = $user_home['host'];
    }
    if (empty($user_home['path'])) {
        $user_home['path'] = '/';
    }
    // Handle ports
    if (!empty($user_home['port'])) {
        $redirect['port'] = $user_home['port'];
    } else {
        unset($redirect['port']);
    }
    // trailing /index.php
    $redirect['path'] = preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/*?$|', '/', $redirect['path']);
    // Remove trailing spaces from the path
    $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']);
    if (!empty($redirect['query'])) {
        // Remove trailing spaces from certain terminating query string args
        $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']);
        // Clean up empty query strings
        $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
        // Redirect obsolete feeds
        $redirect['query'] = preg_replace('#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query']);
        // Remove redundant leading ampersands
        $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    }
    // strip /index.php/ when we're not using PATHINFO permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $redirect['path'] = str_replace('/' . $wp_rewrite->index . '/', '/', $redirect['path']);
    }
    // trailing slashes
    if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) {
        $user_ts_type = '';
        if (get_query_var('paged') > 0) {
            $user_ts_type = 'paged';
        } else {
            foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) {
                $func = 'is_' . $type;
                if (call_user_func($func)) {
                    $user_ts_type = $type;
                    break;
                }
            }
        }
        $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
    } elseif (is_front_page()) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Strip multiple slashes out of the URL
    if (strpos($redirect['path'], '//') > -1) {
        $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
    }
    // Always trailing slash the Front Page URL
    if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Ignore differences in host capitalization, as this can lead to infinite redirects
    // Only redirect no-www <=> yes-www
    if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) {
        $redirect['host'] = $original['host'];
    }
    $compare_original = array($original['host'], $original['path']);
    if (!empty($original['port'])) {
        $compare_original[] = $original['port'];
    }
    if (!empty($original['query'])) {
        $compare_original[] = $original['query'];
    }
    $compare_redirect = array($redirect['host'], $redirect['path']);
    if (!empty($redirect['port'])) {
        $compare_redirect[] = $redirect['port'];
    }
    if (!empty($redirect['query'])) {
        $compare_redirect[] = $redirect['query'];
    }
    if ($compare_original !== $compare_redirect) {
        $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
        if (!empty($redirect['port'])) {
            $redirect_url .= ':' . $redirect['port'];
        }
        $redirect_url .= $redirect['path'];
        if (!empty($redirect['query'])) {
            $redirect_url .= '?' . $redirect['query'];
        }
    }
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    // Hex encoded octets are case-insensitive.
    if (false !== strpos($requested_url, '%')) {
        if (!function_exists('lowercase_octets')) {
            function lowercase_octets($matches)
            {
                return strtolower($matches[0]);
            }
        }
        $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
    }
    /**
     * Filter the canonical redirect URL.
     *
     * Returning false to this filter will cancel the redirect.
     *
     * @since 2.3.0
     *
     * @param string $redirect_url  The redirect URL.
     * @param string $requested_url The requested URL.
     */
    $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);
    // yes, again -- in case the filter aborted the request
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    if ($do_redirect) {
        // protect against chained redirects
        if (!redirect_canonical($redirect_url, false)) {
            wp_redirect($redirect_url, 301);
            exit;
        } else {
            // Debug
            // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
            return;
        }
    } else {
        return $redirect_url;
    }
}
Esempio n. 6
0
/**
 * Generates a Photon URL.
 *
 * @see http://developer.wordpress.com/docs/photon/
 *
 * @param string $image_url URL to the publicly accessible image you want to manipulate
 * @param array|string $args An array of arguments, i.e. array( 'w' => '300', 'resize' => array( 123, 456 ) ), or in string form (w=123&h=456)
 * @return string The raw final URL. You should run this through esc_url() before displaying it.
 */
function jetpack_photon_url($image_url, $args = array(), $scheme = null)
{
    $image_url = trim($image_url);
    if (class_exists('Jetpack')) {
        /**
         * Disables Photon URL processing for local development
         *
         * @module photon
         *
         * @since 4.1.0
         *
         * @param bool false Result of Jetpack::is_development_mode.
         */
        if (true === apply_filters('jetpack_photon_development_mode', Jetpack::is_development_mode())) {
            return $image_url;
        }
    }
    /**
     * Allow specific image URls to avoid going through Photon.
     *
     * @module photon
     *
     * @since 3.2.0
     *
     * @param bool false Should the image be returned as is, without going through Photon. Default to false.
     * @param string $image_url Image URL.
     * @param array|string $args Array of Photon arguments.
     * @param string|null $scheme Image scheme. Default to null.
     */
    if (false !== apply_filters('jetpack_photon_skip_for_url', false, $image_url, $args, $scheme)) {
        return $image_url;
    }
    /**
     * Filter the original image URL before it goes through Photon.
     *
     * @module photon
     *
     * @since 1.9.0
     *
     * @param string $image_url Image URL.
     * @param array|string $args Array of Photon arguments.
     * @param string|null $scheme Image scheme. Default to null.
     */
    $image_url = apply_filters('jetpack_photon_pre_image_url', $image_url, $args, $scheme);
    /**
     * Filter the original Photon image parameters before Photon is applied to an image.
     *
     * @module photon
     *
     * @since 1.9.0
     *
     * @param array|string $args Array of Photon arguments.
     * @param string $image_url Image URL.
     * @param string|null $scheme Image scheme. Default to null.
     */
    $args = apply_filters('jetpack_photon_pre_args', $args, $image_url, $scheme);
    if (empty($image_url)) {
        return $image_url;
    }
    $image_url_parts = @parse_url($image_url);
    // Unable to parse
    if (!is_array($image_url_parts) || empty($image_url_parts['host']) || empty($image_url_parts['path'])) {
        return $image_url;
    }
    if (is_array($args)) {
        // Convert values that are arrays into strings
        foreach ($args as $arg => $value) {
            if (is_array($value)) {
                $args[$arg] = implode(',', $value);
            }
        }
        // Encode values
        // See http://core.trac.wordpress.org/ticket/17923
        $args = rawurlencode_deep($args);
    }
    /** This filter is documented below. */
    $custom_photon_url = apply_filters('jetpack_photon_domain', '', $image_url);
    $custom_photon_url = esc_url($custom_photon_url);
    // You can't run a Photon URL through Photon again because query strings are stripped.
    // So if the image is already a Photon URL, append the new arguments to the existing URL.
    if (in_array($image_url_parts['host'], array('i0.wp.com', 'i1.wp.com', 'i2.wp.com')) || $image_url_parts['host'] === parse_url($custom_photon_url, PHP_URL_HOST)) {
        $photon_url = add_query_arg($args, $image_url);
        return jetpack_photon_url_scheme($photon_url, $scheme);
    }
    /**
     * Allow Photon to use query strings as well.
     * By default, Photon doesn't support query strings so we ignore them and look only at the path.
     * This setting is Photon Server dependent.
     *
     * @module photon
     *
     * @since 1.9.0
     *
     * @param bool false Should images using query strings go through Photon. Default is false.
     * @param string $image_url_parts['host'] Image URL's host.
     */
    if (!apply_filters('jetpack_photon_any_extension_for_domain', false, $image_url_parts['host'])) {
        // Photon doesn't support query strings so we ignore them and look only at the path.
        // However some source images are served via PHP so check the no-query-string extension.
        // For future proofing, this is a blacklist of common issues rather than a whitelist.
        $extension = pathinfo($image_url_parts['path'], PATHINFO_EXTENSION);
        if (empty($extension) || in_array($extension, array('php'))) {
            return $image_url;
        }
    }
    $image_host_path = $image_url_parts['host'] . $image_url_parts['path'];
    // Figure out which CDN subdomain to use
    srand(crc32($image_host_path));
    $subdomain = rand(0, 2);
    srand();
    /**
     * Filters the domain used by the Photon module.
     *
     * @module photon
     *
     * @since 3.4.2
     *
     * @param string https://i{$subdomain}.wp.com Domain used by Photon. $subdomain is a random number between 0 and 2.
     * @param string $image_url URL of the image to be photonized.
     */
    $photon_domain = apply_filters('jetpack_photon_domain', "https://i{$subdomain}.wp.com", $image_url);
    $photon_domain = trailingslashit(esc_url($photon_domain));
    $photon_url = $photon_domain . $image_host_path;
    /**
     * Add query strings to Photon URL.
     * By default, Photon doesn't support query strings so we ignore them.
     * This setting is Photon Server dependent.
     *
     * @module photon
     *
     * @since 1.9.0
     *
     * @param bool false Should query strings be added to the image URL. Default is false.
     * @param string $image_url_parts['host'] Image URL's host.
     */
    if (isset($image_url_parts['query']) && apply_filters('jetpack_photon_add_query_string_to_domain', false, $image_url_parts['host'])) {
        $photon_url .= '?q=' . rawurlencode($image_url_parts['query']);
    }
    if ($args) {
        if (is_array($args)) {
            $photon_url = add_query_arg($args, $photon_url);
        } else {
            // You can pass a query string for complicated requests but where you still want CDN subdomain help, etc.
            $photon_url .= '?' . $args;
        }
    }
    if (isset($image_url_parts['scheme']) && 'https' == $image_url_parts['scheme']) {
        $photon_url = add_query_arg(array('ssl' => 1), $photon_url);
    }
    return jetpack_photon_url_scheme($photon_url, $scheme);
}
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on IIS, page/post previews, and on form data.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 * @uses $wp_rewrite
 * @uses $is_IIS
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return null|false|string Null, if redirect not needed. False, if redirect
 *		not needed or the string of the URL
 */
function redirect_canonical( $requested_url = null, $do_redirect = true ) {
	global $wp_rewrite, $is_IIS, $wp_query, $wpdb;

	if ( is_trackback() || is_search() || is_comments_popup() || is_admin() || !empty($_POST) || is_preview() || is_robots() || $is_IIS )
		return;

	if ( !$requested_url ) {
		// build the URL in the address bar
		$requested_url  = is_ssl() ? 'https://' : 'http://';
		$requested_url .= $_SERVER['HTTP_HOST'];
		$requested_url .= $_SERVER['REQUEST_URI'];
	}

	$original = @parse_url($requested_url);
	if ( false === $original )
		return;

	// Some PHP setups turn requests for / into /index.php in REQUEST_URI
	// See: http://trac.wordpress.org/ticket/5017
	// See: http://trac.wordpress.org/ticket/7173
	// Disabled, for now:
	// $original['path'] = preg_replace('|/index\.php$|', '/', $original['path']);

	$redirect = $original;
	$redirect_url = false;

	// Notice fixing
	if ( !isset($redirect['path']) )
		$redirect['path'] = '';
	if ( !isset($redirect['query']) )
		$redirect['query'] = '';

	if ( is_feed() && ( $id = get_query_var( 'p' ) ) ) {
		if ( $redirect_url = get_post_comments_feed_link( $id, get_query_var( 'feed' ) ) ) {
			$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url );
			$redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
		}
	}

	if ( is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p')) ) {

		$vars = $wpdb->get_results( $wpdb->prepare("SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $id) );

		if ( isset($vars[0]) && $vars = $vars[0] ) {
			if ( 'revision' == $vars->post_type && $vars->post_parent > 0 )
				$id = $vars->post_parent;

			if ( $redirect_url = get_permalink($id) )
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
		}
	}

	// These tests give us a WP-generated permalink
	if ( is_404() ) {

		// Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
		$id = max( get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id') );
		if ( $id && $redirect_post = get_post($id) ) {
			$post_type_obj = get_post_type_object($redirect_post->post_type);
			if ( $post_type_obj->public ) {
				$redirect_url = get_permalink($redirect_post);
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
			}
		}

		if ( ! $redirect_url ) {
			if ( $redirect_url = redirect_guess_404_permalink( $requested_url ) ) {
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
			}
		}

	} elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) {
		// rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
		if ( is_attachment() && !empty($_GET['attachment_id']) && ! $redirect_url ) {
			if ( $redirect_url = get_attachment_link(get_query_var('attachment_id')) )
				$redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
		} elseif ( is_single() && !empty($_GET['p']) && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_query_var('p')) )
				$redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
		} elseif ( is_single() && !empty($_GET['name'])  && ! $redirect_url ) {
			if ( $redirect_url = get_permalink( $wp_query->get_queried_object_id() ) )
				$redirect['query'] = remove_query_arg('name', $redirect['query']);
		} elseif ( is_page() && !empty($_GET['page_id']) && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_query_var('page_id')) )
				$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
		} elseif ( is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front')  && ! $redirect_url ) {
			$redirect_url = home_url('/');
		} elseif ( is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts')  && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_option('page_for_posts')) )
				$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
		} elseif ( !empty($_GET['m']) && ( is_year() || is_month() || is_day() ) ) {
			$m = get_query_var('m');
			switch ( strlen($m) ) {
				case 4: // Yearly
					$redirect_url = get_year_link($m);
					break;
				case 6: // Monthly
					$redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
					break;
				case 8: // Daily
					$redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
					break;
			}
			if ( $redirect_url )
				$redirect['query'] = remove_query_arg('m', $redirect['query']);
		// now moving on to non ?m=X year/month/day links
		} elseif ( is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day']) ) {
			if ( $redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')) )
				$redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
		} elseif ( is_month() && get_query_var('year') && !empty($_GET['monthnum']) ) {
			if ( $redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum')) )
				$redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
		} elseif ( is_year() && !empty($_GET['year']) ) {
			if ( $redirect_url = get_year_link(get_query_var('year')) )
				$redirect['query'] = remove_query_arg('year', $redirect['query']);
		} elseif ( is_author() && !empty($_GET['author']) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
			$author = get_userdata(get_query_var('author'));
			if ( ( false !== $author ) && $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_author = %d AND $wpdb->posts.post_status = 'publish' LIMIT 1", $author->ID ) ) ) {
				if ( $redirect_url = get_author_posts_url($author->ID, $author->user_nicename) )
					$redirect['query'] = remove_query_arg('author', $redirect['query']);
			}
		} elseif ( is_category() || is_tag() || is_tax() ) { // Terms (Tags/categories)

			$term_count = 0;
			foreach ( $wp_query->tax_query->queries as $tax_query )
				$term_count += count( $tax_query['terms'] );

			$obj = $wp_query->get_queried_object();
			if ( $term_count <= 1 && !empty($obj->term_id) && ( $tax_url = get_term_link((int)$obj->term_id, $obj->taxonomy) ) && !is_wp_error($tax_url) ) {
				if ( !empty($redirect['query']) ) {
					// Strip taxonomy query vars off the url.
					$qv_remove = array( 'term', 'taxonomy');
					if ( is_category() ) {
						$qv_remove[] = 'category_name';
						$qv_remove[] = 'cat';
					} elseif ( is_tag() ) {
						$qv_remove[] = 'tag';
						$qv_remove[] = 'tag_id';
					} else { // Custom taxonomies will have a custom query var, remove those too:
						$tax_obj = get_taxonomy( $obj->taxonomy );
						if ( false !== $tax_obj->query_var )
							$qv_remove[] = $tax_obj->query_var;
					}

					$rewrite_vars = array_diff( array_keys($wp_query->query), array_keys($_GET) );

					if ( !array_diff($rewrite_vars, array_keys($_GET))  ) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
						$redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's

						// Create the destination url for this taxonomy
						$tax_url = parse_url($tax_url);
						if ( ! empty($tax_url['query']) ) { // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
							parse_str($tax_url['query'], $query_vars);
							$redirect['query'] = add_query_arg($query_vars, $redirect['query']);
						} else { // Taxonomy is accessible via a "pretty-URL"
							$redirect['path'] = $tax_url['path'];
						}

					} else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
						foreach ( $qv_remove as $_qv ) {
							if ( isset($rewrite_vars[$_qv]) )
								$redirect['query'] = remove_query_arg($_qv, $redirect['query']);
						}
					}
				}

			}
		} elseif ( is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && $cat = get_query_var( 'category_name' ) ) {
			$category = get_category_by_path( $cat );
			$post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
			if ( (!$category || is_wp_error($category)) || ( !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms) ) )
				$redirect_url = get_permalink($wp_query->get_queried_object_id());
		}

		// Post Paging
		if ( is_singular() && ! is_front_page() && get_query_var('page') ) {
			if ( !$redirect_url )
				$redirect_url = get_permalink( get_queried_object_id() );
			$redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
			$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
		}

		// paging and feeds
		if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
			while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path'] ) || preg_match( '#/comment-page-[0-9]+(/+)?$#', $redirect['path'] ) ) {
				// Strip off paging and feed
				$redirect['path'] = preg_replace("#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing paging
				$redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings
				$redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $redirect['path']); // strip off any existing comment paging
			}

			$addl_path = '';
			if ( is_feed() && in_array( get_query_var('feed'), $wp_rewrite->feeds ) ) {
				$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
				if ( !is_singular() && get_query_var( 'withcomments' ) )
					$addl_path .= 'comments/';
				if ( ( 'rss' == get_default_feed() && 'feed' == get_query_var('feed') ) || 'rss' == get_query_var('feed') )
					$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == 'rss2' ) ? '' : 'rss2' ), 'feed' );
				else
					$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() ==  get_query_var('feed') || 'feed' == get_query_var('feed') ) ? '' : get_query_var('feed') ), 'feed' );
				$redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
			} elseif ( is_feed() && 'old' == get_query_var('feed') ) {
				$old_feed_files = array(
					'wp-atom.php'         => 'atom',
					'wp-commentsrss2.php' => 'comments_rss2',
					'wp-feed.php'         => get_default_feed(),
					'wp-rdf.php'          => 'rdf',
					'wp-rss.php'          => 'rss2',
					'wp-rss2.php'         => 'rss2',
				);
				if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
					$redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
					wp_redirect( $redirect_url, 301 );
					die();
				}
			}

			if ( get_query_var('paged') > 0 ) {
				$paged = get_query_var('paged');
				$redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
				if ( !is_feed() ) {
					if ( $paged > 1 && !is_single() ) {
						$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit("$wp_rewrite->pagination_base/$paged", 'paged');
					} elseif ( !is_single() ) {
						$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
					}
				} elseif ( $paged > 1 ) {
					$redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
				}
			}

			if ( get_option('page_comments') && ( ( 'newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 ) || ( 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1 ) ) ) {
				$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit( 'comment-page-' . get_query_var('cpage'), 'commentpaged' );
				$redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
			}

			$redirect['path'] = user_trailingslashit( preg_replace('|/index.php/?$|', '/', $redirect['path']) ); // strip off trailing /index.php/
			if ( !empty( $addl_path ) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/index.php/') === false )
				$redirect['path'] = trailingslashit($redirect['path']) . 'index.php/';
			if ( !empty( $addl_path ) )
				$redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
			$redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
		}

		if ( 'wp-register.php' == basename( $redirect['path'] ) ) {
			if ( is_multisite() )
				$redirect_url = apply_filters( 'wp_signup_location', site_url( 'wp-signup.php' ) );
			else
				$redirect_url = site_url( 'wp-login.php?action=register' );
			wp_redirect( $redirect_url, 301 );
			die();
		}
	}

	// tack on any additional query vars
	$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
	if ( $redirect_url && !empty($redirect['query']) ) {
		parse_str( $redirect['query'], $_parsed_query );
		$redirect = @parse_url($redirect_url);

		if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
			parse_str( $redirect['query'], $_parsed_redirect_query );

			if ( empty( $_parsed_redirect_query['name'] ) )
				unset( $_parsed_query['name'] );
		}

		$_parsed_query = rawurlencode_deep( $_parsed_query );
		$redirect_url = add_query_arg( $_parsed_query, $redirect_url );
	}

	if ( $redirect_url )
		$redirect = @parse_url($redirect_url);

	// www.example.com vs example.com
	$user_home = @parse_url(home_url());
	if ( !empty($user_home['host']) )
		$redirect['host'] = $user_home['host'];
	if ( empty($user_home['path']) )
		$user_home['path'] = '/';

	// Handle ports
	if ( !empty($user_home['port']) )
		$redirect['port'] = $user_home['port'];
	else
		unset($redirect['port']);

	// trailing /index.php
	$redirect['path'] = preg_replace('|/index.php/*?$|', '/', $redirect['path']);

	// Remove trailing spaces from the path
	$redirect['path'] = preg_replace( '#(%20| )+$#', '', $redirect['path'] );

	if ( !empty( $redirect['query'] ) ) {
		// Remove trailing spaces from certain terminating query string args
		$redirect['query'] = preg_replace( '#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query'] );

		// Clean up empty query strings
		$redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');

		// Redirect obsolete feeds
		$redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$3', $redirect['query'] );

		// Remove redundant leading ampersands
		$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
	}

	// strip /index.php/ when we're not using PATHINFO permalinks
	if ( !$wp_rewrite->using_index_permalinks() )
		$redirect['path'] = str_replace('/index.php/', '/', $redirect['path']);

	// trailing slashes
	if ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || ( is_front_page() && (get_query_var('paged') > 1) ) ) ) {
		$user_ts_type = '';
		if ( get_query_var('paged') > 0 ) {
			$user_ts_type = 'paged';
		} else {
			foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) {
				$func = 'is_' . $type;
				if ( call_user_func($func) ) {
					$user_ts_type = $type;
					break;
				}
			}
		}
		$redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
	} elseif ( is_front_page() ) {
		$redirect['path'] = trailingslashit($redirect['path']);
	}

	// Strip multiple slashes out of the URL
	if ( strpos($redirect['path'], '//') > -1 )
		$redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);

	// Always trailing slash the Front Page URL
	if ( trailingslashit( $redirect['path'] ) == trailingslashit( $user_home['path'] ) )
		$redirect['path'] = trailingslashit($redirect['path']);

	// Ignore differences in host capitalization, as this can lead to infinite redirects
	// Only redirect no-www <=> yes-www
	if ( strtolower($original['host']) == strtolower($redirect['host']) ||
		( strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host']) ) )
		$redirect['host'] = $original['host'];

	$compare_original = array($original['host'], $original['path']);

	if ( !empty( $original['port'] ) )
		$compare_original[] = $original['port'];

	if ( !empty( $original['query'] ) )
		$compare_original[] = $original['query'];

	$compare_redirect = array($redirect['host'], $redirect['path']);

	if ( !empty( $redirect['port'] ) )
		$compare_redirect[] = $redirect['port'];

	if ( !empty( $redirect['query'] ) )
		$compare_redirect[] = $redirect['query'];

	if ( $compare_original !== $compare_redirect ) {
		$redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
		if ( !empty($redirect['port']) )
			$redirect_url .= ':' . $redirect['port'];
		$redirect_url .= $redirect['path'];
		if ( !empty($redirect['query']) )
			$redirect_url .= '?' . $redirect['query'];
	}

	if ( !$redirect_url || $redirect_url == $requested_url )
		return false;

	// Hex encoded octets are case-insensitive.
	if ( false !== strpos($requested_url, '%') ) {
		if ( !function_exists('lowercase_octets') ) {
			function lowercase_octets($matches) {
				return strtolower( $matches[0] );
			}
		}
		$requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
	}

	// Note that you can use the "redirect_canonical" filter to cancel a canonical redirect for whatever reason by returning false
	$redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);

	if ( !$redirect_url || $redirect_url == $requested_url ) // yes, again -- in case the filter aborted the request
		return false;

	if ( $do_redirect ) {
		// protect against chained redirects
		if ( !redirect_canonical($redirect_url, false) ) {
			wp_redirect($redirect_url, 301);
			exit();
		} else {
			// Debug
			// die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
			return false;
		}
	} else {
		return $redirect_url;
	}
}
 /**
  * Sanitizes the option's value (settings and contacts)
  * 
  * @since 0.0.1
  * 
  * @param  array $input Multidimensional array for the option
  * @return array The sanitized option
  * 
  * @usedby https://codex.wordpress.org/Function_Reference/register_setting
  * @in class-mcb-admin.php Mobile_Contact_Bar_Admin::admin_init()
  * 
  * @uses https://developer.wordpress.org/reference/functions/sanitize_text_field
  * @uses https://codex.wordpress.org/Function_Reference/absint
  * @uses https://codex.wordpress.org/Function_Reference/sanitize_email
  * @uses https://codex.wordpress.org/Function_Reference/is_email
  * @uses https://codex.wordpress.org/Function_Reference/esc_url_raw
  * @uses https://codex.wordpress.org/Function_Reference/sanitize_key
  * @uses https://developer.wordpress.org/reference/functions/rawurlencode_deep
  * @uses class-mcb-admin.php Mobile_Contact_Bar_Admin::sanitize_hex_color()
  * @uses class-mcb-admin.php Mobile_Contact_Bar_Admin::sanitize_rgba_color()
  * @uses class-mcb-admin.php Mobile_Contact_Bar_Admin::sanitize_float()
  * @uses class-mcb-admin.php Mobile_Contact_Bar_Admin::sanitize_phone_number()
  * @uses class-mcb-admin.php Mobile_Contact_Bar_Admin::sanitize_keys_recursive()
  * 
  */
 public static function sanitize_input($input)
 {
     $in_settings = $input['settings'];
     $in_contacts = $input['contacts'];
     $out_settings = array();
     $out_contacts = array();
     /* -------------------------------------------------------------------------- */
     /*                                  Settings                                  */
     /* -------------------------------------------------------------------------- */
     // workaround empty checkboxes
     $in_settings = array_replace(array_map(function ($field) {
         if ('checkbox' == $field['type']) {
             return 0;
         }
     }, self::$settings), $in_settings);
     // all settings will be saved, at least with their default values
     $in_settings = array_replace(array_map(function ($field) {
         return $field['default'];
     }, self::$settings), $in_settings);
     foreach ($in_settings as $id => $value) {
         switch (self::$settings[$id]['type']) {
             case 'select':
                 if (in_array($value, array_keys(self::$settings[$id]['options']))) {
                     $out_settings[$id] = sanitize_text_field($value);
                 } else {
                     $out_settings[$id] = sanitize_text_field(self::$settings[$id]['default']);
                 }
                 break;
             case 'color-picker':
                 $color = self::sanitize_hex_color($value);
                 if (!$color) {
                     $color = self::sanitize_rgba_color($value);
                 }
                 if (!$color) {
                     $color = self::sanitize_hex_color(self::$settings[$id]['default']);
                 }
                 $out_settings[$id] = $color;
                 break;
             case 'checkbox':
             case 'number':
                 $out_settings[$id] = absint($value);
                 break;
             case 'slider':
                 $float = self::sanitize_float($value);
                 $out_settings[$id] = $float ? $float : self::sanitize_float(self::$settings[$id]['default']);
                 break;
         }
     }
     /* -------------------------------------------------------------------------- */
     /*                                 Contacts                                   */
     /* -------------------------------------------------------------------------- */
     foreach ($in_contacts as $id => $contact) {
         $resource = '';
         switch (self::$contacts[$id]['protocol']) {
             case 'tel':
                 $resource = self::sanitize_phone_number($contact['url']);
                 break;
             case 'skype':
                 $resource = sanitize_text_field($contact['url']);
                 break;
             case 'mailto':
                 $resource = sanitize_email($contact['url']);
                 $resource = is_email($resource) ? $resource : '';
                 break;
             case 'http':
             case 'https':
                 $resource = esc_url_raw($contact['url']);
                 break;
             default:
                 $resource = sanitize_text_field($contact['url']);
                 break;
         }
         if (!empty($resource)) {
             $out_contacts[$id] = array('icon' => sanitize_key(self::$contacts[$id]['icon']), 'protocol' => sanitize_key(self::$contacts[$id]['protocol']), 'resource' => $resource);
         }
         if (isset(self::$contacts[$id]['parameters'])) {
             $in_parameters = array_filter(array_intersect_key($contact, self::$contacts[$id]['parameters']));
             $out_parameters = rawurlencode_deep($in_parameters);
             if (array_filter($out_parameters)) {
                 $out_contacts[$id]['parameters'] = array_filter($out_parameters);
             }
         }
     }
     // two sublists: first one is for contacts with icon, second one is for contacts without icons but with parameters
     $displayable = array_filter($out_contacts, function ($contact) {
         return isset($contact['icon']);
     });
     $storable = array_diff_key($out_contacts, $displayable);
     // contacts with parameters only
     $out_contacts = array_merge($displayable, $storable);
     return array_filter(array_replace(self::$option, array('settings' => self::sanitize_keys_recursive($out_settings), 'contacts' => array_filter($out_contacts) ? self::sanitize_keys_recursive(array_filter($out_contacts)) : null)));
 }
Esempio n. 9
0
 public function bp_core_fetch_avatar_filter_check($html, $params)
 {
     // Check that the passed parameters match the original custom parameters.
     $this->assertEmpty(array_merge(array_diff($params, $this->params), array_diff($this->params, $params)));
     // Check the returned html to see that it matches an expected value.
     // Get the correct default avatar, based on whether gravatars are allowed.
     if ($params['no_grav']) {
         $avatar_url = bp_core_avatar_default('local', $params);
     } else {
         // This test has the slight odor of hokum since it recreates so much code that could be changed at any time.
         $bp = buddypress();
         $host = '//www.gravatar.com/avatar/';
         // Set expected gravatar type
         if (empty($bp->grav_default->{$this->params['object']})) {
             $default_grav = 'wavatar';
         } elseif ('mystery' == $bp->grav_default->{$this->params['object']}) {
             $default_grav = apply_filters('bp_core_mysteryman_src', 'mm', $this->params['width']);
         } else {
             $default_grav = $bp->grav_default->{$this->params['object']};
         }
         $avatar_url = $host . md5(strtolower($this->params['email']));
         // Main Gravatar URL args.
         $url_args = array('s' => $this->params['width']);
         // Force default.
         if (!empty($this->params['force_default'])) {
             $url_args['f'] = 'y';
         }
         // Gravatar rating; http://bit.ly/89QxZA
         $rating = strtolower(get_option('avatar_rating'));
         if (!empty($rating)) {
             $url_args['r'] = $rating;
         }
         // Default avatar.
         if ('gravatar_default' !== $default_grav) {
             $url_args['d'] = $default_grav;
         }
         // Set up the Gravatar URL.
         $avatar_url = esc_url(add_query_arg(rawurlencode_deep(array_filter($url_args)), $avatar_url));
     }
     $expected_html = '<img src="' . $avatar_url . '" id="' . $this->params['css_id'] . '" class="' . $this->params['class'] . ' ' . $this->params['object'] . '-' . $this->params['item_id'] . '-avatar avatar-' . $this->params['width'] . ' photo" width="' . $this->params['width'] . '" height="' . $this->params['height'] . '" alt="' . $this->params['alt'] . '" title="' . $this->params['title'] . '" ' . $this->params['extra_attr'] . ' />';
     $this->assertEquals($html, $expected_html);
 }
 /**
  * Manages canonical redirection of the homepage when using page on front
  *
  * @since 0.1
  *
  * @param string $redirect_url
  * @param string $requested_url
  * @return bool|string modified url, false if redirection is canceled
  */
 public function redirect_canonical($redirect_url, $requested_url)
 {
     global $wp_query;
     if (is_page() && !is_feed() && isset($wp_query->queried_object) && $wp_query->queried_object->ID == $this->curlang->page_on_front) {
         $url = is_paged() ? $this->links_model->add_paged_to_link($this->links->get_home_url(), $wp_query->query_vars['page']) : $this->links->get_home_url();
         // Don't forget additional query vars
         $query = parse_url($redirect_url, PHP_URL_QUERY);
         if (!empty($query)) {
             parse_str($query, $query_vars);
             $query_vars = rawurlencode_deep($query_vars);
             // WP encodes query vars values
             $url = add_query_arg($query_vars, $url);
         }
         return $url;
     }
     return $redirect_url;
 }
 /**
  * Image resizing service.  Takes place of image_downsize().
  *
  * @param bool $ignore Unused.
  * @param int $id Attachment ID for image.
  * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
  * @return bool|array False on failure, array on success.
  * @see image_downsize()
  */
 function image_resize($ignore, $id, $size)
 {
     global $_wp_additional_image_sizes, $post;
     $content_width = isset($GLOBALS['content_width']) ? $GLOBALS['content_width'] : null;
     $crop = false;
     $args = array();
     // For resize requests coming from an image's attachment page, override
     // the supplied $size and use the user-defined $content_width if the
     // theme-defined $content_width has been manually passed in.
     if (is_attachment() && $id === $post->ID) {
         if (is_array($size) && !empty($size) && isset($GLOBALS['content_width']) && $size[0] == $GLOBALS['content_width']) {
             $size = array($content_width, $content_width);
         }
     }
     if ('tellyworth' == $size) {
         // 'full' is reserved because some themes use it (see image_constrain_size_for_editor)
         $_max_w = 4096;
         $_max_h = 4096;
     } elseif ('thumbnail' == $size) {
         $_max_w = get_option('thumbnail_size_w');
         $_max_h = get_option('thumbnail_size_h');
         if (!$_max_w && !$_max_h) {
             $_max_w = 128;
             $_max_h = 96;
         }
         if (get_option('thumbnail_crop')) {
             $crop = true;
         }
     } elseif ('medium' == $size) {
         $_max_w = get_option('medium_size_w');
         $_max_h = get_option('medium_size_h');
         if (!$_max_w && !$_max_h) {
             $_max_w = 300;
             $_max_h = 300;
         }
     } elseif ('large' == $size) {
         $_max_w = get_option('large_size_w');
         $_max_h = get_option('large_size_h');
     } elseif (is_array($size)) {
         $_max_w = $w = $size[0];
         $_max_h = $h = $size[1];
     } elseif (!empty($_wp_additional_image_sizes[$size])) {
         $_max_w = $w = $_wp_additional_image_sizes[$size]['width'];
         $_max_h = $h = $_wp_additional_image_sizes[$size]['height'];
         $crop = $_wp_additional_image_sizes[$size]['crop'];
     } elseif ($content_width > 0) {
         $_max_w = $content_width;
         $_max_h = 0;
     } else {
         $_max_w = 1024;
         $_max_h = 0;
     }
     // Constrain default image sizes to the theme's content width, if available.
     if ($content_width > 0 && in_array($size, array('thumbnail', 'medium', 'large'))) {
         $_max_w = min($_max_w, $content_width);
     }
     $resized = false;
     $img_url = wp_get_attachment_url($id);
     /**
      * Filter the original image Photon-compatible parameters before changes are 
      *
      * @param array|string $args Array of Photon-compatible arguments.
      * @param string $image_url Image URL.
      */
     $args = apply_filters('vip_go_image_resize_pre_args', $args, $image_url);
     if (!$crop) {
         $imagedata = wp_get_attachment_metadata($id);
         if (!empty($imagedata['width']) || !empty($imagedata['height'])) {
             $h = $imagedata['height'];
             $w = $imagedata['width'];
             list($w, $h) = wp_constrain_dimensions($w, $h, $_max_w, $_max_h);
             if ($w < $imagedata['width'] || $h < $imagedata['height']) {
                 $resized = true;
             }
         } else {
             $w = $_max_w;
             $h = $_max_h;
         }
     }
     if ($crop) {
         $constrain = false;
         $imagedata = wp_get_attachment_metadata($id);
         if ($imagedata) {
             $w = $imagedata['width'];
             $h = $imagedata['height'];
         }
         if (empty($w)) {
             $w = $_max_w;
         }
         if (empty($h)) {
             $h = $_max_h;
         }
         // If the image width is bigger than the allowed max, scale it to match
         if ($w >= $_max_w) {
             $w = $_max_w;
         } else {
             $constrain = true;
         }
         // If the image height is bigger than the allowed max, scale it to match
         if ($h >= $_max_h) {
             $h = $_max_h;
         } else {
             $constrain = true;
         }
         if ($constrain) {
             list($w, $h) = wp_constrain_dimensions($w, $h, $_max_w, $_max_h);
         }
         $args['w'] = $w;
         $args['h'] = $h;
         $args['crop'] = '1';
         $resized = true;
     } elseif ('full' != $size) {
         $args['w'] = $w;
         $resized = true;
     }
     if (is_array($args)) {
         // Convert values that are arrays into strings
         foreach ($args as $arg => $value) {
             if (is_array($value)) {
                 $args[$arg] = implode(',', $value);
             }
         }
         // Encode values
         // See http://core.trac.wordpress.org/ticket/17923
         $args = rawurlencode_deep($args);
     }
     $img_url = add_query_arg($args, $img_url);
     return array($img_url, $w, $h, $resized);
 }