Update WP and plugins

This commit is contained in:
Oliver Davies 2019-04-16 20:56:22 +01:00
parent 10a4713229
commit 1fb77fc4ff
864 changed files with 101724 additions and 78262 deletions

File diff suppressed because it is too large Load diff

View file

@ -20,11 +20,12 @@
* @param string $deprecated Deprecated.
* @return string|null The author's display name.
*/
function get_the_author($deprecated = '') {
function get_the_author( $deprecated = '' ) {
global $authordata;
if ( !empty( $deprecated ) )
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.1.0' );
}
/**
* Filters the display name of the current post's author.
@ -33,7 +34,7 @@ function get_the_author($deprecated = '') {
*
* @param string $authordata->display_name The author's display name.
*/
return apply_filters('the_author', is_object($authordata) ? $authordata->display_name : null);
return apply_filters( 'the_author', is_object( $authordata ) ? $authordata->display_name : null );
}
/**
@ -61,9 +62,12 @@ function the_author( $deprecated = '', $deprecated_echo = true ) {
}
if ( true !== $deprecated_echo ) {
_deprecated_argument( __FUNCTION__, '1.5.0',
_deprecated_argument(
__FUNCTION__,
'1.5.0',
/* translators: %s: get_the_author() */
sprintf( __( 'Use %s instead if you do not want the value echoed.' ),
sprintf(
__( 'Use %s instead if you do not want the value echoed.' ),
'<code>get_the_author()</code>'
)
);
@ -84,8 +88,10 @@ function the_author( $deprecated = '', $deprecated_echo = true ) {
* @return string|void The author's display name.
*/
function get_the_modified_author() {
if ( $last_id = get_post_meta( get_post()->ID, '_edit_last', true) ) {
$last_user = get_userdata($last_id);
$last_id = get_post_meta( get_post()->ID, '_edit_last', true );
if ( $last_id ) {
$last_user = get_userdata( $last_id );
/**
* Filters the display name of the author who last edited the current post.
@ -94,7 +100,7 @@ function get_the_modified_author() {
*
* @param string $last_user->display_name The author's display name.
*/
return apply_filters('the_modified_author', $last_user->display_name);
return apply_filters( 'the_modified_author', $last_user->display_name );
}
}
@ -161,8 +167,9 @@ function get_the_author_meta( $field = '', $user_id = false ) {
$authordata = get_userdata( $user_id );
}
if ( in_array( $field, array( 'login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status' ) ) )
if ( in_array( $field, array( 'login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status' ) ) ) {
$field = 'user_' . $field;
}
$value = isset( $authordata->$field ) ? $authordata->$field : '';
@ -220,9 +227,10 @@ function the_author_meta( $field = '', $user_id = false ) {
* else the result of get_the_author().
*/
function get_the_author_link() {
if ( get_the_author_meta('url') ) {
return sprintf( '<a href="%1$s" title="%2$s" rel="author external">%3$s</a>',
esc_url( get_the_author_meta('url') ),
if ( get_the_author_meta( 'url' ) ) {
return sprintf(
'<a href="%1$s" title="%2$s" rel="author external">%3$s</a>',
esc_url( get_the_author_meta( 'url' ) ),
/* translators: %s: author's display name */
esc_attr( sprintf( __( 'Visit %s&#8217;s website' ), get_the_author() ) ),
get_the_author()
@ -280,15 +288,16 @@ function the_author_posts() {
*
* @global object $authordata The current author's DB object.
*
* @return string An HTML link to the author page.
* @return string An HTML link to the author page, or an empty string if $authordata isn't defined.
*/
function get_the_author_posts_link() {
global $authordata;
if ( ! is_object( $authordata ) ) {
return;
return '';
}
$link = sprintf( '<a href="%1$s" title="%2$s" rel="author">%3$s</a>',
$link = sprintf(
'<a href="%1$s" title="%2$s" rel="author">%3$s</a>',
esc_url( get_author_posts_url( $authordata->ID, $authordata->user_nicename ) ),
/* translators: %s: author's display name */
esc_attr( sprintf( __( 'Posts by %s' ), get_the_author() ) ),
@ -334,18 +343,19 @@ function the_author_posts_link( $deprecated = '' ) {
function get_author_posts_url( $author_id, $author_nicename = '' ) {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
if ( empty( $link ) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
} else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$user = get_userdata( $author_id );
if ( ! empty( $user->user_nicename ) ) {
$author_nicename = $user->user_nicename;
}
}
$link = str_replace('%author%', $author_nicename, $link);
$link = str_replace( '%author%', $author_nicename, $link );
$link = home_url( user_trailingslashit( $link ) );
}
@ -381,7 +391,7 @@ function get_author_posts_url( $author_id, $author_nicename = '' ) {
* @type string $order Sorting direction for $orderby. Accepts 'ASC', 'DESC'. Default 'ASC'.
* @type int $number Maximum authors to return or display. Default empty (all authors).
* @type bool $optioncount Show the count in parenthesis next to the author's name. Default false.
* @type bool $exclude_admin Whether to exclude the 'admin' account, if it exists. Default false.
* @type bool $exclude_admin Whether to exclude the 'admin' account, if it exists. Default true.
* @type bool $show_fullname Whether to show the author's full name. Default false.
* @type bool $hide_empty Whether to hide any authors with no posts. Default true.
* @type string $feed If not empty, show a link to the author's feed and use this text as the alt
@ -402,24 +412,34 @@ function wp_list_authors( $args = '' ) {
global $wpdb;
$defaults = array(
'orderby' => 'name', 'order' => 'ASC', 'number' => '',
'optioncount' => false, 'exclude_admin' => true,
'show_fullname' => false, 'hide_empty' => true,
'feed' => '', 'feed_image' => '', 'feed_type' => '', 'echo' => true,
'style' => 'list', 'html' => true, 'exclude' => '', 'include' => ''
'orderby' => 'name',
'order' => 'ASC',
'number' => '',
'optioncount' => false,
'exclude_admin' => true,
'show_fullname' => false,
'hide_empty' => true,
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'echo' => true,
'style' => 'list',
'html' => true,
'exclude' => '',
'include' => '',
);
$args = wp_parse_args( $args, $defaults );
$return = '';
$query_args = wp_array_slice_assoc( $args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
$query_args = wp_array_slice_assoc( $args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
$query_args['fields'] = 'ids';
$authors = get_users( $query_args );
$authors = get_users( $query_args );
$author_count = array();
foreach ( (array) $wpdb->get_results( "SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author" ) as $row ) {
$author_count[$row->post_author] = $row->count;
foreach ( (array) $wpdb->get_results( "SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE " . get_private_posts_cap_sql( 'post' ) . ' GROUP BY post_author' ) as $row ) {
$author_count[ $row->post_author ] = $row->count;
}
foreach ( $authors as $author_id ) {
$author = get_userdata( $author_id );
@ -428,7 +448,7 @@ function wp_list_authors( $args = '' ) {
continue;
}
$posts = isset( $author_count[$author->ID] ) ? $author_count[$author->ID] : 0;
$posts = isset( $author_count[ $author->ID ] ) ? $author_count[ $author->ID ] : 0;
if ( ! $posts && $args['hide_empty'] ) {
continue;
@ -450,7 +470,8 @@ function wp_list_authors( $args = '' ) {
$return .= '<li>';
}
$link = sprintf( '<a href="%1$s" title="%2$s">%3$s</a>',
$link = sprintf(
'<a href="%1$s" title="%2$s">%3$s</a>',
get_author_posts_url( $author->ID, $author->user_nicename ),
/* translators: %s: author's display name */
esc_attr( sprintf( __( 'Posts by %s' ), $author->display_name ) ),
@ -467,7 +488,7 @@ function wp_list_authors( $args = '' ) {
$alt = '';
if ( ! empty( $args['feed'] ) ) {
$alt = ' alt="' . esc_attr( $args['feed'] ) . '"';
$alt = ' alt="' . esc_attr( $args['feed'] ) . '"';
$name = $args['feed'];
}
@ -487,7 +508,7 @@ function wp_list_authors( $args = '' ) {
}
if ( $args['optioncount'] ) {
$link .= ' ('. $posts . ')';
$link .= ' (' . $posts . ')';
}
$return .= $link;
@ -506,11 +527,11 @@ function wp_list_authors( $args = '' ) {
* Determines whether this site has more than one author.
*
* Checks to see if more than one author has published posts.
*
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
*
* @since 3.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
@ -521,7 +542,7 @@ function is_multi_author() {
global $wpdb;
if ( false === ( $is_multi_author = get_transient( 'is_multi_author' ) ) ) {
$rows = (array) $wpdb->get_col("SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 2");
$rows = (array) $wpdb->get_col( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 2" );
$is_multi_author = 1 < count( $rows ) ? 1 : 0;
set_transient( 'is_multi_author', $is_multi_author );
}

View file

@ -152,9 +152,9 @@ function excerpt_remove_blocks( $content ) {
* @param array $allowed_blocks The list of allowed blocks.
*/
$allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
$blocks = parse_blocks( $content );
$output = '';
foreach ( $blocks as $block ) {
$blocks = parse_blocks( $content );
$output = '';
foreach ( $blocks as $block ) {
if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
$output .= render_block( $block );
}
@ -175,6 +175,31 @@ function excerpt_remove_blocks( $content ) {
function render_block( $block ) {
global $post;
/**
* Allows render_block() to be shortcircuited, by returning a non-null value.
*
* @since 5.1.0
*
* @param string $pre_render The pre-rendered content. Default null.
* @param array $block The block being rendered.
*/
$pre_render = apply_filters( 'pre_render_block', null, $block );
if ( ! is_null( $pre_render ) ) {
return $pre_render;
}
$source_block = $block;
/**
* Filters the block being rendered in render_block(), before it's processed.
*
* @since 5.1.0
*
* @param array $block The block being rendered.
* @param array $source_block An un-modified copy of $block, as it appeared in the source content.
*/
$block = apply_filters( 'render_block_data', $block, $source_block );
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
$is_dynamic = $block['blockName'] && null !== $block_type && $block_type->is_dynamic();
$block_content = '';
@ -266,7 +291,6 @@ function do_blocks( $content ) {
* @return string The unmodified content.
*/
function _restore_wpautop_hook( $content ) {
global $wp_filter;
$current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
add_filter( 'the_content', 'wpautop', $current_priority - 1 );

View file

@ -28,7 +28,7 @@
*
* @type int|bool $show_updated Whether to show the time the bookmark was last updated.
* Accepts 1|true or 0|false. Default 0|false.
* @type int|bool $show_description Whether to show the bookmakr description. Accepts 1|true,
* @type int|bool $show_description Whether to show the bookmark description. Accepts 1|true,
* Accepts 1|true or 0|false. Default 0|false.
* @type int|bool $show_images Whether to show the link image if available. Accepts 1|true
* or 0|false. Default 1|true.
@ -50,10 +50,16 @@
*/
function _walk_bookmarks( $bookmarks, $args = '' ) {
$defaults = array(
'show_updated' => 0, 'show_description' => 0,
'show_images' => 1, 'show_name' => 0,
'before' => '<li>', 'after' => '</li>', 'between' => "\n",
'show_rating' => 0, 'link_before' => '', 'link_after' => ''
'show_updated' => 0,
'show_description' => 0,
'show_images' => 1,
'show_name' => 0,
'before' => '<li>',
'after' => '</li>',
'between' => "\n",
'show_rating' => 0,
'link_before' => '',
'link_after' => '',
);
$r = wp_parse_args( $args, $defaults );
@ -72,15 +78,15 @@ function _walk_bookmarks( $bookmarks, $args = '' ) {
if ( ! empty( $bookmark->link_url ) ) {
$the_link = esc_url( $bookmark->link_url );
}
$desc = esc_attr( sanitize_bookmark_field( 'link_description', $bookmark->link_description, $bookmark->link_id, 'display' ) );
$name = esc_attr( sanitize_bookmark_field( 'link_name', $bookmark->link_name, $bookmark->link_id, 'display' ) );
$title = $desc;
$desc = esc_attr( sanitize_bookmark_field( 'link_description', $bookmark->link_description, $bookmark->link_id, 'display' ) );
$name = esc_attr( sanitize_bookmark_field( 'link_name', $bookmark->link_name, $bookmark->link_id, 'display' ) );
$title = $desc;
if ( $r['show_updated'] ) {
if ( '00' != substr( $bookmark->link_updated_f, 0, 2 ) ) {
$title .= ' (';
$title .= sprintf(
__('Last updated: %s'),
__( 'Last updated: %s' ),
date(
get_option( 'links_updated_date_format' ),
$bookmark->link_updated_f + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS )
@ -96,7 +102,7 @@ function _walk_bookmarks( $bookmarks, $args = '' ) {
}
$rel = $bookmark->link_rel;
if ( '' != $rel ) {
$rel = ' rel="' . esc_attr($rel) . '"';
$rel = ' rel="' . esc_attr( $rel ) . '"';
}
$target = $bookmark->link_target;
if ( '' != $target ) {
@ -110,7 +116,7 @@ function _walk_bookmarks( $bookmarks, $args = '' ) {
if ( strpos( $bookmark->link_image, 'http' ) === 0 ) {
$output .= "<img src=\"$bookmark->link_image\" $alt $title />";
} else { // If it's a relative path
$output .= "<img src=\"" . get_option('siteurl') . "$bookmark->link_image\" $alt $title />";
$output .= '<img src="' . get_option( 'siteurl' ) . "$bookmark->link_image\" $alt $title />";
}
if ( $r['show_name'] ) {
$output .= " $name";
@ -199,15 +205,24 @@ function _walk_bookmarks( $bookmarks, $args = '' ) {
*/
function wp_list_bookmarks( $args = '' ) {
$defaults = array(
'orderby' => 'name', 'order' => 'ASC',
'limit' => -1, 'category' => '', 'exclude_category' => '',
'category_name' => '', 'hide_invisible' => 1,
'show_updated' => 0, 'echo' => 1,
'categorize' => 1, 'title_li' => __('Bookmarks'),
'title_before' => '<h2>', 'title_after' => '</h2>',
'category_orderby' => 'name', 'category_order' => 'ASC',
'class' => 'linkcat', 'category_before' => '<li id="%id" class="%class">',
'category_after' => '</li>'
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
'category' => '',
'exclude_category' => '',
'category_name' => '',
'hide_invisible' => 1,
'show_updated' => 0,
'echo' => 1,
'categorize' => 1,
'title_li' => __( 'Bookmarks' ),
'title_before' => '<h2>',
'title_after' => '</h2>',
'category_orderby' => 'name',
'category_order' => 'ASC',
'class' => 'linkcat',
'category_before' => '<li id="%id" class="%class">',
'category_after' => '</li>',
);
$r = wp_parse_args( $args, $defaults );
@ -217,18 +232,21 @@ function wp_list_bookmarks( $args = '' ) {
if ( ! is_array( $r['class'] ) ) {
$r['class'] = explode( ' ', $r['class'] );
}
$r['class'] = array_map( 'sanitize_html_class', $r['class'] );
$r['class'] = trim( join( ' ', $r['class'] ) );
$r['class'] = array_map( 'sanitize_html_class', $r['class'] );
$r['class'] = trim( join( ' ', $r['class'] ) );
if ( $r['categorize'] ) {
$cats = get_terms( 'link_category', array(
'name__like' => $r['category_name'],
'include' => $r['category'],
'exclude' => $r['exclude_category'],
'orderby' => $r['category_orderby'],
'order' => $r['category_order'],
'hierarchical' => 0
) );
$cats = get_terms(
'link_category',
array(
'name__like' => $r['category_name'],
'include' => $r['category'],
'exclude' => $r['exclude_category'],
'orderby' => $r['category_orderby'],
'order' => $r['category_order'],
'hierarchical' => 0,
)
);
if ( empty( $cats ) ) {
$r['categorize'] = false;
}
@ -237,7 +255,7 @@ function wp_list_bookmarks( $args = '' ) {
if ( $r['categorize'] ) {
// Split the bookmarks into ul's for each category
foreach ( (array) $cats as $cat ) {
$params = array_merge( $r, array( 'category' => $cat->term_id ) );
$params = array_merge( $r, array( 'category' => $cat->term_id ) );
$bookmarks = get_bookmarks( $params );
if ( empty( $bookmarks ) ) {
continue;
@ -248,11 +266,11 @@ function wp_list_bookmarks( $args = '' ) {
$r['category_before']
);
/**
* Filters the bookmarks category name.
* Filters the category name.
*
* @since 2.2.0
*
* @param string $cat_name The category name of bookmarks.
* @param string $cat_name The category name.
*/
$catname = apply_filters( 'link_category', $cat->name );
@ -272,7 +290,7 @@ function wp_list_bookmarks( $args = '' ) {
if ( ! empty( $r['title_li'] ) ) {
$output .= str_replace(
array( '%id', '%class' ),
array( "linkcat-" . $r['category'], $r['class'] ),
array( 'linkcat-' . $r['category'], $r['class'] ),
$r['category_before']
);
$output .= $r['title_before'];

View file

@ -19,22 +19,23 @@
* @param string $filter Optional, default is 'raw'.
* @return array|object|null Type returned depends on $output value.
*/
function get_bookmark($bookmark, $output = OBJECT, $filter = 'raw') {
function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) {
global $wpdb;
if ( empty($bookmark) ) {
if ( isset($GLOBALS['link']) )
if ( empty( $bookmark ) ) {
if ( isset( $GLOBALS['link'] ) ) {
$_bookmark = & $GLOBALS['link'];
else
} else {
$_bookmark = null;
} elseif ( is_object($bookmark) ) {
wp_cache_add($bookmark->link_id, $bookmark, 'bookmark');
}
} elseif ( is_object( $bookmark ) ) {
wp_cache_add( $bookmark->link_id, $bookmark, 'bookmark' );
$_bookmark = $bookmark;
} else {
if ( isset($GLOBALS['link']) && ($GLOBALS['link']->link_id == $bookmark) ) {
if ( isset( $GLOBALS['link'] ) && ( $GLOBALS['link']->link_id == $bookmark ) ) {
$_bookmark = & $GLOBALS['link'];
} elseif ( ! $_bookmark = wp_cache_get($bookmark, 'bookmark') ) {
$_bookmark = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark));
} elseif ( ! $_bookmark = wp_cache_get( $bookmark, 'bookmark' ) ) {
$_bookmark = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark ) );
if ( $_bookmark ) {
$_bookmark->link_category = array_unique( wp_get_object_terms( $_bookmark->link_id, 'link_category', array( 'fields' => 'ids' ) ) );
wp_cache_add( $_bookmark->link_id, $_bookmark, 'bookmark' );
@ -42,17 +43,18 @@ function get_bookmark($bookmark, $output = OBJECT, $filter = 'raw') {
}
}
if ( ! $_bookmark )
if ( ! $_bookmark ) {
return $_bookmark;
}
$_bookmark = sanitize_bookmark($_bookmark, $filter);
$_bookmark = sanitize_bookmark( $_bookmark, $filter );
if ( $output == OBJECT ) {
return $_bookmark;
} elseif ( $output == ARRAY_A ) {
return get_object_vars($_bookmark);
return get_object_vars( $_bookmark );
} elseif ( $output == ARRAY_N ) {
return array_values(get_object_vars($_bookmark));
return array_values( get_object_vars( $_bookmark ) );
} else {
return $_bookmark;
}
@ -72,16 +74,19 @@ function get_bookmark_field( $field, $bookmark, $context = 'display' ) {
$bookmark = (int) $bookmark;
$bookmark = get_bookmark( $bookmark );
if ( is_wp_error($bookmark) )
if ( is_wp_error( $bookmark ) ) {
return $bookmark;
}
if ( !is_object($bookmark) )
if ( ! is_object( $bookmark ) ) {
return '';
}
if ( !isset($bookmark->$field) )
if ( ! isset( $bookmark->$field ) ) {
return '';
}
return sanitize_bookmark_field($field, $bookmark->$field, $bookmark->link_id, $context);
return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context );
}
/**
@ -119,16 +124,21 @@ function get_bookmarks( $args = '' ) {
global $wpdb;
$defaults = array(
'orderby' => 'name', 'order' => 'ASC',
'limit' => -1, 'category' => '',
'category_name' => '', 'hide_invisible' => 1,
'show_updated' => 0, 'include' => '',
'exclude' => '', 'search' => ''
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
'category' => '',
'category_name' => '',
'hide_invisible' => 1,
'show_updated' => 0,
'include' => '',
'exclude' => '',
'search' => '',
);
$r = wp_parse_args( $args, $defaults );
$key = md5( serialize( $r ) );
$key = md5( serialize( $r ) );
$cache = false;
if ( 'rand' !== $r['orderby'] && $cache = wp_cache_get( 'get_bookmarks', 'bookmark' ) ) {
if ( is_array( $cache ) && isset( $cache[ $key ] ) ) {
@ -158,33 +168,33 @@ function get_bookmarks( $args = '' ) {
$inclusions = '';
if ( ! empty( $r['include'] ) ) {
$r['exclude'] = ''; //ignore exclude, category, and category_name params if using include
$r['category'] = '';
$r['exclude'] = ''; //ignore exclude, category, and category_name params if using include
$r['category'] = '';
$r['category_name'] = '';
$inclinks = preg_split( '/[\s,]+/', $r['include'] );
$inclinks = wp_parse_id_list( $r['include'] );
if ( count( $inclinks ) ) {
foreach ( $inclinks as $inclink ) {
if ( empty( $inclusions ) ) {
$inclusions = ' AND ( link_id = ' . intval( $inclink ) . ' ';
$inclusions = ' AND ( link_id = ' . $inclink . ' ';
} else {
$inclusions .= ' OR link_id = ' . intval( $inclink ) . ' ';
$inclusions .= ' OR link_id = ' . $inclink . ' ';
}
}
}
}
if (! empty( $inclusions ) ) {
if ( ! empty( $inclusions ) ) {
$inclusions .= ')';
}
$exclusions = '';
if ( ! empty( $r['exclude'] ) ) {
$exlinks = preg_split( '/[\s,]+/', $r['exclude'] );
$exlinks = wp_parse_id_list( $r['exclude'] );
if ( count( $exlinks ) ) {
foreach ( $exlinks as $exlink ) {
if ( empty( $exclusions ) ) {
$exclusions = ' AND ( link_id <> ' . intval( $exlink ) . ' ';
$exclusions = ' AND ( link_id <> ' . $exlink . ' ';
} else {
$exclusions .= ' AND link_id <> ' . intval( $exlink ) . ' ';
$exclusions .= ' AND link_id <> ' . $exlink . ' ';
}
}
}
@ -194,7 +204,7 @@ function get_bookmarks( $args = '' ) {
}
if ( ! empty( $r['category_name'] ) ) {
if ( $r['category'] = get_term_by('name', $r['category_name'], 'link_category') ) {
if ( $r['category'] = get_term_by( 'name', $r['category_name'], 'link_category' ) ) {
$r['category'] = $r['category']->term_id;
} else {
$cache[ $key ] = array();
@ -206,31 +216,31 @@ function get_bookmarks( $args = '' ) {
$search = '';
if ( ! empty( $r['search'] ) ) {
$like = '%' . $wpdb->esc_like( $r['search'] ) . '%';
$search = $wpdb->prepare(" AND ( (link_url LIKE %s) OR (link_name LIKE %s) OR (link_description LIKE %s) ) ", $like, $like, $like );
$like = '%' . $wpdb->esc_like( $r['search'] ) . '%';
$search = $wpdb->prepare( ' AND ( (link_url LIKE %s) OR (link_name LIKE %s) OR (link_description LIKE %s) ) ', $like, $like, $like );
}
$category_query = '';
$join = '';
$join = '';
if ( ! empty( $r['category'] ) ) {
$incategories = preg_split( '/[\s,]+/', $r['category'] );
if ( count($incategories) ) {
$incategories = wp_parse_id_list( $r['category'] );
if ( count( $incategories ) ) {
foreach ( $incategories as $incat ) {
if ( empty( $category_query ) ) {
$category_query = ' AND ( tt.term_id = ' . intval( $incat ) . ' ';
$category_query = ' AND ( tt.term_id = ' . $incat . ' ';
} else {
$category_query .= ' OR tt.term_id = ' . intval( $incat ) . ' ';
$category_query .= ' OR tt.term_id = ' . $incat . ' ';
}
}
}
}
if ( ! empty( $category_query ) ) {
$category_query .= ") AND taxonomy = 'link_category'";
$join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id";
$join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id";
}
if ( $r['show_updated'] ) {
$recently_updated_test = ", IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated ";
$recently_updated_test = ', IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated ';
} else {
$recently_updated_test = '';
}
@ -238,10 +248,10 @@ function get_bookmarks( $args = '' ) {
$get_updated = ( $r['show_updated'] ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : '';
$orderby = strtolower( $r['orderby'] );
$length = '';
$length = '';
switch ( $orderby ) {
case 'length':
$length = ", CHAR_LENGTH(link_name) AS length";
$length = ', CHAR_LENGTH(link_name) AS length';
break;
case 'rand':
$orderby = 'rand()';
@ -251,7 +261,7 @@ function get_bookmarks( $args = '' ) {
break;
default:
$orderparams = array();
$keys = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes', 'link_description' );
$keys = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes', 'link_description' );
foreach ( explode( ',', $orderby ) as $ordparam ) {
$ordparam = trim( $ordparam );
@ -278,7 +288,7 @@ function get_bookmarks( $args = '' ) {
$visible = "AND link_visible = 'Y'";
}
$query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query";
$query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query";
$query .= " $exclusions $inclusions $search";
$query .= " ORDER BY $orderby $order";
if ( $r['limit'] != -1 ) {
@ -303,29 +313,44 @@ function get_bookmarks( $args = '' ) {
*
* @param stdClass|array $bookmark Bookmark row
* @param string $context Optional, default is 'display'. How to filter the
* fields
* fields
* @return stdClass|array Same type as $bookmark but with fields sanitized.
*/
function sanitize_bookmark($bookmark, $context = 'display') {
$fields = array('link_id', 'link_url', 'link_name', 'link_image', 'link_target', 'link_category',
'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_updated',
'link_rel', 'link_notes', 'link_rss', );
function sanitize_bookmark( $bookmark, $context = 'display' ) {
$fields = array(
'link_id',
'link_url',
'link_name',
'link_image',
'link_target',
'link_category',
'link_description',
'link_visible',
'link_owner',
'link_rating',
'link_updated',
'link_rel',
'link_notes',
'link_rss',
);
if ( is_object($bookmark) ) {
if ( is_object( $bookmark ) ) {
$do_object = true;
$link_id = $bookmark->link_id;
$link_id = $bookmark->link_id;
} else {
$do_object = false;
$link_id = $bookmark['link_id'];
$link_id = $bookmark['link_id'];
}
foreach ( $fields as $field ) {
if ( $do_object ) {
if ( isset($bookmark->$field) )
$bookmark->$field = sanitize_bookmark_field($field, $bookmark->$field, $link_id, $context);
if ( isset( $bookmark->$field ) ) {
$bookmark->$field = sanitize_bookmark_field( $field, $bookmark->$field, $link_id, $context );
}
} else {
if ( isset($bookmark[$field]) )
$bookmark[$field] = sanitize_bookmark_field($field, $bookmark[$field], $link_id, $context);
if ( isset( $bookmark[ $field ] ) ) {
$bookmark[ $field ] = sanitize_bookmark_field( $field, $bookmark[ $field ], $link_id, $context );
}
}
}
@ -358,28 +383,30 @@ function sanitize_bookmark($bookmark, $context = 'display') {
*/
function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
switch ( $field ) {
case 'link_id' : // ints
case 'link_rating' :
$value = (int) $value;
break;
case 'link_category' : // array( ints )
$value = array_map('absint', (array) $value);
// We return here so that the categories aren't filtered.
// The 'link_category' filter is for the name of a link category, not an array of a link's link categories
return $value;
case 'link_id': // ints
case 'link_rating':
$value = (int) $value;
break;
case 'link_category': // array( ints )
$value = array_map( 'absint', (array) $value );
// We return here so that the categories aren't filtered.
// The 'link_category' filter is for the name of a link category, not an array of a link's link categories
return $value;
case 'link_visible' : // bool stored as Y|N
$value = preg_replace('/[^YNyn]/', '', $value);
break;
case 'link_target' : // "enum"
$targets = array('_top', '_blank');
if ( ! in_array($value, $targets) )
$value = '';
break;
case 'link_visible': // bool stored as Y|N
$value = preg_replace( '/[^YNyn]/', '', $value );
break;
case 'link_target': // "enum"
$targets = array( '_top', '_blank' );
if ( ! in_array( $value, $targets ) ) {
$value = '';
}
break;
}
if ( 'raw' == $context )
if ( 'raw' == $context ) {
return $value;
}
if ( 'edit' == $context ) {
/** This filter is documented in wp-includes/post.php */
@ -388,7 +415,7 @@ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
if ( 'link_notes' == $field ) {
$value = esc_html( $value ); // textarea_escaped
} else {
$value = esc_attr($value);
$value = esc_attr( $value );
}
} elseif ( 'db' == $context ) {
/** This filter is documented in wp-includes/post.php */
@ -417,5 +444,5 @@ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
function clean_bookmark_cache( $bookmark_id ) {
wp_cache_delete( $bookmark_id, 'bookmark' );
wp_cache_delete( 'get_bookmarks', 'bookmark' );
clean_object_term_cache( $bookmark_id, 'link');
clean_object_term_cache( $bookmark_id, 'link' );
}

View file

@ -81,7 +81,7 @@ function wp_cache_decr( $key, $offset = 1, $group = '' ) {
function wp_cache_delete( $key, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->delete($key, $group);
return $wp_object_cache->delete( $key, $group );
}
/**
@ -115,7 +115,7 @@ function wp_cache_flush() {
* @param bool $found Optional. Whether the key was found in the cache (passed by reference).
* Disambiguates a return of false, a storable value. Default null.
* @return bool|mixed False on failure to retrieve contents or the cache
* contents on success
* contents on success
*/
function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
global $wp_object_cache;
@ -390,7 +390,7 @@ class WP_Object_Cache {
*
* @uses WP_Object_Cache::_exists() Checks to see if the cache already has data.
* @uses WP_Object_Cache::set() Sets the data after the checking the cache
* contents existence.
* contents existence.
*
* @param int|string $key What to call the contents in the cache.
* @param mixed $data The contents to store in the cache.
@ -399,18 +399,22 @@ class WP_Object_Cache {
* @return bool False if cache key and group already exist, true on success
*/
public function add( $key, $data, $group = 'default', $expire = 0 ) {
if ( wp_suspend_cache_addition() )
if ( wp_suspend_cache_addition() ) {
return false;
}
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$id = $this->blog_prefix . $key;
}
if ( $this->_exists( $id, $group ) )
if ( $this->_exists( $id, $group ) ) {
return false;
}
return $this->set( $key, $data, $group, (int) $expire );
}
@ -425,7 +429,7 @@ class WP_Object_Cache {
public function add_global_groups( $groups ) {
$groups = (array) $groups;
$groups = array_fill_keys( $groups, true );
$groups = array_fill_keys( $groups, true );
$this->global_groups = array_merge( $this->global_groups, $groups );
}
@ -440,24 +444,29 @@ class WP_Object_Cache {
* @return false|int False on failure, the item's new value on success.
*/
public function decr( $key, $offset = 1, $group = 'default' ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) )
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) )
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
$this->cache[ $group ][ $key ] = 0;
}
$offset = (int) $offset;
$this->cache[ $group ][ $key ] -= $offset;
if ( $this->cache[ $group ][ $key ] < 0 )
if ( $this->cache[ $group ][ $key ] < 0 ) {
$this->cache[ $group ][ $key ] = 0;
}
return $this->cache[ $group ][ $key ];
}
@ -475,16 +484,19 @@ class WP_Object_Cache {
* @return bool False if the contents weren't deleted and true on success.
*/
public function delete( $key, $group = 'default', $deprecated = false ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) )
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
unset( $this->cache[$group][$key] );
unset( $this->cache[ $group ][ $key ] );
return true;
}
@ -514,29 +526,32 @@ class WP_Object_Cache {
*
* @param int|string $key What the contents in the cache are called.
* @param string $group Optional. Where the cache contents are grouped. Default 'default'.
* @param string $force Optional. Unused. Whether to force a refetch rather than relying on the local
* @param bool $force Optional. Unused. Whether to force a refetch rather than relying on the local
* cache. Default false.
* @param bool $found Optional. Whether the key was found in the cache (passed by reference).
* Disambiguates a return of false, a storable value. Default null.
* @param bool $found Optional. Whether the key was found in the cache (passed by reference).
* Disambiguates a return of false, a storable value. Default null.
* @return false|mixed False on failure to retrieve contents or the cache contents on success.
*/
public function get( $key, $group = 'default', $force = false, &$found = null ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( $this->_exists( $key, $group ) ) {
$found = true;
$this->cache_hits += 1;
if ( is_object($this->cache[$group][$key]) )
return clone $this->cache[$group][$key];
else
return $this->cache[$group][$key];
}
$found = false;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( $this->_exists( $key, $group ) ) {
$found = true;
$this->cache_hits += 1;
if ( is_object( $this->cache[ $group ][ $key ] ) ) {
return clone $this->cache[ $group ][ $key ];
} else {
return $this->cache[ $group ][ $key ];
}
}
$found = false;
$this->cache_misses += 1;
return false;
}
@ -552,24 +567,29 @@ class WP_Object_Cache {
* @return false|int False on failure, the item's new value on success.
*/
public function incr( $key, $offset = 1, $group = 'default' ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) )
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) )
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
$this->cache[ $group ][ $key ] = 0;
}
$offset = (int) $offset;
$this->cache[ $group ][ $key ] += $offset;
if ( $this->cache[ $group ][ $key ] < 0 )
if ( $this->cache[ $group ][ $key ] < 0 ) {
$this->cache[ $group ][ $key ] = 0;
}
return $this->cache[ $group ][ $key ];
}
@ -588,15 +608,18 @@ class WP_Object_Cache {
* @return bool False if not exists, true if contents were replaced.
*/
public function replace( $key, $data, $group = 'default', $expire = 0 ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$id = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $id, $group ) )
if ( ! $this->_exists( $id, $group ) ) {
return false;
}
return $this->set( $key, $data, $group, (int) $expire );
}
@ -614,8 +637,9 @@ class WP_Object_Cache {
// Clear out non-global caches since the blog ID has changed.
foreach ( array_keys( $this->cache ) as $group ) {
if ( ! isset( $this->global_groups[ $group ] ) )
if ( ! isset( $this->global_groups[ $group ] ) ) {
unset( $this->cache[ $group ] );
}
}
}
@ -640,16 +664,19 @@ class WP_Object_Cache {
* @return true Always returns true.
*/
public function set( $key, $data, $group = 'default', $expire = 0 ) {
if ( empty( $group ) )
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( is_object( $data ) )
if ( is_object( $data ) ) {
$data = clone $data;
}
$this->cache[$group][$key] = $data;
$this->cache[ $group ][ $key ] = $data;
return true;
}
@ -662,12 +689,12 @@ class WP_Object_Cache {
* @since 2.0.0
*/
public function stats() {
echo "<p>";
echo '<p>';
echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
echo "</p>";
echo '</p>';
echo '<ul>';
foreach ($this->cache as $group => $cache) {
foreach ( $this->cache as $group => $cache ) {
echo "<li><strong>Group:</strong> $group - ( " . number_format( strlen( serialize( $cache ) ) / KB_IN_BYTES, 2 ) . 'k )</li>';
}
echo '</ul>';
@ -683,7 +710,7 @@ class WP_Object_Cache {
* @param int $blog_id Blog ID.
*/
public function switch_to_blog( $blog_id ) {
$blog_id = (int) $blog_id;
$blog_id = (int) $blog_id;
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
}
@ -706,9 +733,8 @@ class WP_Object_Cache {
* @since 2.0.8
*/
public function __construct() {
$this->multisite = is_multisite();
$this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : '';
$this->multisite = is_multisite();
$this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : '';
/**
* @todo This should be moved to the PHP4 style constructor, PHP5

View file

@ -32,10 +32,10 @@
* @global bool $is_IIS
* @global WP_Query $wp_query
* @global wpdb $wpdb WordPress database abstraction object.
* @global WP $wp Current WordPress environment instance.
* @global WP $wp Current WordPress environment instance.
*
* @param string $requested_url Optional. The URL that was requested, used to
* figure if redirect is needed.
* 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.
*/
@ -56,7 +56,7 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
}
}
if ( is_trackback() || is_search() || is_admin() || is_preview() || is_robots() || ( $is_IIS && !iis7_supports_permalinks() ) ) {
if ( is_trackback() || is_search() || is_admin() || is_preview() || is_robots() || ( $is_IIS && ! iis7_supports_permalinks() ) ) {
return;
}
@ -67,19 +67,21 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
$requested_url .= $_SERVER['REQUEST_URI'];
}
$original = @parse_url($requested_url);
$original = @parse_url( $requested_url );
if ( false === $original ) {
return;
}
$redirect = $original;
$redirect = $original;
$redirect_url = false;
// Notice fixing
if ( !isset($redirect['path']) )
if ( ! isset( $redirect['path'] ) ) {
$redirect['path'] = '';
if ( !isset($redirect['query']) )
}
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
@ -93,21 +95,23 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
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 );
$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')) ) {
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) );
$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 )
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) )
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 );
}
}
}
@ -115,11 +119,11 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
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);
$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 && 'auto-draft' != $redirect_post->post_status ) {
$redirect_url = get_permalink($redirect_post);
$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 );
}
}
@ -130,11 +134,11 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
$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_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_url = get_year_link( get_query_var( 'year' ) );
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'year', 'monthnum' ), $redirect_url );
}
@ -146,12 +150,11 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
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['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 );
$redirect_url = get_permalink( $wp_query->post->ID );
}
} elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) {
} 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' ) ) &&
@ -164,62 +167,72 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
} 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() && 'page' == get_option('show_on_front') && get_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) ) {
} 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() && 'page' == get_option( 'show_on_front' ) && get_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);
$redirect_url = get_year_link( $m );
break;
case 6: // Monthly
$redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
$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));
$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 ( $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']);
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 )
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']) ) {
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');
$qv_remove = array( 'term', 'taxonomy' );
if ( is_category() ) {
$qv_remove[] = 'category_name';
$qv_remove[] = 'cat';
@ -228,44 +241,45 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
$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 )
if ( false !== $tax_obj->query_var ) {
$qv_remove[] = $tax_obj->query_var;
}
}
$rewrite_vars = array_diff( array_keys($wp_query->query), array_keys($_GET) );
$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
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']);
$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']);
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' ) ) {
} elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false && $cat = get_query_var( 'category_name' ) ) {
$category = get_category_by_path( $cat );
if ( ( ! $category || is_wp_error( $category ) ) || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() ) ) {
$redirect_url = get_permalink($wp_query->get_queried_object_id());
$redirect_url = get_permalink( $wp_query->get_queried_object_id() );
}
}
// Post Paging
if ( is_singular() && get_query_var('page') ) {
if ( !$redirect_url )
// Post Paging
if ( is_singular() && get_query_var( 'page' ) ) {
if ( ! $redirect_url ) {
$redirect_url = get_permalink( get_queried_object_id() );
}
$page = get_query_var( 'page' );
if ( $page > 1 ) {
@ -275,29 +289,31 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
$redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( $page, 'single_paged' );
}
}
$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
}
// paging and feeds
if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
// 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
$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' ) )
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') )
}
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' );
} 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') ) {
} elseif ( is_feed() && 'old' == get_query_var( 'feed' ) ) {
$old_feed_files = array(
'wp-atom.php' => 'atom',
'wp-commentsrss2.php' => 'comments_rss2',
@ -313,14 +329,14 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
}
}
if ( get_query_var('paged') > 0 ) {
$paged = get_query_var('paged');
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) : '';
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'] );
@ -328,18 +344,20 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
}
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 )
( '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' );
$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['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'];
}
@ -358,65 +376,87 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
// tack on any additional query vars
$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
if ( $redirect_url && !empty($redirect['query']) ) {
if ( $redirect_url && ! empty( $redirect['query'] ) ) {
parse_str( $redirect['query'], $_parsed_query );
$redirect = @parse_url($redirect_url);
$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'] ) )
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 );
$redirect_url = add_query_arg( $_parsed_query, $redirect_url );
}
if ( $redirect_url )
$redirect = @parse_url($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']) )
$user_home = @parse_url( home_url() );
if ( ! empty( $user_home['host'] ) ) {
$redirect['host'] = $user_home['host'];
if ( empty($user_home['path']) )
}
if ( empty( $user_home['path'] ) ) {
$user_home['path'] = '/';
}
// Handle ports
if ( !empty($user_home['port']) )
if ( ! empty( $user_home['port'] ) ) {
$redirect['port'] = $user_home['port'];
else
unset($redirect['port']);
} else {
unset( $redirect['port'] );
}
// trailing /index.php
$redirect['path'] = preg_replace('|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path']);
$redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
$punctuation_pattern = implode( '|', array_map( 'preg_quote', array(
' ', '%20', // space
'!', '%21', // exclamation mark
'"', '%22', // double quote
"'", '%27', // single quote
'(', '%28', // opening bracket
')', '%29', // closing bracket
',', '%2C', // comma
'.', '%2E', // period
';', '%3B', // semicolon
'{', '%7B', // opening curly bracket
'}', '%7D', // closing curly bracket
'%E2%80%9C', // opening curly quote
'%E2%80%9D', // closing curly quote
) ) );
$punctuation_pattern = implode(
'|',
array_map(
'preg_quote',
array(
' ',
'%20', // space
'!',
'%21', // exclamation mark
'"',
'%22', // double quote
"'",
'%27', // single quote
'(',
'%28', // opening bracket
')',
'%29', // closing bracket
',',
'%2C', // comma
'.',
'%2E', // period
';',
'%3B', // semicolon
'{',
'%7B', // opening curly bracket
'}',
'%7D', // closing curly bracket
'%E2%80%9C', // opening curly quote
'%E2%80%9D', // closing curly quote
)
)
);
// Remove trailing spaces and end punctuation from the path.
$redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
if ( !empty( $redirect['query'] ) ) {
if ( ! empty( $redirect['query'] ) ) {
// Remove trailing spaces and end punctuation from certain terminating query string args.
$redirect['query'] = preg_replace( "#((p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
// Clean up empty query strings
$redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
$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'] );
@ -426,65 +466,75 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
}
// strip /index.php/ when we're not using PATHINFO permalinks
if ( !$wp_rewrite->using_index_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) ) ) ) {
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 ) {
if ( get_query_var( 'paged' ) > 0 ) {
$user_ts_type = 'paged';
} else {
foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) {
foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
$func = 'is_' . $type;
if ( call_user_func($func) ) {
if ( call_user_func( $func ) ) {
$user_ts_type = $type;
break;
}
}
}
$redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
$redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
} elseif ( is_front_page() ) {
$redirect['path'] = trailingslashit($redirect['path']);
$redirect['path'] = trailingslashit( $redirect['path'] );
}
// Strip multiple slashes out of the URL
if ( strpos($redirect['path'], '//') > -1 )
$redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
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']);
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']) ) )
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'] ) )
if ( ! empty( $original['port'] ) ) {
$compare_original[] = $original['port'];
}
if ( !empty( $original['query'] ) )
if ( ! empty( $original['query'] ) ) {
$compare_original[] = $original['query'];
}
$compare_redirect = array( $redirect['host'], $redirect['path'] );
if ( !empty( $redirect['port'] ) )
if ( ! empty( $redirect['port'] ) ) {
$compare_redirect[] = $redirect['port'];
}
if ( !empty( $redirect['query'] ) )
if ( ! empty( $redirect['query'] ) ) {
$compare_redirect[] = $redirect['query'];
}
if ( $compare_original !== $compare_redirect ) {
$redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
if ( !empty($redirect['port']) )
if ( ! empty( $redirect['port'] ) ) {
$redirect_url .= ':' . $redirect['port'];
}
$redirect_url .= $redirect['path'];
if ( !empty($redirect['query']) )
if ( ! empty( $redirect['query'] ) ) {
$redirect_url .= '?' . $redirect['query'];
}
}
if ( ! $redirect_url || $redirect_url == $requested_url ) {
@ -492,8 +542,8 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
}
// Hex encoded octets are case-insensitive.
if ( false !== strpos($requested_url, '%') ) {
if ( !function_exists('lowercase_octets') ) {
if ( false !== strpos( $requested_url, '%' ) ) {
if ( ! function_exists( 'lowercase_octets' ) ) {
/**
* Converts the first hex-encoded octet match to lowercase.
*
@ -503,11 +553,11 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
* @param array $matches Hex-encoded octet matches for the requested URL.
* @return string Lowercased version of the first match.
*/
function lowercase_octets($matches) {
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);
$requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
}
/**
@ -529,8 +579,8 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
if ( $do_redirect ) {
// protect against chained redirects
if ( !redirect_canonical($redirect_url, false) ) {
wp_redirect($redirect_url, 301);
if ( ! redirect_canonical( $redirect_url, false ) ) {
wp_redirect( $redirect_url, 301 );
exit();
} else {
// Debug
@ -554,13 +604,14 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
* @param string $url
* @return string The altered query string
*/
function _remove_qs_args_if_not_in_url( $query_string, Array $args_to_check, $url ) {
function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
$parsed_url = @parse_url( $url );
if ( ! empty( $parsed_url['query'] ) ) {
parse_str( $parsed_url['query'], $parsed_query );
foreach ( $args_to_check as $qv ) {
if ( !isset( $parsed_query[$qv] ) )
if ( ! isset( $parsed_query[ $qv ] ) ) {
$query_string = remove_query_arg( $qv, $query_string );
}
}
} else {
$query_string = remove_query_arg( $args_to_check, $query_string );
@ -609,31 +660,37 @@ function strip_fragment_from_url( $url ) {
function redirect_guess_404_permalink() {
global $wpdb;
if ( get_query_var('name') ) {
$where = $wpdb->prepare("post_name LIKE %s", $wpdb->esc_like( get_query_var('name') ) . '%');
if ( get_query_var( 'name' ) ) {
$where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
// if any of post_type, year, monthnum, or day are set, use them to refine the query
if ( get_query_var('post_type') )
$where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type'));
else
if ( get_query_var( 'post_type' ) ) {
$where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
} else {
$where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
}
if ( get_query_var('year') )
$where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year'));
if ( get_query_var('monthnum') )
$where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum'));
if ( get_query_var('day') )
$where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day'));
if ( get_query_var( 'year' ) ) {
$where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
}
if ( get_query_var( 'monthnum' ) ) {
$where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
}
if ( get_query_var( 'day' ) ) {
$where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
}
$post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'");
if ( ! $post_id )
$post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
if ( ! $post_id ) {
return false;
if ( get_query_var( 'feed' ) )
}
if ( get_query_var( 'feed' ) ) {
return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
elseif ( get_query_var( 'page' ) && 1 < get_query_var( 'page' ) )
} elseif ( get_query_var( 'page' ) && 1 < get_query_var( 'page' ) ) {
return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
else
} else {
return get_permalink( $post_id );
}
}
return false;
@ -651,8 +708,9 @@ function redirect_guess_404_permalink() {
*/
function wp_redirect_admin_locations() {
global $wp_rewrite;
if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) )
if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
return;
}
$admins = array(
home_url( 'wp-admin', 'relative' ),

File diff suppressed because it is too large Load diff

View file

@ -17,13 +17,15 @@
* @return string Link on success, empty string if category does not exist.
*/
function get_category_link( $category ) {
if ( ! is_object( $category ) )
if ( ! is_object( $category ) ) {
$category = (int) $category;
}
$category = get_term_link( $category );
if ( is_wp_error( $category ) )
if ( is_wp_error( $category ) ) {
return '';
}
return $category;
}
@ -69,17 +71,18 @@ function get_category_parents( $id, $link = false, $separator = '/', $nicename =
* @since 0.71
*
* @param int $id Optional, default to current post ID. The post ID.
* @return array Array of WP_Term objects, one for each category assigned to the post.
* @return WP_Term[] Array of WP_Term objects, one for each category assigned to the post.
*/
function get_the_category( $id = false ) {
$categories = get_the_terms( $id, 'category' );
if ( ! $categories || is_wp_error( $categories ) )
if ( ! $categories || is_wp_error( $categories ) ) {
$categories = array();
}
$categories = array_values( $categories );
foreach ( array_keys( $categories ) as $key ) {
_make_cat_compat( $categories[$key] );
_make_cat_compat( $categories[ $key ] );
}
/**
@ -88,8 +91,8 @@ function get_the_category( $id = false ) {
* @since 3.1.0
* @since 4.4.0 Added `$id` parameter.
*
* @param array $categories An array of categories to return for the post.
* @param int $id ID of the post.
* @param WP_Term[] $categories An array of categories to return for the post.
* @param int|false $id ID of the post.
*/
return apply_filters( 'get_the_categories', $categories, $id );
}
@ -103,11 +106,12 @@ function get_the_category( $id = false ) {
* @return string|WP_Error Category name on success, WP_Error on failure.
*/
function get_the_category_by_ID( $cat_ID ) {
$cat_ID = (int) $cat_ID;
$cat_ID = (int) $cat_ID;
$category = get_term( $cat_ID );
if ( is_wp_error( $category ) )
if ( is_wp_error( $category ) ) {
return $category;
}
return ( $category ) ? $category->name : '';
}
@ -137,9 +141,9 @@ function get_the_category_list( $separator = '', $parents = '', $post_id = false
*
* @since 4.4.0
*
* @param array $categories An array of the post's categories.
* @param int|bool $post_id ID of the post we're retrieving categories for. When `false`, we assume the
* current post in the loop.
* @param WP_Term[] $categories An array of the post's categories.
* @param int|bool $post_id ID of the post we're retrieving categories for. When `false`, we assume the
* current post in the loop.
*/
$categories = apply_filters( 'the_category_list', get_the_category( $post_id ), $post_id );
@ -157,42 +161,47 @@ function get_the_category_list( $separator = '', $parents = '', $post_id = false
$thelist .= "\n\t<li>";
switch ( strtolower( $parents ) ) {
case 'multiple':
if ( $category->parent )
if ( $category->parent ) {
$thelist .= get_category_parents( $category->parent, true, $separator );
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name.'</a></li>';
}
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name . '</a></li>';
break;
case 'single':
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>';
if ( $category->parent )
if ( $category->parent ) {
$thelist .= get_category_parents( $category->parent, false, $separator );
$thelist .= $category->name.'</a></li>';
}
$thelist .= $category->name . '</a></li>';
break;
case '':
default:
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name.'</a></li>';
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name . '</a></li>';
}
}
$thelist .= '</ul>';
} else {
$i = 0;
foreach ( $categories as $category ) {
if ( 0 < $i )
if ( 0 < $i ) {
$thelist .= $separator;
}
switch ( strtolower( $parents ) ) {
case 'multiple':
if ( $category->parent )
if ( $category->parent ) {
$thelist .= get_category_parents( $category->parent, true, $separator );
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name.'</a>';
}
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name . '</a>';
break;
case 'single':
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>';
if ( $category->parent )
if ( $category->parent ) {
$thelist .= get_category_parents( $category->parent, false, $separator );
}
$thelist .= "$category->name</a>";
break;
case '':
default:
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name.'</a>';
$thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" ' . $rel . '>' . $category->name . '</a>';
}
++$i;
}
@ -222,9 +231,9 @@ function get_the_category_list( $separator = '', $parents = '', $post_id = false
* Prior to v2.7, only one category could be compared: in_category( $single_category ).
* Prior to v2.7, this function could only be used in the WordPress Loop.
* As of 2.7, the function can be used anywhere if it is provided a post ID or post object.
*
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 1.2.0
@ -234,8 +243,9 @@ function get_the_category_list( $separator = '', $parents = '', $post_id = false
* @return bool True if the current post is in any of the given categories.
*/
function in_category( $category, $post = null ) {
if ( empty( $category ) )
if ( empty( $category ) ) {
return false;
}
return has_category( $category, $post );
}
@ -263,7 +273,7 @@ function the_category( $separator = '', $parents = '', $post_id = false ) {
* @return string Category description, available.
*/
function category_description( $category = 0 ) {
return term_description( $category, 'category' );
return term_description( $category );
}
/**
@ -342,9 +352,12 @@ function wp_dropdown_categories( $args = '' ) {
// Back compat.
if ( isset( $args['type'] ) && 'link' == $args['type'] ) {
_deprecated_argument( __FUNCTION__, '3.0.0',
_deprecated_argument(
__FUNCTION__,
'3.0.0',
/* translators: 1: "type => link", 2: "taxonomy => link_category" */
sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),
sprintf(
__( '%1$s is deprecated. Use %2$s instead.' ),
'<code>type => link</code>',
'<code>taxonomy => link_category</code>'
)
@ -352,7 +365,7 @@ function wp_dropdown_categories( $args = '' ) {
$args['taxonomy'] = 'link_category';
}
$r = wp_parse_args( $args, $defaults );
$r = wp_parse_args( $args, $defaults );
$option_none_value = $r['option_none_value'];
if ( ! isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) {
@ -371,9 +384,9 @@ function wp_dropdown_categories( $args = '' ) {
unset( $get_terms_args['name'] );
$categories = get_terms( $r['taxonomy'], $get_terms_args );
$name = esc_attr( $r['name'] );
$class = esc_attr( $r['class'] );
$id = $r['id'] ? esc_attr( $r['id'] ) : $name;
$name = esc_attr( $r['name'] );
$class = esc_attr( $r['class'] );
$id = $r['id'] ? esc_attr( $r['id'] ) : $name;
$required = $r['required'] ? 'required' : '';
if ( ! $r['hide_if_empty'] || ! empty( $categories ) ) {
@ -399,7 +412,7 @@ function wp_dropdown_categories( $args = '' ) {
* @param WP_Term|null $category The category object, or null if there's no corresponding category.
*/
$show_option_none = apply_filters( 'list_cats', $r['show_option_none'], null );
$output .= "\t<option value='" . esc_attr( $option_none_value ) . "' selected='selected'>$show_option_none</option>\n";
$output .= "\t<option value='" . esc_attr( $option_none_value ) . "' selected='selected'>$show_option_none</option>\n";
}
if ( ! empty( $categories ) ) {
@ -408,16 +421,16 @@ function wp_dropdown_categories( $args = '' ) {
/** This filter is documented in wp-includes/category-template.php */
$show_option_all = apply_filters( 'list_cats', $r['show_option_all'], null );
$selected = ( '0' === strval($r['selected']) ) ? " selected='selected'" : '';
$output .= "\t<option value='0'$selected>$show_option_all</option>\n";
$selected = ( '0' === strval( $r['selected'] ) ) ? " selected='selected'" : '';
$output .= "\t<option value='0'$selected>$show_option_all</option>\n";
}
if ( $r['show_option_none'] ) {
/** This filter is documented in wp-includes/category-template.php */
$show_option_none = apply_filters( 'list_cats', $r['show_option_none'], null );
$selected = selected( $option_none_value, $r['selected'], false );
$output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$selected>$show_option_none</option>\n";
$selected = selected( $option_none_value, $r['selected'], false );
$output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$selected>$show_option_none</option>\n";
}
if ( $r['hierarchical'] ) {
@ -526,8 +539,9 @@ function wp_list_categories( $args = '' ) {
$r = wp_parse_args( $args, $defaults );
if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] )
if ( ! isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) {
$r['pad_counts'] = true;
}
// Descendants of exclusions should be excluded too.
if ( true == $r['hierarchical'] ) {
@ -542,17 +556,18 @@ function wp_list_categories( $args = '' ) {
}
$r['exclude_tree'] = $exclude_tree;
$r['exclude'] = '';
$r['exclude'] = '';
}
if ( ! isset( $r['class'] ) )
if ( ! isset( $r['class'] ) ) {
$r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy'];
}
if ( ! taxonomy_exists( $r['taxonomy'] ) ) {
return false;
}
$show_option_all = $r['show_option_all'];
$show_option_all = $r['show_option_all'];
$show_option_none = $r['show_option_none'];
$categories = get_categories( $r );
@ -642,64 +657,74 @@ function wp_list_categories( $args = '' ) {
}
/**
* Display tag cloud.
*
* The text size is set by the 'smallest' and 'largest' arguments, which will
* use the 'unit' argument value for the CSS text size unit. The 'format'
* argument can be 'flat' (default), 'list', or 'array'. The flat value for the
* 'format' argument will separate tags with spaces. The list value for the
* 'format' argument will format the tags in a UL HTML list. The array value for
* the 'format' argument will return in PHP array type format.
*
* The 'orderby' argument will accept 'name' or 'count' and defaults to 'name'.
* The 'order' is the direction to sort, defaults to 'ASC' and can be 'DESC'.
*
* The 'number' argument is how many tags to return. By default, the limit will
* be to return the top 45 tags in the tag cloud list.
*
* The 'topic_count_text' argument is a nooped plural from _n_noop() to generate the
* text for the tag link count.
*
* The 'topic_count_text_callback' argument is a function, which given the count
* of the posts with that tag returns a text for the tag link count.
*
* The 'post_type' argument is used only when 'link' is set to 'edit'. It determines the post_type
* passed to edit.php for the popular tags edit links.
*
* The 'exclude' and 'include' arguments are used for the get_tags() function. Only one
* should be used, because only one will be used and the other ignored, if they are both set.
* Displays a tag cloud.
*
* @since 2.3.0
* @since 4.8.0 Added the `show_count` argument.
*
* @param array|string|null $args Optional. Override default arguments.
* @param array|string $args {
* Optional. Array or string of arguments for displaying a tag cloud. See wp_generate_tag_cloud()
* and get_terms() for the full lists of arguments that can be passed in `$args`.
*
* @type int $number The number of tags to display. Accepts any positive integer
* or zero to return all. Default 0 (all tags).
* @type string $link Whether to display term editing links or term permalinks.
* Accepts 'edit' and 'view'. Default 'view'.
* @type string $post_type The post type. Used to highlight the proper post type menu
* on the linked edit page. Defaults to the first post type
* associated with the taxonomy.
* @type bool $echo Whether or not to echo the return value. Default true.
* }
* @return void|array Generated tag cloud, only if no failures and 'array' is set for the 'format' argument.
* Otherwise, this function outputs the tag cloud.
*/
function wp_tag_cloud( $args = '' ) {
$defaults = array(
'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC',
'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomy' => 'post_tag', 'post_type' => '', 'echo' => true,
'smallest' => 8,
'largest' => 22,
'unit' => 'pt',
'number' => 45,
'format' => 'flat',
'separator' => "\n",
'orderby' => 'name',
'order' => 'ASC',
'exclude' => '',
'include' => '',
'link' => 'view',
'taxonomy' => 'post_tag',
'post_type' => '',
'echo' => true,
'show_count' => 0,
);
$args = wp_parse_args( $args, $defaults );
$args = wp_parse_args( $args, $defaults );
$tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags
$tags = get_terms(
$args['taxonomy'],
array_merge(
$args,
array(
'orderby' => 'count',
'order' => 'DESC',
)
)
); // Always query top tags
if ( empty( $tags ) || is_wp_error( $tags ) )
if ( empty( $tags ) || is_wp_error( $tags ) ) {
return;
}
foreach ( $tags as $key => $tag ) {
if ( 'edit' == $args['link'] )
if ( 'edit' == $args['link'] ) {
$link = get_edit_term_link( $tag->term_id, $tag->taxonomy, $args['post_type'] );
else
$link = get_term_link( intval($tag->term_id), $tag->taxonomy );
if ( is_wp_error( $link ) )
} else {
$link = get_term_link( intval( $tag->term_id ), $tag->taxonomy );
}
if ( is_wp_error( $link ) ) {
return;
}
$tags[ $key ]->link = $link;
$tags[ $key ]->id = $tag->term_id;
$tags[ $key ]->id = $tag->term_id;
}
$return = wp_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args
@ -714,8 +739,9 @@ function wp_tag_cloud( $args = '' ) {
*/
$return = apply_filters( 'wp_tag_cloud', $return, $args );
if ( 'array' == $args['format'] || empty($args['echo']) )
if ( 'array' == $args['format'] || empty( $args['echo'] ) ) {
return $return;
}
echo $return;
}
@ -729,7 +755,7 @@ function wp_tag_cloud( $args = '' ) {
* @return int Scaled count.
*/
function default_topic_count_scale( $count ) {
return round(log10($count + 1) * 100);
return round( log10( $count + 1 ) * 100 );
}
/**
@ -739,9 +765,9 @@ function default_topic_count_scale( $count ) {
* @since 2.3.0
* @since 4.8.0 Added the `show_count` argument.
*
* @param array $tags List of tags.
* @param WP_Term[] $tags Array of WP_Term objects to generate the tag cloud for.
* @param string|array $args {
* Optional. Array of string of arguments for generating a tag cloud.
* Optional. Array or string of arguments for generating a tag cloud.
*
* @type int $smallest Smallest font size used to display tags. Paired
* with the value of `$unit`, to determine CSS text
@ -780,11 +806,19 @@ function default_topic_count_scale( $count ) {
*/
function wp_generate_tag_cloud( $tags, $args = '' ) {
$defaults = array(
'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 0,
'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC',
'topic_count_text' => null, 'topic_count_text_callback' => null,
'topic_count_scale_callback' => 'default_topic_count_scale', 'filter' => 1,
'show_count' => 0,
'smallest' => 8,
'largest' => 22,
'unit' => 'pt',
'number' => 0,
'format' => 'flat',
'separator' => "\n",
'orderby' => 'name',
'order' => 'ASC',
'topic_count_text' => null,
'topic_count_text_callback' => null,
'topic_count_scale_callback' => 'default_topic_count_scale',
'filter' => 1,
'show_count' => 0,
);
$args = wp_parse_args( $args, $defaults );
@ -808,6 +842,7 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
}
} elseif ( isset( $args['single_text'] ) && isset( $args['multiple_text'] ) ) {
// If no callback exists, look for the old-style single_text and multiple_text arguments.
// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralSingle,WordPress.WP.I18n.NonSingularStringLiteralPlural
$translate_nooped_plural = _n_noop( $args['single_text'], $args['multiple_text'] );
} else {
// This is the default for when no callback, plural, or argument is passed in.
@ -819,8 +854,8 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
*
* @since 2.8.0
*
* @param array $tags Ordered array of terms.
* @param array $args An array of tag cloud arguments.
* @param WP_Term[] $tags Ordered array of terms.
* @param array $args An array of tag cloud arguments.
*/
$tags_sorted = apply_filters( 'tag_cloud_sort', $tags, $args );
if ( empty( $tags_sorted ) ) {
@ -847,23 +882,26 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
}
}
if ( $args['number'] > 0 )
if ( $args['number'] > 0 ) {
$tags = array_slice( $tags, 0, $args['number'] );
}
$counts = array();
$counts = array();
$real_counts = array(); // For the alt tag
foreach ( (array) $tags as $key => $tag ) {
$real_counts[ $key ] = $tag->count;
$counts[ $key ] = call_user_func( $args['topic_count_scale_callback'], $tag->count );
$counts[ $key ] = call_user_func( $args['topic_count_scale_callback'], $tag->count );
}
$min_count = min( $counts );
$spread = max( $counts ) - $min_count;
if ( $spread <= 0 )
$spread = max( $counts ) - $min_count;
if ( $spread <= 0 ) {
$spread = 1;
}
$font_spread = $args['largest'] - $args['smallest'];
if ( $font_spread < 0 )
if ( $font_spread < 0 ) {
$font_spread = 1;
}
$font_step = $font_spread / $spread;
$aria_label = false;
@ -887,7 +925,7 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
foreach ( $tags as $key => $tag ) {
$tag_id = isset( $tag->id ) ? $tag->id : $key;
$count = $counts[ $key ];
$count = $counts[ $key ];
$real_count = $real_counts[ $key ];
if ( $translate_nooped_plural ) {
@ -925,7 +963,7 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
// Generate the output links array.
foreach ( $tags_data as $key => $tag_data ) {
$class = $tag_data['class'] . ' tag-link-position-' . ( $key + 1 );
$a[] = sprintf(
$a[] = sprintf(
'<a href="%1$s"%2$s class="%3$s" style="font-size: %4$s;"%5$s>%6$s%7$s</a>',
esc_url( $tag_data['url'] ),
$tag_data['role'],
@ -938,20 +976,20 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
}
switch ( $args['format'] ) {
case 'array' :
case 'array':
$return =& $a;
break;
case 'list' :
case 'list':
/*
* Force role="list", as some browsers (sic: Safari 10) don't expose to assistive
* technologies the default role when the list is styled with `list-style: none`.
* Note: this is redundant but doesn't harm.
*/
$return = "<ul class='wp-tag-cloud' role='list'>\n\t<li>";
$return = "<ul class='wp-tag-cloud' role='list'>\n\t<li>";
$return .= join( "</li>\n\t<li>", $a );
$return .= "</li>\n</ul>\n";
break;
default :
default:
$return = join( $args['separator'], $a );
break;
}
@ -970,14 +1008,13 @@ function wp_generate_tag_cloud( $tags, $args = '' ) {
* @param array|string $return String containing the generated HTML tag cloud output
* or an array of tag links if the 'format' argument
* equals 'array'.
* @param array $tags An array of terms used in the tag cloud.
* @param WP_Term[] $tags An array of terms used in the tag cloud.
* @param array $args An array of wp_generate_tag_cloud() arguments.
*/
return apply_filters( 'wp_generate_tag_cloud', $return, $tags, $args );
}
else
} else {
return $return;
}
}
/**
@ -1089,7 +1126,7 @@ function get_the_tags( $id = 0 ) {
*
* @see get_the_terms()
*
* @param array $terms An array of tags for the given post.
* @param WP_Term[] $terms An array of tags for the given post.
*/
return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) );
}
@ -1131,8 +1168,9 @@ function get_the_tag_list( $before = '', $sep = '', $after = '', $id = 0 ) {
* @param string $after Optional. After list.
*/
function the_tags( $before = null, $sep = ', ', $after = '' ) {
if ( null === $before )
$before = __('Tags: ');
if ( null === $before ) {
$before = __( 'Tags: ' );
}
$the_tags = get_the_tag_list( $before, $sep, $after );
@ -1179,14 +1217,15 @@ function term_description( $term = 0, $deprecated = null ) {
*
* @since 2.5.0
*
* @param int|object $post Post ID or object.
* @param string $taxonomy Taxonomy name.
* @return array|false|WP_Error Array of WP_Term objects on success, false if there are no terms
* or the post does not exist, WP_Error on failure.
* @param int|WP_Post $post Post ID or object.
* @param string $taxonomy Taxonomy name.
* @return WP_Term[]|false|WP_Error Array of WP_Term objects on success, false if there are no terms
* or the post does not exist, WP_Error on failure.
*/
function get_the_terms( $post, $taxonomy ) {
if ( ! $post = get_post( $post ) )
if ( ! $post = get_post( $post ) ) {
return false;
}
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
@ -1202,14 +1241,15 @@ function get_the_terms( $post, $taxonomy ) {
*
* @since 3.1.0
*
* @param array|WP_Error $terms List of attached terms, or WP_Error on failure.
* @param int $post_id Post ID.
* @param string $taxonomy Name of the taxonomy.
* @param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.
* @param int $post_id Post ID.
* @param string $taxonomy Name of the taxonomy.
*/
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
if ( empty( $terms ) )
if ( empty( $terms ) ) {
return false;
}
return $terms;
}
@ -1229,11 +1269,13 @@ function get_the_terms( $post, $taxonomy ) {
function get_the_term_list( $id, $taxonomy, $before = '', $sep = '', $after = '' ) {
$terms = get_the_terms( $id, $taxonomy );
if ( is_wp_error( $terms ) )
if ( is_wp_error( $terms ) ) {
return $terms;
}
if ( empty( $terms ) )
if ( empty( $terms ) ) {
return false;
}
$links = array();
@ -1253,7 +1295,7 @@ function get_the_term_list( $id, $taxonomy, $before = '', $sep = '', $after = ''
*
* @since 2.5.0
*
* @param array $links An array of term links.
* @param string[] $links An array of term links.
*/
$term_links = apply_filters( "term_links-{$taxonomy}", $links );
@ -1340,15 +1382,16 @@ function get_term_parents_list( $term_id, $taxonomy, $args = array() ) {
function the_terms( $id, $taxonomy, $before = '', $sep = ', ', $after = '' ) {
$term_list = get_the_term_list( $id, $taxonomy, $before, $sep, $after );
if ( is_wp_error( $term_list ) )
if ( is_wp_error( $term_list ) ) {
return false;
}
/**
* Filters the list of terms to display.
*
* @since 2.9.0
*
* @param array $term_list List of terms to display.
* @param string $term_list List of terms to display.
* @param string $taxonomy The taxonomy name.
* @param string $before String to use before the terms.
* @param string $sep String to use between the terms.
@ -1380,9 +1423,9 @@ function has_category( $category = '', $post = null ) {
* Prior to v2.7 of WordPress, tags given as integers would also be checked against the post's tags' names and slugs (in addition to term_ids)
* Prior to v2.7, this function could only be used in the WordPress Loop.
* As of 2.7, the function can be used anywhere if it is provided a post ID or post object.
*
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 2.6.0
@ -1410,14 +1453,16 @@ function has_tag( $tag = '', $post = null ) {
* @return bool True if the current post has any of the given tags (or any tag, if no tag specified).
*/
function has_term( $term = '', $taxonomy = '', $post = null ) {
$post = get_post($post);
$post = get_post( $post );
if ( !$post )
if ( ! $post ) {
return false;
}
$r = is_object_in_term( $post->ID, $taxonomy, $term );
if ( is_wp_error( $r ) )
if ( is_wp_error( $r ) ) {
return false;
}
return $r;
}

View file

@ -25,7 +25,7 @@
*/
function get_categories( $args = '' ) {
$defaults = array( 'taxonomy' => 'category' );
$args = wp_parse_args( $args, $defaults );
$args = wp_parse_args( $args, $defaults );
$taxonomy = $args['taxonomy'];
@ -40,10 +40,13 @@ function get_categories( $args = '' ) {
$taxonomy = apply_filters( 'get_categories_taxonomy', $taxonomy, $args );
// Back compat
if ( isset($args['type']) && 'link' == $args['type'] ) {
_deprecated_argument( __FUNCTION__, '3.0.0',
if ( isset( $args['type'] ) && 'link' == $args['type'] ) {
_deprecated_argument(
__FUNCTION__,
'3.0.0',
/* translators: 1: "type => link", 2: "taxonomy => link_category" */
sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),
sprintf(
__( '%1$s is deprecated. Use %2$s instead.' ),
'<code>type => link</code>',
'<code>taxonomy => link_category</code>'
)
@ -91,8 +94,9 @@ function get_categories( $args = '' ) {
function get_category( $category, $output = OBJECT, $filter = 'raw' ) {
$category = get_term( $category, 'category', $output, $filter );
if ( is_wp_error( $category ) )
if ( is_wp_error( $category ) ) {
return $category;
}
_make_cat_compat( $category );
@ -120,24 +124,30 @@ function get_category( $category, $output = OBJECT, $filter = 'raw' ) {
* @return WP_Term|array|WP_Error|null Type is based on $output value.
*/
function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) {
$category_path = rawurlencode( urldecode( $category_path ) );
$category_path = str_replace( '%2F', '/', $category_path );
$category_path = str_replace( '%20', ' ', $category_path );
$category_path = rawurlencode( urldecode( $category_path ) );
$category_path = str_replace( '%2F', '/', $category_path );
$category_path = str_replace( '%20', ' ', $category_path );
$category_paths = '/' . trim( $category_path, '/' );
$leaf_path = sanitize_title( basename( $category_paths ) );
$leaf_path = sanitize_title( basename( $category_paths ) );
$category_paths = explode( '/', $category_paths );
$full_path = '';
$full_path = '';
foreach ( (array) $category_paths as $pathdir ) {
$full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title( $pathdir );
}
$categories = get_terms( 'category', array('get' => 'all', 'slug' => $leaf_path) );
$categories = get_terms(
'category',
array(
'get' => 'all',
'slug' => $leaf_path,
)
);
if ( empty( $categories ) ) {
return;
}
foreach ( $categories as $category ) {
$path = '/' . $leaf_path;
$path = '/' . $leaf_path;
$curcategory = $category;
while ( ( $curcategory->parent != 0 ) && ( $curcategory->parent != $curcategory->term_id ) ) {
$curcategory = get_term( $curcategory->parent, 'category' );
@ -170,10 +180,11 @@ function get_category_by_path( $category_path, $full_match = true, $output = OBJ
* @param string $slug The category slug.
* @return object Category data object
*/
function get_category_by_slug( $slug ) {
function get_category_by_slug( $slug ) {
$category = get_term_by( 'slug', $slug, 'category' );
if ( $category )
if ( $category ) {
_make_cat_compat( $category );
}
return $category;
}
@ -188,8 +199,9 @@ function get_category_by_slug( $slug ) {
*/
function get_cat_ID( $cat_name ) {
$cat = get_term_by( 'name', $cat_name, 'category' );
if ( $cat )
if ( $cat ) {
return $cat->term_id;
}
return 0;
}
@ -202,10 +214,11 @@ function get_cat_ID( $cat_name ) {
* @return string Category name, or an empty string if category doesn't exist.
*/
function get_cat_name( $cat_id ) {
$cat_id = (int) $cat_id;
$cat_id = (int) $cat_id;
$category = get_term( $cat_id, 'category' );
if ( ! $category || is_wp_error( $category ) )
if ( ! $category || is_wp_error( $category ) ) {
return '';
}
return $category->name;
}
@ -262,7 +275,7 @@ function sanitize_category_field( $field, $value, $cat_id, $context ) {
* @see get_terms() For list of arguments to pass.
*
* @param string|array $args Tag arguments to use when retrieving tags.
* @return array List of tags.
* @return WP_Term[]|int $tags Array of 'post_tag' term objects, or a count thereof.
*/
function get_tags( $args = '' ) {
$tags = get_terms( 'post_tag', $args );
@ -277,8 +290,8 @@ function get_tags( $args = '' ) {
*
* @since 2.3.0
*
* @param array $tags Array of 'post_tag' term objects.
* @param array $args An array of arguments. @see get_terms()
* @param WP_Term[]|int $tags Array of 'post_tag' term objects, or a count thereof.
* @param array $args An array of arguments. @see get_terms()
*/
$tags = apply_filters( 'get_tags', $tags, $args );
return $tags;
@ -343,18 +356,18 @@ function clean_category_cache( $id ) {
*/
function _make_cat_compat( &$category ) {
if ( is_object( $category ) && ! is_wp_error( $category ) ) {
$category->cat_ID = $category->term_id;
$category->category_count = $category->count;
$category->cat_ID = $category->term_id;
$category->category_count = $category->count;
$category->category_description = $category->description;
$category->cat_name = $category->name;
$category->category_nicename = $category->slug;
$category->category_parent = $category->parent;
$category->cat_name = $category->name;
$category->category_nicename = $category->slug;
$category->category_parent = $category->parent;
} elseif ( is_array( $category ) && isset( $category['term_id'] ) ) {
$category['cat_ID'] = &$category['term_id'];
$category['category_count'] = &$category['count'];
$category['cat_ID'] = &$category['term_id'];
$category['category_count'] = &$category['count'];
$category['category_description'] = &$category['description'];
$category['cat_name'] = &$category['name'];
$category['category_nicename'] = &$category['slug'];
$category['category_parent'] = &$category['parent'];
$category['cat_name'] = &$category['name'];
$category['category_nicename'] = &$category['slug'];
$category['category_parent'] = &$category['parent'];
}
}

View file

@ -15,4 +15,4 @@ if ( ! class_exists( 'SimplePie', false ) ) {
require_once( ABSPATH . WPINC . '/class-wp-feed-cache.php' );
require_once( ABSPATH . WPINC . '/class-wp-feed-cache-transient.php' );
require_once( ABSPATH . WPINC . '/class-wp-simplepie-file.php' );
require_once( ABSPATH . WPINC . '/class-wp-simplepie-sanitize-kses.php' );
require_once( ABSPATH . WPINC . '/class-wp-simplepie-sanitize-kses.php' );

View file

@ -28,29 +28,30 @@ if ( ! class_exists( 'Requests' ) ) {
class WP_Http {
// Aliases for HTTP response codes.
const HTTP_CONTINUE = 100;
const SWITCHING_PROTOCOLS = 101;
const PROCESSING = 102;
const HTTP_CONTINUE = 100;
const SWITCHING_PROTOCOLS = 101;
const PROCESSING = 102;
const EARLY_HINTS = 103;
const OK = 200;
const CREATED = 201;
const ACCEPTED = 202;
const NON_AUTHORITATIVE_INFORMATION = 203;
const NO_CONTENT = 204;
const RESET_CONTENT = 205;
const PARTIAL_CONTENT = 206;
const MULTI_STATUS = 207;
const IM_USED = 226;
const OK = 200;
const CREATED = 201;
const ACCEPTED = 202;
const NON_AUTHORITATIVE_INFORMATION = 203;
const NO_CONTENT = 204;
const RESET_CONTENT = 205;
const PARTIAL_CONTENT = 206;
const MULTI_STATUS = 207;
const IM_USED = 226;
const MULTIPLE_CHOICES = 300;
const MOVED_PERMANENTLY = 301;
const FOUND = 302;
const SEE_OTHER = 303;
const NOT_MODIFIED = 304;
const USE_PROXY = 305;
const RESERVED = 306;
const TEMPORARY_REDIRECT = 307;
const PERMANENT_REDIRECT = 308;
const MULTIPLE_CHOICES = 300;
const MOVED_PERMANENTLY = 301;
const FOUND = 302;
const SEE_OTHER = 303;
const NOT_MODIFIED = 304;
const USE_PROXY = 305;
const RESERVED = 306;
const TEMPORARY_REDIRECT = 307;
const PERMANENT_REDIRECT = 308;
const BAD_REQUEST = 400;
const UNAUTHORIZED = 401;
@ -104,7 +105,8 @@ class WP_Http {
* @param string|array $args {
* Optional. Array or string of HTTP request arguments.
*
* @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
* @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', 'PUT', 'DELETE',
* 'TRACE', 'OPTIONS', or 'PATCH'.
* Some transports technically allow others, but should not be
* assumed. Default 'GET'.
* @type int $timeout How long the connection should stay open in seconds. Default 5.
@ -146,60 +148,67 @@ class WP_Http {
*/
public function request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET',
'method' => 'GET',
/**
* Filters the timeout value for an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param int $timeout_value Time in seconds until a request times out.
* Default 5.
* @param int $timeout_value Time in seconds until a request times out. Default 5.
* @param string $url The request URL.
*/
'timeout' => apply_filters( 'http_request_timeout', 5 ),
'timeout' => apply_filters( 'http_request_timeout', 5, $url ),
/**
* Filters the number of redirects allowed during an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param int $redirect_count Number of redirects allowed. Default 5.
* @param int $redirect_count Number of redirects allowed. Default 5.
* @param string $url The request URL.
*/
'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
'redirection' => apply_filters( 'http_request_redirection_count', 5, $url ),
/**
* Filters the version of the HTTP protocol used in a request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
* Default '1.0'.
* @param string $version Version of HTTP used. Accepts '1.0' and '1.1'. Default '1.0'.
* @param string $url The request URL.
*/
'httpversion' => apply_filters( 'http_request_version', '1.0' ),
'httpversion' => apply_filters( 'http_request_version', '1.0', $url ),
/**
* Filters the user agent value sent with an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param string $user_agent WordPress user agent string.
* @param string $url The request URL.
*/
'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ) ),
'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ),
/**
* Filters whether to pass URLs through wp_http_validate_url() in an HTTP request.
*
* @since 3.6.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
* Default false.
* @param bool $pass_url Whether to pass URLs through wp_http_validate_url(). Default false.
* @param string $url The request URL.
*/
'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
'blocking' => true,
'headers' => array(),
'cookies' => array(),
'body' => null,
'compress' => false,
'decompress' => true,
'sslverify' => true,
'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
'stream' => false,
'filename' => null,
'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false, $url ),
'blocking' => true,
'headers' => array(),
'cookies' => array(),
'body' => null,
'compress' => false,
'decompress' => true,
'sslverify' => true,
'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
'stream' => false,
'filename' => null,
'limit_response_size' => null,
);
@ -207,8 +216,9 @@ class WP_Http {
$args = wp_parse_args( $args );
// By default, Head requests do not cause redirections.
if ( isset($args['method']) && 'HEAD' == $args['method'] )
if ( isset( $args['method'] ) && 'HEAD' == $args['method'] ) {
$defaults['redirection'] = 0;
}
$r = wp_parse_args( $args, $defaults );
/**
@ -222,8 +232,9 @@ class WP_Http {
$r = apply_filters( 'http_request_args', $r, $url );
// The transports decrement this, store a copy of the original value for loop purposes.
if ( ! isset( $r['_redirection'] ) )
if ( ! isset( $r['_redirection'] ) ) {
$r['_redirection'] = $r['redirection'];
}
/**
* Filters whether to preempt an HTTP request's return value.
@ -245,8 +256,9 @@ class WP_Http {
*/
$pre = apply_filters( 'pre_http_request', false, $r, $url );
if ( false !== $pre )
if ( false !== $pre ) {
return $pre;
}
if ( function_exists( 'wp_kses_bad_protocol' ) ) {
if ( $r['reject_unsafe_urls'] ) {
@ -260,7 +272,7 @@ class WP_Http {
$arrURL = @parse_url( $url );
if ( empty( $url ) || empty( $arrURL['scheme'] ) ) {
return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
return new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) );
}
if ( $this->block_request( $url ) ) {
@ -288,18 +300,18 @@ class WP_Http {
// WP allows passing in headers as a string, weirdly.
if ( ! is_array( $r['headers'] ) ) {
$processedHeaders = WP_Http::processHeaders( $r['headers'] );
$r['headers'] = $processedHeaders['headers'];
$r['headers'] = $processedHeaders['headers'];
}
// Setup arguments
$headers = $r['headers'];
$data = $r['body'];
$type = $r['method'];
$data = $r['body'];
$type = $r['method'];
$options = array(
'timeout' => $r['timeout'],
'timeout' => $r['timeout'],
'useragent' => $r['user-agent'],
'blocking' => $r['blocking'],
'hooks' => new WP_HTTP_Requests_Hooks( $url, $r ),
'blocking' => $r['blocking'],
'hooks' => new WP_HTTP_Requests_Hooks( $url, $r ),
);
// Ensure redirects follow browser behaviour.
@ -331,7 +343,7 @@ class WP_Http {
// SSL certificate handling
if ( ! $r['sslverify'] ) {
$options['verify'] = false;
$options['verify'] = false;
$options['verifyname'] = false;
} else {
$options['verify'] = $r['sslcertificates'];
@ -346,10 +358,12 @@ class WP_Http {
* Filters whether SSL should be verified for non-local requests.
*
* @since 2.8.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
* @param string $url The request URL.
*/
$options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'] );
$options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url );
// Check for proxies.
$proxy = new WP_HTTP_Proxy();
@ -358,8 +372,8 @@ class WP_Http {
if ( $proxy->use_authentication() ) {
$options['proxy']->use_authentication = true;
$options['proxy']->user = $proxy->username();
$options['proxy']->pass = $proxy->password();
$options['proxy']->user = $proxy->username();
$options['proxy']->pass = $proxy->password();
}
}
@ -371,12 +385,11 @@ class WP_Http {
// Convert the response into an array
$http_response = new WP_HTTP_Requests_Response( $requests_response, $r['filename'] );
$response = $http_response->to_array();
$response = $http_response->to_array();
// Add the original object to the array.
$response['http_response'] = $http_response;
}
catch ( Requests_Exception $e ) {
} catch ( Requests_Exception $e ) {
$response = new WP_Error( 'http_request_failed', $e->getMessage() );
}
@ -400,13 +413,13 @@ class WP_Http {
if ( ! $r['blocking'] ) {
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
'cookies' => array(),
'http_response' => null,
);
}
@ -427,9 +440,8 @@ class WP_Http {
* Normalizes cookies for using in Requests.
*
* @since 4.6.0
* @static
*
* @param array $cookies List of cookies to send with the request.
* @param array $cookies Array of cookies to send with the request.
* @return Requests_Cookie_Jar Cookie holder object.
*/
public static function normalize_cookies( $cookies ) {
@ -454,7 +466,6 @@ class WP_Http {
* specification for compatibility purposes.
*
* @since 4.6.0
* @static
*
* @param string $location URL to redirect to.
* @param array $headers Headers for the redirect.
@ -479,7 +490,7 @@ class WP_Http {
*/
public static function validate_redirects( $location ) {
if ( ! wp_http_validate_url( $location ) ) {
throw new Requests_Exception( __('A valid URL was not provided.'), 'wp_http.redirect_failed_validation' );
throw new Requests_Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' );
}
}
@ -516,8 +527,9 @@ class WP_Http {
$class = 'WP_Http_' . $transport;
// Check to see if this transport is a possibility, calls the transport statically.
if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) {
continue;
}
return $class;
}
@ -534,8 +546,8 @@ class WP_Http {
* The order for requests is cURL, and then PHP Streams.
*
* @since 3.2.0
*
* @static
* @deprecated 5.1.0 Use WP_Http::request()
* @see WP_Http::request()
*
* @param string $url URL to Request
* @param array $args Request arguments
@ -545,30 +557,25 @@ class WP_Http {
static $transports = array();
$class = $this->_get_first_available_transport( $args, $url );
if ( !$class )
if ( ! $class ) {
return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
}
// Transport claims to support request, instantiate it and give it a whirl.
if ( empty( $transports[$class] ) )
$transports[$class] = new $class;
if ( empty( $transports[ $class ] ) ) {
$transports[ $class ] = new $class;
}
$response = $transports[$class]->request( $url, $args );
$response = $transports[ $class ]->request( $url, $args );
/** This action is documented in wp-includes/class-http.php */
do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
if ( is_wp_error( $response ) )
if ( is_wp_error( $response ) ) {
return $response;
}
/**
* Filters the HTTP API response immediately before the response is returned.
*
* @since 2.9.0
*
* @param array $response HTTP response.
* @param array $args HTTP request arguments.
* @param string $url The request URL.
*/
/** This filter is documented in wp-includes/class-http.php */
return apply_filters( 'http_response', $response, $args, $url );
}
@ -583,10 +590,10 @@ class WP_Http {
* @param string|array $args Optional. Override the defaults.
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
public function post($url, $args = array()) {
$defaults = array('method' => 'POST');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
public function post( $url, $args = array() ) {
$defaults = array( 'method' => 'POST' );
$r = wp_parse_args( $args, $defaults );
return $this->request( $url, $r );
}
/**
@ -600,10 +607,10 @@ class WP_Http {
* @param string|array $args Optional. Override the defaults.
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
public function get($url, $args = array()) {
$defaults = array('method' => 'GET');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
public function get( $url, $args = array() ) {
$defaults = array( 'method' => 'GET' );
$r = wp_parse_args( $args, $defaults );
return $this->request( $url, $r );
}
/**
@ -617,25 +624,27 @@ class WP_Http {
* @param string|array $args Optional. Override the defaults.
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
public function head($url, $args = array()) {
$defaults = array('method' => 'HEAD');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
public function head( $url, $args = array() ) {
$defaults = array( 'method' => 'HEAD' );
$r = wp_parse_args( $args, $defaults );
return $this->request( $url, $r );
}
/**
* Parses the responses and splits the parts into headers and body.
*
* @static
* @since 2.7.0
*
* @param string $strResponse The full response string
* @return array Array with 'headers' and 'body' keys.
*/
public static function processResponse($strResponse) {
$res = explode("\r\n\r\n", $strResponse, 2);
public static function processResponse( $strResponse ) {
$res = explode( "\r\n\r\n", $strResponse, 2 );
return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
return array(
'headers' => $res[0],
'body' => isset( $res[1] ) ? $res[1] : '',
);
}
/**
@ -644,74 +653,83 @@ class WP_Http {
* If an array is given then it is assumed to be raw header data with numeric keys with the
* headers as the values. No headers must be passed that were already processed.
*
* @static
* @since 2.7.0
*
* @param string|array $headers
* @param string $url The URL that was requested
* @return array Processed string headers. If duplicate headers are encountered,
* Then a numbered array is returned as the value of that header-key.
* Then a numbered array is returned as the value of that header-key.
*/
public static function processHeaders( $headers, $url = '' ) {
// Split headers, one per array element.
if ( is_string($headers) ) {
if ( is_string( $headers ) ) {
// Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
$headers = str_replace("\r\n", "\n", $headers);
$headers = str_replace( "\r\n", "\n", $headers );
/*
* Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
* <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
*/
$headers = preg_replace('/\n[ \t]/', ' ', $headers);
$headers = preg_replace( '/\n[ \t]/', ' ', $headers );
// Create the headers array.
$headers = explode("\n", $headers);
$headers = explode( "\n", $headers );
}
$response = array('code' => 0, 'message' => '');
$response = array(
'code' => 0,
'message' => '',
);
/*
* If a redirection has taken place, The headers for each page request may have been passed.
* In this case, determine the final HTTP header and parse from there.
*/
for ( $i = count($headers)-1; $i >= 0; $i-- ) {
if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
$headers = array_splice($headers, $i);
for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) {
if ( ! empty( $headers[ $i ] ) && false === strpos( $headers[ $i ], ':' ) ) {
$headers = array_splice( $headers, $i );
break;
}
}
$cookies = array();
$cookies = array();
$newheaders = array();
foreach ( (array) $headers as $tempheader ) {
if ( empty($tempheader) )
if ( empty( $tempheader ) ) {
continue;
}
if ( false === strpos($tempheader, ':') ) {
$stack = explode(' ', $tempheader, 3);
if ( false === strpos( $tempheader, ':' ) ) {
$stack = explode( ' ', $tempheader, 3 );
$stack[] = '';
list( , $response['code'], $response['message']) = $stack;
continue;
}
list($key, $value) = explode(':', $tempheader, 2);
list($key, $value) = explode( ':', $tempheader, 2 );
$key = strtolower( $key );
$key = strtolower( $key );
$value = trim( $value );
if ( isset( $newheaders[ $key ] ) ) {
if ( ! is_array( $newheaders[ $key ] ) )
$newheaders[$key] = array( $newheaders[ $key ] );
if ( ! is_array( $newheaders[ $key ] ) ) {
$newheaders[ $key ] = array( $newheaders[ $key ] );
}
$newheaders[ $key ][] = $value;
} else {
$newheaders[ $key ] = $value;
}
if ( 'set-cookie' == $key )
if ( 'set-cookie' == $key ) {
$cookies[] = new WP_Http_Cookie( $value, $url );
}
}
// Cast the Response Code to an int
$response['code'] = intval( $response['code'] );
return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
return array(
'response' => $response,
'headers' => $newheaders,
'cookies' => $cookies,
);
}
/**
@ -722,16 +740,21 @@ class WP_Http {
* Edits the array by reference.
*
* @since 2.8.0
* @static
*
* @param array $r Full array of args passed into ::request()
*/
public static function buildCookieHeader( &$r ) {
if ( ! empty($r['cookies']) ) {
if ( ! empty( $r['cookies'] ) ) {
// Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
foreach ( $r['cookies'] as $name => $value ) {
if ( ! is_object( $value ) )
$r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
if ( ! is_object( $value ) ) {
$r['cookies'][ $name ] = new WP_Http_Cookie(
array(
'name' => $name,
'value' => $value,
)
);
}
}
$cookies_header = '';
@ -739,7 +762,7 @@ class WP_Http {
$cookies_header .= $cookie->getHeaderValue() . '; ';
}
$cookies_header = substr( $cookies_header, 0, -2 );
$cookies_header = substr( $cookies_header, 0, -2 );
$r['headers']['cookie'] = $cookies_header;
}
}
@ -752,15 +775,15 @@ class WP_Http {
* @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
*
* @since 2.7.0
* @static
*
* @param string $body Body content
* @return string Chunked decoded body on success or raw body on failure.
*/
public static function chunkTransferDecode( $body ) {
// The body is not chunked encoded or is malformed.
if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) {
return $body;
}
$parsed_body = '';
@ -769,10 +792,11 @@ class WP_Http {
while ( true ) {
$has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
if ( ! $has_chunk || empty( $match[1] ) )
if ( ! $has_chunk || empty( $match[1] ) ) {
return $body_original;
}
$length = hexdec( $match[1] );
$length = hexdec( $match[1] );
$chunk_length = strlen( $match[0] );
// Parse out the chunk of data.
@ -782,8 +806,9 @@ class WP_Http {
$body = substr( $body, $length + $chunk_length );
// End of the document.
if ( '0' === trim( $body ) )
if ( '0' === trim( $body ) ) {
return $parsed_body;
}
}
}
@ -809,16 +834,18 @@ class WP_Http {
* @param string $uri URI of url.
* @return bool True to block, false to allow.
*/
public function block_request($uri) {
public function block_request( $uri ) {
// We don't need to block requests, because nothing is blocked.
if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) {
return false;
}
$check = parse_url($uri);
if ( ! $check )
$check = parse_url( $uri );
if ( ! $check ) {
return true;
}
$home = parse_url( get_option('siteurl') );
$home = parse_url( get_option( 'siteurl' ) );
// Don't block requests back to ourselves by default.
if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
@ -833,26 +860,29 @@ class WP_Http {
return apply_filters( 'block_local_requests', false );
}
if ( !defined('WP_ACCESSIBLE_HOSTS') )
if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
return true;
}
static $accessible_hosts = null;
static $wildcard_regex = array();
static $wildcard_regex = array();
if ( null === $accessible_hosts ) {
$accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
$accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS );
if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
if ( false !== strpos( WP_ACCESSIBLE_HOSTS, '*' ) ) {
$wildcard_regex = array();
foreach ( $accessible_hosts as $host )
foreach ( $accessible_hosts as $host ) {
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
}
$wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
}
}
if ( !empty($wildcard_regex) )
return !preg_match($wildcard_regex, $check['host']);
else
return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
if ( ! empty( $wildcard_regex ) ) {
return ! preg_match( $wildcard_regex, $check['host'] );
} else {
return ! in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
}
}
@ -878,15 +908,14 @@ class WP_Http {
*
* @since 3.4.0
*
* @static
*
* @param string $maybe_relative_path The URL which might be relative
* @param string $url The URL which $maybe_relative_path is relative to
* @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
*/
public static function make_absolute_url( $maybe_relative_path, $url ) {
if ( empty( $url ) )
if ( empty( $url ) ) {
return $maybe_relative_path;
}
if ( ! $url_parts = wp_parse_url( $url ) ) {
return $maybe_relative_path;
@ -906,12 +935,14 @@ class WP_Http {
// Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
if ( isset( $relative_url_parts['host'] ) ) {
$absolute_path .= $relative_url_parts['host'];
if ( isset( $relative_url_parts['port'] ) )
if ( isset( $relative_url_parts['port'] ) ) {
$absolute_path .= ':' . $relative_url_parts['port'];
}
} else {
$absolute_path .= $url_parts['host'];
if ( isset( $url_parts['port'] ) )
if ( isset( $url_parts['port'] ) ) {
$absolute_path .= ':' . $url_parts['port'];
}
}
// Start off with the Absolute URL path.
@ -921,7 +952,7 @@ class WP_Http {
if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
$path = $relative_url_parts['path'];
// Else it's a relative path.
// Else it's a relative path.
} elseif ( ! empty( $relative_url_parts['path'] ) ) {
// Strip off any file components from the absolute path.
$path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
@ -939,8 +970,9 @@ class WP_Http {
}
// Add the Query string.
if ( ! empty( $relative_url_parts['query'] ) )
if ( ! empty( $relative_url_parts['query'] ) ) {
$path .= '?' . $relative_url_parts['query'];
}
return $absolute_path . '/' . ltrim( $path, '/' );
}
@ -949,7 +981,6 @@ class WP_Http {
* Handles HTTP Redirects and follows them if appropriate.
*
* @since 3.7.0
* @static
*
* @param string $url The URL which was requested.
* @param array $args The Arguments which were used to make the request.
@ -958,36 +989,42 @@ class WP_Http {
*/
public static function handle_redirects( $url, $args, $response ) {
// If no redirects are present, or, redirects were not requested, perform no action.
if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
return false;
}
// Only perform redirections on redirection http codes.
if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
return false;
}
// Don't redirect if we've run out of redirects.
if ( $args['redirection']-- <= 0 )
return new WP_Error( 'http_request_failed', __('Too many redirects.') );
if ( $args['redirection']-- <= 0 ) {
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
$redirect_location = $response['headers']['location'];
// If there were multiple Location headers, use the last header specified.
if ( is_array( $redirect_location ) )
if ( is_array( $redirect_location ) ) {
$redirect_location = array_pop( $redirect_location );
}
$redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
// POST requests should not POST to a redirected location.
if ( 'POST' == $args['method'] ) {
if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
if ( in_array( $response['response']['code'], array( 302, 303 ) ) ) {
$args['method'] = 'GET';
}
}
// Include valid cookies in the redirect process.
if ( ! empty( $response['cookies'] ) ) {
foreach ( $response['cookies'] as $cookie ) {
if ( $cookie->test( $redirect_location ) )
if ( $cookie->test( $redirect_location ) ) {
$args['cookies'][] = $cookie;
}
}
}
@ -1005,17 +1042,18 @@ class WP_Http {
* @link http://home.deds.nl/~aeron/regex/ for IPv6 regex
*
* @since 3.7.0
* @static
*
* @param string $maybe_ip A suspected IP address
* @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
*/
public static function is_ip_address( $maybe_ip ) {
if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) {
return 4;
}
if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) )
if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) {
return 6;
}
return false;
}

View file

@ -252,7 +252,7 @@ class Services_JSON
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* if var is a string, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
@ -268,7 +268,7 @@ class Services_JSON
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* if var is a string, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
@ -289,7 +289,7 @@ class Services_JSON
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* if var is a string, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs

View file

@ -30,7 +30,6 @@ class WP_oEmbed {
* A list of an early oEmbed providers.
*
* @since 4.0.0
* @static
* @var array
*/
public static $early_providers = array();
@ -49,74 +48,72 @@ class WP_oEmbed {
* @since 2.9.0
*/
public function __construct() {
$host = urlencode( home_url() );
$host = urlencode( home_url() );
$providers = array(
'#https?://((m|www)\.)?youtube\.com/watch.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://((m|www)\.)?youtube\.com/playlist.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://youtu\.be/.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://(.+\.)?vimeo\.com/.*#i' => array( 'https://vimeo.com/api/oembed.{format}', true ),
'#https?://(www\.)?dailymotion\.com/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ),
'#https?://dai\.ly/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ),
'#https?://(www\.)?flickr\.com/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ),
'#https?://flic\.kr/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ),
'#https?://(.+\.)?smugmug\.com/.*#i' => array( 'https://api.smugmug.com/services/oembed/', true ),
'#https?://(www\.)?hulu\.com/watch/.*#i' => array( 'http://www.hulu.com/api/oembed.{format}', true ),
'http://i*.photobucket.com/albums/*' => array( 'http://api.photobucket.com/oembed', false ),
'http://gi*.photobucket.com/groups/*' => array( 'http://api.photobucket.com/oembed', false ),
'#https?://(www\.)?scribd\.com/doc/.*#i' => array( 'https://www.scribd.com/services/oembed', true ),
'#https?://wordpress\.tv/.*#i' => array( 'https://wordpress.tv/oembed/', true ),
'#https?://(.+\.)?polldaddy\.com/.*#i' => array( 'https://polldaddy.com/oembed/', true ),
'#https?://poll\.fm/.*#i' => array( 'https://polldaddy.com/oembed/', true ),
'#https?://(www\.)?funnyordie\.com/videos/.*#i' => array( 'http://www.funnyordie.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/status(es)?/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}$#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/likes$#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/lists/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/timelines/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/i/moments/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?soundcloud\.com/.*#i' => array( 'https://soundcloud.com/oembed', true ),
'#https?://(.+?\.)?slideshare\.net/.*#i' => array( 'https://www.slideshare.net/api/oembed/2', true ),
'#https?://(www\.)?instagr(\.am|am\.com)/p/.*#i' => array( 'https://api.instagram.com/oembed', true ),
'#https?://(open|play)\.spotify\.com/.*#i' => array( 'https://embed.spotify.com/oembed/', true ),
'#https?://(.+\.)?imgur\.com/.*#i' => array( 'https://api.imgur.com/oembed', true ),
'#https?://(www\.)?meetu(\.ps|p\.com)/.*#i' => array( 'https://api.meetup.com/oembed', true ),
'#https?://(www\.)?issuu\.com/.+/docs/.+#i' => array( 'https://issuu.com/oembed_wp', true ),
'#https?://(www\.)?collegehumor\.com/video/.*#i' => array( 'https://www.collegehumor.com/oembed.{format}', true ),
'#https?://(www\.)?mixcloud\.com/.*#i' => array( 'https://www.mixcloud.com/oembed', true ),
'#https?://(www\.|embed\.)?ted\.com/talks/.*#i' => array( 'https://www.ted.com/services/v1/oembed.{format}', true ),
'#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create', true ),
'#https?://(.+)\.tumblr\.com/post/.*#i' => array( 'https://www.tumblr.com/oembed/1.0', true ),
'#https?://(www\.)?kickstarter\.com/projects/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
'#https?://kck\.st/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
'#https?://cloudup\.com/.*#i' => array( 'https://cloudup.com/oembed', true ),
'#https?://(www\.)?reverbnation\.com/.*#i' => array( 'https://www.reverbnation.com/oembed', true ),
'#https?://videopress\.com/v/.*#' => array( 'https://public-api.wordpress.com/oembed/?for=' . $host, true ),
'#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed', true ),
'#https?://(www\.)?speakerdeck\.com/.*#i' => array( 'https://speakerdeck.com/oembed.{format}', true ),
'#https?://www\.facebook\.com/.*/posts/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/activity/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/photos/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/photo(s/|\.php).*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/permalink\.php.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/media/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/questions/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/notes/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/videos/.*#i' => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
'#https?://www\.facebook\.com/video\.php.*#i' => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
'#https?://(www\.)?screencast\.com/.*#i' => array( 'https://api.screencast.com/external/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(com|com\.mx|com\.br|ca)/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(co\.uk|de|fr|it|es|in|nl|ru)/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(co\.jp|com\.au)/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ),
'#https?://(www\.)?a\.co/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.to/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.eu/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.in/.*#i' => array( 'https://read.amazon.in/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.asia/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
'#https?://(www\.)?z\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ),
'#https?://www\.someecards\.com/.+-cards/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
'#https?://www\.someecards\.com/usercards/viewcard/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
'#https?://some\.ly\/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
'#https?://((m|www)\.)?youtube\.com/watch.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://((m|www)\.)?youtube\.com/playlist.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://youtu\.be/.*#i' => array( 'https://www.youtube.com/oembed', true ),
'#https?://(.+\.)?vimeo\.com/.*#i' => array( 'https://vimeo.com/api/oembed.{format}', true ),
'#https?://(www\.)?dailymotion\.com/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ),
'#https?://dai\.ly/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ),
'#https?://(www\.)?flickr\.com/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ),
'#https?://flic\.kr/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ),
'#https?://(.+\.)?smugmug\.com/.*#i' => array( 'https://api.smugmug.com/services/oembed/', true ),
'#https?://(www\.)?hulu\.com/watch/.*#i' => array( 'http://www.hulu.com/api/oembed.{format}', true ),
'#https?://(www\.)?scribd\.com/doc/.*#i' => array( 'https://www.scribd.com/services/oembed', true ),
'#https?://wordpress\.tv/.*#i' => array( 'https://wordpress.tv/oembed/', true ),
'#https?://(.+\.)?polldaddy\.com/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ),
'#https?://poll\.fm/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ),
'#https?://survey\.fm/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/status(es)?/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}$#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/likes$#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/lists/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/\w{1,15}/timelines/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?twitter\.com/i/moments/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
'#https?://(www\.)?soundcloud\.com/.*#i' => array( 'https://soundcloud.com/oembed', true ),
'#https?://(.+?\.)?slideshare\.net/.*#i' => array( 'https://www.slideshare.net/api/oembed/2', true ),
'#https?://(www\.)?instagr(\.am|am\.com)/(p|tv)/.*#i' => array( 'https://api.instagram.com/oembed', true ),
'#https?://(open|play)\.spotify\.com/.*#i' => array( 'https://embed.spotify.com/oembed/', true ),
'#https?://(.+\.)?imgur\.com/.*#i' => array( 'https://api.imgur.com/oembed', true ),
'#https?://(www\.)?meetu(\.ps|p\.com)/.*#i' => array( 'https://api.meetup.com/oembed', true ),
'#https?://(www\.)?issuu\.com/.+/docs/.+#i' => array( 'https://issuu.com/oembed_wp', true ),
'#https?://(www\.)?collegehumor\.com/video/.*#i' => array( 'https://www.collegehumor.com/oembed.{format}', true ),
'#https?://(www\.)?mixcloud\.com/.*#i' => array( 'https://www.mixcloud.com/oembed', true ),
'#https?://(www\.|embed\.)?ted\.com/talks/.*#i' => array( 'https://www.ted.com/services/v1/oembed.{format}', true ),
'#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create', true ),
'#https?://(.+)\.tumblr\.com/post/.*#i' => array( 'https://www.tumblr.com/oembed/1.0', true ),
'#https?://(www\.)?kickstarter\.com/projects/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
'#https?://kck\.st/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
'#https?://cloudup\.com/.*#i' => array( 'https://cloudup.com/oembed', true ),
'#https?://(www\.)?reverbnation\.com/.*#i' => array( 'https://www.reverbnation.com/oembed', true ),
'#https?://videopress\.com/v/.*#' => array( 'https://public-api.wordpress.com/oembed/?for=' . $host, true ),
'#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed', true ),
'#https?://(www\.)?speakerdeck\.com/.*#i' => array( 'https://speakerdeck.com/oembed.{format}', true ),
'#https?://www\.facebook\.com/.*/posts/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/activity/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/photos/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/photo(s/|\.php).*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/permalink\.php.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/media/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/questions/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/notes/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
'#https?://www\.facebook\.com/.*/videos/.*#i' => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
'#https?://www\.facebook\.com/video\.php.*#i' => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
'#https?://(www\.)?screencast\.com/.*#i' => array( 'https://api.screencast.com/external/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(com|com\.mx|com\.br|ca)/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(co\.uk|de|fr|it|es|in|nl|ru)/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.(co\.jp|com\.au)/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
'#https?://([a-z0-9-]+\.)?amazon\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ),
'#https?://(www\.)?a\.co/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.to/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.eu/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.in/.*#i' => array( 'https://read.amazon.in/kp/api/oembed', true ),
'#https?://(www\.)?amzn\.asia/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
'#https?://(www\.)?z\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ),
'#https?://www\.someecards\.com/.+-cards/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
'#https?://www\.someecards\.com/usercards/viewcard/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
'#https?://some\.ly\/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
);
if ( ! empty( self::$early_providers['add'] ) ) {
@ -142,63 +139,64 @@ class WP_oEmbed {
*
* Supported providers:
*
* | Provider | Flavor | Supports HTTPS | Since |
* | ------------ | --------------------------------- | :------------: | ------- |
* | Dailymotion | dailymotion.com | Yes | 2.9.0 |
* | Flickr | flickr.com | Yes | 2.9.0 |
* | Hulu | hulu.com | Yes | 2.9.0 |
* | Photobucket | photobucket.com | No | 2.9.0 |
* | Scribd | scribd.com | Yes | 2.9.0 |
* | Vimeo | vimeo.com | Yes | 2.9.0 |
* | WordPress.tv | wordpress.tv | Yes | 2.9.0 |
* | YouTube | youtube.com/watch | Yes | 2.9.0 |
* | Funny or Die | funnyordie.com | Yes | 3.0.0 |
* | Polldaddy | polldaddy.com | Yes | 3.0.0 |
* | SmugMug | smugmug.com | Yes | 3.0.0 |
* | YouTube | youtu.be | Yes | 3.0.0 |
* | Twitter | twitter.com | Yes | 3.4.0 |
* | Instagram | instagram.com | Yes | 3.5.0 |
* | Instagram | instagr.am | Yes | 3.5.0 |
* | Slideshare | slideshare.net | Yes | 3.5.0 |
* | SoundCloud | soundcloud.com | Yes | 3.5.0 |
* | Dailymotion | dai.ly | Yes | 3.6.0 |
* | Flickr | flic.kr | Yes | 3.6.0 |
* | Spotify | spotify.com | Yes | 3.6.0 |
* | Imgur | imgur.com | Yes | 3.9.0 |
* | Meetup.com | meetup.com | Yes | 3.9.0 |
* | Meetup.com | meetu.ps | Yes | 3.9.0 |
* | Animoto | animoto.com | Yes | 4.0.0 |
* | Animoto | video214.com | Yes | 4.0.0 |
* | CollegeHumor | collegehumor.com | Yes | 4.0.0 |
* | Issuu | issuu.com | Yes | 4.0.0 |
* | Mixcloud | mixcloud.com | Yes | 4.0.0 |
* | Polldaddy | poll.fm | Yes | 4.0.0 |
* | TED | ted.com | Yes | 4.0.0 |
* | YouTube | youtube.com/playlist | Yes | 4.0.0 |
* | Tumblr | tumblr.com | Yes | 4.2.0 |
* | Kickstarter | kickstarter.com | Yes | 4.2.0 |
* | Kickstarter | kck.st | Yes | 4.2.0 |
* | Cloudup | cloudup.com | Yes | 4.3.0 |
* | ReverbNation | reverbnation.com | Yes | 4.4.0 |
* | VideoPress | videopress.com | Yes | 4.4.0 |
* | Reddit | reddit.com | Yes | 4.4.0 |
* | Speaker Deck | speakerdeck.com | Yes | 4.4.0 |
* | Twitter | twitter.com/timelines | Yes | 4.5.0 |
* | Twitter | twitter.com/moments | Yes | 4.5.0 |
* | Facebook | facebook.com | Yes | 4.7.0 |
* | Twitter | twitter.com/user | Yes | 4.7.0 |
* | Twitter | twitter.com/likes | Yes | 4.7.0 |
* | Twitter | twitter.com/lists | Yes | 4.7.0 |
* | Screencast | screencast.com | Yes | 4.8.0 |
* | Amazon | amazon.com|com.mx|com.br|ca | Yes | 4.9.0 |
* | Amazon | amazon.de|fr|it|es|in|nl|ru|co.uk | Yes | 4.9.0 |
* | Amazon | amazon.co.jp|com.au | Yes | 4.9.0 |
* | Amazon | amazon.cn | Yes | 4.9.0 |
* | Amazon | a.co | Yes | 4.9.0 |
* | Amazon | amzn.to|eu|in|asia | Yes | 4.9.0 |
* | Amazon | z.cn | Yes | 4.9.0 |
* | Someecards | someecards.com | Yes | 4.9.0 |
* | Someecards | some.ly | Yes | 4.9.0 |
* | Provider | Flavor | Supports HTTPS | Since |
* | ------------ | ----------------------------------------- | :------------: | ------- |
* | Dailymotion | dailymotion.com | Yes | 2.9.0 |
* | Flickr | flickr.com | Yes | 2.9.0 |
* | Hulu | hulu.com | Yes | 2.9.0 |
* | Scribd | scribd.com | Yes | 2.9.0 |
* | Vimeo | vimeo.com | Yes | 2.9.0 |
* | WordPress.tv | wordpress.tv | Yes | 2.9.0 |
* | YouTube | youtube.com/watch | Yes | 2.9.0 |
* | Crowdsignal | polldaddy.com | Yes | 3.0.0 |
* | SmugMug | smugmug.com | Yes | 3.0.0 |
* | YouTube | youtu.be | Yes | 3.0.0 |
* | Twitter | twitter.com | Yes | 3.4.0 |
* | Instagram | instagram.com | Yes | 3.5.0 |
* | Instagram | instagr.am | Yes | 3.5.0 |
* | Slideshare | slideshare.net | Yes | 3.5.0 |
* | SoundCloud | soundcloud.com | Yes | 3.5.0 |
* | Dailymotion | dai.ly | Yes | 3.6.0 |
* | Flickr | flic.kr | Yes | 3.6.0 |
* | Spotify | spotify.com | Yes | 3.6.0 |
* | Imgur | imgur.com | Yes | 3.9.0 |
* | Meetup.com | meetup.com | Yes | 3.9.0 |
* | Meetup.com | meetu.ps | Yes | 3.9.0 |
* | Animoto | animoto.com | Yes | 4.0.0 |
* | Animoto | video214.com | Yes | 4.0.0 |
* | CollegeHumor | collegehumor.com | Yes | 4.0.0 |
* | Issuu | issuu.com | Yes | 4.0.0 |
* | Mixcloud | mixcloud.com | Yes | 4.0.0 |
* | Crowdsignal | poll.fm | Yes | 4.0.0 |
* | TED | ted.com | Yes | 4.0.0 |
* | YouTube | youtube.com/playlist | Yes | 4.0.0 |
* | Tumblr | tumblr.com | Yes | 4.2.0 |
* | Kickstarter | kickstarter.com | Yes | 4.2.0 |
* | Kickstarter | kck.st | Yes | 4.2.0 |
* | Cloudup | cloudup.com | Yes | 4.3.0 |
* | ReverbNation | reverbnation.com | Yes | 4.4.0 |
* | VideoPress | videopress.com | Yes | 4.4.0 |
* | Reddit | reddit.com | Yes | 4.4.0 |
* | Speaker Deck | speakerdeck.com | Yes | 4.4.0 |
* | Twitter | twitter.com/timelines | Yes | 4.5.0 |
* | Twitter | twitter.com/moments | Yes | 4.5.0 |
* | Facebook | facebook.com | Yes | 4.7.0 |
* | Twitter | twitter.com/user | Yes | 4.7.0 |
* | Twitter | twitter.com/likes | Yes | 4.7.0 |
* | Twitter | twitter.com/lists | Yes | 4.7.0 |
* | Screencast | screencast.com | Yes | 4.8.0 |
* | Amazon | amazon.com (com.mx, com.br, ca) | Yes | 4.9.0 |
* | Amazon | amazon.de (fr, it, es, in, nl, ru, co.uk) | Yes | 4.9.0 |
* | Amazon | amazon.co.jp (com.au) | Yes | 4.9.0 |
* | Amazon | amazon.cn | Yes | 4.9.0 |
* | Amazon | a.co | Yes | 4.9.0 |
* | Amazon | amzn.to (eu, in, asia) | Yes | 4.9.0 |
* | Amazon | z.cn | Yes | 4.9.0 |
* | Someecards | someecards.com | Yes | 4.9.0 |
* | Someecards | some.ly | Yes | 4.9.0 |
* | Crowdsignal | survey.fm | Yes | 5.1.0 |
* | Instagram TV | instagram.com | Yes | 5.1.0 |
* | Instagram TV | instagr.am | Yes | 5.1.0 |
*
* No longer supported providers:
*
@ -211,17 +209,19 @@ class WP_oEmbed {
* | Rdio | rdio.com | Yes | 3.6.0 | 4.4.1 |
* | Rdio | rd.io | Yes | 3.6.0 | 4.4.1 |
* | Vine | vine.co | Yes | 4.1.0 | 4.9.0 |
* | Photobucket | photobucket.com | No | 2.9.0 | 5.1.0 |
* | Funny or Die | funnyordie.com | Yes | 3.0.0 | 5.1.0 |
*
* @see wp_oembed_add_provider()
*
* @since 2.9.0
*
* @param array $providers An array of popular oEmbed providers.
* @param array[] $providers An array of arrays containing data about popular oEmbed providers.
*/
$this->providers = apply_filters( 'oembed_providers', $providers );
// Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop().
add_filter( 'oembed_dataparse', array($this, '_strip_newlines'), 10, 3 );
add_filter( 'oembed_dataparse', array( $this, '_strip_newlines' ), 10, 3 );
}
/**
@ -229,7 +229,7 @@ class WP_oEmbed {
*
* @since 4.0.0
*
* @param callable $name Method to call.
* @param string $name Method to call.
* @param array $arguments Arguments to pass when calling.
* @return mixed|bool Return value of the callback, false otherwise.
*/
@ -256,14 +256,15 @@ class WP_oEmbed {
$provider = false;
if ( !isset($args['discover']) )
if ( ! isset( $args['discover'] ) ) {
$args['discover'] = true;
}
foreach ( $this->providers as $matchmask => $data ) {
list( $providerurl, $regex ) = $data;
// Turn the asterisk-type provider URLs into regex
if ( !$regex ) {
if ( ! $regex ) {
$matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
$matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
}
@ -274,8 +275,9 @@ class WP_oEmbed {
}
}
if ( !$provider && $args['discover'] )
if ( ! $provider && $args['discover'] ) {
$provider = $this->discover( $url );
}
return $provider;
}
@ -288,7 +290,6 @@ class WP_oEmbed {
*
* The just-in-time addition is for the benefit of the {@see 'oembed_providers'} filter.
*
* @static
* @since 4.0.0
*
* @see wp_oembed_add_provider()
@ -316,7 +317,6 @@ class WP_oEmbed {
* The just-in-time removal is for the benefit of the {@see 'oembed_providers'} filter.
*
* @since 4.0.0
* @static
*
* @see wp_oembed_remove_provider()
*
@ -422,7 +422,7 @@ class WP_oEmbed {
*/
public function discover( $url ) {
$providers = array();
$args = array(
$args = array(
'limit_response_size' => 153600, // 150 KB
);
@ -447,15 +447,18 @@ class WP_oEmbed {
*
* @since 2.9.0
*
* @param array $format Array of oEmbed link types. Accepts 'application/json+oembed',
* 'text/xml+oembed', and 'application/xml+oembed' (incorrect,
* used by at least Vimeo).
* @param string[] $format Array of oEmbed link types. Accepts 'application/json+oembed',
* 'text/xml+oembed', and 'application/xml+oembed' (incorrect,
* used by at least Vimeo).
*/
$linktypes = apply_filters( 'oembed_linktypes', array(
'application/json+oembed' => 'json',
'text/xml+oembed' => 'xml',
'application/xml+oembed' => 'xml',
) );
$linktypes = apply_filters(
'oembed_linktypes',
array(
'application/json+oembed' => 'json',
'text/xml+oembed' => 'xml',
'application/xml+oembed' => 'xml',
)
);
// Strip <body>
if ( $html_head_end = stripos( $html, '</head>' ) ) {
@ -465,7 +468,7 @@ class WP_oEmbed {
// Do a quick check
$tagfound = false;
foreach ( $linktypes as $linktype => $format ) {
if ( stripos($html, $linktype) ) {
if ( stripos( $html, $linktype ) ) {
$tagfound = true;
break;
}
@ -475,24 +478,26 @@ class WP_oEmbed {
foreach ( $links[1] as $link ) {
$atts = shortcode_parse_atts( $link );
if ( !empty($atts['type']) && !empty($linktypes[$atts['type']]) && !empty($atts['href']) ) {
$providers[$linktypes[$atts['type']]] = htmlspecialchars_decode( $atts['href'] );
if ( ! empty( $atts['type'] ) && ! empty( $linktypes[ $atts['type'] ] ) && ! empty( $atts['href'] ) ) {
$providers[ $linktypes[ $atts['type'] ] ] = htmlspecialchars_decode( $atts['href'] );
// Stop here if it's JSON (that's all we need)
if ( 'json' == $linktypes[$atts['type']] )
if ( 'json' == $linktypes[ $atts['type'] ] ) {
break;
}
}
}
}
}
// JSON is preferred to XML
if ( !empty($providers['json']) )
if ( ! empty( $providers['json'] ) ) {
return $providers['json'];
elseif ( !empty($providers['xml']) )
} elseif ( ! empty( $providers['xml'] ) ) {
return $providers['xml'];
else
} else {
return false;
}
}
/**
@ -510,7 +515,7 @@ class WP_oEmbed {
$provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider );
$provider = add_query_arg( 'maxheight', (int) $args['height'], $provider );
$provider = add_query_arg( 'url', urlencode($url), $provider );
$provider = add_query_arg( 'url', urlencode( $url ), $provider );
$provider = add_query_arg( 'dnt', 1, $provider );
/**
@ -527,8 +532,9 @@ class WP_oEmbed {
foreach ( array( 'json', 'xml' ) as $format ) {
$result = $this->_fetch_with_format( $provider, $format );
if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() )
if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() ) {
continue;
}
return ( $result && ! is_wp_error( $result ) ) ? $result : false;
}
return false;
@ -550,10 +556,12 @@ class WP_oEmbed {
$args = apply_filters( 'oembed_remote_get_args', array(), $provider_url_with_args );
$response = wp_safe_remote_get( $provider_url_with_args, $args );
if ( 501 == wp_remote_retrieve_response_code( $response ) )
if ( 501 == wp_remote_retrieve_response_code( $response ) ) {
return new WP_Error( 'not-implemented' );
if ( ! $body = wp_remote_retrieve_body( $response ) )
}
if ( ! $body = wp_remote_retrieve_body( $response ) ) {
return false;
}
$parse_method = "_parse_$format";
return $this->$parse_method( $body );
}
@ -580,8 +588,9 @@ class WP_oEmbed {
* @return object|false
*/
private function _parse_xml( $response_body ) {
if ( ! function_exists( 'libxml_disable_entity_loader' ) )
if ( ! function_exists( 'libxml_disable_entity_loader' ) ) {
return false;
}
$loader = libxml_disable_entity_loader( true );
$errors = libxml_use_internal_errors( true );
@ -603,25 +612,30 @@ class WP_oEmbed {
* @return stdClass|false
*/
private function _parse_xml_body( $response_body ) {
if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) )
if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) ) {
return false;
}
$dom = new DOMDocument;
$dom = new DOMDocument;
$success = $dom->loadXML( $response_body );
if ( ! $success )
if ( ! $success ) {
return false;
}
if ( isset( $dom->doctype ) )
if ( isset( $dom->doctype ) ) {
return false;
}
foreach ( $dom->childNodes as $child ) {
if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType )
if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) {
return false;
}
}
$xml = simplexml_import_dom( $dom );
if ( ! $xml )
if ( ! $xml ) {
return false;
}
$return = new stdClass;
foreach ( $xml as $key => $value ) {
@ -641,31 +655,36 @@ class WP_oEmbed {
* @return false|string False on error, otherwise the HTML needed to embed.
*/
public function data2html( $data, $url ) {
if ( ! is_object( $data ) || empty( $data->type ) )
if ( ! is_object( $data ) || empty( $data->type ) ) {
return false;
}
$return = false;
switch ( $data->type ) {
case 'photo':
if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) )
if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) ) {
break;
if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) )
}
if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) ) {
break;
}
$title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
$return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr($title) . '" width="' . esc_attr($data->width) . '" height="' . esc_attr($data->height) . '" /></a>';
$title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
$return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr( $title ) . '" width="' . esc_attr( $data->width ) . '" height="' . esc_attr( $data->height ) . '" /></a>';
break;
case 'video':
case 'rich':
if ( ! empty( $data->html ) && is_string( $data->html ) )
if ( ! empty( $data->html ) && is_string( $data->html ) ) {
$return = $data->html;
}
break;
case 'link':
if ( ! empty( $data->title ) && is_string( $data->title ) )
if ( ! empty( $data->title ) && is_string( $data->title ) ) {
$return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>';
}
break;
default:
@ -702,26 +721,26 @@ class WP_oEmbed {
return $html;
}
$count = 1;
$found = array();
$token = '__PRE__';
$search = array( "\t", "\n", "\r", ' ' );
$replace = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' );
$count = 1;
$found = array();
$token = '__PRE__';
$search = array( "\t", "\n", "\r", ' ' );
$replace = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' );
$tokenized = str_replace( $search, $replace, $html );
preg_match_all( '#(<pre[^>]*>.+?</pre>)#i', $tokenized, $matches, PREG_SET_ORDER );
foreach ( $matches as $i => $match ) {
$tag_html = str_replace( $replace, $search, $match[0] );
$tag_html = str_replace( $replace, $search, $match[0] );
$tag_token = $token . $i;
$found[ $tag_token ] = $tag_html;
$html = str_replace( $tag_html, $tag_token, $html, $count );
$html = str_replace( $tag_html, $tag_token, $html, $count );
}
$replaced = str_replace( $replace, $search, $html );
$stripped = str_replace( array( "\r\n", "\n" ), '', $replaced );
$pre = array_values( $found );
$tokens = array_keys( $found );
$pre = array_values( $found );
$tokens = array_keys( $found );
return str_replace( $tokens, $pre, $stripped );
}

View file

@ -35,7 +35,10 @@ class Walker_CategoryDropdown extends Walker {
*
* @see Walker::$db_fields
*/
public $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
public $db_fields = array(
'parent' => 'parent',
'id' => 'term_id',
);
/**
* Starts the element output.
@ -52,7 +55,7 @@ class Walker_CategoryDropdown extends Walker {
* @param int $id Optional. ID of the current category. Default 0 (unused).
*/
public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
$pad = str_repeat('&nbsp;', $depth * 3);
$pad = str_repeat( '&nbsp;', $depth * 3 );
/** This filter is documented in wp-includes/category-template.php */
$cat_name = apply_filters( 'list_cats', $category->name, $category );
@ -63,15 +66,17 @@ class Walker_CategoryDropdown extends Walker {
$value_field = 'term_id';
}
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $category->{$value_field} ) . "\"";
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $category->{$value_field} ) . '"';
// Type-juggling causes false matches, so we force everything to a string.
if ( (string) $category->{$value_field} === (string) $args['selected'] )
if ( (string) $category->{$value_field} === (string) $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>';
$output .= $pad.$cat_name;
if ( $args['show_count'] )
$output .= '&nbsp;&nbsp;('. number_format_i18n( $category->count ) .')';
$output .= $pad . $cat_name;
if ( $args['show_count'] ) {
$output .= '&nbsp;&nbsp;(' . number_format_i18n( $category->count ) . ')';
}
$output .= "</option>\n";
}
}

View file

@ -35,7 +35,10 @@ class Walker_Category extends Walker {
* @see Walker::$db_fields
* @todo Decouple this
*/
public $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
public $db_fields = array(
'parent' => 'parent',
'id' => 'term_id',
);
/**
* Starts the list before the elements are added.
@ -50,10 +53,11 @@ class Walker_Category extends Walker {
* value is 'list'. See wp_list_categories(). Default empty array.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
if ( 'list' != $args['style'] )
if ( 'list' != $args['style'] ) {
return;
}
$indent = str_repeat("\t", $depth);
$indent = str_repeat( "\t", $depth );
$output .= "$indent<ul class='children'>\n";
}
@ -70,10 +74,11 @@ class Walker_Category extends Walker {
* value is 'list'. See wp_list_categories(). Default empty array.
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
if ( 'list' != $args['style'] )
if ( 'list' != $args['style'] ) {
return;
}
$indent = str_repeat("\t", $depth);
$indent = str_repeat( "\t", $depth );
$output .= "$indent</ul>\n";
}
@ -129,10 +134,10 @@ class Walker_Category extends Walker {
$link .= '<a href="' . esc_url( get_term_feed_link( $category->term_id, $category->taxonomy, $args['feed_type'] ) ) . '"';
if ( empty( $args['feed'] ) ) {
$alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"';
$alt = ' alt="' . sprintf( __( 'Feed for all posts filed under %s' ), $cat_name ) . '"';
} else {
$alt = ' alt="' . $args['feed'] . '"';
$name = $args['feed'];
$alt = ' alt="' . $args['feed'] . '"';
$name = $args['feed'];
$link .= empty( $args['title'] ) ? '' : $args['title'];
}
@ -141,7 +146,7 @@ class Walker_Category extends Walker {
if ( empty( $args['feed_image'] ) ) {
$link .= $name;
} else {
$link .= "<img src='" . $args['feed_image'] . "'$alt" . ' />';
$link .= "<img src='" . esc_url( $args['feed_image'] ) . "'$alt" . ' />';
}
$link .= '</a>';
@ -154,7 +159,7 @@ class Walker_Category extends Walker {
$link .= ' (' . number_format_i18n( $category->count ) . ')';
}
if ( 'list' == $args['style'] ) {
$output .= "\t<li";
$output .= "\t<li";
$css_classes = array(
'cat-item',
'cat-item-' . $category->term_id,
@ -162,10 +167,13 @@ class Walker_Category extends Walker {
if ( ! empty( $args['current_category'] ) ) {
// 'current_category' can be an array, so we use `get_terms()`.
$_current_terms = get_terms( $category->taxonomy, array(
'include' => $args['current_category'],
'hide_empty' => false,
) );
$_current_terms = get_terms(
$category->taxonomy,
array(
'include' => $args['current_category'],
'hide_empty' => false,
)
);
foreach ( $_current_terms as $_current_term ) {
if ( $category->term_id == $_current_term->term_id ) {
@ -175,7 +183,7 @@ class Walker_Category extends Walker {
}
while ( $_current_term->parent ) {
if ( $category->term_id == $_current_term->parent ) {
$css_classes[] = 'current-cat-ancestor';
$css_classes[] = 'current-cat-ancestor';
break;
}
$_current_term = get_term( $_current_term->parent, $category->taxonomy );
@ -196,8 +204,9 @@ class Walker_Category extends Walker {
* @param array $args An array of wp_list_categories() arguments.
*/
$css_classes = implode( ' ', apply_filters( 'category_css_class', $css_classes, $category, $depth, $args ) );
$css_classes = $css_classes ? ' class="' . esc_attr( $css_classes ) . '"' : '';
$output .= ' class="' . $css_classes . '"';
$output .= $css_classes;
$output .= ">$link\n";
} elseif ( isset( $args['separator'] ) ) {
$output .= "\t$link" . $args['separator'] . "\n";
@ -220,8 +229,9 @@ class Walker_Category extends Walker {
* to output. See wp_list_categories(). Default empty array.
*/
public function end_el( &$output, $page, $depth = 0, $args = array() ) {
if ( 'list' != $args['style'] )
if ( 'list' != $args['style'] ) {
return;
}
$output .= "</li>\n";
}

View file

@ -35,7 +35,10 @@ class Walker_Comment extends Walker {
* @see Walker::$db_fields
* @todo Decouple this
*/
public $db_fields = array ('parent' => 'comment_parent', 'id' => 'comment_ID');
public $db_fields = array(
'parent' => 'comment_parent',
'id' => 'comment_ID',
);
/**
* Starts the list before the elements are added.
@ -126,11 +129,12 @@ class Walker_Comment extends Walker {
* @param string $output Used to append additional content. Passed by reference.
*/
public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( !$element )
if ( ! $element ) {
return;
}
$id_field = $this->db_fields['id'];
$id = $element->$id_field;
$id = $element->$id_field;
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
@ -139,9 +143,10 @@ class Walker_Comment extends Walker {
* and display them at this level. This is to prevent them being orphaned to the end
* of the list.
*/
if ( $max_depth <= $depth + 1 && isset( $children_elements[$id]) ) {
foreach ( $children_elements[ $id ] as $child )
if ( $max_depth <= $depth + 1 && isset( $children_elements[ $id ] ) ) {
foreach ( $children_elements[ $id ] as $child ) {
$this->display_element( $child, $children_elements, $max_depth, $depth, $args, $output );
}
unset( $children_elements[ $id ] );
}
@ -167,9 +172,9 @@ class Walker_Comment extends Walker {
public function start_el( &$output, $comment, $depth = 0, $args = array(), $id = 0 ) {
$depth++;
$GLOBALS['comment_depth'] = $depth;
$GLOBALS['comment'] = $comment;
$GLOBALS['comment'] = $comment;
if ( !empty( $args['callback'] ) ) {
if ( ! empty( $args['callback'] ) ) {
ob_start();
call_user_func( $args['callback'], $comment, $args, $depth );
$output .= ob_get_clean();
@ -205,16 +210,17 @@ class Walker_Comment extends Walker {
* @param array $args Optional. An array of arguments. Default empty array.
*/
public function end_el( &$output, $comment, $depth = 0, $args = array() ) {
if ( !empty( $args['end-callback'] ) ) {
if ( ! empty( $args['end-callback'] ) ) {
ob_start();
call_user_func( $args['end-callback'], $comment, $args, $depth );
$output .= ob_get_clean();
return;
}
if ( 'div' == $args['style'] )
if ( 'div' == $args['style'] ) {
$output .= "</div><!-- #comment-## -->\n";
else
} else {
$output .= "</li><!-- #comment-## -->\n";
}
}
/**
@ -230,12 +236,12 @@ class Walker_Comment extends Walker {
*/
protected function ping( $comment, $depth, $args ) {
$tag = ( 'div' == $args['style'] ) ? 'div' : 'li';
?>
?>
<<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( '', $comment ); ?>>
<div class="comment-body">
<?php _e( 'Pingback:' ); ?> <?php comment_author_link( $comment ); ?> <?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?>
</div>
<?php
<?php
}
/**
@ -251,54 +257,87 @@ class Walker_Comment extends Walker {
*/
protected function comment( $comment, $depth, $args ) {
if ( 'div' == $args['style'] ) {
$tag = 'div';
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$tag = 'li';
$add_below = 'div-comment';
}
?>
$commenter = wp_get_current_commenter();
if ( $commenter['comment_author_email'] ) {
$moderation_note = __( 'Your comment is awaiting moderation.' );
} else {
$moderation_note = __( 'Your comment is awaiting moderation. This is a preview, your comment will be visible after it has been approved.' );
}
?>
<<?php echo $tag; ?> <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?> id="comment-<?php comment_ID(); ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID(); ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
<?php
if ( 0 != $args['avatar_size'] ) {
echo get_avatar( $comment, $args['avatar_size'] );}
?>
<?php
/* translators: %s: comment author link */
printf( __( '%s <span class="says">says:</span>' ),
printf(
__( '%s <span class="says">says:</span>' ),
sprintf( '<cite class="fn">%s</cite>', get_comment_author_link( $comment ) )
);
?>
</div>
<?php if ( '0' == $comment->comment_approved ) : ?>
<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ) ?></em>
<em class="comment-awaiting-moderation"><?php echo $moderation_note; ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
<?php
/* translators: 1: comment date, 2: comment time */
printf( __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)' ), '&nbsp;&nbsp;', '' );
printf( __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() );
?>
</a>
<?php
edit_comment_link( __( '(Edit)' ), '&nbsp;&nbsp;', '' );
?>
</div>
<?php comment_text( $comment, array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
<?php
comment_text(
$comment,
array_merge(
$args,
array(
'add_below' => $add_below,
'depth' => $depth,
'max_depth' => $args['max_depth'],
)
)
);
?>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => $add_below,
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="reply">',
'after' => '</div>'
) ) );
comment_reply_link(
array_merge(
$args,
array(
'add_below' => $add_below,
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="reply">',
'after' => '</div>',
)
)
);
?>
<?php if ( 'div' != $args['style'] ) : ?>
</div>
<?php endif; ?>
<?php
<?php
}
/**
@ -314,15 +353,27 @@ class Walker_Comment extends Walker {
*/
protected function html5_comment( $comment, $depth, $args ) {
$tag = ( 'div' === $args['style'] ) ? 'div' : 'li';
?>
$commenter = wp_get_current_commenter();
if ( $commenter['comment_author_email'] ) {
$moderation_note = __( 'Your comment is awaiting moderation.' );
} else {
$moderation_note = __( 'Your comment is awaiting moderation. This is a preview, your comment will be visible after it has been approved.' );
}
?>
<<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?>>
<article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
<?php
if ( 0 != $args['avatar_size'] ) {
echo get_avatar( $comment, $args['avatar_size'] );}
?>
<?php
/* translators: %s: comment author link */
printf( __( '%s <span class="says">says:</span>' ),
printf(
__( '%s <span class="says">says:</span>' ),
sprintf( '<b class="fn">%s</b>', get_comment_author_link( $comment ) )
);
?>
@ -341,7 +392,7 @@ class Walker_Comment extends Walker {
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<em class="comment-awaiting-moderation"><?php echo $moderation_note; ?></em>
<?php endif; ?>
</footer><!-- .comment-meta -->
@ -350,15 +401,20 @@ class Walker_Comment extends Walker {
</div><!-- .comment-content -->
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="reply">',
'after' => '</div>'
) ) );
comment_reply_link(
array_merge(
$args,
array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="reply">',
'after' => '</div>',
)
)
);
?>
</article><!-- .comment-body -->
<?php
<?php
}
}

View file

@ -34,7 +34,10 @@ class Walker_Nav_Menu extends Walker {
*
* @see Walker::$db_fields
*/
public $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );
public $db_fields = array(
'parent' => 'menu_item_parent',
'id' => 'db_id',
);
/**
* Starts the list before the elements are added.
@ -65,7 +68,7 @@ class Walker_Nav_Menu extends Walker {
*
* @since 4.8.0
*
* @param array $classes The CSS classes that are applied to the menu `<ul>` element.
* @param string[] $classes Array of the CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
@ -94,7 +97,7 @@ class Walker_Nav_Menu extends Walker {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
$indent = str_repeat( $t, $depth );
$output .= "$indent</ul>{$n}";
}
@ -122,7 +125,7 @@ class Walker_Nav_Menu extends Walker {
}
$indent = ( $depth ) ? str_repeat( $t, $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
/**
@ -137,12 +140,12 @@ class Walker_Nav_Menu extends Walker {
$args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );
/**
* Filters the CSS class(es) applied to a menu item's list item element.
* Filters the CSS classes applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param string[] $classes Array of the CSS classes that are applied to the menu item's `<li>` element.
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
@ -161,16 +164,17 @@ class Walker_Nav_Menu extends Walker {
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $class_names .'>';
$output .= $indent . '<li' . $id . $class_names . '>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['aria-current'] = $item->current ? 'page' : '';
/**
* Filters the HTML attributes applied to a menu item's anchor element.
@ -181,10 +185,11 @@ class Walker_Nav_Menu extends Walker {
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* @type string $aria_current The aria-current attribute.
* }
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
@ -195,7 +200,7 @@ class Walker_Nav_Menu extends Walker {
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
@ -215,8 +220,8 @@ class Walker_Nav_Menu extends Walker {
*/
$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;

View file

@ -35,7 +35,10 @@ class Walker_PageDropdown extends Walker {
* @see Walker::$db_fields
* @todo Decouple this
*/
public $db_fields = array( 'parent' => 'post_parent', 'id' => 'ID' );
public $db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
/**
* Starts the element output.
@ -54,15 +57,16 @@ class Walker_PageDropdown extends Walker {
* @param int $id Optional. ID of the current page. Default 0 (unused).
*/
public function start_el( &$output, $page, $depth = 0, $args = array(), $id = 0 ) {
$pad = str_repeat('&nbsp;', $depth * 3);
$pad = str_repeat( '&nbsp;', $depth * 3 );
if ( ! isset( $args['value_field'] ) || ! isset( $page->{$args['value_field']} ) ) {
$args['value_field'] = 'ID';
}
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $page->{$args['value_field']} ) . "\"";
if ( $page->ID == $args['selected'] )
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $page->{$args['value_field']} ) . '"';
if ( $page->ID == $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>';
$title = $page->post_title;
@ -76,8 +80,8 @@ class Walker_PageDropdown extends Walker {
*
* @since 3.1.0
*
* @param string $title Page title.
* @param object $page Page data object.
* @param string $title Page title.
* @param WP_Post $page Page data object.
*/
$title = apply_filters( 'list_pages', $title, $page );

View file

@ -35,7 +35,10 @@ class Walker_Page extends Walker {
* @see Walker::$db_fields
* @todo Decouple this.
*/
public $db_fields = array( 'parent' => 'post_parent', 'id' => 'ID' );
public $db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
/**
* Outputs the beginning of the current level in the tree before elements are output.
@ -57,7 +60,7 @@ class Walker_Page extends Walker {
$t = '';
$n = '';
}
$indent = str_repeat( $t, $depth );
$indent = str_repeat( $t, $depth );
$output .= "{$n}{$indent}<ul class='children'>{$n}";
}
@ -81,7 +84,7 @@ class Walker_Page extends Walker {
$t = '';
$n = '';
}
$indent = str_repeat( $t, $depth );
$indent = str_repeat( $t, $depth );
$output .= "{$indent}</ul>{$n}";
}
@ -127,7 +130,7 @@ class Walker_Page extends Walker {
} elseif ( $_current_page && $page->ID == $_current_page->post_parent ) {
$css_class[] = 'current_page_parent';
}
} elseif ( $page->ID == get_option('page_for_posts') ) {
} elseif ( $page->ID == get_option( 'page_for_posts' ) ) {
$css_class[] = 'current_page_parent';
}
@ -138,14 +141,14 @@ class Walker_Page extends Walker {
*
* @see wp_list_pages()
*
* @param array $css_class An array of CSS classes to be applied
* to each list item.
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of arguments.
* @param int $current_page ID of the current page.
* @param string[] $css_class An array of CSS classes to be applied to each list item.
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of arguments.
* @param int $current_page ID of the current page.
*/
$css_classes = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );
$css_classes = $css_classes ? ' class="' . esc_attr( $css_classes ) . '"' : '';
if ( '' === $page->post_title ) {
/* translators: %d: ID of a post */
@ -153,10 +156,11 @@ class Walker_Page extends Walker {
}
$args['link_before'] = empty( $args['link_before'] ) ? '' : $args['link_before'];
$args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after'];
$args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after'];
$atts = array();
$atts['href'] = get_permalink( $page->ID );
$atts = array();
$atts['href'] = get_permalink( $page->ID );
$atts['aria-current'] = ( $page->ID == $current_page ) ? 'page' : '';
/**
* Filters the HTML attributes applied to a page menu item's anchor element.
@ -166,7 +170,8 @@ class Walker_Page extends Walker {
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $href The href attribute.
* @type string $href The href attribute.
* @type string $aria_current The aria-current attribute.
* }
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
@ -178,13 +183,13 @@ class Walker_Page extends Walker {
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = esc_attr( $value );
$value = esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$output .= $indent . sprintf(
'<li class="%s"><a%s>%s%s%s</a>',
'<li%s><a%s>%s%s%s</a>',
$css_classes,
$attributes,
$args['link_before'],
@ -201,7 +206,7 @@ class Walker_Page extends Walker {
}
$date_format = empty( $args['date_format'] ) ? '' : $args['date_format'];
$output .= " " . mysql2date( $date_format, $time );
$output .= ' ' . mysql2date( $date_format, $time );
}
}

View file

@ -23,10 +23,10 @@ class WP_Admin_Bar {
*/
public function __get( $name ) {
switch ( $name ) {
case 'proto' :
case 'proto':
return is_ssl() ? 'https://' : 'http://';
case 'menu' :
case 'menu':
_deprecated_argument( 'WP_Admin_Bar', '3.3.0', 'Modify admin bar nodes with WP_Admin_Bar::get_node(), WP_Admin_Bar::add_node(), and WP_Admin_Bar::remove_node(), not the <code>menu</code> property.' );
return array(); // Sorry, folks.
}
@ -41,12 +41,12 @@ class WP_Admin_Bar {
/* Populate settings we need for the menu based on the current user. */
$this->user->blogs = get_blogs_of_user( get_current_user_id() );
if ( is_multisite() ) {
$this->user->active_blog = get_active_blog_for_user( get_current_user_id() );
$this->user->domain = empty( $this->user->active_blog ) ? user_admin_url() : trailingslashit( get_home_url( $this->user->active_blog->blog_id ) );
$this->user->active_blog = get_active_blog_for_user( get_current_user_id() );
$this->user->domain = empty( $this->user->active_blog ) ? user_admin_url() : trailingslashit( get_home_url( $this->user->active_blog->blog_id ) );
$this->user->account_domain = $this->user->domain;
} else {
$this->user->active_blog = $this->user->blogs[get_current_blog_id()];
$this->user->domain = trailingslashit( home_url() );
$this->user->active_blog = $this->user->blogs[ get_current_blog_id() ];
$this->user->domain = trailingslashit( home_url() );
$this->user->account_domain = $this->user->domain;
}
}
@ -60,14 +60,15 @@ class WP_Admin_Bar {
* To remove the default padding styles from WordPress for the Toolbar, use the following code:
* add_theme_support( 'admin-bar', array( 'callback' => '__return_false' ) );
*/
$admin_bar_args = get_theme_support( 'admin-bar' );
$admin_bar_args = get_theme_support( 'admin-bar' );
$header_callback = $admin_bar_args[0]['callback'];
}
if ( empty($header_callback) )
if ( empty( $header_callback ) ) {
$header_callback = '_admin_bar_bump_cb';
}
add_action('wp_head', $header_callback);
add_action( 'wp_head', $header_callback );
wp_enqueue_script( 'admin-bar' );
wp_enqueue_style( 'admin-bar' );
@ -114,16 +115,19 @@ class WP_Admin_Bar {
*/
public function add_node( $args ) {
// Shim for old method signature: add_node( $parent_id, $menu_obj, $args )
if ( func_num_args() >= 3 && is_string( func_get_arg(0) ) )
$args = array_merge( array( 'parent' => func_get_arg(0) ), func_get_arg(2) );
if ( func_num_args() >= 3 && is_string( func_get_arg( 0 ) ) ) {
$args = array_merge( array( 'parent' => func_get_arg( 0 ) ), func_get_arg( 2 ) );
}
if ( is_object( $args ) )
if ( is_object( $args ) ) {
$args = get_object_vars( $args );
}
// Ensure we have a valid title.
if ( empty( $args['id'] ) ) {
if ( empty( $args['title'] ) )
if ( empty( $args['title'] ) ) {
return;
}
_doing_it_wrong( __METHOD__, __( 'The menu ID should not be empty.' ), '3.3.0' );
// Deprecated: Generate an ID from the title.
@ -140,18 +144,20 @@ class WP_Admin_Bar {
);
// If the node already exists, keep any data that isn't provided.
if ( $maybe_defaults = $this->get_node( $args['id'] ) )
if ( $maybe_defaults = $this->get_node( $args['id'] ) ) {
$defaults = get_object_vars( $maybe_defaults );
}
// Do the same for 'meta' items.
if ( ! empty( $defaults['meta'] ) && ! empty( $args['meta'] ) )
if ( ! empty( $defaults['meta'] ) && ! empty( $args['meta'] ) ) {
$args['meta'] = wp_parse_args( $args['meta'], $defaults['meta'] );
}
$args = wp_parse_args( $args, $defaults );
$back_compat_parents = array(
'my-account-with-avatar' => array( 'my-account', '3.3' ),
'my-blogs' => array( 'my-sites', '3.3' ),
'my-blogs' => array( 'my-sites', '3.3' ),
);
if ( isset( $back_compat_parents[ $args['parent'] ] ) ) {
@ -177,8 +183,9 @@ class WP_Admin_Bar {
* @return object Node.
*/
final public function get_node( $id ) {
if ( $node = $this->_get_node( $id ) )
if ( $node = $this->_get_node( $id ) ) {
return clone $node;
}
}
/**
@ -186,22 +193,26 @@ class WP_Admin_Bar {
* @return object|void
*/
final protected function _get_node( $id ) {
if ( $this->bound )
if ( $this->bound ) {
return;
}
if ( empty( $id ) )
if ( empty( $id ) ) {
$id = 'root';
}
if ( isset( $this->nodes[ $id ] ) )
if ( isset( $this->nodes[ $id ] ) ) {
return $this->nodes[ $id ];
}
}
/**
* @return array|void
*/
final public function get_nodes() {
if ( ! $nodes = $this->_get_nodes() )
if ( ! $nodes = $this->_get_nodes() ) {
return;
}
foreach ( $nodes as &$node ) {
$node = clone $node;
@ -213,8 +224,9 @@ class WP_Admin_Bar {
* @return array|void
*/
final protected function _get_nodes() {
if ( $this->bound )
if ( $this->bound ) {
return;
}
return $this->nodes;
}
@ -259,39 +271,45 @@ class WP_Admin_Bar {
*/
public function render() {
$root = $this->_bind();
if ( $root )
if ( $root ) {
$this->_render( $root );
}
}
/**
* @return object|void
*/
final protected function _bind() {
if ( $this->bound )
if ( $this->bound ) {
return;
}
// Add the root node.
// Clear it first, just in case. Don't mess with The Root.
$this->remove_node( 'root' );
$this->add_node( array(
'id' => 'root',
'group' => false,
) );
$this->add_node(
array(
'id' => 'root',
'group' => false,
)
);
// Normalize nodes: define internal 'children' and 'type' properties.
foreach ( $this->_get_nodes() as $node ) {
$node->children = array();
$node->type = ( $node->group ) ? 'group' : 'item';
$node->type = ( $node->group ) ? 'group' : 'item';
unset( $node->group );
// The Root wants your orphans. No lonely items allowed.
if ( ! $node->parent )
if ( ! $node->parent ) {
$node->parent = 'root';
}
}
foreach ( $this->_get_nodes() as $node ) {
if ( 'root' == $node->id )
if ( 'root' == $node->id ) {
continue;
}
// Fetch the parent node. If it isn't registered, ignore the node.
if ( ! $parent = $this->_get_node( $node->parent ) ) {
@ -302,10 +320,11 @@ class WP_Admin_Bar {
$group_class = ( $node->parent == 'root' ) ? 'ab-top-menu' : 'ab-submenu';
if ( $node->type == 'group' ) {
if ( empty( $node->meta['class'] ) )
if ( empty( $node->meta['class'] ) ) {
$node->meta['class'] = $group_class;
else
} else {
$node->meta['class'] .= ' ' . $group_class;
}
}
// Items in items aren't allowed. Wrap nested items in 'default' groups.
@ -318,24 +337,26 @@ class WP_Admin_Bar {
if ( ! $default ) {
// Use _set_node because add_node can be overloaded.
// Make sure to specify default settings for all properties.
$this->_set_node( array(
'id' => $default_id,
'parent' => $parent->id,
'type' => 'group',
'children' => array(),
'meta' => array(
'class' => $group_class,
),
'title' => false,
'href' => false,
) );
$default = $this->_get_node( $default_id );
$this->_set_node(
array(
'id' => $default_id,
'parent' => $parent->id,
'type' => 'group',
'children' => array(),
'meta' => array(
'class' => $group_class,
),
'title' => false,
'href' => false,
)
);
$default = $this->_get_node( $default_id );
$parent->children[] = $default;
}
$parent = $default;
// Groups in groups aren't allowed. Add a special 'container' node.
// The container will invisibly wrap both groups.
// Groups in groups aren't allowed. Add a special 'container' node.
// The container will invisibly wrap both groups.
} elseif ( $parent->type == 'group' && $node->type == 'group' ) {
$container_id = $parent->id . '-container';
$container = $this->_get_node( $container_id );
@ -344,15 +365,17 @@ class WP_Admin_Bar {
if ( ! $container ) {
// Use _set_node because add_node can be overloaded.
// Make sure to specify default settings for all properties.
$this->_set_node( array(
'id' => $container_id,
'type' => 'container',
'children' => array( $parent ),
'parent' => false,
'title' => false,
'href' => false,
'meta' => array(),
) );
$this->_set_node(
array(
'id' => $container_id,
'type' => 'container',
'children' => array( $parent ),
'parent' => false,
'title' => false,
'href' => false,
'meta' => array(),
)
);
$container = $this->_get_node( $container_id );
@ -363,10 +386,11 @@ class WP_Admin_Bar {
$container->parent = $grandparent->id;
$index = array_search( $parent, $grandparent->children, true );
if ( $index === false )
if ( $index === false ) {
$grandparent->children[] = $container;
else
} else {
array_splice( $grandparent->children, $index, 1, array( $container ) );
}
}
$parent->parent = $container->id;
@ -382,13 +406,12 @@ class WP_Admin_Bar {
$parent->children[] = $node;
}
$root = $this->_get_node( 'root' );
$root = $this->_get_node( 'root' );
$this->bound = true;
return $root;
}
/**
*
* @global bool $is_IE
* @param object $root
*/
@ -399,12 +422,13 @@ class WP_Admin_Bar {
// We have to do this here since admin bar shows on the front end.
$class = 'nojq nojs';
if ( $is_IE ) {
if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 7' ) )
if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 7' ) ) {
$class .= ' ie7';
elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 8' ) )
} elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 8' ) ) {
$class .= ' ie8';
elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 9' ) )
} elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 9' ) ) {
$class .= ' ie9';
}
} elseif ( wp_is_mobile() ) {
$class .= ' mobile';
}
@ -414,13 +438,15 @@ class WP_Admin_Bar {
<?php if ( ! is_admin() ) { ?>
<a class="screen-reader-shortcut" href="#wp-toolbar" tabindex="1"><?php _e( 'Skip to toolbar' ); ?></a>
<?php } ?>
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="<?php esc_attr_e( 'Toolbar' ); ?>" tabindex="0">
<?php foreach ( $root->children as $group ) {
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="<?php esc_attr_e( 'Toolbar' ); ?>">
<?php
foreach ( $root->children as $group ) {
$this->_render_group( $group );
} ?>
}
?>
</div>
<?php if ( is_user_logged_in() ) : ?>
<a class="screen-reader-shortcut" href="<?php echo esc_url( wp_logout_url() ); ?>"><?php _e('Log Out'); ?></a>
<a class="screen-reader-shortcut" href="<?php echo esc_url( wp_logout_url() ); ?>"><?php _e( 'Log Out' ); ?></a>
<?php endif; ?>
</div>
@ -431,14 +457,15 @@ class WP_Admin_Bar {
* @param object $node
*/
final protected function _render_container( $node ) {
if ( $node->type != 'container' || empty( $node->children ) )
if ( $node->type != 'container' || empty( $node->children ) ) {
return;
}
?><div id="<?php echo esc_attr( 'wp-admin-bar-' . $node->id ); ?>" class="ab-group-container"><?php
foreach ( $node->children as $group ) {
$this->_render_group( $group );
}
?></div><?php
echo '<div id="' . esc_attr( 'wp-admin-bar-' . $node->id ) . '" class="ab-group-container">';
foreach ( $node->children as $group ) {
$this->_render_group( $group );
}
echo '</div>';
}
/**
@ -449,107 +476,93 @@ class WP_Admin_Bar {
$this->_render_container( $node );
return;
}
if ( $node->type != 'group' || empty( $node->children ) )
if ( $node->type != 'group' || empty( $node->children ) ) {
return;
}
if ( ! empty( $node->meta['class'] ) )
if ( ! empty( $node->meta['class'] ) ) {
$class = ' class="' . esc_attr( trim( $node->meta['class'] ) ) . '"';
else
} else {
$class = '';
}
?><ul id="<?php echo esc_attr( 'wp-admin-bar-' . $node->id ); ?>"<?php echo $class; ?>><?php
foreach ( $node->children as $item ) {
$this->_render_item( $item );
}
?></ul><?php
echo "<ul id='" . esc_attr( 'wp-admin-bar-' . $node->id ) . "'$class>";
foreach ( $node->children as $item ) {
$this->_render_item( $item );
}
echo '</ul>';
}
/**
* @param object $node
*/
final protected function _render_item( $node ) {
if ( $node->type != 'item' )
if ( $node->type != 'item' ) {
return;
}
$is_parent = ! empty( $node->children );
$has_link = ! empty( $node->href );
// Allow only numeric values, then casted to integers, and allow a tabindex value of `0` for a11y.
$tabindex = ( isset( $node->meta['tabindex'] ) && is_numeric( $node->meta['tabindex'] ) ) ? (int) $node->meta['tabindex'] : '';
$tabindex = ( isset( $node->meta['tabindex'] ) && is_numeric( $node->meta['tabindex'] ) ) ? (int) $node->meta['tabindex'] : '';
$aria_attributes = ( '' !== $tabindex ) ? ' tabindex="' . $tabindex . '"' : '';
$menuclass = '';
if ( $is_parent ) {
$menuclass = 'menupop ';
$menuclass = 'menupop ';
$aria_attributes .= ' aria-haspopup="true"';
}
if ( ! empty( $node->meta['class'] ) )
if ( ! empty( $node->meta['class'] ) ) {
$menuclass .= $node->meta['class'];
}
if ( $menuclass )
if ( $menuclass ) {
$menuclass = ' class="' . esc_attr( trim( $menuclass ) ) . '"';
}
?>
echo "<li id='" . esc_attr( 'wp-admin-bar-' . $node->id ) . "'$menuclass>";
<li id="<?php echo esc_attr( 'wp-admin-bar-' . $node->id ); ?>"<?php echo $menuclass; ?>><?php
if ( $has_link ):
?><a class="ab-item"<?php echo $aria_attributes; ?> href="<?php echo esc_url( $node->href ) ?>"<?php
if ( ! empty( $node->meta['onclick'] ) ) :
?> onclick="<?php echo esc_js( $node->meta['onclick'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['target'] ) ) :
?> target="<?php echo esc_attr( $node->meta['target'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['title'] ) ) :
?> title="<?php echo esc_attr( $node->meta['title'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['rel'] ) ) :
?> rel="<?php echo esc_attr( $node->meta['rel'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['lang'] ) ) :
?> lang="<?php echo esc_attr( $node->meta['lang'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['dir'] ) ) :
?> dir="<?php echo esc_attr( $node->meta['dir'] ); ?>"<?php
endif;
?>><?php
else:
?><div class="ab-item ab-empty-item"<?php echo $aria_attributes;
if ( ! empty( $node->meta['title'] ) ) :
?> title="<?php echo esc_attr( $node->meta['title'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['lang'] ) ) :
?> lang="<?php echo esc_attr( $node->meta['lang'] ); ?>"<?php
endif;
if ( ! empty( $node->meta['dir'] ) ) :
?> dir="<?php echo esc_attr( $node->meta['dir'] ); ?>"<?php
endif;
?>><?php
endif;
if ( $has_link ) {
$attributes = array( 'onclick', 'target', 'title', 'rel', 'lang', 'dir' );
echo "<a class='ab-item'$aria_attributes href='" . esc_url( $node->href ) . "'";
if ( ! empty( $node->meta['onclick'] ) ) {
echo ' onclick="' . esc_js( $node->meta['onclick'] ) . '"';
}
} else {
$attributes = array( 'onclick', 'target', 'title', 'rel', 'lang', 'dir' );
echo '<div class="ab-item ab-empty-item"' . $aria_attributes;
}
echo $node->title;
foreach ( $attributes as $attribute ) {
if ( ! empty( $node->meta[ $attribute ] ) ) {
echo " $attribute='" . esc_attr( $node->meta[ $attribute ] ) . "'";
}
}
if ( $has_link ) :
?></a><?php
else:
?></div><?php
endif;
echo ">{$node->title}";
if ( $is_parent ) :
?><div class="ab-sub-wrapper"><?php
foreach ( $node->children as $group ) {
$this->_render_group( $group );
}
?></div><?php
endif;
if ( $has_link ) {
echo '</a>';
} else {
echo '</div>';
}
if ( ! empty( $node->meta['html'] ) )
echo $node->meta['html'];
if ( $is_parent ) {
echo '<div class="ab-sub-wrapper">';
foreach ( $node->children as $group ) {
$this->_render_group( $group );
}
echo '</div>';
}
?>
</li><?php
if ( ! empty( $node->meta['html'] ) ) {
echo $node->meta['html'];
}
echo '</li>';
}
/**

View file

@ -23,8 +23,9 @@ class WP_Ajax_Response {
* @param string|array $args Optional. Will be passed to add() method.
*/
public function __construct( $args = '' ) {
if ( !empty($args) )
$this->add($args);
if ( ! empty( $args ) ) {
$this->add( $args );
}
}
/**
@ -63,36 +64,39 @@ class WP_Ajax_Response {
*/
public function add( $args = '' ) {
$defaults = array(
'what' => 'object', 'action' => false,
'id' => '0', 'old_id' => false,
'position' => 1,
'data' => '', 'supplemental' => array()
'what' => 'object',
'action' => false,
'id' => '0',
'old_id' => false,
'position' => 1,
'data' => '',
'supplemental' => array(),
);
$r = wp_parse_args( $args, $defaults );
$position = preg_replace( '/[^a-z0-9:_-]/i', '', $r['position'] );
$id = $r['id'];
$what = $r['what'];
$action = $r['action'];
$old_id = $r['old_id'];
$data = $r['data'];
$id = $r['id'];
$what = $r['what'];
$action = $r['action'];
$old_id = $r['old_id'];
$data = $r['data'];
if ( is_wp_error( $id ) ) {
$data = $id;
$id = 0;
$id = 0;
}
$response = '';
if ( is_wp_error( $data ) ) {
foreach ( (array) $data->get_error_codes() as $code ) {
$response .= "<wp_error code='$code'><![CDATA[" . $data->get_error_message( $code ) . "]]></wp_error>";
$response .= "<wp_error code='$code'><![CDATA[" . $data->get_error_message( $code ) . ']]></wp_error>';
if ( ! $error_data = $data->get_error_data( $code ) ) {
continue;
}
$class = '';
if ( is_object( $error_data ) ) {
$class = ' class="' . get_class( $error_data ) . '"';
$class = ' class="' . get_class( $error_data ) . '"';
$error_data = get_object_vars( $error_data );
}
@ -106,7 +110,7 @@ class WP_Ajax_Response {
}
}
$response .= "</wp_error_data>";
$response .= '</wp_error_data>';
}
} else {
$response = "<response_data><![CDATA[$data]]></response_data>";
@ -123,13 +127,13 @@ class WP_Ajax_Response {
if ( false === $action ) {
$action = $_POST['action'];
}
$x = '';
$x = '';
$x .= "<response action='{$action}_$id'>"; // The action attribute in the xml output is formatted like a nonce action
$x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>";
$x .= $response;
$x .= $s;
$x .= "</$what>";
$x .= "</response>";
$x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>";
$x .= $response;
$x .= $s;
$x .= "</$what>";
$x .= '</response>';
$this->responses[] = $x;
return $x;
@ -145,12 +149,14 @@ class WP_Ajax_Response {
public function send() {
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ) );
echo "<?xml version='1.0' encoding='" . get_option( 'blog_charset' ) . "' standalone='yes'?><wp_ajax>";
foreach ( (array) $this->responses as $response )
foreach ( (array) $this->responses as $response ) {
echo $response;
}
echo '</wp_ajax>';
if ( wp_doing_ajax() )
if ( wp_doing_ajax() ) {
wp_die();
else
} else {
die();
}
}
}

View file

@ -410,7 +410,7 @@ class WP_Block_Parser {
* match back in PHP to see which one it was.
*/
$has_match = preg_match(
'/<!--\s+(?<closer>\/)?wp:(?<namespace>[a-z][a-z0-9_-]*\/)?(?<name>[a-z][a-z0-9_-]*)\s+(?<attrs>{(?:(?:[^}]+|}+(?=})|(?!}\s+\/?-->).)*+)?}\s+)?(?<void>\/)?-->/s',
'/<!--\s+(?P<closer>\/)?wp:(?P<namespace>[a-z][a-z0-9_-]*\/)?(?P<name>[a-z][a-z0-9_-]*)\s+(?P<attrs>{(?:(?:[^}]+|}+(?=})|(?!}\s+\/?-->).)*+)?}\s+)?(?P<void>\/)?-->/s',
$this->document,
$matches,
PREG_OFFSET_CAPTURE,

View file

@ -118,7 +118,7 @@ class WP_Comment_Query {
*
* @since 4.0.0
*
* @param callable $name Method to call.
* @param string $name Method to call.
* @param array $arguments Arguments to pass when calling.
* @return mixed|false Return value of the callback, false otherwise.
*/
@ -222,9 +222,10 @@ class WP_Comment_Query {
* Default empty.
* @type string $search Search term(s) to retrieve matching comments for.
* Default empty.
* @type string $status Comment status to limit results by. Accepts 'hold'
* (`comment_status=0`), 'approve' (`comment_status=1`),
* 'all', or a custom comment status. Default 'all'.
* @type string|array $status Comment stati to limit results by. Accepts an array
* or space/comma-separated list of 'hold' (`comment_status=0`),
* 'approve' (`comment_status=1`), 'all', or a custom
* comment status. Default 'all'.
* @type string|array $type Include comments of a given type, or array of types.
* Accepts 'comment', 'pings' (includes 'pingback' and
* 'trackback'), or anycustom type string. Default empty.
@ -241,7 +242,7 @@ class WP_Comment_Query {
* The parameter is ignored (forced to `false`) when
* `$fields` is 'ids' or 'counts'. Accepts 'threaded',
* 'flat', or false. Default: false.
* @type string $cache_domain Unique cache key to be produced when this query is stored in
* @type string $cache_domain Unique cache key to be produced when this query is stored in
* an object cache. Default is 'core'.
* @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
* Default true.
@ -251,49 +252,49 @@ class WP_Comment_Query {
*/
public function __construct( $query = '' ) {
$this->query_var_defaults = array(
'author_email' => '',
'author_url' => '',
'author__in' => '',
'author__not_in' => '',
'include_unapproved' => '',
'fields' => '',
'ID' => '',
'comment__in' => '',
'comment__not_in' => '',
'karma' => '',
'number' => '',
'offset' => '',
'no_found_rows' => true,
'orderby' => '',
'order' => 'DESC',
'paged' => 1,
'parent' => '',
'parent__in' => '',
'parent__not_in' => '',
'post_author__in' => '',
'post_author__not_in' => '',
'post_ID' => '',
'post_id' => 0,
'post__in' => '',
'post__not_in' => '',
'post_author' => '',
'post_name' => '',
'post_parent' => '',
'post_status' => '',
'post_type' => '',
'status' => 'all',
'type' => '',
'type__in' => '',
'type__not_in' => '',
'user_id' => '',
'search' => '',
'count' => false,
'meta_key' => '',
'meta_value' => '',
'meta_query' => '',
'date_query' => null, // See WP_Date_Query
'hierarchical' => false,
'cache_domain' => 'core',
'author_email' => '',
'author_url' => '',
'author__in' => '',
'author__not_in' => '',
'include_unapproved' => '',
'fields' => '',
'ID' => '',
'comment__in' => '',
'comment__not_in' => '',
'karma' => '',
'number' => '',
'offset' => '',
'no_found_rows' => true,
'orderby' => '',
'order' => 'DESC',
'paged' => 1,
'parent' => '',
'parent__in' => '',
'parent__not_in' => '',
'post_author__in' => '',
'post_author__not_in' => '',
'post_ID' => '',
'post_id' => 0,
'post__in' => '',
'post__not_in' => '',
'post_author' => '',
'post_name' => '',
'post_parent' => '',
'post_status' => '',
'post_type' => '',
'status' => 'all',
'type' => '',
'type__in' => '',
'type__not_in' => '',
'user_id' => '',
'search' => '',
'count' => false,
'meta_key' => '',
'meta_value' => '',
'meta_query' => '',
'date_query' => null, // See WP_Date_Query
'hierarchical' => false,
'cache_domain' => 'core',
'update_comment_meta_cache' => true,
'update_comment_post_cache' => false,
);
@ -308,7 +309,6 @@ class WP_Comment_Query {
*
* @since 4.2.0 Extracted from WP_Comment_Query::query().
*
*
* @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
*/
public function parse_query( $query = '' ) {
@ -386,7 +386,7 @@ class WP_Comment_Query {
$_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
unset( $_args['fields'] );
$key = md5( serialize( $_args ) );
$key = md5( serialize( $_args ) );
$last_changed = wp_cache_get_last_changed( 'comment' );
$cache_key = "get_comments:$key:$last_changed";
@ -449,8 +449,8 @@ class WP_Comment_Query {
*
* @since 3.1.0
*
* @param array $_comments An array of comments.
* @param WP_Comment_Query $this Current instance of WP_Comment_Query (passed by reference).
* @param WP_Comment[] $_comments An array of comments.
* @param WP_Comment_Query $this Current instance of WP_Comment_Query (passed by reference).
*/
$_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
@ -471,6 +471,8 @@ class WP_Comment_Query {
* @since 4.4.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
*/
protected function get_comment_ids() {
global $wpdb;
@ -480,30 +482,32 @@ class WP_Comment_Query {
// 'status' accepts an array or a comma-separated string.
$status_clauses = array();
$statuses = $this->query_vars['status'];
if ( ! is_array( $statuses ) ) {
$statuses = preg_split( '/[\s,]+/', $statuses );
$statuses = wp_parse_list( $this->query_vars['status'] );
// Empty 'status' should be interpreted as 'all'.
if ( empty( $statuses ) ) {
$statuses = array( 'all' );
}
// 'any' overrides other statuses.
if ( ! in_array( 'any', $statuses ) ) {
foreach ( $statuses as $status ) {
switch ( $status ) {
case 'hold' :
case 'hold':
$status_clauses[] = "comment_approved = '0'";
break;
case 'approve' :
case 'approve':
$status_clauses[] = "comment_approved = '1'";
break;
case 'all' :
case '' :
case 'all':
case '':
$status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
break;
default :
$status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
default:
$status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status );
break;
}
}
@ -515,20 +519,16 @@ class WP_Comment_Query {
// User IDs or emails whose unapproved comments are included, regardless of $status.
if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
$include_unapproved = $this->query_vars['include_unapproved'];
$include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] );
// Accepts arrays or comma-separated strings.
if ( ! is_array( $include_unapproved ) ) {
$include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
}
$unapproved_ids = $unapproved_emails = array();
$unapproved_ids = array();
$unapproved_emails = array();
foreach ( $include_unapproved as $unapproved_identifier ) {
// Numeric values are assumed to be user ids.
if ( is_numeric( $unapproved_identifier ) ) {
$approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
// Otherwise we match against email addresses.
// Otherwise we match against email addresses.
} else {
$approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
}
@ -554,8 +554,8 @@ class WP_Comment_Query {
$this->query_vars['orderby'] :
preg_split( '/[,\s]/', $this->query_vars['orderby'] );
$orderby_array = array();
$found_orderby_comment_ID = false;
$orderby_array = array();
$found_orderby_comment_id = false;
foreach ( $ordersby as $_key => $_value ) {
if ( ! $_value ) {
continue;
@ -563,14 +563,14 @@ class WP_Comment_Query {
if ( is_int( $_key ) ) {
$_orderby = $_value;
$_order = $order;
$_order = $order;
} else {
$_orderby = $_key;
$_order = $_value;
$_order = $_value;
}
if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
$found_orderby_comment_ID = true;
if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
$found_orderby_comment_id = true;
}
$parsed = $this->parse_orderby( $_orderby );
@ -593,24 +593,24 @@ class WP_Comment_Query {
}
// To ensure determinate sorting, always include a comment_ID clause.
if ( ! $found_orderby_comment_ID ) {
$comment_ID_order = '';
if ( ! $found_orderby_comment_id ) {
$comment_id_order = '';
// Inherit order from comment_date or comment_date_gmt, if available.
foreach ( $orderby_array as $orderby_clause ) {
if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
$comment_ID_order = $match[1];
$comment_id_order = $match[1];
break;
}
}
// If no date-related order is available, use the date from the first available clause.
if ( ! $comment_ID_order ) {
if ( ! $comment_id_order ) {
foreach ( $orderby_array as $orderby_clause ) {
if ( false !== strpos( 'ASC', $orderby_clause ) ) {
$comment_ID_order = 'ASC';
$comment_id_order = 'ASC';
} else {
$comment_ID_order = 'DESC';
$comment_id_order = 'DESC';
}
break;
@ -618,11 +618,11 @@ class WP_Comment_Query {
}
// Default to DESC.
if ( ! $comment_ID_order ) {
$comment_ID_order = 'DESC';
if ( ! $comment_id_order ) {
$comment_id_order = 'DESC';
}
$orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
$orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order";
}
$orderby = implode( ', ', $orderby_array );
@ -632,8 +632,8 @@ class WP_Comment_Query {
$number = absint( $this->query_vars['number'] );
$offset = absint( $this->query_vars['offset'] );
$paged = absint( $this->query_vars['paged'] );
$limits = '';
$paged = absint( $this->query_vars['paged'] );
$limits = '';
if ( ! empty( $number ) ) {
if ( $offset ) {
@ -698,7 +698,7 @@ class WP_Comment_Query {
// Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
$raw_types = array(
'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
'NOT IN' => (array) $this->query_vars['type__not_in'],
);
@ -710,7 +710,7 @@ class WP_Comment_Query {
switch ( $type ) {
// An empty translates to 'all', for backward compatibility
case '':
case 'all' :
case 'all':
break;
case 'comment':
@ -731,7 +731,7 @@ class WP_Comment_Query {
if ( ! empty( $comment_types[ $operator ] ) ) {
$types_sql = implode( ', ', $comment_types[ $operator ] );
$this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
$this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
}
}
@ -763,14 +763,14 @@ class WP_Comment_Query {
// If any post-related query vars are passed, join the posts table.
$join_posts_table = false;
$plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
$post_fields = array_filter( $plucked );
$plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
$post_fields = array_filter( $plucked );
if ( ! empty( $post_fields ) ) {
$join_posts_table = true;
foreach ( $post_fields as $field_name => $field_value ) {
// $field_value may be an array.
$esses = array_fill( 0, count( (array) $field_value ), '%s' );
$esses = array_fill( 0, count( (array) $field_value ), '%s' );
$this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
}
}
@ -791,8 +791,8 @@ class WP_Comment_Query {
$join_posts_table = true;
$esses = array_fill( 0, count( $q_values ), '%s' );
$this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ")", $q_values );
$esses = array_fill( 0, count( $q_values ), '%s' );
$this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values );
}
}
@ -808,13 +808,13 @@ class WP_Comment_Query {
// Post author IDs for an IN clause.
if ( ! empty( $this->query_vars['post_author__in'] ) ) {
$join_posts_table = true;
$join_posts_table = true;
$this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
}
// Post author IDs for a NOT IN clause.
if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
$join_posts_table = true;
$join_posts_table = true;
$this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
}
@ -837,7 +837,7 @@ class WP_Comment_Query {
}
if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
$this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
$this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
$this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
}
@ -849,17 +849,17 @@ class WP_Comment_Query {
*
* @since 3.1.0
*
* @param array $pieces A compacted array of comment query clauses.
* @param WP_Comment_Query $this Current instance of WP_Comment_Query (passed by reference).
* @param string[] $pieces An associative array of comment query clauses.
* @param WP_Comment_Query $this Current instance of WP_Comment_Query (passed by reference).
*/
$clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
$fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
$join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
$where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
$orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
$limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
$groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
$this->filtered_where_clause = $where;
@ -932,7 +932,7 @@ class WP_Comment_Query {
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $comments Array of top-level comments whose descendants should be filled in.
* @param WP_Comment[] $comments Array of top-level comments whose descendants should be filled in.
* @return array
*/
protected function fill_descendants( $comments ) {
@ -942,18 +942,18 @@ class WP_Comment_Query {
0 => wp_list_pluck( $comments, 'comment_ID' ),
);
$key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
$key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
$last_changed = wp_cache_get_last_changed( 'comment' );
// Fetch an entire level of the descendant tree at a time.
$level = 0;
$level = 0;
$exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
do {
// Parent-child relationships may be cached. Only query for those that are not.
$child_ids = $uncached_parent_ids = array();
$child_ids = $uncached_parent_ids = array();
$_parent_ids = $levels[ $level ];
foreach ( $_parent_ids as $parent_id ) {
$cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
$cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
$parent_child_ids = wp_cache_get( $cache_key, 'comment' );
if ( false !== $parent_child_ids ) {
$child_ids = array_merge( $child_ids, $parent_child_ids );
@ -980,7 +980,7 @@ class WP_Comment_Query {
$parent_map = array_fill_keys( $uncached_parent_ids, array() );
foreach ( $level_comments as $level_comment ) {
$parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
$child_ids[] = $level_comment->comment_ID;
$child_ids[] = $level_comment->comment_ID;
}
foreach ( $parent_map as $parent_id => $children ) {
@ -1016,9 +1016,9 @@ class WP_Comment_Query {
// If the comment isn't in the reference array, it goes in the top level of the thread.
if ( ! isset( $ref[ $c->comment_parent ] ) ) {
$threaded_comments[ $_c->comment_ID ] = $_c;
$ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
$ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
// Otherwise, set it as a child of its parent.
// Otherwise, set it as a child of its parent.
} else {
$ref[ $_c->comment_parent ]->add_child( $_c );
@ -1060,7 +1060,7 @@ class WP_Comment_Query {
$searches[] = $wpdb->prepare( "$col LIKE %s", $like );
}
return ' AND (' . implode(' OR ', $searches) . ')';
return ' AND (' . implode( ' OR ', $searches ) . ')';
}
/**
@ -1112,12 +1112,12 @@ class WP_Comment_Query {
$parsed = "$wpdb->commentmeta.meta_value+0";
} elseif ( $orderby == 'comment__in' ) {
$comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
$parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
$parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
} elseif ( in_array( $orderby, $allowed_keys ) ) {
if ( isset( $meta_query_clauses[ $orderby ] ) ) {
$meta_clause = $meta_query_clauses[ $orderby ];
$parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
$parsed = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
} else {
$parsed = "$wpdb->comments.$orderby";
}

View file

@ -162,7 +162,6 @@ final class WP_Comment {
* Retrieves a WP_Comment instance.
*
* @since 4.4.0
* @static
*
* @global wpdb $wpdb WordPress database abstraction object.
*
@ -256,13 +255,13 @@ final class WP_Comment {
*/
public function get_children( $args = array() ) {
$defaults = array(
'format' => 'tree',
'status' => 'all',
'format' => 'tree',
'status' => 'all',
'hierarchical' => 'threaded',
'orderby' => '',
'orderby' => '',
);
$_args = wp_parse_args( $args, $defaults );
$_args = wp_parse_args( $args, $defaults );
$_args['parent'] = $this->comment_ID;
if ( is_null( $this->children ) ) {
@ -276,7 +275,7 @@ final class WP_Comment {
if ( 'flat' === $_args['format'] ) {
$children = array();
foreach ( $this->children as $child ) {
$child_args = $_args;
$child_args = $_args;
$child_args['format'] = 'flat';
// get_children() resets this value automatically.
unset( $child_args['parent'] );

View file

@ -20,8 +20,6 @@ class WP_Customize_Control {
* Used when sorting two instances whose priorities are equal.
*
* @since 4.1.0
*
* @static
* @var int
*/
protected static $instance_count = 0;
@ -213,7 +211,7 @@ class WP_Customize_Control {
}
$this->manager = $manager;
$this->id = $id;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
@ -230,8 +228,8 @@ class WP_Customize_Control {
foreach ( $this->settings as $key => $setting ) {
$settings[ $key ] = $this->manager->get_setting( $setting );
}
} else if ( is_string( $this->settings ) ) {
$this->setting = $this->manager->get_setting( $this->settings );
} elseif ( is_string( $this->settings ) ) {
$this->setting = $this->manager->get_setting( $this->settings );
$settings['default'] = $this->setting;
}
$this->settings = $settings;
@ -253,7 +251,7 @@ class WP_Customize_Control {
*/
final public function active() {
$control = $this;
$active = call_user_func( $this->active_callback, $this );
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Control::active().
@ -308,13 +306,13 @@ class WP_Customize_Control {
$this->json['settings'][ $key ] = $setting->id;
}
$this->json['type'] = $this->type;
$this->json['priority'] = $this->priority;
$this->json['active'] = $this->active();
$this->json['section'] = $this->section;
$this->json['content'] = $this->get_content();
$this->json['label'] = $this->label;
$this->json['description'] = $this->description;
$this->json['type'] = $this->type;
$this->json['priority'] = $this->priority;
$this->json['active'] = $this->active();
$this->json['section'] = $this->section;
$this->json['content'] = $this->get_content();
$this->json['label'] = $this->label;
$this->json['description'] = $this->description;
$this->json['instanceNumber'] = $this->instance_number;
if ( 'dropdown-pages' === $this->type ) {
@ -385,8 +383,9 @@ class WP_Customize_Control {
* @uses WP_Customize_Control::render()
*/
final public function maybe_render() {
if ( ! $this->check_capabilities() )
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires just before the current Customizer control is rendered.
@ -480,8 +479,8 @@ class WP_Customize_Control {
* @since 3.4.0
*/
protected function render_content() {
$input_id = '_customize-input-' . $this->id;
$description_id = '_customize-description-' . $this->id;
$input_id = '_customize-input-' . $this->id;
$description_id = '_customize-description-' . $this->id;
$describedby_attr = ( ! empty( $this->description ) ) ? ' aria-describedby="' . esc_attr( $description_id ) . '" ' : '';
switch ( $this->type ) {
case 'checkbox':
@ -513,7 +512,7 @@ class WP_Customize_Control {
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description ; ?></span>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<?php foreach ( $this->choices as $value => $label ) : ?>
@ -567,9 +566,8 @@ class WP_Customize_Control {
rows="5"
<?php echo $describedby_attr; ?>
<?php $this->input_attrs(); ?>
<?php $this->link(); ?>>
<?php echo esc_textarea( $this->value() ); ?>
</textarea>
<?php $this->link(); ?>
><?php echo esc_textarea( $this->value() ); ?></textarea>
<?php
break;
case 'dropdown-pages':
@ -582,10 +580,10 @@ class WP_Customize_Control {
<?php endif; ?>
<?php
$dropdown_name = '_customize-dropdown-pages-' . $this->id;
$show_option_none = __( '&mdash; Select &mdash;' );
$dropdown_name = '_customize-dropdown-pages-' . $this->id;
$show_option_none = __( '&mdash; Select &mdash;' );
$option_none_value = '0';
$dropdown = wp_dropdown_pages(
$dropdown = wp_dropdown_pages(
array(
'name' => $dropdown_name,
'echo' => 0,
@ -595,7 +593,7 @@ class WP_Customize_Control {
)
);
if ( empty( $dropdown ) ) {
$dropdown = sprintf( '<select id="%1$s" name="%1$s">', esc_attr( $dropdown_name ) );
$dropdown = sprintf( '<select id="%1$s" name="%1$s">', esc_attr( $dropdown_name ) );
$dropdown .= sprintf( '<option value="%1$s">%2$s</option>', esc_attr( $option_none_value ), esc_html( $show_option_none ) );
$dropdown .= '</select>';
}

File diff suppressed because it is too large Load diff

View file

@ -42,7 +42,7 @@ final class WP_Customize_Nav_Menus {
* @param object $manager An instance of the WP_Customize_Manager class.
*/
public function __construct( $manager ) {
$this->manager = $manager;
$this->manager = $manager;
$this->original_nav_menu_locations = get_nav_menu_locations();
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
@ -75,8 +75,8 @@ final class WP_Customize_Nav_Menus {
*
* @since 4.5.0
*
* @param array $nonces Array of nonces.
* @return array $nonces Modified array of nonces.
* @param string[] $nonces Array of nonces.
* @return string[] $nonces Modified array of nonces.
*/
public function filter_nonces( $nonces ) {
$nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
@ -95,15 +95,15 @@ final class WP_Customize_Nav_Menus {
wp_die( -1 );
}
$all_items = array();
$all_items = array();
$item_types = array();
if ( isset( $_POST['item_types'] ) && is_array( $_POST['item_types'] ) ) {
$item_types = wp_unslash( $_POST['item_types'] );
} elseif ( isset( $_POST['type'] ) && isset( $_POST['object'] ) ) { // Back compat.
$item_types[] = array(
'type' => wp_unslash( $_POST['type'] ),
'type' => wp_unslash( $_POST['type'] ),
'object' => wp_unslash( $_POST['object'] ),
'page' => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ),
'page' => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ),
);
} else {
wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
@ -113,10 +113,10 @@ final class WP_Customize_Nav_Menus {
if ( empty( $item_type['type'] ) || empty( $item_type['object'] ) ) {
wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
}
$type = sanitize_key( $item_type['type'] );
$type = sanitize_key( $item_type['type'] );
$object = sanitize_key( $item_type['object'] );
$page = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] );
$items = $this->load_available_items_query( $type, $object, $page );
$page = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] );
$items = $this->load_available_items_query( $type, $object, $page );
if ( is_wp_error( $items ) ) {
wp_send_json_error( $items->get_error_code() );
}
@ -179,13 +179,18 @@ final class WP_Customize_Nav_Menus {
}
}
$posts = array_merge( $posts, get_posts( array(
'numberposts' => 10,
'offset' => 10 * $page,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => $object,
) ) );
$posts = array_merge(
$posts,
get_posts(
array(
'numberposts' => 10,
'offset' => 10 * $page,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => $object,
)
)
);
foreach ( $posts as $post ) {
$post_title = $post->post_title;
@ -204,18 +209,21 @@ final class WP_Customize_Nav_Menus {
);
}
} elseif ( 'taxonomy' === $type ) {
$terms = get_terms( $object, array(
'child_of' => 0,
'exclude' => '',
'hide_empty' => false,
'hierarchical' => 1,
'include' => '',
'number' => 10,
'offset' => 10 * $page,
'order' => 'DESC',
'orderby' => 'count',
'pad_counts' => false,
) );
$terms = get_terms(
$object,
array(
'child_of' => 0,
'exclude' => '',
'hide_empty' => false,
'hierarchical' => 1,
'include' => '',
'number' => 10,
'offset' => 10 * $page,
'order' => 'DESC',
'orderby' => 'count',
'pad_counts' => false,
)
);
if ( is_wp_error( $terms ) ) {
return $terms;
}
@ -269,8 +277,13 @@ final class WP_Customize_Nav_Menus {
$p = 1;
}
$s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
$items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
$s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
$items = $this->search_available_items_query(
array(
'pagenum' => $p,
's' => $s,
)
);
if ( empty( $items ) ) {
wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
@ -293,7 +306,7 @@ final class WP_Customize_Nav_Menus {
$items = array();
$post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
$query = array(
$query = array(
'post_type' => array_keys( $post_type_objects ),
'suppress_filters' => true,
'update_post_term_cache' => false,
@ -314,20 +327,22 @@ final class WP_Customize_Nav_Menus {
// Prepend list of posts with nav_menus_created_posts search results on first page.
$nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' );
if ( 1 === $args['pagenum'] && $nav_menus_created_posts_setting && count( $nav_menus_created_posts_setting->value() ) > 0 ) {
$stub_post_query = new WP_Query( array_merge(
$query,
array(
'post_status' => 'auto-draft',
'post__in' => $nav_menus_created_posts_setting->value(),
'posts_per_page' => -1,
$stub_post_query = new WP_Query(
array_merge(
$query,
array(
'post_status' => 'auto-draft',
'post__in' => $nav_menus_created_posts_setting->value(),
'posts_per_page' => -1,
)
)
) );
$posts = array_merge( $posts, $stub_post_query->posts );
);
$posts = array_merge( $posts, $stub_post_query->posts );
}
// Query posts.
$get_posts = new WP_Query( $query );
$posts = array_merge( $posts, $get_posts->posts );
$posts = array_merge( $posts, $get_posts->posts );
// Create items for posts.
foreach ( $posts as $post ) {
@ -349,11 +364,14 @@ final class WP_Customize_Nav_Menus {
// Query taxonomy terms.
$taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
$terms = get_terms( $taxonomies, array(
'name__like' => $args['s'],
'number' => 20,
'offset' => 20 * ($args['pagenum'] - 1),
) );
$terms = get_terms(
$taxonomies,
array(
'name__like' => $args['s'],
'number' => 20,
'offset' => 20 * ( $args['pagenum'] - 1 ),
)
);
// Check if any taxonomies were found.
if ( ! empty( $terms ) ) {
@ -372,7 +390,7 @@ final class WP_Customize_Nav_Menus {
// Add "Home" link if search term matches. Treat as a page, but switch to custom on add.
if ( isset( $args['s'] ) ) {
$title = _x( 'Home', 'nav menu home label' );
$title = _x( 'Home', 'nav menu home label' );
$matches = function_exists( 'mb_stripos' ) ? false !== mb_stripos( $title, $args['s'] ) : false !== stripos( $title, $args['s'] );
if ( $matches ) {
$items[] = array(
@ -421,9 +439,9 @@ final class WP_Customize_Nav_Menus {
// Pass data to JS.
$settings = array(
'allMenus' => wp_get_nav_menus(),
'itemTypes' => $this->available_item_types(),
'l10n' => array(
'allMenus' => wp_get_nav_menus(),
'itemTypes' => $this->available_item_types(),
'l10n' => array(
'untitled' => _x( '(no label)', 'missing menu item navigation label' ),
'unnamed' => _x( '(unnamed)', 'Missing menu name.' ),
'custom_label' => __( 'Custom Link' ),
@ -456,9 +474,9 @@ final class WP_Customize_Nav_Menus {
'reorderLabelOn' => esc_attr__( 'Reorder menu items' ),
'reorderLabelOff' => esc_attr__( 'Close reorder mode' ),
),
'settingTransport' => 'postMessage',
'phpIntMax' => PHP_INT_MAX,
'defaultSettingValues' => array(
'settingTransport' => 'postMessage',
'phpIntMax' => PHP_INT_MAX,
'defaultSettingValues' => array(
'nav_menu' => $temp_nav_menu_setting->default,
'nav_menu_item' => $temp_nav_menu_item_setting->default,
),
@ -471,21 +489,21 @@ final class WP_Customize_Nav_Menus {
// This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
$nav_menus_l10n = array(
'oneThemeLocationNoMenus' => null,
'moveUp' => __( 'Move up one' ),
'moveDown' => __( 'Move down one' ),
'moveToTop' => __( 'Move to the top' ),
'moveUp' => __( 'Move up one' ),
'moveDown' => __( 'Move down one' ),
'moveToTop' => __( 'Move to the top' ),
/* translators: %s: previous item name */
'moveUnder' => __( 'Move under %s' ),
'moveUnder' => __( 'Move under %s' ),
/* translators: %s: previous item name */
'moveOutFrom' => __( 'Move out from under %s' ),
'moveOutFrom' => __( 'Move out from under %s' ),
/* translators: %s: previous item name */
'under' => __( 'Under %s' ),
'under' => __( 'Under %s' ),
/* translators: %s: previous item name */
'outFrom' => __( 'Out from under %s' ),
'outFrom' => __( 'Out from under %s' ),
/* translators: 1: item name, 2: item position, 3: total number of items */
'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ),
'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ),
/* translators: 1: item name, 2: item position, 3: parent item name */
'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
);
wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
}
@ -577,12 +595,22 @@ final class WP_Customize_Nav_Menus {
} else {
$description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
}
$this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
'title' => __( 'Menus' ),
'description' => $description,
'priority' => 100,
// 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
) ) );
/*
* Once multiple theme supports are allowed in WP_Customize_Panel,
* this panel can be restricted to themes that support menus or widgets.
*/
$this->manager->add_panel(
new WP_Customize_Nav_Menus_Panel(
$this->manager,
'nav_menus',
array(
'title' => __( 'Menus' ),
'description' => $description,
'priority' => 100,
)
)
);
$menus = wp_get_nav_menus();
// Menu locations.
@ -600,12 +628,15 @@ final class WP_Customize_Nav_Menus {
$description .= '<p>' . sprintf( __( 'If your theme has widget areas, you can also add menus there. Visit the <a href="%s">Widgets panel</a> and add a &#8220;Navigation Menu widget&#8221; to display a menu in a sidebar or footer.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
}
$this->manager->add_section( 'menu_locations', array(
'title' => 1 === $num_locations ? _x( 'View Location', 'menu locations' ) : _x( 'View All Locations', 'menu locations' ),
'panel' => 'nav_menus',
'priority' => 30,
'description' => $description,
) );
$this->manager->add_section(
'menu_locations',
array(
'title' => 1 === $num_locations ? _x( 'View Location', 'menu locations' ) : _x( 'View All Locations', 'menu locations' ),
'panel' => 'nav_menus',
'priority' => 30,
'description' => $description,
)
);
$choices = array( '0' => __( '&mdash; Select &mdash;' ) );
foreach ( $menus as $menu ) {
@ -634,13 +665,16 @@ final class WP_Customize_Nav_Menus {
remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
} else {
$this->manager->add_setting( $setting_id, array(
'sanitize_callback' => array( $this, 'intval_base10' ),
'theme_supports' => 'menus',
'type' => 'theme_mod',
'transport' => 'postMessage',
'default' => 0,
) );
$this->manager->add_setting(
$setting_id,
array(
'sanitize_callback' => array( $this, 'intval_base10' ),
'theme_supports' => 'menus',
'type' => 'theme_mod',
'transport' => 'postMessage',
'default' => 0,
)
);
}
// Override the assigned nav menu location if mapped during previewed theme switch.
@ -648,12 +682,18 @@ final class WP_Customize_Nav_Menus {
$this->manager->set_post_value( $setting_id, $mapped_nav_menu_locations[ $location ] );
}
$this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
'label' => $description,
'location_id' => $location,
'section' => 'menu_locations',
'choices' => $choices,
) ) );
$this->manager->add_control(
new WP_Customize_Nav_Menu_Location_Control(
$this->manager,
$setting_id,
array(
'label' => $description,
'location_id' => $location,
'section' => 'menu_locations',
'choices' => $choices,
)
)
);
}
// Register each menu as a Customizer section, and add each menu item to each menu.
@ -662,16 +702,28 @@ final class WP_Customize_Nav_Menus {
// Create a section for each menu.
$section_id = 'nav_menu[' . $menu_id . ']';
$this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
'priority' => 10,
'panel' => 'nav_menus',
) ) );
$this->manager->add_section(
new WP_Customize_Nav_Menu_Section(
$this->manager,
$section_id,
array(
'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
'priority' => 10,
'panel' => 'nav_menus',
)
)
);
$nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
$this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
'transport' => 'postMessage',
) ) );
$this->manager->add_setting(
new WP_Customize_Nav_Menu_Setting(
$this->manager,
$nav_menu_setting_id,
array(
'transport' => 'postMessage',
)
)
);
// Add the menu contents.
$menu_items = (array) wp_get_nav_menu_items( $menu_id );
@ -687,36 +739,57 @@ final class WP_Customize_Nav_Menus {
}
$value['nav_menu_term_id'] = $menu_id;
$this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
'value' => $value,
'transport' => 'postMessage',
) ) );
$this->manager->add_setting(
new WP_Customize_Nav_Menu_Item_Setting(
$this->manager,
$menu_item_setting_id,
array(
'value' => $value,
'transport' => 'postMessage',
)
)
);
// Create a control for each menu item.
$this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
'label' => $item->title,
'section' => $section_id,
'priority' => 10 + $i,
) ) );
$this->manager->add_control(
new WP_Customize_Nav_Menu_Item_Control(
$this->manager,
$menu_item_setting_id,
array(
'label' => $item->title,
'section' => $section_id,
'priority' => 10 + $i,
)
)
);
}
// Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
}
// Add the add-new-menu section and controls.
$this->manager->add_section( 'add_menu', array(
'type' => 'new_menu',
'title' => __( 'New Menu' ),
'panel' => 'nav_menus',
'priority' => 20,
) );
$this->manager->add_section(
'add_menu',
array(
'type' => 'new_menu',
'title' => __( 'New Menu' ),
'panel' => 'nav_menus',
'priority' => 20,
)
);
$this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array(
'transport' => 'postMessage',
'type' => 'option', // To prevent theme prefix in changeset.
'default' => array(),
'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
) ) );
$this->manager->add_setting(
new WP_Customize_Filter_Setting(
$this->manager,
'nav_menus_created_posts',
array(
'transport' => 'postMessage',
'type' => 'option', // To prevent theme prefix in changeset.
'default' => array(),
'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
)
)
);
}
/**
@ -749,10 +822,10 @@ final class WP_Customize_Nav_Menus {
if ( $post_types ) {
foreach ( $post_types as $slug => $post_type ) {
$item_types[] = array(
'title' => $post_type->labels->name,
'title' => $post_type->labels->name,
'type_label' => $post_type->labels->singular_name,
'type' => 'post_type',
'object' => $post_type->name,
'type' => 'post_type',
'object' => $post_type->name,
);
}
}
@ -764,10 +837,10 @@ final class WP_Customize_Nav_Menus {
continue;
}
$item_types[] = array(
'title' => $taxonomy->labels->name,
'title' => $taxonomy->labels->name,
'type_label' => $taxonomy->labels->singular_name,
'type' => 'taxonomy',
'object' => $taxonomy->name,
'type' => 'taxonomy',
'object' => $taxonomy->name,
);
}
}
@ -793,10 +866,10 @@ final class WP_Customize_Nav_Menus {
* @param array $postarr {
* Post array. Note that post_status is overridden to be `auto-draft`.
*
* @var string $post_title Post title. Required.
* @var string $post_type Post type. Required.
* @var string $post_name Post name.
* @var string $post_content Post content.
* @var string $post_title Post title. Required.
* @var string $post_type Post type. Required.
* @var string $post_name Post name.
* @var string $post_content Post content.
* }
* @return WP_Post|WP_Error Inserted auto-draft post object or error.
*/
@ -825,7 +898,7 @@ final class WP_Customize_Nav_Menus {
$postarr['meta_input'] = array();
}
$postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
$postarr['meta_input']['_customize_changeset_uuid'] = $this->manager->changeset_uuid();
$postarr['meta_input']['_customize_changeset_uuid'] = $this->manager->changeset_uuid();
unset( $postarr['post_name'] );
add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
@ -857,7 +930,7 @@ final class WP_Customize_Nav_Menus {
wp_send_json_error( 'missing_params', 400 );
}
$params = wp_unslash( $_POST['params'] );
$params = wp_unslash( $_POST['params'] );
$illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
if ( ! empty( $illegal_params ) ) {
wp_send_json_error( 'illegal_params', 400 );
@ -865,7 +938,7 @@ final class WP_Customize_Nav_Menus {
$params = array_merge(
array(
'post_type' => '',
'post_type' => '',
'post_title' => '',
),
$params
@ -898,7 +971,7 @@ final class WP_Customize_Nav_Menus {
}
$data = array(
/* translators: %1$s is the post type name and %2$s is the error message. */
/* translators: 1: post type name, 2: error message */
'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
);
wp_send_json_error( $data );
@ -930,10 +1003,12 @@ final class WP_Customize_Nav_Menus {
<span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
</span>
<button type="button" class="button-link item-add">
<span class="screen-reader-text"><?php
/* translators: 1: Title of a menu item, 2: Type of a menu item */
<span class="screen-reader-text">
<?php
/* translators: 1: title of a menu item, 2: type of a menu item */
printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
?></span>
?>
</span>
</button>
</div>
</div>
@ -985,7 +1060,7 @@ final class WP_Customize_Nav_Menus {
</button>
</h3>
</script>
<?php
<?php
}
/**
@ -1013,7 +1088,7 @@ final class WP_Customize_Nav_Menus {
<div id="available-menu-items-search" class="accordion-section cannot-expand">
<div class="accordion-section-title">
<label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
<input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ) ?>" aria-describedby="menu-items-search-desc" />
<input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ); ?>" aria-describedby="menu-items-search-desc" />
<p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
<span class="spinner"></span>
</div>
@ -1024,7 +1099,7 @@ final class WP_Customize_Nav_Menus {
<?php
// Ensure the page post type comes first in the list.
$item_types = $this->available_item_types();
$item_types = $this->available_item_types();
$page_item_type = null;
foreach ( $item_types as $i => $item_type ) {
if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
@ -1043,7 +1118,7 @@ final class WP_Customize_Nav_Menus {
}
?>
</div><!-- #available-menu-items -->
<?php
<?php
}
/**
@ -1065,9 +1140,12 @@ final class WP_Customize_Nav_Menus {
<span class="spinner"></span>
<span class="no-items"><?php _e( 'No items' ); ?></span>
<button type="button" class="button-link" aria-expanded="false">
<span class="screen-reader-text"><?php
<span class="screen-reader-text">
<?php
/* translators: %s: Title of a section with menu items */
printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) );
?>
</span>
<span class="toggle-indicator" aria-hidden="true"></span>
</button>
</h4>
@ -1247,11 +1325,11 @@ final class WP_Customize_Nav_Menus {
}
$target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
$args = array(
'ID' => $post_id,
$args = array(
'ID' => $post_id,
'post_status' => $target_status,
);
$post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
$post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
if ( $post_name ) {
$args['post_name'] = $post_name;
}
@ -1269,7 +1347,7 @@ final class WP_Customize_Nav_Menus {
*
* @since 4.3.0
* @see wp_nav_menu()
* @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
* @see WP_Customize_Widgets::filter_dynamic_sidebar_params()
*
* @param array $args An array containing wp_nav_menu() arguments.
* @return array Arguments.
@ -1310,7 +1388,7 @@ final class WP_Customize_Nav_Menus {
// Empty out args which may not be JSON-serializable.
if ( ! $can_partial_refresh ) {
$exported_args['fallback_cb'] = '';
$exported_args['walker'] = '';
$exported_args['walker'] = '';
}
/*
@ -1324,7 +1402,7 @@ final class WP_Customize_Nav_Menus {
ksort( $exported_args );
$exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
$args['customize_preview_nav_menus_args'] = $exported_args;
$args['customize_preview_nav_menus_args'] = $exported_args;
$this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
return $args;
}
@ -1344,9 +1422,9 @@ final class WP_Customize_Nav_Menus {
*/
public function filter_wp_nav_menu( $nav_menu_content, $args ) {
if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
$attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
$attributes .= ' data-customize-partial-type="nav_menu_instance"';
$attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
$attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
$attributes .= ' data-customize-partial-type="nav_menu_instance"';
$attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
$nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . str_replace( '\\', '\\\\', $attributes ), $nav_menu_content, 1 );
}
return $nav_menu_content;

View file

@ -24,8 +24,6 @@ class WP_Customize_Panel {
* Used when sorting two instances whose priorities are equal.
*
* @since 4.1.0
*
* @static
* @var int
*/
protected static $instance_count = 0;
@ -152,7 +150,7 @@ class WP_Customize_Panel {
}
$this->manager = $manager;
$this->id = $id;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
@ -170,7 +168,7 @@ class WP_Customize_Panel {
* @return bool Whether the panel is active to the current preview.
*/
final public function active() {
$panel = $this;
$panel = $this;
$active = call_user_func( $this->active_callback, $this );
/**
@ -208,11 +206,11 @@ class WP_Customize_Panel {
* @return array The array to be exported to the client as JSON.
*/
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'type' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'type' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
$array['autoExpandSoleSection'] = $this->auto_expand_sole_section;
return $array;
}
@ -318,7 +316,7 @@ class WP_Customize_Panel {
<script type="text/html" id="tmpl-customize-panel-<?php echo esc_attr( $this->type ); ?>">
<?php $this->render_template(); ?>
</script>
<?php
<?php
}
/**
@ -358,10 +356,12 @@ class WP_Customize_Panel {
<li class="panel-meta customize-info accordion-section <# if ( ! data.description ) { #> cannot-expand<# } #>">
<button class="customize-panel-back" tabindex="-1"><span class="screen-reader-text"><?php _e( 'Back' ); ?></span></button>
<div class="accordion-section-title">
<span class="preview-notice"><?php
<span class="preview-notice">
<?php
/* translators: %s: the site/panel title in the Customizer */
echo sprintf( __( 'You are customizing %s' ), '<strong class="panel-title">{{ data.title }}</strong>' );
?></span>
?>
</span>
<# if ( data.description ) { #>
<button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button>
<# } #>

View file

@ -24,8 +24,6 @@ class WP_Customize_Section {
* Used when sorting two instances whose priorities are equal.
*
* @since 4.1.0
*
* @static
* @var int
*/
protected static $instance_count = 0;
@ -163,7 +161,7 @@ class WP_Customize_Section {
}
$this->manager = $manager;
$this->id = $id;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
@ -182,7 +180,7 @@ class WP_Customize_Section {
*/
final public function active() {
$section = $this;
$active = call_user_func( $this->active_callback, $this );
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Section::active().
@ -219,10 +217,10 @@ class WP_Customize_Section {
* @return array The array to be exported to the client as JSON.
*/
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'panel', 'type', 'description_hidden' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'panel', 'type', 'description_hidden' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
if ( $this->panel ) {

View file

@ -135,7 +135,6 @@ class WP_Customize_Setting {
* Cache of multidimensional values to improve performance.
*
* @since 4.4.0
* @static
* @var array
*/
protected static $aggregated_multidimensionals = array();
@ -169,15 +168,15 @@ class WP_Customize_Setting {
}
$this->manager = $manager;
$this->id = $id;
$this->id = $id;
// Parse the ID for array keys.
$this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) );
$this->id_data['base'] = array_shift( $this->id_data['keys'] );
// Rebuild the ID.
$this->id = $this->id_data[ 'base' ];
if ( ! empty( $this->id_data[ 'keys' ] ) ) {
$this->id = $this->id_data['base'];
if ( ! empty( $this->id_data['keys'] ) ) {
$this->id .= '[' . implode( '][', $this->id_data['keys'] ) . ']';
}
@ -311,8 +310,8 @@ class WP_Customize_Setting {
return true;
}
$id_base = $this->id_data['base'];
$is_multidimensional = ! empty( $this->id_data['keys'] );
$id_base = $this->id_data['base'];
$is_multidimensional = ! empty( $this->id_data['keys'] );
$multidimensional_filter = array( $this, '_multidimensional_preview_filter' );
/*
@ -321,19 +320,19 @@ class WP_Customize_Setting {
* then the preview short-circuits because there is nothing that needs
* to be previewed.
*/
$undefined = new stdClass();
$undefined = new stdClass();
$needs_preview = ( $undefined !== $this->post_value( $undefined ) );
$value = null;
$value = null;
// Since no post value was defined, check if we have an initial value set.
if ( ! $needs_preview ) {
if ( $this->is_multidimensional_aggregated ) {
$root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
$root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
$value = $this->multidimensional_get( $root, $this->id_data['keys'], $undefined );
} else {
$default = $this->default;
$default = $this->default;
$this->default = $undefined; // Temporarily set default to undefined so we can detect if existing value is set.
$value = $this->value();
$value = $this->value();
$this->default = $default;
}
$needs_preview = ( $undefined === $value ); // Because the default needs to be supplied.
@ -348,7 +347,7 @@ class WP_Customize_Setting {
}
switch ( $this->type ) {
case 'theme_mod' :
case 'theme_mod':
if ( ! $is_multidimensional ) {
add_filter( "theme_mod_{$id_base}", array( $this, '_preview_filter' ) );
} else {
@ -359,7 +358,7 @@ class WP_Customize_Setting {
self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
}
break;
case 'option' :
case 'option':
if ( ! $is_multidimensional ) {
add_filter( "pre_option_{$id_base}", array( $this, '_preview_filter' ) );
} else {
@ -371,8 +370,7 @@ class WP_Customize_Setting {
self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
}
break;
default :
default:
/**
* Fires when the WP_Customize_Setting::preview() method is called for settings
* not handled as theme_mods or options.
@ -436,7 +434,7 @@ class WP_Customize_Setting {
return $original;
}
$undefined = new stdClass(); // Symbol hack.
$undefined = new stdClass(); // Symbol hack.
$post_value = $this->post_value( $undefined );
if ( $undefined !== $post_value ) {
$value = $post_value;
@ -483,8 +481,8 @@ class WP_Customize_Setting {
// Do the replacements of the posted/default sub value into the root value.
$value = $previewed_setting->post_value( $previewed_setting->default );
$root = self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'];
$root = $previewed_setting->multidimensional_replace( $root, $previewed_setting->id_data['keys'], $value );
$root = self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'];
$root = $previewed_setting->multidimensional_replace( $root, $previewed_setting->id_data['keys'], $value );
self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'] = $root;
// Mark this setting having been applied so that it will be skipped when the filter is called again.
@ -596,7 +594,7 @@ class WP_Customize_Setting {
*/
$validity = apply_filters( "customize_validate_{$this->id}", $validity, $value, $this );
if ( is_wp_error( $validity ) && empty( $validity->errors ) ) {
if ( is_wp_error( $validity ) && ! $validity->has_errors() ) {
$validity = true;
}
return $validity;
@ -720,7 +718,7 @@ class WP_Customize_Setting {
* @return mixed The value.
*/
public function value() {
$id_base = $this->id_data['base'];
$id_base = $this->id_data['base'];
$is_core_type = ( 'option' === $this->type || 'theme_mod' === $this->type );
if ( ! $is_core_type && ! $this->is_multidimensional_aggregated ) {
@ -753,7 +751,7 @@ class WP_Customize_Setting {
$value = apply_filters( "customize_value_{$id_base}", $value, $this );
} elseif ( $this->is_multidimensional_aggregated ) {
$root_value = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
$value = $this->multidimensional_get( $root_value, $this->id_data['keys'], $this->default );
$value = $this->multidimensional_get( $root_value, $this->id_data['keys'], $this->default );
// Ensure that the post value is used if the setting is previewed, since preview filters aren't applying on cached $root_value.
if ( $this->is_previewed ) {
@ -786,8 +784,9 @@ class WP_Customize_Setting {
*/
$value = apply_filters( "customize_sanitize_js_{$this->id}", $this->value(), $this );
if ( is_string( $value ) )
return html_entity_decode( $value, ENT_QUOTES, 'UTF-8');
if ( is_string( $value ) ) {
return html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
}
return $value;
}
@ -816,11 +815,13 @@ class WP_Customize_Setting {
* @return bool False if theme doesn't support the setting or user can't change setting, otherwise true.
*/
final public function check_capabilities() {
if ( $this->capability && ! call_user_func_array( 'current_user_can', (array) $this->capability ) )
if ( $this->capability && ! call_user_func_array( 'current_user_can', (array) $this->capability ) ) {
return false;
}
if ( $this->theme_supports && ! call_user_func_array( 'current_theme_supports', (array) $this->theme_supports ) )
if ( $this->theme_supports && ! call_user_func_array( 'current_theme_supports', (array) $this->theme_supports ) ) {
return false;
}
return true;
}
@ -836,21 +837,25 @@ class WP_Customize_Setting {
* @return array|void Keys are 'root', 'node', and 'key'.
*/
final protected function multidimensional( &$root, $keys, $create = false ) {
if ( $create && empty( $root ) )
if ( $create && empty( $root ) ) {
$root = array();
}
if ( ! isset( $root ) || empty( $keys ) )
if ( ! isset( $root ) || empty( $keys ) ) {
return;
}
$last = array_pop( $keys );
$node = &$root;
foreach ( $keys as $key ) {
if ( $create && ! isset( $node[ $key ] ) )
if ( $create && ! isset( $node[ $key ] ) ) {
$node[ $key ] = array();
}
if ( ! is_array( $node ) || ! isset( $node[ $key ] ) )
if ( ! is_array( $node ) || ! isset( $node[ $key ] ) ) {
return;
}
$node = &$node[ $key ];
}
@ -865,8 +870,9 @@ class WP_Customize_Setting {
}
}
if ( ! isset( $node[ $last ] ) )
if ( ! isset( $node[ $last ] ) ) {
return;
}
return array(
'root' => &$root,
@ -886,15 +892,17 @@ class WP_Customize_Setting {
* @return mixed
*/
final protected function multidimensional_replace( $root, $keys, $value ) {
if ( ! isset( $value ) )
if ( ! isset( $value ) ) {
return $root;
elseif ( empty( $keys ) ) // If there are no keys, we're replacing the root.
} elseif ( empty( $keys ) ) { // If there are no keys, we're replacing the root.
return $value;
}
$result = $this->multidimensional( $root, $keys, true );
if ( isset( $result ) )
if ( isset( $result ) ) {
$result['node'][ $result['key'] ] = $value;
}
return $root;
}
@ -910,8 +918,9 @@ class WP_Customize_Setting {
* @return mixed The requested value or the default value.
*/
final protected function multidimensional_get( $root, $keys, $default = null ) {
if ( empty( $keys ) ) // If there are no keys, test the root.
if ( empty( $keys ) ) { // If there are no keys, test the root.
return isset( $root ) ? $root : $default;
}
$result = $this->multidimensional( $root, $keys );
return isset( $result ) ? $result['node'][ $result['key'] ] : $default;

View file

@ -100,32 +100,32 @@ final class WP_Customize_Widgets {
$this->manager = $manager;
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
// Skip remaining hooks when the user can't manage widgets anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
// Selective Refresh.
add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
}
/**
@ -198,7 +198,7 @@ final class WP_Customize_Widgets {
* @since 4.2.0
*/
public function register_settings() {
$widget_setting_ids = array();
$widget_setting_ids = array();
$incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
foreach ( $incoming_setting_ids as $setting_id ) {
if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
@ -319,7 +319,7 @@ final class WP_Customize_Widgets {
* @return array
*/
public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
$sidebars_widgets = $GLOBALS['sidebars_widgets'];
$sidebars_widgets = $GLOBALS['sidebars_widgets'];
$sidebars_widgets['array_version'] = 3;
return $sidebars_widgets;
}
@ -399,22 +399,28 @@ final class WP_Customize_Widgets {
* theme_mod when the theme is switched.
*/
if ( ! $this->manager->is_theme_active() ) {
$setting_id = 'old_sidebars_widgets_data';
$setting_args = $this->get_setting_args( $setting_id, array(
'type' => 'global_variable',
'dirty' => true,
) );
$setting_id = 'old_sidebars_widgets_data';
$setting_args = $this->get_setting_args(
$setting_id,
array(
'type' => 'global_variable',
'dirty' => true,
)
);
$this->manager->add_setting( $setting_id, $setting_args );
}
$this->manager->add_panel( 'widgets', array(
'type' => 'widgets',
'title' => __( 'Widgets' ),
'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
'priority' => 110,
'active_callback' => array( $this, 'is_panel_active' ),
'auto_expand_sole_section' => true,
) );
$this->manager->add_panel(
'widgets',
array(
'type' => 'widgets',
'title' => __( 'Widgets' ),
'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
'priority' => 110,
'active_callback' => array( $this, 'is_panel_active' ),
'auto_expand_sole_section' => true,
)
);
foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
if ( empty( $sidebar_widget_ids ) ) {
@ -442,11 +448,11 @@ final class WP_Customize_Widgets {
if ( $is_active_sidebar ) {
$section_args = array(
'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
'description' => $wp_registered_sidebars[ $sidebar_id ]['description'],
'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
'panel' => 'widgets',
'sidebar_id' => $sidebar_id,
'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
'panel' => 'widgets',
'sidebar_id' => $sidebar_id,
);
/**
@ -463,11 +469,15 @@ final class WP_Customize_Widgets {
$section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
$this->manager->add_section( $section );
$control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
) );
$control = new WP_Widget_Area_Customize_Control(
$this->manager,
$setting_id,
array(
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
)
);
$new_setting_ids[] = $setting_id;
$this->manager->add_control( $control );
@ -478,25 +488,29 @@ final class WP_Customize_Widgets {
foreach ( $sidebar_widget_ids as $i => $widget_id ) {
// Skip widgets that may have gone away due to a plugin being deactivated.
if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[$widget_id] ) ) {
if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
continue;
}
$registered_widget = $wp_registered_widgets[$widget_id];
$registered_widget = $wp_registered_widgets[ $widget_id ];
$setting_id = $this->get_setting_id( $widget_id );
$id_base = $wp_registered_widget_controls[$widget_id]['id_base'];
$id_base = $wp_registered_widget_controls[ $widget_id ]['id_base'];
$control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
'label' => $registered_widget['name'],
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'widget_id' => $widget_id,
'widget_id_base' => $id_base,
'priority' => $i,
'width' => $wp_registered_widget_controls[$widget_id]['width'],
'height' => $wp_registered_widget_controls[$widget_id]['height'],
'is_wide' => $this->is_wide_widget( $widget_id ),
) );
$control = new WP_Widget_Form_Customize_Control(
$this->manager,
$setting_id,
array(
'label' => $registered_widget['name'],
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'widget_id' => $widget_id,
'widget_id_base' => $id_base,
'priority' => $i,
'width' => $wp_registered_widget_controls[ $widget_id ]['width'],
'height' => $wp_registered_widget_controls[ $widget_id ]['height'],
'is_wide' => $this->is_wide_widget( $widget_id ),
)
);
$this->manager->add_control( $control );
}
}
@ -562,7 +576,7 @@ final class WP_Customize_Widgets {
global $wp_registered_widget_controls;
$parsed_widget_id = $this->parse_widget_id( $widget_id );
$width = $wp_registered_widget_controls[$widget_id]['width'];
$width = $wp_registered_widget_controls[ $widget_id ]['width'];
$is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
$is_wide = ( $width > 250 && ! $is_core );
@ -587,7 +601,7 @@ final class WP_Customize_Widgets {
*/
public function parse_widget_id( $widget_id ) {
$parsed = array(
'number' => null,
'number' => null,
'id_base' => null,
);
@ -708,46 +722,58 @@ final class WP_Customize_Widgets {
* Gather all strings in PHP that may be needed by JS on the client.
* Once JS i18n is implemented (in #20491), this can be removed.
*/
$some_non_rendered_areas_messages = array();
$some_non_rendered_areas_messages = array();
$some_non_rendered_areas_messages[1] = html_entity_decode(
__( 'Your theme has 1 other widget area, but this particular page doesn&#8217;t display it.' ),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
$registered_sidebar_count = count( $wp_registered_sidebars );
$registered_sidebar_count = count( $wp_registered_sidebars );
for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
$some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode( sprintf(
/* translators: %s: the number of other widget areas registered but not rendered */
_n(
'Your theme has %s other widget area, but this particular page doesn&#8217;t display it.',
'Your theme has %s other widget areas, but this particular page doesn&#8217;t display them.',
$non_rendered_count
$some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
sprintf(
/* translators: %s: the number of other widget areas registered but not rendered */
_n(
'Your theme has %s other widget area, but this particular page doesn&#8217;t display it.',
'Your theme has %s other widget areas, but this particular page doesn&#8217;t display them.',
$non_rendered_count
),
number_format_i18n( $non_rendered_count )
),
number_format_i18n( $non_rendered_count )
), ENT_QUOTES, get_bloginfo( 'charset' ) );
ENT_QUOTES,
get_bloginfo( 'charset' )
);
}
if ( 1 === $registered_sidebar_count ) {
$no_areas_shown_message = html_entity_decode( sprintf(
__( 'Your theme has 1 widget area, but this particular page doesn&#8217;t display it.' )
), ENT_QUOTES, get_bloginfo( 'charset' ) );
} else {
$no_areas_shown_message = html_entity_decode( sprintf(
/* translators: %s: the total number of widget areas registered */
_n(
'Your theme has %s widget area, but this particular page doesn&#8217;t display it.',
'Your theme has %s widget areas, but this particular page doesn&#8217;t display them.',
$registered_sidebar_count
$no_areas_shown_message = html_entity_decode(
sprintf(
__( 'Your theme has 1 widget area, but this particular page doesn&#8217;t display it.' )
),
number_format_i18n( $registered_sidebar_count )
), ENT_QUOTES, get_bloginfo( 'charset' ) );
ENT_QUOTES,
get_bloginfo( 'charset' )
);
} else {
$no_areas_shown_message = html_entity_decode(
sprintf(
/* translators: %s: the total number of widget areas registered */
_n(
'Your theme has %s widget area, but this particular page doesn&#8217;t display it.',
'Your theme has %s widget areas, but this particular page doesn&#8217;t display them.',
$registered_sidebar_count
),
number_format_i18n( $registered_sidebar_count )
),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
}
$settings = array(
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
'l10n' => array(
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
'l10n' => array(
'saveBtnLabel' => __( 'Apply' ),
'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
'removeBtnLabel' => __( 'Remove' ),
@ -765,7 +791,7 @@ final class WP_Customize_Widgets {
'widgetsFound' => __( 'Number of widgets found: %d' ),
'noWidgetsFound' => __( 'No widgets found.' ),
),
'tpl' => array(
'tpl' => array(
'widgetReorderNav' => $widget_reorder_nav_tpl,
'moveWidgetArea' => $move_widget_area_tpl,
),
@ -797,23 +823,25 @@ final class WP_Customize_Widgets {
<span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
</button>
<h3>
<span class="customize-action"><?php
<span class="customize-action">
<?php
/* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
echo sprintf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
?></span>
?>
</span>
<?php _e( 'Add a Widget' ); ?>
</h3>
</div>
<div id="available-widgets-filter">
<label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
<input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ) ?>" aria-describedby="widgets-search-desc" />
<input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ); ?>" aria-describedby="widgets-search-desc" />
<div class="search-icon" aria-hidden="true"></div>
<button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
<p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
</div>
<div id="available-widgets-list">
<?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
<div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ) ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ) ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ) ?>" tabindex="0">
<?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
<div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ); ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ); ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ); ?>" tabindex="0">
<?php echo $available_widget['control_tpl']; ?>
</div>
<?php endforeach; ?>
@ -858,13 +886,13 @@ final class WP_Customize_Widgets {
);
if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
$args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
$args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
$args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
$args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
$args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
} elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
$args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
$args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
$args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
$args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
$args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
}
$args = array_merge( $args, $overrides );
@ -889,11 +917,11 @@ final class WP_Customize_Widgets {
*
* @since 3.9.0
*
* @param array $widget_ids Array of widget IDs.
* @return array Array of sanitized widget IDs.
* @param string[] $widget_ids Array of widget IDs.
* @return string[] Array of sanitized widget IDs.
*/
public function sanitize_sidebar_widgets( $widget_ids ) {
$widget_ids = array_map( 'strval', (array) $widget_ids );
$widget_ids = array_map( 'strval', (array) $widget_ids );
$sanitized_widget_ids = array();
foreach ( $widget_ids as $widget_id ) {
$sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
@ -949,9 +977,9 @@ final class WP_Customize_Widgets {
);
$is_disabled = false;
$is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
$is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
if ( $is_multi_widget ) {
$id_base = $wp_registered_widget_controls[$widget['id']]['id_base'];
$id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
$args['_temp_id'] = "$id_base-__i__";
$args['_multi_num'] = next_widget_id_number( $id_base );
$args['_add'] = 'multi';
@ -964,22 +992,30 @@ final class WP_Customize_Widgets {
$id_base = $widget['id'];
}
$list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
$control_tpl = $this->get_widget_control( $list_widget_controls_args );
$list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
array(
0 => $args,
1 => $widget['params'][0],
)
);
$control_tpl = $this->get_widget_control( $list_widget_controls_args );
// The properties here are mapped to the Backbone Widget model.
$available_widget = array_merge( $available_widget, array(
'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
'is_multi' => $is_multi_widget,
'control_tpl' => $control_tpl,
'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
'is_disabled' => $is_disabled,
'id_base' => $id_base,
'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
'width' => $wp_registered_widget_controls[$widget['id']]['width'],
'height' => $wp_registered_widget_controls[$widget['id']]['height'],
'is_wide' => $this->is_wide_widget( $widget['id'] ),
) );
$available_widget = array_merge(
$available_widget,
array(
'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
'is_multi' => $is_multi_widget,
'control_tpl' => $control_tpl,
'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
'is_disabled' => $is_disabled,
'id_base' => $id_base,
'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
'width' => $wp_registered_widget_controls[ $widget['id'] ]['width'],
'height' => $wp_registered_widget_controls[ $widget['id'] ]['height'],
'is_wide' => $this->is_wide_widget( $widget['id'] ),
)
);
$available_widgets[] = $available_widget;
}
@ -1009,10 +1045,10 @@ final class WP_Customize_Widgets {
* @return string Widget control form HTML markup.
*/
public function get_widget_control( $args ) {
$args[0]['before_form'] = '<div class="form">';
$args[0]['after_form'] = '</div><!-- .form -->';
$args[0]['before_form'] = '<div class="form">';
$args[0]['after_form'] = '</div><!-- .form -->';
$args[0]['before_widget_content'] = '<div class="widget-content">';
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
ob_start();
call_user_func_array( 'wp_widget_control', $args );
$control_tpl = ob_get_clean();
@ -1032,19 +1068,21 @@ final class WP_Customize_Widgets {
*/
public function get_widget_control_parts( $args ) {
$args[0]['before_widget_content'] = '<div class="widget-content">';
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
$control_markup = $this->get_widget_control( $args );
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
$control_markup = $this->get_widget_control( $args );
$content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
$content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
$content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
$control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
$control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
$control .= substr( $control_markup, $content_end_pos );
$content = trim( substr(
$control_markup,
$content_start_pos + strlen( $args[0]['before_widget_content'] ),
$content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
) );
$content = trim(
substr(
$control_markup,
$content_start_pos + strlen( $args[0]['before_widget_content'] ),
$content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
)
);
return compact( 'control', 'content' );
}
@ -1056,8 +1094,8 @@ final class WP_Customize_Widgets {
*/
public function customize_preview_init() {
add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
}
/**
@ -1127,7 +1165,7 @@ final class WP_Customize_Widgets {
* and at the very end of the wp_footer,
*
* @since 3.9.0
*
*
* @global array $wp_registered_sidebars
* @global array $wp_registered_widgets
*/
@ -1135,8 +1173,8 @@ final class WP_Customize_Widgets {
global $wp_registered_sidebars, $wp_registered_widgets;
$switched_locale = switch_to_locale( get_user_locale() );
$l10n = array(
'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
$l10n = array(
'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
);
if ( $switched_locale ) {
restore_previous_locale();
@ -1144,11 +1182,11 @@ final class WP_Customize_Widgets {
// Prepare Customizer settings to pass to JavaScript.
$settings = array(
'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'l10n' => $l10n,
'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'l10n' => $l10n,
'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
);
foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
@ -1281,8 +1319,7 @@ final class WP_Customize_Widgets {
if ( empty( $value['is_widget_customizer_js_value'] )
|| empty( $value['instance_hash_key'] )
|| empty( $value['encoded_serialized_instance'] ) )
{
|| empty( $value['encoded_serialized_instance'] ) ) {
return;
}
@ -1398,14 +1435,14 @@ final class WP_Customize_Widgets {
}
if ( ! is_null( $parsed_id['number'] ) ) {
$value = array();
$value[$parsed_id['number']] = $instance;
$key = 'widget-' . $parsed_id['id_base'];
$_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
$added_input_vars[] = $key;
$value = array();
$value[ $parsed_id['number'] ] = $instance;
$key = 'widget-' . $parsed_id['id_base'];
$_REQUEST[ $key ] = $_POST[ $key ] = wp_slash( $value );
$added_input_vars[] = $key;
} else {
foreach ( $instance as $key => $value ) {
$_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
$_REQUEST[ $key ] = $_POST[ $key ] = wp_slash( $value );
$added_input_vars[] = $key;
}
}
@ -1509,7 +1546,7 @@ final class WP_Customize_Widgets {
$widget_id = $this->get_post_value( 'widget-id' );
$parsed_id = $this->parse_widget_id( $widget_id );
$id_base = $parsed_id['id_base'];
$id_base = $parsed_id['id_base'];
$is_updating_widget_template = (
isset( $_POST[ 'widget-' . $id_base ] )
@ -1527,7 +1564,7 @@ final class WP_Customize_Widgets {
wp_send_json_error( $updated_widget->get_error_code() );
}
$form = $updated_widget['form'];
$form = $updated_widget['form'];
$instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
wp_send_json_success( compact( 'form', 'instance' ) );
@ -1588,13 +1625,15 @@ final class WP_Customize_Widgets {
/**
* Inject selective refresh data attributes into widget container elements.
*
* @since 4.5.0
*
* @param array $params {
* Dynamic sidebar params.
*
* @type array $args Sidebar args.
* @type array $widget_args Widget args.
* }
* @see WP_Customize_Nav_Menus_Partial_Refresh::filter_wp_nav_menu_args()
* @see WP_Customize_Nav_Menus::filter_wp_nav_menu_args()
*
* @return array Params.
*/
@ -1602,13 +1641,13 @@ final class WP_Customize_Widgets {
$sidebar_args = array_merge(
array(
'before_widget' => '',
'after_widget' => '',
'after_widget' => '',
),
$params[0]
);
// Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
$matches = array();
$matches = array();
$is_valid = (
isset( $sidebar_args['id'] )
&&
@ -1628,14 +1667,14 @@ final class WP_Customize_Widgets {
);
if ( isset( $this->context_sidebar_instance_number ) ) {
$context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
} else if ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
} elseif ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
$context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
}
$attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
$attributes .= ' data-customize-partial-type="widget"';
$attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
$attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
$attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
$attributes .= ' data-customize-partial-type="widget"';
$attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
$attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
$sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
$params[0] = $sidebar_args;
@ -1670,13 +1709,16 @@ final class WP_Customize_Widgets {
}
$allowed_html[ $tag_name ] = array_merge(
$allowed_html[ $tag_name ],
array_fill_keys( array(
'data-customize-partial-id',
'data-customize-partial-type',
'data-customize-partial-placement-context',
'data-customize-partial-widget-id',
'data-customize-partial-options',
), true )
array_fill_keys(
array(
'data-customize-partial-id',
'data-customize-partial-type',
'data-customize-partial-placement-context',
'data-customize-partial-widget-id',
'data-customize-partial-options',
),
true
)
);
}
return $allowed_html;
@ -1815,14 +1857,14 @@ final class WP_Customize_Widgets {
// Render the widget.
ob_start();
dynamic_sidebar( $this->rendering_sidebar_id = $context['sidebar_id'] );
$container = ob_get_clean();
$container = ob_get_clean();
// Reset variables for next partial render.
remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
$this->context_sidebar_instance_number = null;
$this->rendering_sidebar_id = null;
$this->rendering_widget_id = null;
$this->rendering_sidebar_id = null;
$this->rendering_widget_id = null;
return $container;
}
@ -1975,7 +2017,7 @@ final class WP_Customize_Widgets {
remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
}
$this->_captured_options = array();
$this->_captured_options = array();
$this->_is_capturing_option_updates = false;
}

View file

@ -90,8 +90,9 @@ class _WP_Dependency {
*/
public function __construct() {
@list( $this->handle, $this->src, $this->deps, $this->ver, $this->args ) = func_get_args();
if ( ! is_array($this->deps) )
if ( ! is_array( $this->deps ) ) {
$this->deps = array();
}
}
/**
@ -104,15 +105,27 @@ class _WP_Dependency {
* @return bool False if not scalar, true otherwise.
*/
public function add_data( $name, $data ) {
if ( !is_scalar($name) )
if ( ! is_scalar( $name ) ) {
return false;
$this->extra[$name] = $data;
}
$this->extra[ $name ] = $data;
return true;
}
/**
* Sets the translation domain for this dependency.
*
* @since 5.0.0
*
* @param string $domain The translation textdomain.
* @param string $path Optional. The full file path to the directory containing translation files.
*
* @return bool False if $domain is not a string, true otherwise.
*/
public function set_translations( $domain, $path = null ) {
if ( !is_string($domain) )
if ( ! is_string( $domain ) ) {
return false;
}
$this->textdomain = $domain;
$this->translations_path = $path;
return true;

File diff suppressed because it is too large Load diff

View file

@ -9,10 +9,10 @@
class WP_Embed {
public $handlers = array();
public $post_ID;
public $usecache = true;
public $usecache = true;
public $linkifunknown = true;
public $last_attr = array();
public $last_url = '';
public $last_attr = array();
public $last_url = '';
/**
* When a URL cannot be embedded, return false instead of returning a link
@ -81,16 +81,17 @@ class WP_Embed {
public function maybe_run_ajax_cache() {
$post = get_post();
if ( ! $post || empty( $_GET['message'] ) )
if ( ! $post || empty( $_GET['message'] ) ) {
return;
}
?>
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
});
</script>
<?php
<?php
}
/**
@ -106,7 +107,7 @@ class WP_Embed {
* @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
*/
public function register_handler( $id, $regex, $callback, $priority = 10 ) {
$this->handlers[$priority][$id] = array(
$this->handlers[ $priority ][ $id ] = array(
'regex' => $regex,
'callback' => $callback,
);
@ -156,7 +157,7 @@ class WP_Embed {
}
$rawattr = $attr;
$attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
$attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
$this->last_attr = $attr;
@ -169,7 +170,7 @@ class WP_Embed {
foreach ( $this->handlers as $priority => $handlers ) {
foreach ( $handlers as $id => $handler ) {
if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) ) {
/**
* Filters the returned embed handler.
*
@ -182,6 +183,7 @@ class WP_Embed {
* @param array $attr An array of shortcode attributes.
*/
return apply_filters( 'embed_handler_html', $return, $url, $attr );
}
}
}
}
@ -216,7 +218,7 @@ class WP_Embed {
$cached_post_id = $this->find_oembed_post_id( $key_suffix );
if ( $post_ID ) {
$cache = get_post_meta( $post_ID, $cachekey, true );
$cache = get_post_meta( $post_ID, $cachekey, true );
$cache_time = get_post_meta( $post_ID, $cachekey_time, true );
if ( ! $cache_time ) {
@ -285,32 +287,44 @@ class WP_Embed {
}
$insert_post_args = array(
'post_name' => $key_suffix,
'post_name' => $key_suffix,
'post_status' => 'publish',
'post_type' => 'oembed_cache',
'post_type' => 'oembed_cache',
);
if ( $html ) {
if ( $cached_post_id ) {
wp_update_post( wp_slash( array(
'ID' => $cached_post_id,
'post_content' => $html,
) ) );
} else {
wp_insert_post( wp_slash( array_merge(
$insert_post_args,
array(
'post_content' => $html,
wp_update_post(
wp_slash(
array(
'ID' => $cached_post_id,
'post_content' => $html,
)
)
) ) );
);
} else {
wp_insert_post(
wp_slash(
array_merge(
$insert_post_args,
array(
'post_content' => $html,
)
)
)
);
}
} elseif ( ! $cache ) {
wp_insert_post( wp_slash( array_merge(
$insert_post_args,
array(
'post_content' => '{{unknown}}',
wp_insert_post(
wp_slash(
array_merge(
$insert_post_args,
array(
'post_content' => '{{unknown}}',
)
)
)
) ) );
);
}
if ( $has_kses ) {
@ -335,12 +349,14 @@ class WP_Embed {
*/
public function delete_oembed_caches( $post_ID ) {
$post_metas = get_post_custom_keys( $post_ID );
if ( empty($post_metas) )
if ( empty( $post_metas ) ) {
return;
}
foreach ( $post_metas as $post_meta_key ) {
if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) ) {
delete_post_meta( $post_ID, $post_meta_key );
}
}
}
@ -358,15 +374,15 @@ class WP_Embed {
*
* @since 2.9.0
*
* @param array $post_types Array of post types to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
* @param string[] $post_types Array of post type names to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
*/
if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ){
if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ) {
return;
}
// Trigger a caching
if ( ! empty( $post->post_content ) ) {
$this->post_ID = $post->ID;
$this->post_ID = $post->ID;
$this->usecache = false;
$content = $this->run_shortcode( $post->post_content );
@ -406,9 +422,9 @@ class WP_Embed {
* @return string The embed HTML on success, otherwise the original URL.
*/
public function autoembed_callback( $match ) {
$oldval = $this->linkifunknown;
$oldval = $this->linkifunknown;
$this->linkifunknown = false;
$return = $this->shortcode( array(), $match[2] );
$return = $this->shortcode( array(), $match[2] );
$this->linkifunknown = $oldval;
return $match[1] . $return . $match[3];
@ -425,7 +441,7 @@ class WP_Embed {
return false;
}
$output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
$output = ( $this->linkifunknown ) ? '<a href="' . esc_url( $url ) . '">' . esc_html( $url ) . '</a>' : $url;
/**
* Filters the returned, maybe-linked embed URL.
@ -454,17 +470,19 @@ class WP_Embed {
return $oembed_post_id;
}
$oembed_post_query = new WP_Query( array(
'post_type' => 'oembed_cache',
'post_status' => 'publish',
'name' => $cache_key,
'posts_per_page' => 1,
'no_found_rows' => true,
'cache_results' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'lazy_load_term_meta' => false,
) );
$oembed_post_query = new WP_Query(
array(
'post_type' => 'oembed_cache',
'post_status' => 'publish',
'name' => $cache_key,
'posts_per_page' => 1,
'no_found_rows' => true,
'cache_results' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'lazy_load_term_meta' => false,
)
);
if ( ! empty( $oembed_post_query->posts ) ) {
// Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed.

View file

@ -52,13 +52,15 @@ class WP_Error {
* @param mixed $data Optional. Error data.
*/
public function __construct( $code = '', $message = '', $data = '' ) {
if ( empty($code) )
if ( empty( $code ) ) {
return;
}
$this->errors[$code][] = $message;
$this->errors[ $code ][] = $message;
if ( ! empty($data) )
$this->error_data[$code] = $data;
if ( ! empty( $data ) ) {
$this->error_data[ $code ] = $data;
}
}
/**
@ -69,10 +71,11 @@ class WP_Error {
* @return array List of error codes, if available.
*/
public function get_error_codes() {
if ( empty($this->errors) )
if ( ! $this->has_errors() ) {
return array();
}
return array_keys($this->errors);
return array_keys( $this->errors );
}
/**
@ -85,8 +88,9 @@ class WP_Error {
public function get_error_code() {
$codes = $this->get_error_codes();
if ( empty($codes) )
if ( empty( $codes ) ) {
return '';
}
return $codes[0];
}
@ -99,20 +103,22 @@ class WP_Error {
* @param string|int $code Optional. Retrieve messages matching code, if exists.
* @return array Error strings on success, or empty array on failure (if using code parameter).
*/
public function get_error_messages($code = '') {
public function get_error_messages( $code = '' ) {
// Return all messages if no code specified.
if ( empty($code) ) {
if ( empty( $code ) ) {
$all_messages = array();
foreach ( (array) $this->errors as $code => $messages )
$all_messages = array_merge($all_messages, $messages);
foreach ( (array) $this->errors as $code => $messages ) {
$all_messages = array_merge( $all_messages, $messages );
}
return $all_messages;
}
if ( isset($this->errors[$code]) )
return $this->errors[$code];
else
if ( isset( $this->errors[ $code ] ) ) {
return $this->errors[ $code ];
} else {
return array();
}
}
/**
@ -126,12 +132,14 @@ class WP_Error {
* @param string|int $code Optional. Error code to retrieve message.
* @return string
*/
public function get_error_message($code = '') {
if ( empty($code) )
public function get_error_message( $code = '' ) {
if ( empty( $code ) ) {
$code = $this->get_error_code();
$messages = $this->get_error_messages($code);
if ( empty($messages) )
}
$messages = $this->get_error_messages( $code );
if ( empty( $messages ) ) {
return '';
}
return $messages[0];
}
@ -143,12 +151,28 @@ class WP_Error {
* @param string|int $code Optional. Error code.
* @return mixed Error data, if it exists.
*/
public function get_error_data($code = '') {
if ( empty($code) )
public function get_error_data( $code = '' ) {
if ( empty( $code ) ) {
$code = $this->get_error_code();
}
if ( isset($this->error_data[$code]) )
return $this->error_data[$code];
if ( isset( $this->error_data[ $code ] ) ) {
return $this->error_data[ $code ];
}
}
/**
* Verify if the instance contains errors.
*
* @since 5.1.0
*
* @return bool
*/
public function has_errors() {
if ( ! empty( $this->errors ) ) {
return true;
}
return false;
}
/**
@ -160,10 +184,11 @@ class WP_Error {
* @param string $message Error message.
* @param mixed $data Optional. Error data.
*/
public function add($code, $message, $data = '') {
$this->errors[$code][] = $message;
if ( ! empty($data) )
$this->error_data[$code] = $data;
public function add( $code, $message, $data = '' ) {
$this->errors[ $code ][] = $message;
if ( ! empty( $data ) ) {
$this->error_data[ $code ] = $data;
}
}
/**
@ -176,11 +201,12 @@ class WP_Error {
* @param mixed $data Error data.
* @param string|int $code Error code.
*/
public function add_data($data, $code = '') {
if ( empty($code) )
public function add_data( $data, $code = '' ) {
if ( empty( $code ) ) {
$code = $this->get_error_code();
}
$this->error_data[$code] = $data;
$this->error_data[ $code ] = $data;
}
/**

View file

@ -50,8 +50,8 @@ class WP_Feed_Cache_Transient {
* @param string $filename Unique identifier for cache object.
* @param string $extension 'spi' or 'spc'.
*/
public function __construct($location, $filename, $extension) {
$this->name = 'feed_' . $filename;
public function __construct( $location, $filename, $extension ) {
$this->name = 'feed_' . $filename;
$this->mod_name = 'feed_mod_' . $filename;
$lifetime = $this->lifetime;
@ -63,7 +63,7 @@ class WP_Feed_Cache_Transient {
* @param int $lifetime Cache duration in seconds. Default is 43200 seconds (12 hours).
* @param string $filename Unique identifier for the cache object.
*/
$this->lifetime = apply_filters( 'wp_feed_cache_transient_lifetime', $lifetime, $filename);
$this->lifetime = apply_filters( 'wp_feed_cache_transient_lifetime', $lifetime, $filename );
}
/**
@ -74,13 +74,13 @@ class WP_Feed_Cache_Transient {
* @param SimplePie $data Data to save.
* @return true Always true.
*/
public function save($data) {
public function save( $data ) {
if ( $data instanceof SimplePie ) {
$data = $data->data;
}
set_transient($this->name, $data, $this->lifetime);
set_transient($this->mod_name, time(), $this->lifetime);
set_transient( $this->name, $data, $this->lifetime );
set_transient( $this->mod_name, time(), $this->lifetime );
return true;
}
@ -92,7 +92,7 @@ class WP_Feed_Cache_Transient {
* @return mixed Transient value.
*/
public function load() {
return get_transient($this->name);
return get_transient( $this->name );
}
/**
@ -103,7 +103,7 @@ class WP_Feed_Cache_Transient {
* @return mixed Transient value.
*/
public function mtime() {
return get_transient($this->mod_name);
return get_transient( $this->mod_name );
}
/**
@ -114,7 +114,7 @@ class WP_Feed_Cache_Transient {
* @return bool False if value was not set and true if value was set.
*/
public function touch() {
return set_transient($this->mod_name, time(), $this->lifetime);
return set_transient( $this->mod_name, time(), $this->lifetime );
}
/**
@ -125,8 +125,8 @@ class WP_Feed_Cache_Transient {
* @return true Always true.
*/
public function unlink() {
delete_transient($this->name);
delete_transient($this->mod_name);
delete_transient( $this->name );
delete_transient( $this->mod_name );
return true;
}
}

View file

@ -26,7 +26,7 @@ class WP_Feed_Cache extends SimplePie_Cache {
* @param string $extension 'spi' or 'spc'.
* @return WP_Feed_Cache_Transient Feed cache handler object that uses transients.
*/
public function create($location, $filename, $extension) {
return new WP_Feed_Cache_Transient($location, $filename, $extension);
public function create( $location, $filename, $extension ) {
return new WP_Feed_Cache_Transient( $location, $filename, $extension );
}
}

View file

@ -71,12 +71,12 @@ final class WP_Hook implements Iterator, ArrayAccess {
* @param int $accepted_args The number of arguments the function accepts.
*/
public function add_filter( $tag, $function_to_add, $priority, $accepted_args ) {
$idx = _wp_filter_build_unique_id( $tag, $function_to_add, $priority );
$idx = _wp_filter_build_unique_id( $tag, $function_to_add, $priority );
$priority_existed = isset( $this->callbacks[ $priority ] );
$this->callbacks[ $priority ][ $idx ] = array(
'function' => $function_to_add,
'accepted_args' => $accepted_args
'function' => $function_to_add,
'accepted_args' => $accepted_args,
);
// if we're adding a new priority to the list, put them back in sorted order
@ -243,7 +243,7 @@ final class WP_Hook implements Iterator, ArrayAccess {
if ( false === $priority ) {
$this->callbacks = array();
} else if ( isset( $this->callbacks[ $priority ] ) ) {
} elseif ( isset( $this->callbacks[ $priority ] ) ) {
unset( $this->callbacks[ $priority ] );
}
@ -269,14 +269,14 @@ final class WP_Hook implements Iterator, ArrayAccess {
$nesting_level = $this->nesting_level++;
$this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
$num_args = count( $args );
$num_args = count( $args );
do {
$this->current_priority[ $nesting_level ] = $priority = current( $this->iterations[ $nesting_level ] );
foreach ( $this->callbacks[ $priority ] as $the_ ) {
if( ! $this->doing_action ) {
$args[ 0 ] = $value;
if ( ! $this->doing_action ) {
$args[0] = $value;
}
// Avoid the array_slice if possible.
@ -285,7 +285,7 @@ final class WP_Hook implements Iterator, ArrayAccess {
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int)$the_['accepted_args'] ) );
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}
}
} while ( false !== next( $this->iterations[ $nesting_level ] ) );
@ -323,7 +323,7 @@ final class WP_Hook implements Iterator, ArrayAccess {
* @param array $args Arguments to pass to the hook callbacks. Passed by reference.
*/
public function do_all_hook( &$args ) {
$nesting_level = $this->nesting_level++;
$nesting_level = $this->nesting_level++;
$this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
do {
@ -356,7 +356,6 @@ final class WP_Hook implements Iterator, ArrayAccess {
* Normalizes filters set up before WordPress has initialized to WP_Hook objects.
*
* @since 4.7.0
* @static
*
* @param array $filters Filters to normalize.
* @return WP_Hook[] Array of normalized filters.

View file

@ -82,21 +82,24 @@ class WP_Http_Cookie {
* and $port values.
*/
public function __construct( $data, $requested_url = '' ) {
if ( $requested_url )
if ( $requested_url ) {
$arrURL = @parse_url( $requested_url );
if ( isset( $arrURL['host'] ) )
}
if ( isset( $arrURL['host'] ) ) {
$this->domain = $arrURL['host'];
}
$this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
if ( '/' != substr( $this->path, -1 ) )
if ( '/' != substr( $this->path, -1 ) ) {
$this->path = dirname( $this->path ) . '/';
}
if ( is_string( $data ) ) {
// Assume it's a header string direct from a previous request.
$pairs = explode( ';', $data );
// Special handling for first pair; name=value. Also be careful of "=" in value.
$name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
$value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
$name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
$value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
$this->name = $name;
$this->value = urldecode( $value );
@ -105,32 +108,37 @@ class WP_Http_Cookie {
// Set everything else as a property.
foreach ( $pairs as $pair ) {
$pair = rtrim($pair);
$pair = rtrim( $pair );
// Handle the cookie ending in ; which results in a empty final pair.
if ( empty($pair) )
if ( empty( $pair ) ) {
continue;
}
list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
$key = strtolower( trim( $key ) );
if ( 'expires' == $key )
$key = strtolower( trim( $key ) );
if ( 'expires' == $key ) {
$val = strtotime( $val );
}
$this->$key = $val;
}
} else {
if ( !isset( $data['name'] ) )
if ( ! isset( $data['name'] ) ) {
return;
}
// Set properties based directly on parameters.
foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
if ( isset( $data[ $field ] ) )
if ( isset( $data[ $field ] ) ) {
$this->$field = $data[ $field ];
}
}
if ( isset( $data['expires'] ) )
if ( isset( $data['expires'] ) ) {
$this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
else
} else {
$this->expires = null;
}
}
}
@ -145,37 +153,43 @@ class WP_Http_Cookie {
* @return bool true if allowed, false otherwise.
*/
public function test( $url ) {
if ( is_null( $this->name ) )
if ( is_null( $this->name ) ) {
return false;
}
// Expires - if expired then nothing else matters.
if ( isset( $this->expires ) && time() > $this->expires )
if ( isset( $this->expires ) && time() > $this->expires ) {
return false;
}
// Get details on the URL we're thinking about sending to.
$url = parse_url( $url );
$url = parse_url( $url );
$url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
$url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
// Values to use for comparison against the URL.
$path = isset( $this->path ) ? $this->path : '/';
$port = isset( $this->port ) ? $this->port : null;
$path = isset( $this->path ) ? $this->path : '/';
$port = isset( $this->port ) ? $this->port : null;
$domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
if ( false === stripos( $domain, '.' ) )
if ( false === stripos( $domain, '.' ) ) {
$domain .= '.local';
}
// Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
$domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
if ( substr( $url['host'], -strlen( $domain ) ) != $domain ) {
return false;
}
// Port - supports "port-lists" in the format: "80,8000,8080".
if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
if ( ! empty( $port ) && ! in_array( $url['port'], explode( ',', $port ) ) ) {
return false;
}
// Path - request path must start with path restriction.
if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
if ( substr( $url['path'], 0, strlen( $path ) ) != $path ) {
return false;
}
return true;
}
@ -188,8 +202,9 @@ class WP_Http_Cookie {
* @return string Header encoded cookie name and value.
*/
public function getHeaderValue() {
if ( ! isset( $this->name ) || ! isset( $this->value ) )
if ( ! isset( $this->name ) || ! isset( $this->value ) ) {
return '';
}
/**
* Filters the header-encoded cookie value.

View file

@ -67,12 +67,16 @@ class WP_Http_Curl {
* @param string|array $args Optional. Override the defaults.
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
public function request($url, $args = array()) {
public function request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET', 'timeout' => 5,
'redirection' => 5, 'httpversion' => '1.0',
'blocking' => true,
'headers' => array(), 'body' => null, 'cookies' => array()
'method' => 'GET',
'timeout' => 5,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => null,
'cookies' => array(),
);
$r = wp_parse_args( $args, $defaults );
@ -105,14 +109,14 @@ class WP_Http_Curl {
}
}
$is_local = isset($r['local']) && $r['local'];
$ssl_verify = isset($r['sslverify']) && $r['sslverify'];
$is_local = isset( $r['local'] ) && $r['local'];
$ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
if ( $is_local ) {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify, $url );
} elseif ( ! $is_local ) {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
/** This filter is documented in wp-includes/class-http.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify, $url );
}
/*
@ -123,7 +127,7 @@ class WP_Http_Curl {
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_URL, $url);
curl_setopt( $handle, CURLOPT_URL, $url );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
@ -139,8 +143,9 @@ class WP_Http_Curl {
* a bug #17490 with redirected POST requests, so handle redirections outside Curl.
*/
curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
if ( defined( 'CURLOPT_PROTOCOLS' ) ) { // PHP 5.2.10 / cURL 7.19.4
curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
}
switch ( $r['method'] ) {
case 'HEAD':
@ -156,8 +161,9 @@ class WP_Http_Curl {
break;
default:
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
if ( ! is_null( $r['body'] ) )
if ( ! is_null( $r['body'] ) ) {
curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
}
break;
}
@ -168,30 +174,35 @@ class WP_Http_Curl {
curl_setopt( $handle, CURLOPT_HEADER, false );
if ( isset( $r['limit_response_size'] ) )
if ( isset( $r['limit_response_size'] ) ) {
$this->max_body_length = intval( $r['limit_response_size'] );
else
} else {
$this->max_body_length = false;
}
// If streaming to a file open a file handle, and setup our curl streaming handler.
if ( $r['stream'] ) {
if ( ! WP_DEBUG )
if ( ! WP_DEBUG ) {
$this->stream_handle = @fopen( $r['filename'], 'w+' );
else
} else {
$this->stream_handle = fopen( $r['filename'], 'w+' );
}
if ( ! $this->stream_handle ) {
return new WP_Error( 'http_request_failed', sprintf(
/* translators: 1: fopen() 2: file name */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$r['filename']
) );
return new WP_Error(
'http_request_failed',
sprintf(
/* translators: 1: fopen(), 2: file name */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$r['filename']
)
);
}
} else {
$this->stream_handle = false;
}
if ( !empty( $r['headers'] ) ) {
if ( ! empty( $r['headers'] ) ) {
// cURL expects full header strings in each element.
$headers = array();
foreach ( $r['headers'] as $name => $value ) {
@ -200,10 +211,11 @@ class WP_Http_Curl {
curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
}
if ( $r['httpversion'] == '1.0' )
if ( $r['httpversion'] == '1.0' ) {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
else
} else {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
}
/**
* Fires before the cURL request is executed.
@ -233,16 +245,24 @@ class WP_Http_Curl {
}
curl_close( $handle );
return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
);
}
curl_exec( $handle );
$theHeaders = WP_Http::processHeaders( $this->headers, $url );
$theBody = $this->body;
$theHeaders = WP_Http::processHeaders( $this->headers, $url );
$theBody = $this->body;
$bytes_written_total = $this->bytes_written_total;
$this->headers = '';
$this->body = '';
$this->headers = '';
$this->body = '';
$this->bytes_written_total = 0;
$curl_error = curl_errno( $handle );
@ -274,23 +294,26 @@ class WP_Http_Curl {
curl_close( $handle );
if ( $r['stream'] )
if ( $r['stream'] ) {
fclose( $this->stream_handle );
}
$response = array(
'headers' => $theHeaders['headers'],
'body' => null,
'headers' => $theHeaders['headers'],
'body' => null,
'response' => $theHeaders['response'],
'cookies' => $theHeaders['cookies'],
'filename' => $r['filename']
'cookies' => $theHeaders['cookies'],
'filename' => $r['filename'],
);
// Handle redirects.
if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) ) {
return $redirect_response;
}
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode( $theHeaders['headers'] ) ) {
$theBody = WP_Http_Encoding::decompress( $theBody );
}
$response['body'] = $theBody;
@ -332,13 +355,13 @@ class WP_Http_Curl {
if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
$data_length = ( $this->max_body_length - $this->bytes_written_total );
$data = substr( $data, 0, $data_length );
$data = substr( $data, 0, $data_length );
}
if ( $this->stream_handle ) {
$bytes_written = fwrite( $this->stream_handle, $data );
} else {
$this->body .= $data;
$this->body .= $data;
$bytes_written = $data_length;
}
@ -351,23 +374,24 @@ class WP_Http_Curl {
/**
* Determines whether this class can be used for retrieving a URL.
*
* @static
* @since 2.7.0
*
* @param array $args Optional. Array of request arguments. Default empty array.
* @return bool False means this class can not be used, true means it can.
*/
public static function test( $args = array() ) {
if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) ) {
return false;
}
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
$curl_version = curl_version();
// Check whether this cURL version support SSL requests.
if ( ! (CURL_VERSION_SSL & $curl_version['features']) )
if ( ! ( CURL_VERSION_SSL & $curl_version['features'] ) ) {
return false;
}
}
/**

View file

@ -23,8 +23,6 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @param string $raw String to compress.
* @param int $level Optional, default is 9. Compression level, 9 is highest.
* @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
@ -44,31 +42,34 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @param string $compressed String to decompress.
* @param int $length The optional length of the compressed data.
* @return string|bool False on failure.
*/
public static function decompress( $compressed, $length = null ) {
if ( empty($compressed) )
if ( empty( $compressed ) ) {
return $compressed;
}
if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
if ( false !== ( $decompressed = @gzinflate( $compressed ) ) ) {
return $decompressed;
}
if ( false !== ( $decompressed = self::compatible_gzinflate( $compressed ) ) )
if ( false !== ( $decompressed = self::compatible_gzinflate( $compressed ) ) ) {
return $decompressed;
}
if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) ) {
return $decompressed;
}
if ( function_exists('gzdecode') ) {
if ( function_exists( 'gzdecode' ) ) {
$decompressed = @gzdecode( $compressed );
if ( false !== $decompressed )
if ( false !== $decompressed ) {
return $decompressed;
}
}
return $compressed;
@ -91,38 +92,41 @@ class WP_Http_Encoding {
* @link https://secure.php.net/manual/en/function.gzinflate.php#70875
* @link https://secure.php.net/manual/en/function.gzinflate.php#77336
*
* @static
*
* @param string $gzData String to decompress.
* @return string|bool False on failure.
*/
public static function compatible_gzinflate($gzData) {
public static function compatible_gzinflate( $gzData ) {
// Compressed data might contain a full header, if so strip it for gzinflate().
if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
$i = 10;
$flg = ord( substr($gzData, 3, 1) );
if ( substr( $gzData, 0, 3 ) == "\x1f\x8b\x08" ) {
$i = 10;
$flg = ord( substr( $gzData, 3, 1 ) );
if ( $flg > 0 ) {
if ( $flg & 4 ) {
list($xlen) = unpack('v', substr($gzData, $i, 2) );
$i = $i + 2 + $xlen;
list($xlen) = unpack( 'v', substr( $gzData, $i, 2 ) );
$i = $i + 2 + $xlen;
}
if ( $flg & 8 )
$i = strpos($gzData, "\0", $i) + 1;
if ( $flg & 16 )
$i = strpos($gzData, "\0", $i) + 1;
if ( $flg & 2 )
if ( $flg & 8 ) {
$i = strpos( $gzData, "\0", $i ) + 1;
}
if ( $flg & 16 ) {
$i = strpos( $gzData, "\0", $i ) + 1;
}
if ( $flg & 2 ) {
$i = $i + 2;
}
}
$decompressed = @gzinflate( substr($gzData, $i, -8) );
if ( false !== $decompressed )
$decompressed = @gzinflate( substr( $gzData, $i, -8 ) );
if ( false !== $decompressed ) {
return $decompressed;
}
}
// Compressed data from java.util.zip.Deflater amongst others.
$decompressed = @gzinflate( substr($gzData, 2) );
if ( false !== $decompressed )
$decompressed = @gzinflate( substr( $gzData, 2 ) );
if ( false !== $decompressed ) {
return $decompressed;
}
return false;
}
@ -132,32 +136,34 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @param string $url
* @param array $args
* @return string Types of encoding to accept.
*/
public static function accept_encoding( $url, $args ) {
$type = array();
$type = array();
$compression_enabled = self::is_available();
if ( ! $args['decompress'] ) // Decompression specifically disabled.
if ( ! $args['decompress'] ) { // Decompression specifically disabled.
$compression_enabled = false;
elseif ( $args['stream'] ) // Disable when streaming to file.
} elseif ( $args['stream'] ) { // Disable when streaming to file.
$compression_enabled = false;
elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it.
} elseif ( isset( $args['limit_response_size'] ) ) { // If only partial content is being requested, we won't be able to decompress it.
$compression_enabled = false;
}
if ( $compression_enabled ) {
if ( function_exists( 'gzinflate' ) )
if ( function_exists( 'gzinflate' ) ) {
$type[] = 'deflate;q=1.0';
}
if ( function_exists( 'gzuncompress' ) )
if ( function_exists( 'gzuncompress' ) ) {
$type[] = 'compress;q=0.5';
}
if ( function_exists( 'gzdecode' ) )
if ( function_exists( 'gzdecode' ) ) {
$type[] = 'gzip;q=0.5';
}
}
/**
@ -172,7 +178,7 @@ class WP_Http_Encoding {
*/
$type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
return implode(', ', $type);
return implode( ', ', $type );
}
/**
@ -180,8 +186,6 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @return string Content-Encoding string to send in the header.
*/
public static function content_encoding() {
@ -193,17 +197,16 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @param array|string $headers All of the available headers.
* @return bool
*/
public static function should_decode($headers) {
public static function should_decode( $headers ) {
if ( is_array( $headers ) ) {
if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
if ( array_key_exists( 'content-encoding', $headers ) && ! empty( $headers['content-encoding'] ) ) {
return true;
}
} elseif ( is_string( $headers ) ) {
return ( stripos($headers, 'content-encoding:') !== false );
return ( stripos( $headers, 'content-encoding:' ) !== false );
}
return false;
@ -218,11 +221,9 @@ class WP_Http_Encoding {
*
* @since 2.8.0
*
* @static
*
* @return bool
*/
public static function is_available() {
return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
return ( function_exists( 'gzuncompress' ) || function_exists( 'gzdeflate' ) || function_exists( 'gzinflate' ) );
}
}

View file

@ -4,7 +4,6 @@
*
* @package WordPress
* @since 3.1.0
*
*/
class WP_HTTP_IXR_Client extends IXR_Client {
public $scheme;
@ -19,14 +18,14 @@ class WP_HTTP_IXR_Client extends IXR_Client {
* @param int|bool $port
* @param int $timeout
*/
public function __construct($server, $path = false, $port = false, $timeout = 15) {
public function __construct( $server, $path = false, $port = false, $timeout = 15 ) {
if ( ! $path ) {
// Assume we have been given a URL instead
$bits = parse_url($server);
$bits = parse_url( $server );
$this->scheme = $bits['scheme'];
$this->server = $bits['host'];
$this->port = isset($bits['port']) ? $bits['port'] : $port;
$this->path = !empty($bits['path']) ? $bits['path'] : '/';
$this->port = isset( $bits['port'] ) ? $bits['port'] : $port;
$this->path = ! empty( $bits['path'] ) ? $bits['path'] : '/';
// Make absolutely sure we have a path
if ( ! $this->path ) {
@ -39,33 +38,33 @@ class WP_HTTP_IXR_Client extends IXR_Client {
} else {
$this->scheme = 'http';
$this->server = $server;
$this->path = $path;
$this->port = $port;
$this->path = $path;
$this->port = $port;
}
$this->useragent = 'The Incutio XML-RPC PHP Library';
$this->timeout = $timeout;
$this->timeout = $timeout;
}
/**
* @return bool
*/
public function query() {
$args = func_get_args();
$method = array_shift($args);
$request = new IXR_Request($method, $args);
$xml = $request->getXml();
$args = func_get_args();
$method = array_shift( $args );
$request = new IXR_Request( $method, $args );
$xml = $request->getXml();
$port = $this->port ? ":$this->port" : '';
$url = $this->scheme . '://' . $this->server . $port . $this->path;
$url = $this->scheme . '://' . $this->server . $port . $this->path;
$args = array(
'headers' => array('Content-Type' => 'text/xml'),
'headers' => array( 'Content-Type' => 'text/xml' ),
'user-agent' => $this->useragent,
'body' => $xml,
);
// Merge Custom headers ala #8145
foreach ( $this->headers as $header => $value ) {
$args['headers'][$header] = $value;
$args['headers'][ $header ] = $value;
}
/**
@ -73,7 +72,7 @@ class WP_HTTP_IXR_Client extends IXR_Client {
*
* @since 4.4.0
*
* @param array $headers Array of headers to be sent.
* @param string[] $headers Associative array of headers to be sent.
*/
$args['headers'] = apply_filters( 'wp_http_ixr_client_headers', $args['headers'] );
@ -83,20 +82,20 @@ class WP_HTTP_IXR_Client extends IXR_Client {
// Now send the request
if ( $this->debug ) {
echo '<pre class="ixr_request">' . htmlspecialchars($xml) . "\n</pre>\n\n";
echo '<pre class="ixr_request">' . htmlspecialchars( $xml ) . "\n</pre>\n\n";
}
$response = wp_remote_post($url, $args);
$response = wp_remote_post( $url, $args );
if ( is_wp_error($response) ) {
$errno = $response->get_error_code();
$errorstr = $response->get_error_message();
$this->error = new IXR_Error(-32300, "transport error: $errno $errorstr");
if ( is_wp_error( $response ) ) {
$errno = $response->get_error_code();
$errorstr = $response->get_error_message();
$this->error = new IXR_Error( -32300, "transport error: $errno $errorstr" );
return false;
}
if ( 200 != wp_remote_retrieve_response_code( $response ) ) {
$this->error = new IXR_Error(-32301, 'transport error - HTTP status code was not 200 (' . wp_remote_retrieve_response_code( $response ) . ')');
$this->error = new IXR_Error( -32301, 'transport error - HTTP status code was not 200 (' . wp_remote_retrieve_response_code( $response ) . ')' );
return false;
}
@ -108,13 +107,13 @@ class WP_HTTP_IXR_Client extends IXR_Client {
$this->message = new IXR_Message( wp_remote_retrieve_body( $response ) );
if ( ! $this->message->parse() ) {
// XML error
$this->error = new IXR_Error(-32700, 'parse error. not well formed');
$this->error = new IXR_Error( -32700, 'parse error. not well formed' );
return false;
}
// Is the message a fault?
if ( $this->message->messageType == 'fault' ) {
$this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
$this->error = new IXR_Error( $this->message->faultCode, $this->message->faultString );
return false;
}

View file

@ -52,7 +52,7 @@ class WP_HTTP_Proxy {
* @return bool
*/
public function is_enabled() {
return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
return defined( 'WP_PROXY_HOST' ) && defined( 'WP_PROXY_PORT' );
}
/**
@ -66,7 +66,7 @@ class WP_HTTP_Proxy {
* @return bool
*/
public function use_authentication() {
return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
return defined( 'WP_PROXY_USERNAME' ) && defined( 'WP_PROXY_PASSWORD' );
}
/**
@ -77,8 +77,9 @@ class WP_HTTP_Proxy {
* @return string
*/
public function host() {
if ( defined('WP_PROXY_HOST') )
if ( defined( 'WP_PROXY_HOST' ) ) {
return WP_PROXY_HOST;
}
return '';
}
@ -91,8 +92,9 @@ class WP_HTTP_Proxy {
* @return string
*/
public function port() {
if ( defined('WP_PROXY_PORT') )
if ( defined( 'WP_PROXY_PORT' ) ) {
return WP_PROXY_PORT;
}
return '';
}
@ -105,8 +107,9 @@ class WP_HTTP_Proxy {
* @return string
*/
public function username() {
if ( defined('WP_PROXY_USERNAME') )
if ( defined( 'WP_PROXY_USERNAME' ) ) {
return WP_PROXY_USERNAME;
}
return '';
}
@ -119,8 +122,9 @@ class WP_HTTP_Proxy {
* @return string
*/
public function password() {
if ( defined('WP_PROXY_PASSWORD') )
if ( defined( 'WP_PROXY_PASSWORD' ) ) {
return WP_PROXY_PASSWORD;
}
return '';
}
@ -167,13 +171,14 @@ class WP_HTTP_Proxy {
* parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
* This will be displayed on sites, which is not reasonable.
*/
$check = @parse_url($uri);
$check = @parse_url( $uri );
// Malformed URL, can not process, but this could mean ssl, so let through anyway.
if ( $check === false )
if ( $check === false ) {
return true;
}
$home = parse_url( get_option('siteurl') );
$home = parse_url( get_option( 'siteurl' ) );
/**
* Filters whether to preempt sending the request through the proxy server.
@ -189,31 +194,36 @@ class WP_HTTP_Proxy {
* @param array $home Associative array result of parsing the site URL.
*/
$result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
if ( ! is_null( $result ) )
if ( ! is_null( $result ) ) {
return $result;
}
if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) )
if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
return false;
}
if ( !defined('WP_PROXY_BYPASS_HOSTS') )
if ( ! defined( 'WP_PROXY_BYPASS_HOSTS' ) ) {
return true;
}
static $bypass_hosts = null;
static $bypass_hosts = null;
static $wildcard_regex = array();
if ( null === $bypass_hosts ) {
$bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
$bypass_hosts = preg_split( '|,\s*|', WP_PROXY_BYPASS_HOSTS );
if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
if ( false !== strpos( WP_PROXY_BYPASS_HOSTS, '*' ) ) {
$wildcard_regex = array();
foreach ( $bypass_hosts as $host )
foreach ( $bypass_hosts as $host ) {
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
}
$wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
}
}
if ( !empty($wildcard_regex) )
return !preg_match($wildcard_regex, $check['host']);
else
return !in_array( $check['host'], $bypass_hosts );
if ( ! empty( $wildcard_regex ) ) {
return ! preg_match( $wildcard_regex, $check['host'] );
} else {
return ! in_array( $check['host'], $bypass_hosts );
}
}
}

View file

@ -36,7 +36,7 @@ class WP_HTTP_Requests_Hooks extends Requests_Hooks {
* @param array $request Request data in WP_Http format.
*/
public function __construct( $url, $request ) {
$this->url = $url;
$this->url = $url;
$this->request = $request;
}

View file

@ -162,13 +162,15 @@ class WP_HTTP_Requests_Response extends WP_HTTP_Response {
public function get_cookies() {
$cookies = array();
foreach ( $this->response->cookies as $cookie ) {
$cookies[] = new WP_Http_Cookie( array(
'name' => $cookie->name,
'value' => urldecode( $cookie->value ),
'expires' => isset( $cookie->attributes['expires'] ) ? $cookie->attributes['expires'] : null,
'path' => isset( $cookie->attributes['path'] ) ? $cookie->attributes['path'] : null,
'domain' => isset( $cookie->attributes['domain'] ) ? $cookie->attributes['domain'] : null,
));
$cookies[] = new WP_Http_Cookie(
array(
'name' => $cookie->name,
'value' => urldecode( $cookie->value ),
'expires' => isset( $cookie->attributes['expires'] ) ? $cookie->attributes['expires'] : null,
'path' => isset( $cookie->attributes['path'] ) ? $cookie->attributes['path'] : null,
'domain' => isset( $cookie->attributes['domain'] ) ? $cookie->attributes['domain'] : null,
)
);
}
return $cookies;
@ -183,13 +185,13 @@ class WP_HTTP_Requests_Response extends WP_HTTP_Response {
*/
public function to_array() {
return array(
'headers' => $this->get_headers(),
'body' => $this->get_data(),
'headers' => $this->get_headers(),
'body' => $this->get_data(),
'response' => array(
'code' => $this->get_status(),
'message' => get_status_header_desc( $this->get_status() ),
),
'cookies' => $this->get_cookies(),
'cookies' => $this->get_cookies(),
'filename' => $this->filename,
);
}

View file

@ -26,12 +26,16 @@ class WP_Http_Streams {
* @param string|array $args Optional. Override the defaults.
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
public function request($url, $args = array()) {
public function request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET', 'timeout' => 5,
'redirection' => 5, 'httpversion' => '1.0',
'blocking' => true,
'headers' => array(), 'body' => null, 'cookies' => array()
'method' => 'GET',
'timeout' => 5,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => null,
'cookies' => array(),
);
$r = wp_parse_args( $args, $defaults );
@ -47,14 +51,14 @@ class WP_Http_Streams {
// Construct Cookie: header if any cookies are set.
WP_Http::buildCookieHeader( $r );
$arrURL = parse_url($url);
$arrURL = parse_url( $url );
$connect_host = $arrURL['host'];
$secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
if ( ! isset( $arrURL['port'] ) ) {
if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
$arrURL['port'] = 443;
$arrURL['port'] = 443;
$secure_transport = true;
} else {
$arrURL['port'] = 80;
@ -67,10 +71,11 @@ class WP_Http_Streams {
}
if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
if ( isset( $r['headers']['Host'] ) )
if ( isset( $r['headers']['Host'] ) ) {
$arrURL['host'] = $r['headers']['Host'];
else
} else {
$arrURL['host'] = $r['headers']['host'];
}
unset( $r['headers']['Host'], $r['headers']['host'] );
}
@ -79,48 +84,47 @@ class WP_Http_Streams {
* to ::1, which fails when the server is not set up for it. For compatibility, always
* connect to the IPv4 address.
*/
if ( 'localhost' == strtolower( $connect_host ) )
if ( 'localhost' == strtolower( $connect_host ) ) {
$connect_host = '127.0.0.1';
}
$connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
$is_local = isset( $r['local'] ) && $r['local'];
$is_local = isset( $r['local'] ) && $r['local'];
$ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
if ( $is_local ) {
/**
* Filters whether SSL should be verified for local requests.
*
* @since 2.8.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
* @param string $url The request URL.
*/
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify, $url );
} elseif ( ! $is_local ) {
/**
* Filters whether SSL should be verified for non-local requests.
*
* @since 2.8.0
*
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
*/
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
/** This filter is documented in wp-includes/class-http.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify, $url );
}
$proxy = new WP_HTTP_Proxy();
$context = stream_context_create( array(
'ssl' => array(
'verify_peer' => $ssl_verify,
//'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
'capture_peer_cert' => $ssl_verify,
'SNI_enabled' => true,
'cafile' => $r['sslcertificates'],
'allow_self_signed' => ! $ssl_verify,
$context = stream_context_create(
array(
'ssl' => array(
'verify_peer' => $ssl_verify,
//'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
'capture_peer_cert' => $ssl_verify,
'SNI_enabled' => true,
'cafile' => $r['sslcertificates'],
'allow_self_signed' => ! $ssl_verify,
),
)
) );
);
$timeout = (int) floor( $r['timeout'] );
$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
$timeout = (int) floor( $r['timeout'] );
$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
$connect_timeout = max( $timeout, 1 );
// Store error number.
@ -129,52 +133,58 @@ class WP_Http_Streams {
// Store error string.
$connection_error_str = null;
if ( !WP_DEBUG ) {
if ( ! WP_DEBUG ) {
// In the event that the SSL connection fails, silence the many PHP Warnings.
if ( $secure_transport )
$error_reporting = error_reporting(0);
if ( $secure_transport ) {
$error_reporting = error_reporting( 0 );
}
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
$handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
else
} else {
$handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
}
if ( $secure_transport )
if ( $secure_transport ) {
error_reporting( $error_reporting );
}
} else {
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
$handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
else
} else {
$handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
}
}
if ( false === $handle ) {
// SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str ) {
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
}
return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
return new WP_Error( 'http_request_failed', $connection_error . ': ' . $connection_error_str );
}
// Verify that the SSL certificate is valid for this request.
if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) ) {
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
}
}
stream_set_timeout( $handle, $timeout, $utimeout );
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { //Some proxies require full URL in this field.
$requestPath = $url;
else
$requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
} else {
$requestPath = $arrURL['path'] . ( isset( $arrURL['query'] ) ? '?' . $arrURL['query'] : '' );
}
$strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
$strHeaders = strtoupper( $r['method'] ) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
$include_port_in_host_header = (
( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) ||
( 'http' == $arrURL['scheme'] && 80 != $arrURL['port'] ) ||
( 'http' == $arrURL['scheme'] && 80 != $arrURL['port'] ) ||
( 'https' == $arrURL['scheme'] && 443 != $arrURL['port'] )
);
@ -184,63 +194,80 @@ class WP_Http_Streams {
$strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
}
if ( isset($r['user-agent']) )
if ( isset( $r['user-agent'] ) ) {
$strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
}
if ( is_array($r['headers']) ) {
foreach ( (array) $r['headers'] as $header => $headerValue )
if ( is_array( $r['headers'] ) ) {
foreach ( (array) $r['headers'] as $header => $headerValue ) {
$strHeaders .= $header . ': ' . $headerValue . "\r\n";
}
} else {
$strHeaders .= $r['headers'];
}
if ( $proxy->use_authentication() )
if ( $proxy->use_authentication() ) {
$strHeaders .= $proxy->authentication_header() . "\r\n";
}
$strHeaders .= "\r\n";
if ( ! is_null($r['body']) )
if ( ! is_null( $r['body'] ) ) {
$strHeaders .= $r['body'];
}
fwrite($handle, $strHeaders);
fwrite( $handle, $strHeaders );
if ( ! $r['blocking'] ) {
stream_set_blocking( $handle, 0 );
fclose( $handle );
return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
);
}
$strResponse = '';
$bodyStarted = false;
$strResponse = '';
$bodyStarted = false;
$keep_reading = true;
$block_size = 4096;
if ( isset( $r['limit_response_size'] ) )
$block_size = 4096;
if ( isset( $r['limit_response_size'] ) ) {
$block_size = min( $block_size, $r['limit_response_size'] );
}
// If streaming to a file setup the file handle.
if ( $r['stream'] ) {
if ( ! WP_DEBUG )
if ( ! WP_DEBUG ) {
$stream_handle = @fopen( $r['filename'], 'w+' );
else
} else {
$stream_handle = fopen( $r['filename'], 'w+' );
}
if ( ! $stream_handle ) {
return new WP_Error( 'http_request_failed', sprintf(
/* translators: 1: fopen() 2: file name */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$r['filename']
) );
return new WP_Error(
'http_request_failed',
sprintf(
/* translators: 1: fopen(), 2: file name */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$r['filename']
)
);
}
$bytes_written = 0;
while ( ! feof($handle) && $keep_reading ) {
while ( ! feof( $handle ) && $keep_reading ) {
$block = fread( $handle, $block_size );
if ( ! $bodyStarted ) {
$strResponse .= $block;
if ( strpos( $strResponse, "\r\n\r\n" ) ) {
$process = WP_Http::processResponse( $strResponse );
$process = WP_Http::processResponse( $strResponse );
$bodyStarted = true;
$block = $process['body'];
$block = $process['body'];
unset( $strResponse );
$process['body'] = '';
}
@ -250,7 +277,7 @@ class WP_Http_Streams {
if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] ) {
$this_block_size = ( $r['limit_response_size'] - $bytes_written );
$block = substr( $block, 0, $this_block_size );
$block = substr( $block, 0, $this_block_size );
}
$bytes_written_to_file = fwrite( $stream_handle, $block );
@ -263,7 +290,7 @@ class WP_Http_Streams {
$bytes_written += $bytes_written_to_file;
$keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
$keep_reading = ! isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
}
fclose( $stream_handle );
@ -271,13 +298,13 @@ class WP_Http_Streams {
} else {
$header_length = 0;
while ( ! feof( $handle ) && $keep_reading ) {
$block = fread( $handle, $block_size );
$block = fread( $handle, $block_size );
$strResponse .= $block;
if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
$header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
$bodyStarted = true;
$bodyStarted = true;
}
$keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
$keep_reading = ( ! $bodyStarted || ! isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
}
$process = WP_Http::processResponse( $strResponse );
@ -290,27 +317,31 @@ class WP_Http_Streams {
$arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
$response = array(
'headers' => $arrHeaders['headers'],
'headers' => $arrHeaders['headers'],
// Not yet processed.
'body' => null,
'body' => null,
'response' => $arrHeaders['response'],
'cookies' => $arrHeaders['cookies'],
'filename' => $r['filename']
'cookies' => $arrHeaders['cookies'],
'filename' => $r['filename'],
);
// Handle redirects.
if ( false !== ( $redirect_response = WP_Http::handle_redirects( $url, $r, $response ) ) )
if ( false !== ( $redirect_response = WP_Http::handle_redirects( $url, $r, $response ) ) ) {
return $redirect_response;
}
// If the body was chunk encoded, then decode it.
if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
$process['body'] = WP_Http::chunkTransferDecode($process['body']);
if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] ) {
$process['body'] = WP_Http::chunkTransferDecode( $process['body'] );
}
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode( $arrHeaders['headers'] ) ) {
$process['body'] = WP_Http_Encoding::decompress( $process['body'] );
}
if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] ) {
$process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
}
$response['body'] = $process['body'];
@ -328,7 +359,6 @@ class WP_Http_Streams {
* IP Address support is included if the request is being made to an IP address.
*
* @since 3.7.0
* @static
*
* @param stream $stream The PHP Stream which the SSL request is being made over
* @param string $host The hostname being requested
@ -337,12 +367,14 @@ class WP_Http_Streams {
public static function verify_ssl_certificate( $stream, $host ) {
$context_options = stream_context_get_options( $stream );
if ( empty( $context_options['ssl']['peer_certificate'] ) )
if ( empty( $context_options['ssl']['peer_certificate'] ) ) {
return false;
}
$cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
if ( ! $cert )
if ( ! $cert ) {
return false;
}
/*
* If the request is being made to an IP address, we'll validate against IP fields
@ -355,25 +387,29 @@ class WP_Http_Streams {
$match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
foreach ( $match_against as $match ) {
list( $match_type, $match_host ) = explode( ':', $match );
if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
if ( $host_type == strtolower( trim( $match_type ) ) ) { // IP: or DNS:
$certificate_hostnames[] = strtolower( trim( $match_host ) );
}
}
} elseif ( !empty( $cert['subject']['CN'] ) ) {
} elseif ( ! empty( $cert['subject']['CN'] ) ) {
// Only use the CN when the certificate includes no subjectAltName extension.
$certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
}
// Exact hostname/IP matches.
if ( in_array( strtolower( $host ), $certificate_hostnames ) )
if ( in_array( strtolower( $host ), $certificate_hostnames ) ) {
return true;
}
// IP's can't be wildcards, Stop processing.
if ( 'ip' == $host_type )
if ( 'ip' == $host_type ) {
return false;
}
// Test to see if the domain is at least 2 deep for wildcard support.
if ( substr_count( $host, '.' ) < 2 )
if ( substr_count( $host, '.' ) < 2 ) {
return false;
}
// Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
$wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
@ -384,7 +420,6 @@ class WP_Http_Streams {
/**
* Determines whether this class can be used for retrieving a URL.
*
* @static
* @since 2.7.0
* @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
*
@ -392,16 +427,19 @@ class WP_Http_Streams {
* @return bool False means this class can not be used, true means it can.
*/
public static function test( $args = array() ) {
if ( ! function_exists( 'stream_socket_client' ) )
if ( ! function_exists( 'stream_socket_client' ) ) {
return false;
}
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
if ( ! extension_loaded( 'openssl' ) )
if ( ! extension_loaded( 'openssl' ) ) {
return false;
if ( ! function_exists( 'openssl_x509_parse' ) )
}
if ( ! function_exists( 'openssl_x509_parse' ) ) {
return false;
}
}
/**

View file

@ -33,19 +33,18 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param array $args
* @return bool
*/
public static function test( $args = array() ) {
if ( ! extension_loaded('gd') || ! function_exists('gd_info') )
if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) ) {
return false;
}
// On some setups GD library does not provide imagerotate() - Ticket #11536
if ( isset( $args['methods'] ) &&
in_array( 'rotate', $args['methods'] ) &&
! function_exists('imagerotate') ){
in_array( 'rotate', $args['methods'] ) &&
! function_exists( 'imagerotate' ) ) {
return false;
}
@ -58,20 +57,18 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param string $mime_type
* @return bool
*/
public static function supports_mime_type( $mime_type ) {
$image_types = imagetypes();
switch( $mime_type ) {
switch ( $mime_type ) {
case 'image/jpeg':
return ($image_types & IMG_JPG) != 0;
return ( $image_types & IMG_JPG ) != 0;
case 'image/png':
return ($image_types & IMG_PNG) != 0;
return ( $image_types & IMG_PNG ) != 0;
case 'image/gif':
return ($image_types & IMG_GIF) != 0;
return ( $image_types & IMG_GIF ) != 0;
}
return false;
@ -85,23 +82,27 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return bool|WP_Error True if loaded successfully; WP_Error on failure.
*/
public function load() {
if ( $this->image )
if ( $this->image ) {
return true;
}
if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
return new WP_Error( 'error_loading_image', __('File doesn&#8217;t exist?'), $this->file );
if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
return new WP_Error( 'error_loading_image', __( 'File doesn&#8217;t exist?' ), $this->file );
}
// Set artificially high because GD uses uncompressed images in memory.
wp_raise_memory_limit( 'image' );
$this->image = @imagecreatefromstring( file_get_contents( $this->file ) );
if ( ! is_resource( $this->image ) )
return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file );
if ( ! is_resource( $this->image ) ) {
return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
}
$size = @getimagesize( $this->file );
if ( ! $size )
return new WP_Error( 'invalid_image', __('Could not read image size.'), $this->file );
if ( ! $size ) {
return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
}
if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
imagealphablending( $this->image, false );
@ -124,11 +125,13 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return true
*/
protected function update_size( $width = false, $height = false ) {
if ( ! $width )
if ( ! $width ) {
$width = imagesx( $this->image );
}
if ( ! $height )
if ( ! $height ) {
$height = imagesy( $this->image );
}
return parent::update_size( $width, $height );
}
@ -149,8 +152,9 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return true|WP_Error
*/
public function resize( $max_w, $max_h, $crop = false ) {
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
return true;
}
$resized = $this->_resize( $max_w, $max_h, $crop );
@ -159,14 +163,14 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
$this->image = $resized;
return true;
} elseif ( is_wp_error( $resized ) )
} elseif ( is_wp_error( $resized ) ) {
return $resized;
}
return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
}
/**
*
* @param int $max_w
* @param int $max_h
* @param bool|array $crop
@ -175,7 +179,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
protected function _resize( $max_w, $max_h, $crop = false ) {
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
if ( ! $dims ) {
return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file );
return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
}
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
@ -187,7 +191,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
return $resized;
}
return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
}
/**
@ -213,7 +217,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return array An array of resized images' metadata by size.
*/
public function multi_resize( $sizes ) {
$metadata = array();
$metadata = array();
$orig_size = $this->size;
foreach ( $sizes as $size => $size_data ) {
@ -232,7 +236,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
$size_data['crop'] = false;
}
$image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
$image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
$duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
if ( ! is_wp_error( $image ) && ! $duplicate ) {
@ -242,7 +246,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
if ( ! is_wp_error( $resized ) && $resized ) {
unset( $resized['path'] );
$metadata[$size] = $resized;
$metadata[ $size ] = $resized;
}
}
@ -269,10 +273,12 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
// If destination width/height isn't specified, use same as
// width/height from source.
if ( ! $dst_w )
if ( ! $dst_w ) {
$dst_w = $src_w;
if ( ! $dst_h )
}
if ( ! $dst_h ) {
$dst_h = $src_h;
}
$dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
@ -281,8 +287,9 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
$src_h -= $src_y;
}
if ( function_exists( 'imageantialias' ) )
if ( function_exists( 'imageantialias' ) ) {
imageantialias( $dst, true );
}
imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
@ -293,7 +300,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
return true;
}
return new WP_Error( 'image_crop_error', __('Image crop failed.'), $this->file );
return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
}
/**
@ -306,9 +313,9 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return true|WP_Error
*/
public function rotate( $angle ) {
if ( function_exists('imagerotate') ) {
if ( function_exists( 'imagerotate' ) ) {
$transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
$rotated = imagerotate( $this->image, $angle, $transparency );
$rotated = imagerotate( $this->image, $angle, $transparency );
if ( is_resource( $rotated ) ) {
imagealphablending( $rotated, true );
@ -319,7 +326,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
return true;
}
}
return new WP_Error( 'image_rotate_error', __('Image rotate failed.'), $this->file );
return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
}
/**
@ -327,18 +334,18 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
*
* @since 3.5.0
*
* @param bool $horz Flip along Horizontal Axis
* @param bool $vert Flip along Vertical Axis
* @param bool $horz Flip along Horizontal Axis.
* @param bool $vert Flip along Vertical Axis.
* @return true|WP_Error
*/
public function flip( $horz, $vert ) {
$w = $this->size['width'];
$h = $this->size['height'];
$w = $this->size['width'];
$h = $this->size['height'];
$dst = wp_imagecreatetruecolor( $w, $h );
if ( is_resource( $dst ) ) {
$sx = $vert ? ($w - 1) : 0;
$sy = $horz ? ($h - 1) : 0;
$sx = $vert ? ( $w - 1 ) : 0;
$sy = $horz ? ( $h - 1 ) : 0;
$sw = $vert ? -$w : $w;
$sh = $horz ? -$h : $h;
@ -348,7 +355,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
return true;
}
}
return new WP_Error( 'image_flip_error', __('Image flip failed.'), $this->file );
return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
}
/**
@ -364,7 +371,7 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
$saved = $this->_save( $this->image, $filename, $mime_type );
if ( ! is_wp_error( $saved ) ) {
$this->file = $saved['path'];
$this->file = $saved['path'];
$this->mime_type = $saved['mime-type'];
}
@ -380,31 +387,33 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
protected function _save( $image, $filename = null, $mime_type = null ) {
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
if ( ! $filename )
if ( ! $filename ) {
$filename = $this->generate_filename( null, null, $extension );
}
if ( 'image/gif' == $mime_type ) {
if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) )
return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
}
elseif ( 'image/png' == $mime_type ) {
if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} elseif ( 'image/png' == $mime_type ) {
// convert from full colors to index colors, like original PNG.
if ( function_exists('imageistruecolor') && ! imageistruecolor( $image ) )
if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
}
if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) )
return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
}
elseif ( 'image/jpeg' == $mime_type ) {
if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) )
return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
}
else {
return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} elseif ( 'image/jpeg' == $mime_type ) {
if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} else {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
// Set correct file permissions
$stat = stat( dirname( $filename ) );
$stat = stat( dirname( $filename ) );
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
@ chmod( $filename, $perms );
@ -459,8 +468,9 @@ class WP_Image_Editor_GD extends WP_Image_Editor {
* @return bool
*/
protected function make_image( $filename, $function, $arguments ) {
if ( wp_is_stream( $filename ) )
if ( wp_is_stream( $filename ) ) {
$arguments[1] = null;
}
return parent::make_image( $filename, $function, $arguments );
}

View file

@ -37,19 +37,19 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param array $args
* @return bool
*/
public static function test( $args = array() ) {
// First, test Imagick's extension and classes.
if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) )
if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) ) {
return false;
}
if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) )
if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) ) {
return false;
}
$required_methods = array(
'clear',
@ -74,8 +74,9 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
);
// Now, test for deep requirements within Imagick.
if ( ! defined( 'imagick::COMPRESSION_JPEG' ) )
if ( ! defined( 'imagick::COMPRESSION_JPEG' ) ) {
return false;
}
$class_methods = array_map( 'strtolower', get_class_methods( 'Imagick' ) );
if ( array_diff( $required_methods, $class_methods ) ) {
@ -95,26 +96,25 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param string $mime_type
* @return bool
*/
public static function supports_mime_type( $mime_type ) {
$imagick_extension = strtoupper( self::get_extension( $mime_type ) );
if ( ! $imagick_extension )
if ( ! $imagick_extension ) {
return false;
}
// setIteratorIndex is optional unless mime is an animated format.
// Here, we just say no if you are missing it and aren't loading a jpeg.
if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && $mime_type != 'image/jpeg' )
if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && $mime_type != 'image/jpeg' ) {
return false;
}
try {
return ( (bool) @Imagick::queryFormats( $imagick_extension ) );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return false;
}
}
@ -127,11 +127,13 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
* @return true|WP_Error True if loaded; WP_Error on failure.
*/
public function load() {
if ( $this->image instanceof Imagick )
if ( $this->image instanceof Imagick ) {
return true;
}
if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
return new WP_Error( 'error_loading_image', __('File doesn&#8217;t exist?'), $this->file );
if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
return new WP_Error( 'error_loading_image', __( 'File doesn&#8217;t exist?' ), $this->file );
}
/*
* Even though Imagick uses less PHP memory than GD, set higher limit
@ -140,9 +142,9 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
wp_raise_memory_limit( 'image' );
try {
$this->image = new Imagick();
$this->image = new Imagick();
$file_extension = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) );
$filename = $this->file;
$filename = $this->file;
if ( 'pdf' == $file_extension ) {
$filename = $this->pdf_setup();
@ -152,16 +154,17 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
// only applies correctly before the image is read.
$this->image->readImage( $filename );
if ( ! $this->image->valid() )
return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file);
if ( ! $this->image->valid() ) {
return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
}
// Select the first frame to handle animated images properly
if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) )
$this->image->setIteratorIndex(0);
if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) ) {
$this->image->setIteratorIndex( 0 );
}
$this->mime_type = $this->get_mime_type( $this->image->getImageFormat() );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'invalid_image', $e->getMessage(), $this->file );
}
@ -193,12 +196,10 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
if ( 'image/jpeg' == $this->mime_type ) {
$this->image->setImageCompressionQuality( $quality );
$this->image->setImageCompression( imagick::COMPRESSION_JPEG );
}
else {
} else {
$this->image->setImageCompressionQuality( $quality );
}
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_quality_error', $e->getMessage() );
}
@ -217,20 +218,21 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
*/
protected function update_size( $width = null, $height = null ) {
$size = null;
if ( !$width || !$height ) {
if ( ! $width || ! $height ) {
try {
$size = $this->image->getImageGeometry();
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
}
}
if ( ! $width )
if ( ! $width ) {
$width = $size['width'];
}
if ( ! $height )
if ( ! $height ) {
$height = $size['height'];
}
return parent::update_size( $width, $height );
}
@ -250,12 +252,14 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
* @return bool|WP_Error
*/
public function resize( $max_w, $max_h, $crop = false ) {
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
return true;
}
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
if ( ! $dims )
return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
if ( ! $dims ) {
return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ) );
}
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
if ( $crop ) {
@ -335,7 +339,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
* unless we would be resampling to a scale smaller than 128x128.
*/
if ( is_callable( array( $this->image, 'sampleImage' ) ) ) {
$resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
$resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
$sample_factor = 5;
if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) {
@ -398,9 +402,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
if ( is_callable( array( $this->image, 'setInterlaceScheme' ) ) && defined( 'Imagick::INTERLACE_NO' ) ) {
$this->image->setInterlaceScheme( Imagick::INTERLACE_NO );
}
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_resize_error', $e->getMessage() );
}
}
@ -428,13 +430,14 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
* @return array An array of resized images' metadata by size.
*/
public function multi_resize( $sizes ) {
$metadata = array();
$orig_size = $this->size;
$metadata = array();
$orig_size = $this->size;
$orig_image = $this->image->getImage();
foreach ( $sizes as $size => $size_data ) {
if ( ! $this->image )
if ( ! $this->image ) {
$this->image = $orig_image->getImage();
}
if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
continue;
@ -452,7 +455,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
}
$resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
$duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
$duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
$resized = $this->_save( $this->image );
@ -463,7 +466,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
if ( ! is_wp_error( $resized ) && $resized ) {
unset( $resized['path'] );
$metadata[$size] = $resized;
$metadata[ $size ] = $resized;
}
}
@ -497,15 +500,17 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
try {
$this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
$this->image->setImagePage( $src_w, $src_h, 0, 0);
$this->image->setImagePage( $src_w, $src_h, 0, 0 );
if ( $dst_w || $dst_h ) {
// If destination width/height isn't specified, use same as
// width/height from source.
if ( ! $dst_w )
if ( ! $dst_w ) {
$dst_w = $src_w;
if ( ! $dst_h )
}
if ( ! $dst_h ) {
$dst_h = $src_h;
}
$thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
if ( is_wp_error( $thumb_result ) ) {
@ -514,8 +519,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
return $this->update_size();
}
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_crop_error', $e->getMessage() );
}
return $this->update_size();
@ -535,7 +539,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
* (GD rotates counter-clockwise)
*/
try {
$this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
$this->image->rotateImage( new ImagickPixel( 'none' ), 360 - $angle );
// Normalise Exif orientation data so that display is consistent across devices.
if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) {
@ -544,12 +548,12 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
// Since this changes the dimensions of the image, update the size.
$result = $this->update_size();
if ( is_wp_error( $result ) )
if ( is_wp_error( $result ) ) {
return $result;
}
$this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_rotate_error', $e->getMessage() );
}
return true;
@ -566,13 +570,14 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
*/
public function flip( $horz, $vert ) {
try {
if ( $horz )
if ( $horz ) {
$this->image->flipImage();
}
if ( $vert )
if ( $vert ) {
$this->image->flopImage();
}
catch ( Exception $e ) {
}
} catch ( Exception $e ) {
return new WP_Error( 'image_flip_error', $e->getMessage() );
}
return true;
@ -591,13 +596,12 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
$saved = $this->_save( $this->image, $destfilename, $mime_type );
if ( ! is_wp_error( $saved ) ) {
$this->file = $saved['path'];
$this->file = $saved['path'];
$this->mime_type = $saved['mime-type'];
try {
$this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
}
}
@ -606,7 +610,6 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
}
/**
*
* @param Imagick $image
* @param string $filename
* @param string $mime_type
@ -615,8 +618,9 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
protected function _save( $image, $filename = null, $mime_type = null ) {
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
if ( ! $filename )
if ( ! $filename ) {
$filename = $this->generate_filename( null, null, $extension );
}
try {
// Store initial Format
@ -627,13 +631,12 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
// Reset original Format
$this->image->setImageFormat( $orig_format );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
}
// Set correct file permissions
$stat = stat( dirname( $filename ) );
$stat = stat( dirname( $filename ) );
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
@ chmod( $filename, $perms );
@ -668,8 +671,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
// Reset Image to original Format
$this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'image_stream_error', $e->getMessage() );
}
@ -719,7 +721,6 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
$this->image->removeImageProfile( $key );
}
}
} catch ( Exception $e ) {
return new WP_Error( 'image_strip_meta_error', $e->getMessage() );
}
@ -743,8 +744,7 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor {
// Only load the first page.
return $this->file . '[0]';
}
catch ( Exception $e ) {
} catch ( Exception $e ) {
return new WP_Error( 'pdf_setup_failed', $e->getMessage(), $this->file );
}
}

View file

@ -12,12 +12,12 @@
* @since 3.5.0
*/
abstract class WP_Image_Editor {
protected $file = null;
protected $size = null;
protected $mime_type = null;
protected $file = null;
protected $size = null;
protected $mime_type = null;
protected $default_mime_type = 'image/jpeg';
protected $quality = false;
protected $default_quality = 82;
protected $quality = false;
protected $default_quality = 82;
/**
* Each instance handles a single file.
@ -34,7 +34,6 @@ abstract class WP_Image_Editor {
*
* @since 3.5.0
*
* @static
* @abstract
*
* @param array $args
@ -50,7 +49,6 @@ abstract class WP_Image_Editor {
*
* @since 3.5.0
*
* @static
* @abstract
*
* @param string $mime_type
@ -191,8 +189,8 @@ abstract class WP_Image_Editor {
*/
protected function update_size( $width = null, $height = null ) {
$this->size = array(
'width' => (int) $width,
'height' => (int) $height
'width' => (int) $width,
'height' => (int) $height,
);
return true;
}
@ -271,7 +269,7 @@ abstract class WP_Image_Editor {
$this->quality = $quality;
return true;
} else {
return new WP_Error( 'invalid_image_quality', __('Attempted to set image quality outside of the range [1,100].') );
return new WP_Error( 'invalid_image_quality', __( 'Attempted to set image quality outside of the range [1,100].' ) );
}
}
@ -298,12 +296,11 @@ abstract class WP_Image_Editor {
}
if ( $filename ) {
$file_ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
$file_ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
$file_mime = $this->get_mime_type( $file_ext );
}
else {
} else {
// If no file specified, grab editor's current extension and mime-type.
$file_ext = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) );
$file_ext = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) );
$file_mime = $this->mime_type;
}
@ -311,7 +308,7 @@ abstract class WP_Image_Editor {
// file extension. If so, prefer extension from file.
if ( ! $mime_type || ( $file_mime == $mime_type ) ) {
$mime_type = $file_mime;
$new_ext = $file_ext;
$new_ext = $file_ext;
}
// Double-check that the mime-type selected is supported by the editor.
@ -327,7 +324,7 @@ abstract class WP_Image_Editor {
* @param string $mime_type Mime type string.
*/
$mime_type = apply_filters( 'image_editor_default_mime_type', $this->default_mime_type );
$new_ext = $this->get_extension( $mime_type );
$new_ext = $this->get_extension( $mime_type );
}
if ( $filename ) {
@ -352,17 +349,19 @@ abstract class WP_Image_Editor {
*/
public function generate_filename( $suffix = null, $dest_path = null, $extension = null ) {
// $suffix will be appended to the destination filename, just before the extension
if ( ! $suffix )
if ( ! $suffix ) {
$suffix = $this->get_suffix();
}
$dir = pathinfo( $this->file, PATHINFO_DIRNAME );
$ext = pathinfo( $this->file, PATHINFO_EXTENSION );
$dir = pathinfo( $this->file, PATHINFO_DIRNAME );
$ext = pathinfo( $this->file, PATHINFO_EXTENSION );
$name = wp_basename( $this->file, ".$ext" );
$name = wp_basename( $this->file, ".$ext" );
$new_ext = strtolower( $extension ? $extension : $ext );
if ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) )
if ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) ) {
$dir = $_dest_path;
}
return trailingslashit( $dir ) . "{$name}-{$suffix}.{$new_ext}";
}
@ -375,8 +374,9 @@ abstract class WP_Image_Editor {
* @return false|string suffix
*/
public function get_suffix() {
if ( ! $this->get_size() )
if ( ! $this->get_size() ) {
return false;
}
return "{$this->size['width']}x{$this->size['height']}";
}
@ -428,21 +428,20 @@ abstract class WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param string $extension
* @return string|false
*/
protected static function get_mime_type( $extension = null ) {
if ( ! $extension )
if ( ! $extension ) {
return false;
}
$mime_types = wp_get_mime_types();
$extensions = array_keys( $mime_types );
foreach ( $extensions as $_extension ) {
if ( preg_match( "/{$extension}/i", $_extension ) ) {
return $mime_types[$_extension];
return $mime_types[ $_extension ];
}
}
@ -455,16 +454,15 @@ abstract class WP_Image_Editor {
*
* @since 3.5.0
*
* @static
*
* @param string $mime_type
* @return string|false
*/
protected static function get_extension( $mime_type = null ) {
$extensions = explode( '|', array_search( $mime_type, wp_get_mime_types() ) );
if ( empty( $extensions[0] ) )
if ( empty( $extensions[0] ) ) {
return false;
}
return $extensions[0];
}

View file

@ -97,7 +97,7 @@ class WP_List_Util {
return array();
}
$count = count( $args );
$count = count( $args );
$filtered = array();
foreach ( $this->output as $key => $obj ) {
@ -115,7 +115,7 @@ class WP_List_Util {
( 'OR' == $operator && $matched > 0 ) ||
( 'NOT' == $operator && 0 == $matched )
) {
$filtered[$key] = $obj;
$filtered[ $key ] = $obj;
}
}
@ -140,6 +140,8 @@ class WP_List_Util {
* `$list` will be preserved in the results.
*/
public function pluck( $field, $index_key = null ) {
$newlist = array();
if ( ! $index_key ) {
/*
* This is simple. Could at some point wrap array_column()
@ -147,11 +149,14 @@ class WP_List_Util {
*/
foreach ( $this->output as $key => $value ) {
if ( is_object( $value ) ) {
$this->output[ $key ] = $value->$field;
$newlist[ $key ] = $value->$field;
} else {
$this->output[ $key ] = $value[ $field ];
$newlist[ $key ] = $value[ $field ];
}
}
$this->output = $newlist;
return $this->output;
}
@ -159,7 +164,6 @@ class WP_List_Util {
* When index_key is not set for a particular item, push the value
* to the end of the stack. This is how array_column() behaves.
*/
$newlist = array();
foreach ( $this->output as $value ) {
if ( is_object( $value ) ) {
if ( isset( $value->$index_key ) ) {

View file

@ -53,6 +53,8 @@ class WP_Locale_Switcher {
* Initializes the locale switcher.
*
* Hooks into the {@see 'locale'} filter to change the locale on the fly.
*
* @since 4.7.0
*/
public function init() {
add_filter( 'locale', array( $this, 'filter_locale' ) );

View file

@ -43,14 +43,6 @@ class WP_Locale {
*/
public $weekday_abbrev;
/**
* Stores the default start of the week.
*
* @since 4.4.0
* @var string
*/
public $start_of_week;
/**
* Stores the translated strings for the full month names.
*
@ -126,13 +118,13 @@ class WP_Locale {
*/
public function init() {
// The Weekdays
$this->weekday[0] = /* translators: weekday */ __('Sunday');
$this->weekday[1] = /* translators: weekday */ __('Monday');
$this->weekday[2] = /* translators: weekday */ __('Tuesday');
$this->weekday[3] = /* translators: weekday */ __('Wednesday');
$this->weekday[4] = /* translators: weekday */ __('Thursday');
$this->weekday[5] = /* translators: weekday */ __('Friday');
$this->weekday[6] = /* translators: weekday */ __('Saturday');
$this->weekday[0] = /* translators: weekday */ __( 'Sunday' );
$this->weekday[1] = /* translators: weekday */ __( 'Monday' );
$this->weekday[2] = /* translators: weekday */ __( 'Tuesday' );
$this->weekday[3] = /* translators: weekday */ __( 'Wednesday' );
$this->weekday[4] = /* translators: weekday */ __( 'Thursday' );
$this->weekday[5] = /* translators: weekday */ __( 'Friday' );
$this->weekday[6] = /* translators: weekday */ __( 'Saturday' );
// The first letter of each day.
$this->weekday_initial[ __( 'Sunday' ) ] = /* translators: one-letter abbreviation of the weekday */ _x( 'S', 'Sunday initial' );
@ -144,13 +136,13 @@ class WP_Locale {
$this->weekday_initial[ __( 'Saturday' ) ] = /* translators: one-letter abbreviation of the weekday */ _x( 'S', 'Saturday initial' );
// Abbreviations for each day.
$this->weekday_abbrev[__('Sunday')] = /* translators: three-letter abbreviation of the weekday */ __('Sun');
$this->weekday_abbrev[__('Monday')] = /* translators: three-letter abbreviation of the weekday */ __('Mon');
$this->weekday_abbrev[__('Tuesday')] = /* translators: three-letter abbreviation of the weekday */ __('Tue');
$this->weekday_abbrev[__('Wednesday')] = /* translators: three-letter abbreviation of the weekday */ __('Wed');
$this->weekday_abbrev[__('Thursday')] = /* translators: three-letter abbreviation of the weekday */ __('Thu');
$this->weekday_abbrev[__('Friday')] = /* translators: three-letter abbreviation of the weekday */ __('Fri');
$this->weekday_abbrev[__('Saturday')] = /* translators: three-letter abbreviation of the weekday */ __('Sat');
$this->weekday_abbrev[ __( 'Sunday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Sun' );
$this->weekday_abbrev[ __( 'Monday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Mon' );
$this->weekday_abbrev[ __( 'Tuesday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Tue' );
$this->weekday_abbrev[ __( 'Wednesday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Wed' );
$this->weekday_abbrev[ __( 'Thursday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Thu' );
$this->weekday_abbrev[ __( 'Friday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Fri' );
$this->weekday_abbrev[ __( 'Saturday' ) ] = /* translators: three-letter abbreviation of the weekday */ __( 'Sat' );
// The Months
$this->month['01'] = /* translators: month name */ __( 'January' );
@ -195,10 +187,10 @@ class WP_Locale {
$this->month_abbrev[ __( 'December' ) ] = /* translators: three-letter abbreviation of the month */ _x( 'Dec', 'December abbreviation' );
// The Meridiems
$this->meridiem['am'] = __('am');
$this->meridiem['pm'] = __('pm');
$this->meridiem['AM'] = __('AM');
$this->meridiem['PM'] = __('PM');
$this->meridiem['am'] = __( 'am' );
$this->meridiem['pm'] = __( 'pm' );
$this->meridiem['AM'] = __( 'AM' );
$this->meridiem['PM'] = __( 'PM' );
// Numbers formatting
// See https://secure.php.net/number_format
@ -222,11 +214,13 @@ class WP_Locale {
$this->number_format['decimal_point'] = ( 'number_format_decimal_point' === $decimal_point ) ? '.' : $decimal_point;
// Set text direction.
if ( isset( $GLOBALS['text_direction'] ) )
if ( isset( $GLOBALS['text_direction'] ) ) {
$this->text_direction = $GLOBALS['text_direction'];
/* translators: 'rtl' or 'ltr'. This sets the text direction for WordPress. */
elseif ( 'rtl' == _x( 'ltr', 'text direction' ) )
/* translators: 'rtl' or 'ltr'. This sets the text direction for WordPress. */
} elseif ( 'rtl' == _x( 'ltr', 'text direction' ) ) {
$this->text_direction = 'rtl';
}
if ( 'rtl' === $this->text_direction && strpos( get_bloginfo( 'version' ), '-src' ) ) {
$this->text_direction = 'ltr';
@ -253,11 +247,11 @@ class WP_Locale {
*
* @since 2.1.0
*
* @param int $weekday_number 0 for Sunday through 6 Saturday
* @return string Full translated weekday
* @param int $weekday_number 0 for Sunday through 6 Saturday.
* @return string Full translated weekday.
*/
public function get_weekday($weekday_number) {
return $this->weekday[$weekday_number];
public function get_weekday( $weekday_number ) {
return $this->weekday[ $weekday_number ];
}
/**
@ -270,11 +264,11 @@ class WP_Locale {
*
* @since 2.1.0
*
* @param string $weekday_name
* @return string
* @param string $weekday_name Full translated weekday word.
* @return string Translated weekday initial.
*/
public function get_weekday_initial($weekday_name) {
return $this->weekday_initial[$weekday_name];
public function get_weekday_initial( $weekday_name ) {
return $this->weekday_initial[ $weekday_name ];
}
/**
@ -285,11 +279,11 @@ class WP_Locale {
*
* @since 2.1.0
*
* @param string $weekday_name Full translated weekday word
* @return string Translated weekday abbreviation
* @param string $weekday_name Full translated weekday word.
* @return string Translated weekday abbreviation.
*/
public function get_weekday_abbrev($weekday_name) {
return $this->weekday_abbrev[$weekday_name];
public function get_weekday_abbrev( $weekday_name ) {
return $this->weekday_abbrev[ $weekday_name ];
}
/**
@ -305,11 +299,11 @@ class WP_Locale {
*
* @since 2.1.0
*
* @param string|int $month_number '01' through '12'
* @return string Translated full month name
* @param string|int $month_number '01' through '12'.
* @return string Translated full month name.
*/
public function get_month($month_number) {
return $this->month[zeroise($month_number, 2)];
public function get_month( $month_number ) {
return $this->month[ zeroise( $month_number, 2 ) ];
}
/**
@ -320,11 +314,11 @@ class WP_Locale {
*
* @since 2.1.0
*
* @param string $month_name Translated month to get abbreviated version
* @return string Translated abbreviated month
* @param string $month_name Translated month to get abbreviated version.
* @return string Translated abbreviated month.
*/
public function get_month_abbrev($month_name) {
return $this->month_abbrev[$month_name];
public function get_month_abbrev( $month_name ) {
return $this->month_abbrev[ $month_name ];
}
/**
@ -337,8 +331,8 @@ class WP_Locale {
* @param string $meridiem Either 'am', 'pm', 'AM', or 'PM'. Not translated version.
* @return string Translated version
*/
public function get_meridiem($meridiem) {
return $this->meridiem[$meridiem];
public function get_meridiem( $meridiem ) {
return $this->meridiem[ $meridiem ];
}
/**

View file

@ -46,10 +46,10 @@ class WP_MatchesMapRegex {
* @param string $subject subject if regex
* @param array $matches data to use in map
*/
public function __construct($subject, $matches) {
public function __construct( $subject, $matches ) {
$this->_subject = $subject;
$this->_matches = $matches;
$this->output = $this->_map();
$this->output = $this->_map();
}
/**
@ -57,14 +57,12 @@ class WP_MatchesMapRegex {
*
* static helper function to ease use
*
* @static
*
* @param string $subject subject
* @param array $matches data used for substitution
* @return string
*/
public static function apply($subject, $matches) {
$oSelf = new WP_MatchesMapRegex($subject, $matches);
public static function apply( $subject, $matches ) {
$oSelf = new WP_MatchesMapRegex( $subject, $matches );
return $oSelf->output;
}
@ -74,8 +72,8 @@ class WP_MatchesMapRegex {
* @return string
*/
private function _map() {
$callback = array($this, 'callback');
return preg_replace_callback($this->_pattern, $callback, $this->_subject);
$callback = array( $this, 'callback' );
return preg_replace_callback( $this->_pattern, $callback, $this->_subject );
}
/**
@ -84,8 +82,8 @@ class WP_MatchesMapRegex {
* @param array $matches preg_replace regexp matches
* @return string
*/
public function callback($matches) {
$index = intval(substr($matches[0], 9, -1));
return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
public function callback( $matches ) {
$index = intval( substr( $matches[0], 9, -1 ) );
return ( isset( $this->_matches[ $index ] ) ? urlencode( $this->_matches[ $index ] ) : '' );
}
}

View file

@ -99,7 +99,7 @@ class WP_Meta_Query {
*
* @since 3.2.0
* @since 4.2.0 Introduced support for naming query clauses by associative array keys.
*
* @since 5.1.0 Introduced $compare_key clause parameter, which enables LIKE key matches.
*
* @param array $meta_query {
* Array of meta query clauses. When first-order clauses or sub-clauses use strings as
@ -110,23 +110,26 @@ class WP_Meta_Query {
* @type array {
* Optional. An array of first-order clause parameters, or another fully-formed meta query.
*
* @type string $key Meta key to filter by.
* @type string $value Meta value to filter by.
* @type string $compare MySQL operator used for comparing the $value. Accepts '=',
* '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE',
* 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'REGEXP',
* 'NOT REGEXP', 'RLIKE', 'EXISTS' or 'NOT EXISTS'.
* Default is 'IN' when `$value` is an array, '=' otherwise.
* @type string $type MySQL data type that the meta_value column will be CAST to for
* comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
* 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
* Default is 'CHAR'.
* @type string $key Meta key to filter by.
* @type string $compare_key MySQL operator used for comparing the $key. Accepts '=' and 'LIKE'.
* Default '='.
* @type string $value Meta value to filter by.
* @type string $compare MySQL operator used for comparing the $value. Accepts '=',
* '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE',
* 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'REGEXP',
* 'NOT REGEXP', 'RLIKE', 'EXISTS' or 'NOT EXISTS'.
* Default is 'IN' when `$value` is an array, '=' otherwise.
* @type string $type MySQL data type that the meta_value column will be CAST to for
* comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
* 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
* Default is 'CHAR'.
* }
* }
*/
public function __construct( $meta_query = false ) {
if ( !$meta_query )
if ( ! $meta_query ) {
return;
}
if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
$this->relation = 'OR';
@ -161,7 +164,7 @@ class WP_Meta_Query {
} elseif ( ! is_array( $query ) ) {
continue;
// First-order clause.
// First-order clause.
} elseif ( $this->is_first_order_clause( $query ) ) {
if ( isset( $query['value'] ) && array() === $query['value'] ) {
unset( $query['value'] );
@ -169,7 +172,7 @@ class WP_Meta_Query {
$clean_queries[ $key ] = $query;
// Otherwise, it's a nested query, so we recurse.
// Otherwise, it's a nested query, so we recurse.
} else {
$cleaned_query = $this->sanitize_query( $query );
@ -186,17 +189,17 @@ class WP_Meta_Query {
// Sanitize the 'relation' key provided in the query.
if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
$clean_queries['relation'] = 'OR';
$this->has_or_relation = true;
$this->has_or_relation = true;
/*
* If there is only a single clause, call the relation 'OR'.
* This value will not actually be used to join clauses, but it
* simplifies the logic around combining key-only queries.
*/
/*
* If there is only a single clause, call the relation 'OR'.
* This value will not actually be used to join clauses, but it
* simplifies the logic around combining key-only queries.
*/
} elseif ( 1 === count( $clean_queries ) ) {
$clean_queries['relation'] = 'OR';
// Default to AND.
// Default to AND.
} else {
$clean_queries['relation'] = 'AND';
}
@ -236,7 +239,7 @@ class WP_Meta_Query {
* the rest of the meta_query).
*/
$primary_meta_query = array();
foreach ( array( 'key', 'compare', 'type' ) as $key ) {
foreach ( array( 'key', 'compare', 'type', 'compare_key' ) as $key ) {
if ( ! empty( $qv[ "meta_$key" ] ) ) {
$primary_meta_query[ $key ] = $qv[ "meta_$key" ];
}
@ -275,16 +278,19 @@ class WP_Meta_Query {
* @return string MySQL type.
*/
public function get_cast_for_type( $type = '' ) {
if ( empty( $type ) )
if ( empty( $type ) ) {
return 'CHAR';
}
$meta_type = strtoupper( $type );
if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) ) {
return 'CHAR';
}
if ( 'NUMERIC' == $meta_type )
if ( 'NUMERIC' == $meta_type ) {
$meta_type = 'SIGNED';
}
return $meta_type;
}
@ -333,7 +339,7 @@ class WP_Meta_Query {
*
* @since 3.1.0
*
* @param array $clauses Array containing the query's JOIN and WHERE clauses.
* @param array $sql Array containing the query's JOIN and WHERE clauses.
* @param array $queries Array of meta queries.
* @param string $type Type of meta.
* @param string $primary_table Primary table.
@ -364,7 +370,7 @@ class WP_Meta_Query {
* To keep $this->queries unaltered, pass a copy.
*/
$queries = $this->queries;
$sql = $this->get_sql_for_query( $queries );
$sql = $this->get_sql_for_query( $queries );
if ( ! empty( $sql['where'] ) ) {
$sql['where'] = ' AND ' . $sql['where'];
@ -404,7 +410,7 @@ class WP_Meta_Query {
$indent = '';
for ( $i = 0; $i < $depth; $i++ ) {
$indent .= " ";
$indent .= ' ';
}
foreach ( $query as $key => &$clause ) {
@ -426,7 +432,7 @@ class WP_Meta_Query {
}
$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
// This is a subquery, so we recurse.
// This is a subquery, so we recurse.
} else {
$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
@ -482,7 +488,7 @@ class WP_Meta_Query {
$sql_chunks = array(
'where' => array(),
'join' => array(),
'join' => array(),
);
if ( isset( $clause['compare'] ) ) {
@ -491,18 +497,39 @@ class WP_Meta_Query {
$clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
}
if ( ! in_array( $clause['compare'], array(
'=', '!=', '>', '>=', '<', '<=',
'LIKE', 'NOT LIKE',
'IN', 'NOT IN',
'BETWEEN', 'NOT BETWEEN',
'EXISTS', 'NOT EXISTS',
'REGEXP', 'NOT REGEXP', 'RLIKE'
) ) ) {
if ( ! in_array(
$clause['compare'],
array(
'=',
'!=',
'>',
'>=',
'<',
'<=',
'LIKE',
'NOT LIKE',
'IN',
'NOT IN',
'BETWEEN',
'NOT BETWEEN',
'EXISTS',
'NOT EXISTS',
'REGEXP',
'NOT REGEXP',
'RLIKE',
)
) ) {
$clause['compare'] = '=';
}
$meta_compare = $clause['compare'];
if ( isset( $clause['compare_key'] ) && 'LIKE' === strtoupper( $clause['compare_key'] ) ) {
$clause['compare_key'] = strtoupper( $clause['compare_key'] );
} else {
$clause['compare_key'] = '=';
}
$meta_compare = $clause['compare'];
$meta_compare_key = $clause['compare_key'];
// First build the JOIN clause, if one is required.
$join = '';
@ -510,16 +537,21 @@ class WP_Meta_Query {
// We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
$alias = $this->find_compatible_table_alias( $clause, $parent_query );
if ( false === $alias ) {
$i = count( $this->table_aliases );
$i = count( $this->table_aliases );
$alias = $i ? 'mt' . $i : $this->meta_table;
// JOIN clauses for NOT EXISTS have their own syntax.
if ( 'NOT EXISTS' === $meta_compare ) {
$join .= " LEFT JOIN $this->meta_table";
$join .= $i ? " AS $alias" : '';
$join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
// All other JOIN clauses.
if ( 'LIKE' === $meta_compare_key ) {
$join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )", '%' . $wpdb->esc_like( $clause['key'] ) . '%' );
} else {
$join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
}
// All other JOIN clauses.
} else {
$join .= " INNER JOIN $this->meta_table";
$join .= $i ? " AS $alias" : '';
@ -527,15 +559,15 @@ class WP_Meta_Query {
}
$this->table_aliases[] = $alias;
$sql_chunks['join'][] = $join;
$sql_chunks['join'][] = $join;
}
// Save the alias to this clause, for future siblings to find.
$clause['alias'] = $alias;
// Determine the data type.
$_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
$meta_type = $this->get_cast_for_type( $_meta_type );
$_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
$meta_type = $this->get_cast_for_type( $_meta_type );
$clause['cast'] = $meta_type;
// Fallback for clause keys is the table alias. Key must be a string.
@ -544,7 +576,7 @@ class WP_Meta_Query {
}
// Ensure unique clause keys, so none are overwritten.
$iterator = 1;
$iterator = 1;
$clause_key_base = $clause_key;
while ( isset( $this->clauses[ $clause_key ] ) ) {
$clause_key = $clause_key_base . '-' . $iterator;
@ -561,7 +593,11 @@ class WP_Meta_Query {
if ( 'NOT EXISTS' === $meta_compare ) {
$sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
} else {
$sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
if ( 'LIKE' === $meta_compare_key ) {
$sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key LIKE %s", '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%' );
} else {
$sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
}
}
}
@ -578,36 +614,36 @@ class WP_Meta_Query {
}
switch ( $meta_compare ) {
case 'IN' :
case 'NOT IN' :
case 'IN':
case 'NOT IN':
$meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
$where = $wpdb->prepare( $meta_compare_string, $meta_value );
$where = $wpdb->prepare( $meta_compare_string, $meta_value );
break;
case 'BETWEEN' :
case 'NOT BETWEEN' :
case 'BETWEEN':
case 'NOT BETWEEN':
$meta_value = array_slice( $meta_value, 0, 2 );
$where = $wpdb->prepare( '%s AND %s', $meta_value );
$where = $wpdb->prepare( '%s AND %s', $meta_value );
break;
case 'LIKE' :
case 'NOT LIKE' :
case 'LIKE':
case 'NOT LIKE':
$meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
$where = $wpdb->prepare( '%s', $meta_value );
$where = $wpdb->prepare( '%s', $meta_value );
break;
// EXISTS with a value is interpreted as '='.
case 'EXISTS' :
case 'EXISTS':
$meta_compare = '=';
$where = $wpdb->prepare( '%s', $meta_value );
$where = $wpdb->prepare( '%s', $meta_value );
break;
// 'value' is ignored for NOT EXISTS.
case 'NOT EXISTS' :
case 'NOT EXISTS':
$where = '';
break;
default :
default:
$where = $wpdb->prepare( '%s', $meta_value );
break;
@ -687,7 +723,7 @@ class WP_Meta_Query {
if ( 'OR' === $parent_query['relation'] ) {
$compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
// Clauses joined by AND with "negative" operators share a join only if they also share a key.
// Clauses joined by AND with "negative" operators share a join only if they also share a key.
} elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
$compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
}
@ -710,7 +746,7 @@ class WP_Meta_Query {
* @param array $parent_query Parent of $clause.
* @param object $this WP_Meta_Query object.
*/
return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this );
}
/**

View file

@ -52,7 +52,7 @@ class WP_Metadata_Lazyloader {
*/
public function __construct() {
$this->settings = array(
'term' => array(
'term' => array(
'filter' => 'get_term_metadata',
'callback' => array( $this, 'lazyload_term_meta' ),
),
@ -97,7 +97,7 @@ class WP_Metadata_Lazyloader {
*
* @since 4.5.0
*
* @param array $object_ids Object IDs.
* @param array $object_ids Array of object IDs.
* @param string $object_type Type of object being queued.
* @param WP_Metadata_Lazyloader $lazyloader The lazy-loader object.
*/

View file

@ -91,25 +91,25 @@ class WP_Network_Query {
*
* @type array $network__in Array of network IDs to include. Default empty.
* @type array $network__not_in Array of network IDs to exclude. Default empty.
* @type bool $count Whether to return a network count (true) or array of network objects.
* Default false.
* @type string $fields Network fields to return. Accepts 'ids' (returns an array of network IDs)
* or empty (returns an array of complete network objects). Default empty.
* @type int $number Maximum number of networks to retrieve. Default empty (no limit).
* @type int $offset Number of networks to offset the query. Used to build LIMIT clause.
* Default 0.
* @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* @type string|array $orderby Network status or array of statuses. Accepts 'id', 'domain', 'path',
* 'domain_length', 'path_length' and 'network__in'. Also accepts false,
* an empty array, or 'none' to disable `ORDER BY` clause. Default 'id'.
* @type string $order How to order retrieved networks. Accepts 'ASC', 'DESC'. Default 'ASC'.
* @type string $domain Limit results to those affiliated with a given domain. Default empty.
* @type array $domain__in Array of domains to include affiliated networks for. Default empty.
* @type array $domain__not_in Array of domains to exclude affiliated networks for. Default empty.
* @type string $path Limit results to those affiliated with a given path. Default empty.
* @type array $path__in Array of paths to include affiliated networks for. Default empty.
* @type array $path__not_in Array of paths to exclude affiliated networks for. Default empty.
* @type string $search Search term(s) to retrieve matching networks for. Default empty.
* @type bool $count Whether to return a network count (true) or array of network objects.
* Default false.
* @type string $fields Network fields to return. Accepts 'ids' (returns an array of network IDs)
* or empty (returns an array of complete network objects). Default empty.
* @type int $number Maximum number of networks to retrieve. Default empty (no limit).
* @type int $offset Number of networks to offset the query. Used to build LIMIT clause.
* Default 0.
* @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* @type string|array $orderby Network status or array of statuses. Accepts 'id', 'domain', 'path',
* 'domain_length', 'path_length' and 'network__in'. Also accepts false,
* an empty array, or 'none' to disable `ORDER BY` clause. Default 'id'.
* @type string $order How to order retrieved networks. Accepts 'ASC', 'DESC'. Default 'ASC'.
* @type string $domain Limit results to those affiliated with a given domain. Default empty.
* @type array $domain__in Array of domains to include affiliated networks for. Default empty.
* @type array $domain__not_in Array of domains to exclude affiliated networks for. Default empty.
* @type string $path Limit results to those affiliated with a given path. Default empty.
* @type array $path__in Array of paths to include affiliated networks for. Default empty.
* @type array $path__not_in Array of paths to exclude affiliated networks for. Default empty.
* @type string $search Search term(s) to retrieve matching networks for. Default empty.
* @type bool $update_network_cache Whether to prime the cache for found networks. Default true.
* }
*/
@ -144,7 +144,6 @@ class WP_Network_Query {
*
* @since 4.6.0
*
*
* @param string|array $query WP_Network_Query arguments. See WP_Network_Query::__construct()
*/
public function parse_query( $query = '' ) {
@ -204,10 +203,10 @@ class WP_Network_Query {
// Ignore the $fields argument as the queried result will be the same regardless.
unset( $_args['fields'] );
$key = md5( serialize( $_args ) );
$key = md5( serialize( $_args ) );
$last_changed = wp_cache_get_last_changed( 'networks' );
$cache_key = "get_network_ids:$key:$last_changed";
$cache_key = "get_network_ids:$key:$last_changed";
$cache_value = wp_cache_get( $cache_key, 'networks' );
if ( false === $cache_value ) {
@ -217,12 +216,12 @@ class WP_Network_Query {
}
$cache_value = array(
'network_ids' => $network_ids,
'network_ids' => $network_ids,
'found_networks' => $this->found_networks,
);
wp_cache_add( $cache_key, $cache_value, 'networks' );
} else {
$network_ids = $cache_value['network_ids'];
$network_ids = $cache_value['network_ids'];
$this->found_networks = $cache_value['found_networks'];
}
@ -260,7 +259,7 @@ class WP_Network_Query {
*
* @since 4.6.0
*
* @param array $_networks An array of WP_Network objects.
* @param WP_Network[] $_networks An array of WP_Network objects.
* @param WP_Network_Query $this Current instance of WP_Network_Query (passed by reference).
*/
$_networks = apply_filters_ref_array( 'the_networks', array( $_networks, &$this ) );
@ -301,10 +300,10 @@ class WP_Network_Query {
if ( is_int( $_key ) ) {
$_orderby = $_value;
$_order = $order;
$_order = $order;
} else {
$_orderby = $_key;
$_order = $_value;
$_order = $_value;
}
$parsed = $this->parse_orderby( $_orderby );
@ -403,16 +402,16 @@ class WP_Network_Query {
*
* @since 4.6.0
*
* @param array $pieces A compacted array of network query clauses.
* @param string[] $pieces An associative array of network query clauses.
* @param WP_Network_Query $this Current instance of WP_Network_Query (passed by reference).
*/
$clauses = apply_filters_ref_array( 'networks_clauses', array( compact( $pieces ), &$this ) );
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
if ( $where ) {
@ -482,8 +481,8 @@ class WP_Network_Query {
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $string Search string.
* @param array $columns Columns to search.
* @param string $string Search string.
* @param string[] $columns Array of columns to search.
*
* @return string Search SQL.
*/
@ -522,9 +521,9 @@ class WP_Network_Query {
$parsed = false;
if ( $orderby == 'network__in' ) {
$network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
$parsed = "FIELD( {$wpdb->site}.id, $network__in )";
$parsed = "FIELD( {$wpdb->site}.id, $network__in )";
} elseif ( $orderby == 'domain_length' || $orderby == 'path_length' ) {
$field = substr( $orderby, 0, -7 );
$field = substr( $orderby, 0, -7 );
$parsed = "CHAR_LENGTH($wpdb->site.$field)";
} elseif ( in_array( $orderby, $allowed_keys ) ) {
$parsed = "$wpdb->site.$orderby";

View file

@ -125,7 +125,7 @@ class WP_Network {
* @param WP_Network|object $network A network object.
*/
public function __construct( $network ) {
foreach( get_object_vars( $network ) as $key => $value ) {
foreach ( get_object_vars( $network ) as $key => $value ) {
$this->$key = $value;
}
@ -254,13 +254,15 @@ class WP_Network {
$main_site_id = wp_cache_get( $cache_key, 'site-options' );
if ( false === $main_site_id ) {
$_sites = get_sites( array(
'fields' => 'ids',
'number' => 1,
'domain' => $this->domain,
'path' => $this->path,
'network_id' => $this->id,
) );
$_sites = get_sites(
array(
'fields' => 'ids',
'number' => 1,
'domain' => $this->domain,
'path' => $this->path,
'network_id' => $this->id,
)
);
$main_site_id = ! empty( $_sites ) ? array_shift( $_sites ) : 0;
wp_cache_add( $cache_key, $main_site_id, 'site-options' );
@ -282,7 +284,7 @@ class WP_Network {
return;
}
$default = ucfirst( $this->domain );
$default = ucfirst( $this->domain );
$this->site_name = get_network_option( $this->id, 'site_name', $default );
}
@ -316,7 +318,6 @@ class WP_Network {
* requested site address.
*
* @since 4.4.0
* @static
*
* @param string $domain Domain to check.
* @param string $path Path to check.
@ -350,12 +351,14 @@ class WP_Network {
if ( wp_using_ext_object_cache() ) {
$using_paths = wp_cache_get( 'networks_have_paths', 'site-options' );
if ( false === $using_paths ) {
$using_paths = get_networks( array(
'number' => 1,
'count' => true,
'path__not_in' => '/',
) );
wp_cache_add( 'networks_have_paths', $using_paths, 'site-options' );
$using_paths = get_networks(
array(
'number' => 1,
'count' => true,
'path__not_in' => '/',
)
);
wp_cache_add( 'networks_have_paths', $using_paths, 'site-options' );
}
}
@ -400,12 +403,12 @@ class WP_Network {
*
* @since 3.9.0
*
* @param null|bool|object $network Network value to return by path.
* @param string $domain The requested domain.
* @param string $path The requested path, in full.
* @param int|null $segments The suggested number of paths to consult.
* Default null, meaning the entire path was to be consulted.
* @param array $paths The paths to search for, based on $path and $segments.
* @param null|bool|WP_Network $network Network value to return by path.
* @param string $domain The requested domain.
* @param string $path The requested path, in full.
* @param int|null $segments The suggested number of paths to consult.
* Default null, meaning the entire path was to be consulted.
* @param string[] $paths Array of paths to search for, based on `$path` and `$segments`.
*/
$pre = apply_filters( 'pre_get_network_by_path', null, $domain, $path, $segments, $paths );
if ( null !== $pre ) {
@ -413,13 +416,15 @@ class WP_Network {
}
if ( ! $using_paths ) {
$networks = get_networks( array(
'number' => 1,
'orderby' => array(
'domain_length' => 'DESC',
),
'domain__in' => $domains,
) );
$networks = get_networks(
array(
'number' => 1,
'orderby' => array(
'domain_length' => 'DESC',
),
'domain__in' => $domains,
)
);
if ( ! empty( $networks ) ) {
return array_shift( $networks );
@ -428,14 +433,16 @@ class WP_Network {
return false;
}
$networks = get_networks( array(
'orderby' => array(
'domain_length' => 'DESC',
'path_length' => 'DESC',
),
'domain__in' => $domains,
'path__in' => $paths,
) );
$networks = get_networks(
array(
'orderby' => array(
'domain_length' => 'DESC',
'path_length' => 'DESC',
),
'domain__in' => $domains,
'path__in' => $paths,
)
);
/*
* Domains are sorted by length of domain, then by length of path.

View file

@ -31,67 +31,75 @@ final class WP_oEmbed_Controller {
*/
$maxwidth = apply_filters( 'oembed_default_width', 600 );
register_rest_route( 'oembed/1.0', '/embed', array(
register_rest_route(
'oembed/1.0',
'/embed',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'args' => array(
'url' => array(
'required' => true,
'sanitize_callback' => 'esc_url_raw',
),
'format' => array(
'default' => 'json',
'sanitize_callback' => 'wp_oembed_ensure_format',
),
'maxwidth' => array(
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
),
),
) );
register_rest_route( 'oembed/1.0', '/proxy', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_proxy_item' ),
'permission_callback' => array( $this, 'get_proxy_item_permissions_check' ),
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'esc_url_raw',
),
'format' => array(
'description' => __( 'The oEmbed format to use.' ),
'type' => 'string',
'default' => 'json',
'enum' => array(
'json',
'xml',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'args' => array(
'url' => array(
'required' => true,
'sanitize_callback' => 'esc_url_raw',
),
'format' => array(
'default' => 'json',
'sanitize_callback' => 'wp_oembed_ensure_format',
),
'maxwidth' => array(
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
),
'maxwidth' => array(
'description' => __( 'The maximum width of the embed frame in pixels.' ),
'type' => 'integer',
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
'maxheight' => array(
'description' => __( 'The maximum height of the embed frame in pixels.' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'discover' => array(
'description' => __( 'Whether to perform an oEmbed discovery request for non-whitelisted providers.' ),
'type' => 'boolean',
'default' => true,
),
)
);
register_rest_route(
'oembed/1.0',
'/proxy',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_proxy_item' ),
'permission_callback' => array( $this, 'get_proxy_item_permissions_check' ),
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'esc_url_raw',
),
'format' => array(
'description' => __( 'The oEmbed format to use.' ),
'type' => 'string',
'default' => 'json',
'enum' => array(
'json',
'xml',
),
),
'maxwidth' => array(
'description' => __( 'The maximum width of the embed frame in pixels.' ),
'type' => 'integer',
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
'maxheight' => array(
'description' => __( 'The maximum height of the embed frame in pixels.' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'discover' => array(
'description' => __( 'Whether to perform an oEmbed discovery request for non-whitelisted providers.' ),
'type' => 'boolean',
'default' => true,
),
),
),
),
) );
)
);
}
/**
@ -157,7 +165,7 @@ final class WP_oEmbed_Controller {
// Serve oEmbed data from cache if set.
unset( $args['_wpnonce'] );
$cache_key = 'oembed_' . md5( serialize( $args ) );
$data = get_transient( $cache_key );
$data = get_transient( $cache_key );
if ( ! empty( $data ) ) {
return $data;
}

View file

@ -17,7 +17,6 @@
* @property-read array $ancestors
* @property-read int $post_category
* @property-read string $tag_input
*
*/
final class WP_Post {
@ -223,7 +222,6 @@ final class WP_Post {
* Retrieve WP_Post instance.
*
* @since 3.5.0
* @static
*
* @global wpdb $wpdb WordPress database abstraction object.
*
@ -243,8 +241,9 @@ final class WP_Post {
if ( ! $_post ) {
$_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
if ( ! $_post )
if ( ! $_post ) {
return false;
}
$_post = sanitize_post( $_post, 'raw' );
wp_cache_add( $_post->ID, $_post, 'posts' );
@ -263,8 +262,9 @@ final class WP_Post {
* @param WP_Post|object $post Post object.
*/
public function __construct( $post ) {
foreach ( get_object_vars( $post ) as $key => $value )
foreach ( get_object_vars( $post ) as $key => $value ) {
$this->$key = $value;
}
}
/**
@ -276,17 +276,21 @@ final class WP_Post {
* @return bool
*/
public function __isset( $key ) {
if ( 'ancestors' == $key )
if ( 'ancestors' == $key ) {
return true;
}
if ( 'page_template' == $key )
if ( 'page_template' == $key ) {
return true;
}
if ( 'post_category' == $key )
return true;
if ( 'post_category' == $key ) {
return true;
}
if ( 'tags_input' == $key )
return true;
if ( 'tags_input' == $key ) {
return true;
}
return metadata_exists( 'post', $this->ID, $key );
}
@ -305,33 +309,39 @@ final class WP_Post {
}
if ( 'post_category' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
if ( is_object_in_taxonomy( $this->post_type, 'category' ) ) {
$terms = get_the_terms( $this, 'category' );
}
if ( empty( $terms ) )
if ( empty( $terms ) ) {
return array();
}
return wp_list_pluck( $terms, 'term_id' );
}
if ( 'tags_input' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) ) {
$terms = get_the_terms( $this, 'post_tag' );
}
if ( empty( $terms ) )
if ( empty( $terms ) ) {
return array();
}
return wp_list_pluck( $terms, 'name' );
}
// Rest of the values need filtering.
if ( 'ancestors' == $key )
if ( 'ancestors' == $key ) {
$value = get_post_ancestors( $this );
else
} else {
$value = get_post_meta( $this->ID, $key, true );
}
if ( $this->filter )
if ( $this->filter ) {
$value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
}
return $value;
}
@ -342,14 +352,16 @@ final class WP_Post {
* @since 3.5.0
*
* @param string $filter Filter.
* @return self|array|bool|object|WP_Post
* @return array|bool|object|WP_Post
*/
public function filter( $filter ) {
if ( $this->filter == $filter )
if ( $this->filter == $filter ) {
return $this;
}
if ( $filter == 'raw' )
if ( $filter == 'raw' ) {
return self::get_instance( $this->ID );
}
return sanitize_post( $this, $filter );
}
@ -365,8 +377,9 @@ final class WP_Post {
$post = get_object_vars( $this );
foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
if ( $this->__isset( $key ) )
if ( $this->__isset( $key ) ) {
$post[ $key ] = $this->__get( $key );
}
}
return $post;

File diff suppressed because it is too large Load diff

View file

@ -288,7 +288,7 @@ class WP_Rewrite {
'%post_id%',
'%author%',
'%pagename%',
'%search%'
'%search%',
);
/**
@ -309,7 +309,7 @@ class WP_Rewrite {
'([0-9]+)',
'([^/]+)',
'([^/]+?)',
'(.+)'
'(.+)',
);
/**
@ -329,7 +329,7 @@ class WP_Rewrite {
'p=',
'author_name=',
'pagename=',
's='
's=',
);
/**
@ -350,7 +350,7 @@ class WP_Rewrite {
* @return bool True, if permalinks are enabled.
*/
public function using_permalinks() {
return ! empty($this->permalink_structure);
return ! empty( $this->permalink_structure );
}
/**
@ -399,11 +399,11 @@ class WP_Rewrite {
* @param int $number Index number.
* @return string
*/
public function preg_index($number) {
public function preg_index( $number ) {
$match_prefix = '$';
$match_suffix = '';
if ( ! empty($this->matches) ) {
if ( ! empty( $this->matches ) ) {
$match_prefix = '$' . $this->matches . '[';
$match_suffix = ']';
}
@ -427,31 +427,32 @@ class WP_Rewrite {
global $wpdb;
// Get pages in order of hierarchy, i.e. children after parents.
$pages = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'");
$pages = $wpdb->get_results( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'" );
$posts = get_page_hierarchy( $pages );
// If we have no pages get out quick.
if ( !$posts )
if ( ! $posts ) {
return array( array(), array() );
}
// Now reverse it, because we need parents after children for rewrite rules to work properly.
$posts = array_reverse($posts, true);
$posts = array_reverse( $posts, true );
$page_uris = array();
$page_uris = array();
$page_attachment_uris = array();
foreach ( $posts as $id => $post ) {
// URL => page name
$uri = get_page_uri($id);
$attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ));
if ( !empty($attachments) ) {
$uri = get_page_uri( $id );
$attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ) );
if ( ! empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
$attach_uri = get_page_uri($attachment->ID);
$page_attachment_uris[$attach_uri] = $attachment->ID;
$attach_uri = get_page_uri( $attachment->ID );
$page_attachment_uris[ $attach_uri ] = $attachment->ID;
}
}
$page_uris[$uri] = $id;
$page_uris[ $uri ] = $id;
}
return array( $page_uris, $page_attachment_uris );
@ -491,39 +492,41 @@ class WP_Rewrite {
* @return string|false False on no permalink structure. Date permalink structure.
*/
public function get_date_permastruct() {
if ( isset($this->date_structure) )
if ( isset( $this->date_structure ) ) {
return $this->date_structure;
}
if ( empty($this->permalink_structure) ) {
if ( empty( $this->permalink_structure ) ) {
$this->date_structure = '';
return false;
}
// The date permalink must have year, month, and day separated by slashes.
$endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
$endians = array( '%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%' );
$this->date_structure = '';
$date_endian = '';
$date_endian = '';
foreach ( $endians as $endian ) {
if ( false !== strpos($this->permalink_structure, $endian) ) {
$date_endian= $endian;
if ( false !== strpos( $this->permalink_structure, $endian ) ) {
$date_endian = $endian;
break;
}
}
if ( empty($date_endian) )
if ( empty( $date_endian ) ) {
$date_endian = '%year%/%monthnum%/%day%';
}
/*
* Do not allow the date tags and %post_id% to overlap in the permalink
* structure. If they do, move the date tags to $front/date/.
*/
$front = $this->front;
preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
preg_match_all( '/%.+?%/', $this->permalink_structure, $tokens );
$tok_index = 1;
foreach ( (array) $tokens[0] as $token) {
if ( '%post_id%' == $token && ($tok_index <= 3) ) {
foreach ( (array) $tokens[0] as $token ) {
if ( '%post_id%' == $token && ( $tok_index <= 3 ) ) {
$front = $front . 'date/';
break;
}
@ -548,12 +551,13 @@ class WP_Rewrite {
public function get_year_permastruct() {
$structure = $this->get_date_permastruct();
if ( empty($structure) )
if ( empty( $structure ) ) {
return false;
}
$structure = str_replace('%monthnum%', '', $structure);
$structure = str_replace('%day%', '', $structure);
$structure = preg_replace('#/+#', '/', $structure);
$structure = str_replace( '%monthnum%', '', $structure );
$structure = str_replace( '%day%', '', $structure );
$structure = preg_replace( '#/+#', '/', $structure );
return $structure;
}
@ -571,11 +575,12 @@ class WP_Rewrite {
public function get_month_permastruct() {
$structure = $this->get_date_permastruct();
if ( empty($structure) )
if ( empty( $structure ) ) {
return false;
}
$structure = str_replace('%day%', '', $structure);
$structure = preg_replace('#/+#', '/', $structure);
$structure = str_replace( '%day%', '', $structure );
$structure = preg_replace( '#/+#', '/', $structure );
return $structure;
}
@ -606,7 +611,7 @@ class WP_Rewrite {
* @return string|false False on failure. Category permalink structure.
*/
public function get_category_permastruct() {
return $this->get_extra_permastruct('category');
return $this->get_extra_permastruct( 'category' );
}
/**
@ -622,7 +627,7 @@ class WP_Rewrite {
* @return string|false False on failure. Tag permalink structure.
*/
public function get_tag_permastruct() {
return $this->get_extra_permastruct('post_tag');
return $this->get_extra_permastruct( 'post_tag' );
}
/**
@ -633,12 +638,14 @@ class WP_Rewrite {
* @param string $name Permalink structure name.
* @return string|false False if not found. Permalink structure string.
*/
public function get_extra_permastruct($name) {
if ( empty($this->permalink_structure) )
public function get_extra_permastruct( $name ) {
if ( empty( $this->permalink_structure ) ) {
return false;
}
if ( isset($this->extra_permastructs[$name]) )
return $this->extra_permastructs[$name]['struct'];
if ( isset( $this->extra_permastructs[ $name ] ) ) {
return $this->extra_permastructs[ $name ]['struct'];
}
return false;
}
@ -655,10 +662,11 @@ class WP_Rewrite {
* @return string|false False if not found. Permalink structure string.
*/
public function get_author_permastruct() {
if ( isset($this->author_structure) )
if ( isset( $this->author_structure ) ) {
return $this->author_structure;
}
if ( empty($this->permalink_structure) ) {
if ( empty( $this->permalink_structure ) ) {
$this->author_structure = '';
return false;
}
@ -680,10 +688,11 @@ class WP_Rewrite {
* @return string|false False if not found. Permalink structure string.
*/
public function get_search_permastruct() {
if ( isset($this->search_structure) )
if ( isset( $this->search_structure ) ) {
return $this->search_structure;
}
if ( empty($this->permalink_structure) ) {
if ( empty( $this->permalink_structure ) ) {
$this->search_structure = '';
return false;
}
@ -705,10 +714,11 @@ class WP_Rewrite {
* @return string|false False if not found. Permalink structure string.
*/
public function get_page_permastruct() {
if ( isset($this->page_structure) )
if ( isset( $this->page_structure ) ) {
return $this->page_structure;
}
if (empty($this->permalink_structure)) {
if ( empty( $this->permalink_structure ) ) {
$this->page_structure = '';
return false;
}
@ -730,10 +740,11 @@ class WP_Rewrite {
* @return string|false False if not found. Permalink structure string.
*/
public function get_feed_permastruct() {
if ( isset($this->feed_structure) )
if ( isset( $this->feed_structure ) ) {
return $this->feed_structure;
}
if ( empty($this->permalink_structure) ) {
if ( empty( $this->permalink_structure ) ) {
$this->feed_structure = '';
return false;
}
@ -755,10 +766,11 @@ class WP_Rewrite {
* @return string|false False if not found. Permalink structure string.
*/
public function get_comment_feed_permastruct() {
if ( isset($this->comment_feed_structure) )
if ( isset( $this->comment_feed_structure ) ) {
return $this->comment_feed_structure;
}
if (empty($this->permalink_structure)) {
if ( empty( $this->permalink_structure ) ) {
$this->comment_feed_structure = '';
return false;
}
@ -788,11 +800,11 @@ class WP_Rewrite {
$position = array_search( $tag, $this->rewritecode );
if ( false !== $position && null !== $position ) {
$this->rewritereplace[ $position ] = $regex;
$this->queryreplace[ $position ] = $query;
$this->queryreplace[ $position ] = $query;
} else {
$this->rewritecode[] = $tag;
$this->rewritecode[] = $tag;
$this->rewritereplace[] = $regex;
$this->queryreplace[] = $query;
$this->queryreplace[] = $query;
}
}
@ -844,12 +856,13 @@ class WP_Rewrite {
* Default true.
* @return array Rewrite rule list.
*/
public function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
public function generate_rewrite_rules( $permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true ) {
// Build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
$feedregex2 = '';
foreach ( (array) $this->feeds as $feed_name)
foreach ( (array) $this->feeds as $feed_name ) {
$feedregex2 .= $feed_name . '|';
$feedregex2 = '(' . trim($feedregex2, '|') . ')/?$';
}
$feedregex2 = '(' . trim( $feedregex2, '|' ) . ')/?$';
/*
* $feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
@ -859,35 +872,35 @@ class WP_Rewrite {
// Build a regex to match the trackback and page/xx parts of URLs.
$trackbackregex = 'trackback/?$';
$pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
$commentregex = $this->comments_pagination_base . '-([0-9]{1,})/?$';
$embedregex = 'embed/?$';
$pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
$commentregex = $this->comments_pagination_base . '-([0-9]{1,})/?$';
$embedregex = 'embed/?$';
// Build up an array of endpoint regexes to append => queries to append.
if ( $endpoints ) {
$ep_query_append = array ();
foreach ( (array) $this->endpoints as $endpoint) {
$ep_query_append = array();
foreach ( (array) $this->endpoints as $endpoint ) {
// Match everything after the endpoint name, but allow for nothing to appear there.
$epmatch = $endpoint[1] . '(/(.*))?/?$';
// This will be appended on to the rest of the query for each dir.
$epquery = '&' . $endpoint[2] . '=';
$ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
$epquery = '&' . $endpoint[2] . '=';
$ep_query_append[ $epmatch ] = array( $endpoint[0], $epquery );
}
}
// Get everything up to the first rewrite tag.
$front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
$front = substr( $permalink_structure, 0, strpos( $permalink_structure, '%' ) );
// Build an array of the tags (note that said array ends up being in $tokens[0]).
preg_match_all('/%.+?%/', $permalink_structure, $tokens);
preg_match_all( '/%.+?%/', $permalink_structure, $tokens );
$num_tokens = count($tokens[0]);
$num_tokens = count( $tokens[0] );
$index = $this->index; //probably 'index.php'
$feedindex = $index;
$index = $this->index; //probably 'index.php'
$feedindex = $index;
$trackbackindex = $index;
$embedindex = $index;
$embedindex = $index;
/*
* Build a list from the rewritecode and queryreplace arrays, that will look something
@ -895,51 +908,53 @@ class WP_Rewrite {
*/
$queries = array();
for ( $i = 0; $i < $num_tokens; ++$i ) {
if ( 0 < $i )
$queries[$i] = $queries[$i - 1] . '&';
else
$queries[$i] = '';
if ( 0 < $i ) {
$queries[ $i ] = $queries[ $i - 1 ] . '&';
} else {
$queries[ $i ] = '';
}
$query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
$queries[$i] .= $query_token;
$query_token = str_replace( $this->rewritecode, $this->queryreplace, $tokens[0][ $i ] ) . $this->preg_index( $i + 1 );
$queries[ $i ] .= $query_token;
}
// Get the structure, minus any cruft (stuff that isn't tags) at the front.
$structure = $permalink_structure;
if ( $front != '/' )
$structure = str_replace($front, '', $structure);
if ( $front != '/' ) {
$structure = str_replace( $front, '', $structure );
}
/*
* Create a list of dirs to walk over, making rewrite rules for each level
* so for example, a $structure of /%year%/%monthnum%/%postname% would create
* rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname%
*/
$structure = trim($structure, '/');
$dirs = $walk_dirs ? explode('/', $structure) : array( $structure );
$num_dirs = count($dirs);
$structure = trim( $structure, '/' );
$dirs = $walk_dirs ? explode( '/', $structure ) : array( $structure );
$num_dirs = count( $dirs );
// Strip slashes from the front of $front.
$front = preg_replace('|^/+|', '', $front);
$front = preg_replace( '|^/+|', '', $front );
// The main workhorse loop.
$post_rewrite = array();
$struct = $front;
$struct = $front;
for ( $j = 0; $j < $num_dirs; ++$j ) {
// Get the struct for this dir, and trim slashes off the front.
$struct .= $dirs[$j] . '/'; // Accumulate. see comment near explode('/', $structure) above.
$struct = ltrim($struct, '/');
$struct .= $dirs[ $j ] . '/'; // Accumulate. see comment near explode('/', $structure) above.
$struct = ltrim( $struct, '/' );
// Replace tags with regexes.
$match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
$match = str_replace( $this->rewritecode, $this->rewritereplace, $struct );
// Make a list of tags, and store how many there are in $num_toks.
$num_toks = preg_match_all('/%.+?%/', $struct, $toks);
$num_toks = preg_match_all( '/%.+?%/', $struct, $toks );
// Get the 'tagname=$matches[i]'.
$query = ( ! empty( $num_toks ) && isset( $queries[$num_toks - 1] ) ) ? $queries[$num_toks - 1] : '';
$query = ( ! empty( $num_toks ) && isset( $queries[ $num_toks - 1 ] ) ) ? $queries[ $num_toks - 1 ] : '';
// Set up $ep_mask_specific which is used to match more specific URL types.
switch ( $dirs[$j] ) {
switch ( $dirs[ $j ] ) {
case '%year%':
$ep_mask_specific = EP_YEAR;
break;
@ -955,25 +970,25 @@ class WP_Rewrite {
// Create query for /page/xx.
$pagematch = $match . $pageregex;
$pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
$pagequery = $index . '?' . $query . '&paged=' . $this->preg_index( $num_toks + 1 );
// Create query for /comment-page-xx.
$commentmatch = $match . $commentregex;
$commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1);
$commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index( $num_toks + 1 );
if ( get_option('page_on_front') ) {
if ( get_option( 'page_on_front' ) ) {
// Create query for Root /comment-page-xx.
$rootcommentmatch = $match . $commentregex;
$rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1);
$rootcommentquery = $index . '?' . $query . '&page_id=' . get_option( 'page_on_front' ) . '&cpage=' . $this->preg_index( $num_toks + 1 );
}
// Create query for /feed/(feed|atom|rss|rss2|rdf).
$feedmatch = $match . $feedregex;
$feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
$feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 );
// Create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex).
$feedmatch2 = $match . $feedregex2;
$feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
$feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 );
// Create query and regex for embeds.
$embedmatch = $match . $embedregex;
@ -981,7 +996,7 @@ class WP_Rewrite {
// If asked to, turn the feed queries into comment feed ones.
if ( $forcomments ) {
$feedquery .= '&withcomments=1';
$feedquery .= '&withcomments=1';
$feedquery2 .= '&withcomments=1';
}
@ -990,7 +1005,11 @@ class WP_Rewrite {
// ...adding on /feed/ regexes => queries
if ( $feed ) {
$rewrite = array( $feedmatch => $feedquery, $feedmatch2 => $feedquery2, $embedmatch => $embedquery );
$rewrite = array(
$feedmatch => $feedquery,
$feedmatch2 => $feedquery2,
$embedmatch => $embedquery,
);
}
//...and /page/xx ones
@ -1000,17 +1019,18 @@ class WP_Rewrite {
// Only on pages with comments add ../comment-page-xx/.
if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask ) {
$rewrite = array_merge($rewrite, array($commentmatch => $commentquery));
} elseif ( EP_ROOT & $ep_mask && get_option('page_on_front') ) {
$rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery));
$rewrite = array_merge( $rewrite, array( $commentmatch => $commentquery ) );
} elseif ( EP_ROOT & $ep_mask && get_option( 'page_on_front' ) ) {
$rewrite = array_merge( $rewrite, array( $rootcommentmatch => $rootcommentquery ) );
}
// Do endpoints.
if ( $endpoints ) {
foreach ( (array) $ep_query_append as $regex => $ep) {
foreach ( (array) $ep_query_append as $regex => $ep ) {
// Add the endpoints on if the mask fits.
if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific )
$rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific ) {
$rewrite[ $match . $regex ] = $index . '?' . $query . $ep[1] . $this->preg_index( $num_toks + 2 );
}
}
}
@ -1025,20 +1045,21 @@ class WP_Rewrite {
* 2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
* minute all present). Set these flags now as we need them for the endpoints.
*/
if ( strpos($struct, '%postname%') !== false
|| strpos($struct, '%post_id%') !== false
|| strpos($struct, '%pagename%') !== false
|| (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)
if ( strpos( $struct, '%postname%' ) !== false
|| strpos( $struct, '%post_id%' ) !== false
|| strpos( $struct, '%pagename%' ) !== false
|| ( strpos( $struct, '%year%' ) !== false && strpos( $struct, '%monthnum%' ) !== false && strpos( $struct, '%day%' ) !== false && strpos( $struct, '%hour%' ) !== false && strpos( $struct, '%minute%' ) !== false && strpos( $struct, '%second%' ) !== false )
) {
$post = true;
if ( strpos($struct, '%pagename%') !== false )
if ( strpos( $struct, '%pagename%' ) !== false ) {
$page = true;
}
}
if ( ! $post ) {
// For custom post types, we need to add on endpoints as well.
foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) {
if ( strpos($struct, "%$ptype%") !== false ) {
foreach ( get_post_types( array( '_builtin' => false ) ) as $ptype ) {
if ( strpos( $struct, "%$ptype%" ) !== false ) {
$post = true;
// This is for page style attachment URLs.
@ -1059,10 +1080,10 @@ class WP_Rewrite {
$embedquery = $embedindex . '?' . $query . '&embed=true';
// Trim slashes from the end of the regex for this dir.
$match = rtrim($match, '/');
$match = rtrim( $match, '/' );
// Get rid of brackets.
$submatchbase = str_replace( array('(', ')'), '', $match);
$submatchbase = str_replace( array( '(', ')' ), '', $match );
// Add a rule for at attachments, which take the form of <permalink>/some-text.
$sub1 = $submatchbase . '/([^/]+)/';
@ -1104,18 +1125,18 @@ class WP_Rewrite {
$sub2embed = $sub2 . $embedregex;
// Create queries for these extra tag-ons we've just dealt with.
$subquery = $index . '?attachment=' . $this->preg_index(1);
$subtbquery = $subquery . '&tb=1';
$subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
$subcommentquery = $subquery . '&cpage=' . $this->preg_index(2);
$subembedquery = $subquery . '&embed=true';
$subquery = $index . '?attachment=' . $this->preg_index( 1 );
$subtbquery = $subquery . '&tb=1';
$subfeedquery = $subquery . '&feed=' . $this->preg_index( 2 );
$subcommentquery = $subquery . '&cpage=' . $this->preg_index( 2 );
$subembedquery = $subquery . '&embed=true';
// Do endpoints for attachments.
if ( !empty($endpoints) ) {
if ( ! empty( $endpoints ) ) {
foreach ( (array) $ep_query_append as $regex => $ep ) {
if ( $ep[0] & EP_ATTACHMENT ) {
$rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
$rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
$rewrite[ $sub1 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 );
$rewrite[ $sub2 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 );
}
}
}
@ -1134,13 +1155,13 @@ class WP_Rewrite {
* When cast to int, returned 0.
*/
$match = $match . '(?:/([0-9]+))?/?$';
$query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
$query = $index . '?' . $query . '&page=' . $this->preg_index( $num_toks + 1 );
// Not matching a permalink so this is a lot simpler.
// Not matching a permalink so this is a lot simpler.
} else {
// Close the match and finalise the query.
$match .= '?$';
$query = $index . '?' . $query;
$query = $index . '?' . $query;
}
/*
@ -1148,12 +1169,12 @@ class WP_Rewrite {
* only contains rules/queries for trackback, pages etc) to the main regex/query for
* this dir
*/
$rewrite = array_merge($rewrite, array($match => $query));
$rewrite = array_merge( $rewrite, array( $match => $query ) );
// If we're matching a permalink, add those extras (attachments etc) on.
if ( $post ) {
// Add trackback.
$rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
$rewrite = array_merge( array( $trackbackmatch => $trackbackquery ), $rewrite );
// Add embed.
$rewrite = array_merge( array( $embedmatch => $embedquery ), $rewrite );
@ -1161,21 +1182,34 @@ class WP_Rewrite {
// Add regexes/queries for attachments, attachment trackbacks and so on.
if ( ! $page ) {
// Require <permalink>/attachment/stuff form for pages because of confusion with subpages.
$rewrite = array_merge( $rewrite, array(
$sub1 => $subquery,
$sub1tb => $subtbquery,
$sub1feed => $subfeedquery,
$sub1feed2 => $subfeedquery,
$sub1comment => $subcommentquery,
$sub1embed => $subembedquery
) );
$rewrite = array_merge(
$rewrite,
array(
$sub1 => $subquery,
$sub1tb => $subtbquery,
$sub1feed => $subfeedquery,
$sub1feed2 => $subfeedquery,
$sub1comment => $subcommentquery,
$sub1embed => $subembedquery,
)
);
}
$rewrite = array_merge( array( $sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery, $sub2embed => $subembedquery ), $rewrite );
$rewrite = array_merge(
array(
$sub2 => $subquery,
$sub2tb => $subtbquery,
$sub2feed => $subfeedquery,
$sub2feed2 => $subfeedquery,
$sub2comment => $subcommentquery,
$sub2embed => $subembedquery,
),
$rewrite
);
}
}
// Add the rules for this dir to the accumulating $post_rewrite.
$post_rewrite = array_merge($rewrite, $post_rewrite);
$post_rewrite = array_merge( $rewrite, $post_rewrite );
}
// The finished rules. phew!
@ -1197,8 +1231,8 @@ class WP_Rewrite {
* @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over.
* @return array
*/
public function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
public function generate_rewrite_rule( $permalink_structure, $walk_dirs = false ) {
return $this->generate_rewrite_rules( $permalink_structure, EP_NONE, false, false, false, $walk_dirs );
}
/**
@ -1221,11 +1255,12 @@ class WP_Rewrite {
public function rewrite_rules() {
$rewrite = array();
if ( empty($this->permalink_structure) )
if ( empty( $this->permalink_structure ) ) {
return $rewrite;
}
// robots.txt -only if installed at the root
$home_path = parse_url( home_url() );
$home_path = parse_url( home_url() );
$robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array();
// Old feed and service files.
@ -1237,7 +1272,7 @@ class WP_Rewrite {
// Registration rules.
$registration_pages = array();
if ( is_multisite() && is_main_site() ) {
$registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
$registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
$registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true';
}
@ -1257,7 +1292,7 @@ class WP_Rewrite {
$post_rewrite = apply_filters( 'post_rewrite_rules', $post_rewrite );
// Date rewrite rules.
$date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
$date_rewrite = $this->generate_rewrite_rules( $this->get_date_permastruct(), EP_DATE );
/**
* Filters rewrite rules used for date archives.
@ -1271,7 +1306,7 @@ class WP_Rewrite {
$date_rewrite = apply_filters( 'date_rewrite_rules', $date_rewrite );
// Root-level rewrite rules.
$root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
$root_rewrite = $this->generate_rewrite_rules( $this->root . '/', EP_ROOT );
/**
* Filters rewrite rules used for root-level archives.
@ -1286,7 +1321,7 @@ class WP_Rewrite {
$root_rewrite = apply_filters( 'root_rewrite_rules', $root_rewrite );
// Comments rewrite rules.
$comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, false, true, true, false);
$comments_rewrite = $this->generate_rewrite_rules( $this->root . $this->comments_base, EP_COMMENTS, false, true, true, false );
/**
* Filters rewrite rules used for comment feed archives.
@ -1301,7 +1336,7 @@ class WP_Rewrite {
// Search rewrite rules.
$search_structure = $this->get_search_permastruct();
$search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
$search_rewrite = $this->generate_rewrite_rules( $search_structure, EP_SEARCH );
/**
* Filters rewrite rules used for search archives.
@ -1316,7 +1351,7 @@ class WP_Rewrite {
$search_rewrite = apply_filters( 'search_rewrite_rules', $search_rewrite );
// Author rewrite rules.
$author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
$author_rewrite = $this->generate_rewrite_rules( $this->get_author_permastruct(), EP_AUTHORS );
/**
* Filters rewrite rules used for author archives.
@ -1345,10 +1380,11 @@ class WP_Rewrite {
// Extra permastructs.
foreach ( $this->extra_permastructs as $permastructname => $struct ) {
if ( is_array( $struct ) ) {
if ( count( $struct ) == 2 )
if ( count( $struct ) == 2 ) {
$rules = $this->generate_rewrite_rules( $struct[0], $struct[1] );
else
} else {
$rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] );
}
} else {
$rules = $this->generate_rewrite_rules( $struct );
}
@ -1378,14 +1414,15 @@ class WP_Rewrite {
$rules = apply_filters( 'tag_rewrite_rules', $rules );
}
$this->extra_rules_top = array_merge($this->extra_rules_top, $rules);
$this->extra_rules_top = array_merge( $this->extra_rules_top, $rules );
}
// Put them together.
if ( $this->use_verbose_page_rules )
$this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules);
else
$this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules);
if ( $this->use_verbose_page_rules ) {
$this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules );
} else {
$this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules );
}
/**
* Fires after the rewrite rules are generated.
@ -1421,15 +1458,15 @@ class WP_Rewrite {
* @return array Rewrite rules.
*/
public function wp_rewrite_rules() {
$this->rules = get_option('rewrite_rules');
if ( empty($this->rules) ) {
$this->rules = get_option( 'rewrite_rules' );
if ( empty( $this->rules ) ) {
$this->matches = 'matches';
$this->rewrite_rules();
if ( ! did_action( 'wp_loaded' ) ) {
add_action( 'wp_loaded', array( $this, 'flush_rules' ) );
return $this->rules;
}
update_option('rewrite_rules', $this->rules);
update_option( 'rewrite_rules', $this->rules );
}
return $this->rules;
@ -1449,20 +1486,23 @@ class WP_Rewrite {
* @return string
*/
public function mod_rewrite_rules() {
if ( ! $this->using_permalinks() )
if ( ! $this->using_permalinks() ) {
return '';
}
$site_root = parse_url( site_url() );
if ( isset( $site_root['path'] ) )
$site_root = trailingslashit($site_root['path']);
if ( isset( $site_root['path'] ) ) {
$site_root = trailingslashit( $site_root['path'] );
}
$home_root = parse_url(home_url());
if ( isset( $home_root['path'] ) )
$home_root = trailingslashit($home_root['path']);
else
$home_root = parse_url( home_url() );
if ( isset( $home_root['path'] ) ) {
$home_root = trailingslashit( $home_root['path'] );
} else {
$home_root = '/';
}
$rules = "<IfModule mod_rewrite.c>\n";
$rules = "<IfModule mod_rewrite.c>\n";
$rules .= "RewriteEngine On\n";
$rules .= "RewriteBase $home_root\n";
@ -1470,29 +1510,30 @@ class WP_Rewrite {
$rules .= "RewriteRule ^index\.php$ - [L]\n";
// Add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all).
foreach ( (array) $this->non_wp_rules as $match => $query) {
foreach ( (array) $this->non_wp_rules as $match => $query ) {
// Apache 1.3 does not support the reluctant (non-greedy) modifier.
$match = str_replace('.+?', '.+', $match);
$match = str_replace( '.+?', '.+', $match );
$rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
}
if ( $this->use_verbose_rules ) {
$this->matches = '';
$rewrite = $this->rewrite_rules();
$num_rules = count($rewrite);
$rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
$rewrite = $this->rewrite_rules();
$num_rules = count( $rewrite );
$rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
"RewriteCond %{REQUEST_FILENAME} -d\n" .
"RewriteRule ^.*$ - [S=$num_rules]\n";
foreach ( (array) $rewrite as $match => $query) {
foreach ( (array) $rewrite as $match => $query ) {
// Apache 1.3 does not support the reluctant (non-greedy) modifier.
$match = str_replace('.+?', '.+', $match);
$match = str_replace( '.+?', '.+', $match );
if ( strpos($query, $this->index) !== false )
if ( strpos( $query, $this->index ) !== false ) {
$rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
else
} else {
$rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
}
}
} else {
$rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
@ -1535,8 +1576,9 @@ class WP_Rewrite {
* @return string IIS7 URL rewrite rule sets.
*/
public function iis7_url_rewrite_rules( $add_parent_tags = false ) {
if ( ! $this->using_permalinks() )
if ( ! $this->using_permalinks() ) {
return '';
}
$rules = '';
if ( $add_parent_tags ) {
$rules .= '<configuration>
@ -1590,7 +1632,7 @@ class WP_Rewrite {
public function add_rule( $regex, $query, $after = 'bottom' ) {
if ( is_array( $query ) ) {
$external = false;
$query = add_query_arg( $query, 'index.php' );
$query = add_query_arg( $query, 'index.php' );
} else {
$index = false === strpos( $query, '?' ) ? strlen( $query ) : strpos( $query, '?' );
$front = substr( $query, 0, $index );
@ -1692,27 +1734,30 @@ class WP_Rewrite {
*/
public function add_permastruct( $name, $struct, $args = array() ) {
// Back-compat for the old parameters: $with_front and $ep_mask.
if ( ! is_array( $args ) )
if ( ! is_array( $args ) ) {
$args = array( 'with_front' => $args );
if ( func_num_args() == 4 )
}
if ( func_num_args() == 4 ) {
$args['ep_mask'] = func_get_arg( 3 );
}
$defaults = array(
'with_front' => true,
'ep_mask' => EP_NONE,
'paged' => true,
'feed' => true,
'with_front' => true,
'ep_mask' => EP_NONE,
'paged' => true,
'feed' => true,
'forcomments' => false,
'walk_dirs' => true,
'endpoints' => true,
'walk_dirs' => true,
'endpoints' => true,
);
$args = array_intersect_key( $args, $defaults );
$args = wp_parse_args( $args, $defaults );
$args = array_intersect_key( $args, $defaults );
$args = wp_parse_args( $args, $defaults );
if ( $args['with_front'] )
if ( $args['with_front'] ) {
$struct = $this->front . $struct;
else
} else {
$struct = $this->root . $struct;
}
$args['struct'] = $struct;
$this->extra_permastructs[ $name ] = $args;
@ -1771,10 +1816,12 @@ class WP_Rewrite {
if ( ! $hard || ! apply_filters( 'flush_rewrite_rules_hard', true ) ) {
return;
}
if ( function_exists( 'save_mod_rewrite_rules' ) )
if ( function_exists( 'save_mod_rewrite_rules' ) ) {
save_mod_rewrite_rules();
if ( function_exists( 'iis7_save_url_rewrite_rules' ) )
}
if ( function_exists( 'iis7_save_url_rewrite_rules' ) ) {
iis7_save_url_rewrite_rules();
}
}
/**
@ -1787,27 +1834,29 @@ class WP_Rewrite {
* @since 1.5.0
*/
public function init() {
$this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
$this->permalink_structure = get_option('permalink_structure');
$this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
$this->root = '';
$this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
$this->permalink_structure = get_option( 'permalink_structure' );
$this->front = substr( $this->permalink_structure, 0, strpos( $this->permalink_structure, '%' ) );
$this->root = '';
if ( $this->using_index_permalinks() )
if ( $this->using_index_permalinks() ) {
$this->root = $this->index . '/';
}
unset($this->author_structure);
unset($this->date_structure);
unset($this->page_structure);
unset($this->search_structure);
unset($this->feed_structure);
unset($this->comment_feed_structure);
$this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );
unset( $this->author_structure );
unset( $this->date_structure );
unset( $this->page_structure );
unset( $this->search_structure );
unset( $this->feed_structure );
unset( $this->comment_feed_structure );
$this->use_trailing_slashes = ( '/' == substr( $this->permalink_structure, -1, 1 ) );
// Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) )
$this->use_verbose_page_rules = true;
else
if ( preg_match( '/^[^%]*%(?:postname|category|tag|author)%/', $this->permalink_structure ) ) {
$this->use_verbose_page_rules = true;
} else {
$this->use_verbose_page_rules = false;
}
}
/**
@ -1824,10 +1873,10 @@ class WP_Rewrite {
*
* @param string $permalink_structure Permalink structure.
*/
public function set_permalink_structure($permalink_structure) {
public function set_permalink_structure( $permalink_structure ) {
if ( $permalink_structure != $this->permalink_structure ) {
$old_permalink_structure = $this->permalink_structure;
update_option('permalink_structure', $permalink_structure);
update_option( 'permalink_structure', $permalink_structure );
$this->init();
@ -1854,9 +1903,9 @@ class WP_Rewrite {
*
* @param string $category_base Category permalink structure base.
*/
public function set_category_base($category_base) {
if ( $category_base != get_option('category_base') ) {
update_option('category_base', $category_base);
public function set_category_base( $category_base ) {
if ( $category_base != get_option( 'category_base' ) ) {
update_option( 'category_base', $category_base );
$this->init();
}
}
@ -1873,7 +1922,7 @@ class WP_Rewrite {
* @param string $tag_base Tag permalink structure base.
*/
public function set_tag_base( $tag_base ) {
if ( $tag_base != get_option( 'tag_base') ) {
if ( $tag_base != get_option( 'tag_base' ) ) {
update_option( 'tag_base', $tag_base );
$this->init();
}
@ -1883,7 +1932,6 @@ class WP_Rewrite {
* Constructor - Calls init(), which runs setup.
*
* @since 1.5.0
*
*/
public function __construct() {
$this->init();

View file

@ -41,7 +41,7 @@ class WP_Role {
* @param array $capabilities List of capabilities.
*/
public function __construct( $role, $capabilities ) {
$this->name = $role;
$this->name = $role;
$this->capabilities = $capabilities;
}
@ -54,7 +54,7 @@ class WP_Role {
* @param bool $grant Whether role has capability privilege.
*/
public function add_cap( $cap, $grant = true ) {
$this->capabilities[$cap] = $grant;
$this->capabilities[ $cap ] = $grant;
wp_roles()->add_cap( $this->name, $cap, $grant );
}
@ -71,7 +71,7 @@ class WP_Role {
* @param string $cap Capability name.
*/
public function remove_cap( $cap ) {
unset( $this->capabilities[$cap] );
unset( $this->capabilities[ $cap ] );
wp_roles()->remove_cap( $this->name, $cap );
}
@ -94,16 +94,17 @@ class WP_Role {
*
* @since 2.0.0
*
* @param array $capabilities Array of role capabilities.
* @param bool[] $capabilities Associative array of capabilities for the role.
* @param string $cap Capability name.
* @param string $name Role name.
*/
$capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name );
if ( !empty( $capabilities[$cap] ) )
return $capabilities[$cap];
else
if ( ! empty( $capabilities[ $cap ] ) ) {
return $capabilities[ $cap ];
} else {
return false;
}
}
}

View file

@ -15,10 +15,10 @@
* in the value of the 'capability' key.
*
* array (
* 'rolename' => array (
* 'name' => 'rolename',
* 'capabilities' => array()
* )
* 'rolename' => array (
* 'name' => 'rolename',
* 'capabilities' => array()
* )
* )
*
* @since 2.0.0
@ -28,7 +28,7 @@ class WP_Roles {
* List of roles and capabilities.
*
* @since 2.0.0
* @var array
* @var array[]
*/
public $roles;
@ -36,7 +36,7 @@ class WP_Roles {
* List of the role objects.
*
* @since 2.0.0
* @var array
* @var WP_Role[]
*/
public $role_objects = array();
@ -44,7 +44,7 @@ class WP_Roles {
* List of role names.
*
* @since 2.0.0
* @var array
* @var string[]
*/
public $role_names = array();
@ -76,7 +76,7 @@ class WP_Roles {
* Constructor
*
* @since 2.0.0
* @since 4.9.0 The $site_id argument was added.
* @since 4.9.0 The `$site_id` argument was added.
*
* @global array $wp_user_roles Used to set the 'roles' property value.
*
@ -95,7 +95,7 @@ class WP_Roles {
*
* @since 4.0.0
*
* @param callable $name Method to call.
* @param string $name Method to call.
* @param array $arguments Arguments to pass when calling.
* @return mixed|false Return value of the callback, false otherwise.
*/
@ -157,15 +157,16 @@ class WP_Roles {
return;
}
$this->roles[$role] = array(
'name' => $display_name,
'capabilities' => $capabilities
);
if ( $this->use_db )
$this->roles[ $role ] = array(
'name' => $display_name,
'capabilities' => $capabilities,
);
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
$this->role_objects[$role] = new WP_Role( $role, $capabilities );
$this->role_names[$role] = $display_name;
return $this->role_objects[$role];
}
$this->role_objects[ $role ] = new WP_Role( $role, $capabilities );
$this->role_names[ $role ] = $display_name;
return $this->role_objects[ $role ];
}
/**
@ -176,18 +177,21 @@ class WP_Roles {
* @param string $role Role name.
*/
public function remove_role( $role ) {
if ( ! isset( $this->role_objects[$role] ) )
if ( ! isset( $this->role_objects[ $role ] ) ) {
return;
}
unset( $this->role_objects[$role] );
unset( $this->role_names[$role] );
unset( $this->roles[$role] );
unset( $this->role_objects[ $role ] );
unset( $this->role_names[ $role ] );
unset( $this->roles[ $role ] );
if ( $this->use_db )
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
if ( get_option( 'default_role' ) == $role )
if ( get_option( 'default_role' ) == $role ) {
update_option( 'default_role', 'subscriber' );
}
}
/**
@ -200,12 +204,14 @@ class WP_Roles {
* @param bool $grant Optional, default is true. Whether role is capable of performing capability.
*/
public function add_cap( $role, $cap, $grant = true ) {
if ( ! isset( $this->roles[$role] ) )
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
$this->roles[$role]['capabilities'][$cap] = $grant;
if ( $this->use_db )
$this->roles[ $role ]['capabilities'][ $cap ] = $grant;
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}
/**
@ -217,12 +223,14 @@ class WP_Roles {
* @param string $cap Capability name.
*/
public function remove_cap( $role, $cap ) {
if ( ! isset( $this->roles[$role] ) )
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
unset( $this->roles[$role]['capabilities'][$cap] );
if ( $this->use_db )
unset( $this->roles[ $role ]['capabilities'][ $cap ] );
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}
/**
@ -234,10 +242,11 @@ class WP_Roles {
* @return WP_Role|null WP_Role object if found, null if the role does not exist.
*/
public function get_role( $role ) {
if ( isset( $this->role_objects[$role] ) )
return $this->role_objects[$role];
else
if ( isset( $this->role_objects[ $role ] ) ) {
return $this->role_objects[ $role ];
} else {
return null;
}
}
/**
@ -245,7 +254,7 @@ class WP_Roles {
*
* @since 2.0.0
*
* @return array List of role names.
* @return string[] List of role names.
*/
public function get_names() {
return $this->role_names;
@ -260,7 +269,7 @@ class WP_Roles {
* @return bool
*/
public function is_role( $role ) {
return isset( $this->role_names[$role] );
return isset( $this->role_names[ $role ] );
}
/**
@ -274,10 +283,10 @@ class WP_Roles {
}
$this->role_objects = array();
$this->role_names = array();
$this->role_names = array();
foreach ( array_keys( $this->roles ) as $role ) {
$this->role_objects[ $role ] = new WP_Role( $role, $this->roles[ $role ]['capabilities'] );
$this->role_names[ $role ] = $this->roles[ $role ]['name'];
$this->role_names[ $role ] = $this->roles[ $role ]['name'];
}
/**

View file

@ -23,7 +23,7 @@ abstract class WP_Session_Tokens {
protected $user_id;
/**
* Protected constructor.
* Protected constructor. Use the `get_instance()` method to get the instance.
*
* @since 4.0.0
*
@ -34,20 +34,20 @@ abstract class WP_Session_Tokens {
}
/**
* Retrieves a session token manager instance for a user.
* Retrieves a session manager instance for a user.
*
* This method contains a {@see 'session_token_manager'} filter, allowing a plugin to swap out
* the session manager for a subclass of `WP_Session_Tokens`.
*
* @since 4.0.0
* @static
*
* @param int $user_id User whose session to manage.
* @return WP_User_Meta_Session_Tokens WP_User_Meta_Session_Tokens class instance by default.
* @return WP_Session_Tokens The session object, which is by default an instance of
* the `WP_User_Meta_Session_Tokens` class.
*/
final public static function get_instance( $user_id ) {
/**
* Filters the session token manager used.
* Filters the class name for the session token manager.
*
* @since 4.0.0
*
@ -59,7 +59,7 @@ abstract class WP_Session_Tokens {
}
/**
* Hashes a session token for storage.
* Hashes the given session token for storage.
*
* @since 4.0.0
*
@ -76,12 +76,12 @@ abstract class WP_Session_Tokens {
}
/**
* Get a user's session.
* Retrieves a user's session for the given token.
*
* @since 4.0.0
*
* @param string $token Session token
* @return array User session
* @param string $token Session token.
* @return array|null The session, or null if it does not exist.
*/
final public function get( $token ) {
$verifier = $this->hash_token( $token );
@ -89,7 +89,7 @@ abstract class WP_Session_Tokens {
}
/**
* Validate a user's session token as authentic.
* Validates the given session token for authenticity and validity.
*
* Checks that the given token is present and hasn't expired.
*
@ -104,11 +104,11 @@ abstract class WP_Session_Tokens {
}
/**
* Generate a session token and attach session information to it.
* Generates a session token and attaches session information to it.
*
* A session token is a long, random string. It is used in a cookie
* link that cookie to an expiration time and to ensure the cookie
* becomes invalidated upon logout.
* to link that cookie to an expiration time and to ensure the cookie
* becomes invalidated when the user logs out.
*
* This function generates a token and stores it with the associated
* expiration time (and potentially other session information via the
@ -123,19 +123,18 @@ abstract class WP_Session_Tokens {
/**
* Filters the information attached to the newly created session.
*
* Could be used in the future to attach information such as
* IP address or user agent to a session.
* Can be used to attach further information to a session.
*
* @since 4.0.0
*
* @param array $session Array of extra data.
* @param int $user_id User ID.
*/
$session = apply_filters( 'attach_session_information', array(), $this->user_id );
$session = apply_filters( 'attach_session_information', array(), $this->user_id );
$session['expiration'] = $expiration;
// IP address.
if ( !empty( $_SERVER['REMOTE_ADDR'] ) ) {
if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
$session['ip'] = $_SERVER['REMOTE_ADDR'];
}
@ -155,7 +154,7 @@ abstract class WP_Session_Tokens {
}
/**
* Update a session token.
* Updates the data for the session with the given token.
*
* @since 4.0.0
*
@ -168,7 +167,7 @@ abstract class WP_Session_Tokens {
}
/**
* Destroy a session token.
* Destroys the session with the given token.
*
* @since 4.0.0
*
@ -180,8 +179,7 @@ abstract class WP_Session_Tokens {
}
/**
* Destroy all session tokens for this user,
* except a single token, presumably the one in use.
* Destroys all sessions for this user except the one with the given token (presumably the one in use).
*
* @since 4.0.0
*
@ -189,7 +187,7 @@ abstract class WP_Session_Tokens {
*/
final public function destroy_others( $token_to_keep ) {
$verifier = $this->hash_token( $token_to_keep );
$session = $this->get_session( $verifier );
$session = $this->get_session( $verifier );
if ( $session ) {
$this->destroy_other_sessions( $verifier );
} else {
@ -198,8 +196,7 @@ abstract class WP_Session_Tokens {
}
/**
* Determine whether a session token is still valid,
* based on expiration.
* Determines whether a session is still valid, based on its expiration timestamp.
*
* @since 4.0.0
*
@ -211,7 +208,7 @@ abstract class WP_Session_Tokens {
}
/**
* Destroy all session tokens for a user.
* Destroys all sessions for a user.
*
* @since 4.0.0
*/
@ -220,10 +217,9 @@ abstract class WP_Session_Tokens {
}
/**
* Destroy all session tokens for all users.
* Destroys all sessions for all users.
*
* @since 4.0.0
* @static
*/
final public static function destroy_all_for_all_users() {
/** This filter is documented in wp-includes/class-wp-session-tokens.php */
@ -232,50 +228,49 @@ abstract class WP_Session_Tokens {
}
/**
* Retrieve all sessions of a user.
* Retrieves all sessions for a user.
*
* @since 4.0.0
*
* @return array Sessions of a user.
* @return array Sessions for a user.
*/
final public function get_all() {
return array_values( $this->get_sessions() );
}
/**
* This method should retrieve all sessions of a user, keyed by verifier.
* Retrieves all sessions of the user.
*
* @since 4.0.0
*
* @return array Sessions of a user, keyed by verifier.
* @return array Sessions of the user.
*/
abstract protected function get_sessions();
/**
* This method should look up a session by its verifier (token hash).
* Retrieves a session based on its verifier (token hash).
*
* @since 4.0.0
*
* @param string $verifier Verifier of the session to retrieve.
* @param string $verifier Verifier for the session to retrieve.
* @return array|null The session, or null if it does not exist.
*/
abstract protected function get_session( $verifier );
/**
* This method should update a session by its verifier.
* Updates a session based on its verifier (token hash).
*
* Omitting the second argument should destroy the session.
* Omitting the second argument destroys the session.
*
* @since 4.0.0
*
* @param string $verifier Verifier of the session to update.
* @param string $verifier Verifier for the session to update.
* @param array $session Optional. Session. Omitting this argument destroys the session.
*/
abstract protected function update_session( $verifier, $session = null );
/**
* This method should destroy all session tokens for this user,
* except a single session passed.
* Destroys all sessions for this user, except the single session with the given verifier.
*
* @since 4.0.0
*
@ -284,17 +279,16 @@ abstract class WP_Session_Tokens {
abstract protected function destroy_other_sessions( $verifier );
/**
* This method should destroy all sessions for a user.
* Destroys all sessions for the user.
*
* @since 4.0.0
*/
abstract protected function destroy_all_sessions();
/**
* This static method should destroy all session tokens for all users.
* Destroys all sessions for all users.
*
* @since 4.0.0
* @static
*/
public static function drop_sessions() {}
}

View file

@ -32,39 +32,41 @@ class WP_SimplePie_File extends SimplePie_File {
* @param boolean $force_fsockopen Optional. Whether to force opening internet or unix domain socket
* connection or not. Default false.
*/
public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) {
$this->url = $url;
$this->timeout = $timeout;
public function __construct( $url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false ) {
$this->url = $url;
$this->timeout = $timeout;
$this->redirects = $redirects;
$this->headers = $headers;
$this->headers = $headers;
$this->useragent = $useragent;
$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
if ( preg_match('/^http(s)?:\/\//i', $url) ) {
if ( preg_match( '/^http(s)?:\/\//i', $url ) ) {
$args = array(
'timeout' => $this->timeout,
'timeout' => $this->timeout,
'redirection' => $this->redirects,
);
if ( !empty($this->headers) )
if ( ! empty( $this->headers ) ) {
$args['headers'] = $this->headers;
}
if ( SIMPLEPIE_USERAGENT != $this->useragent ) //Use default WP user agent unless custom has been specified
if ( SIMPLEPIE_USERAGENT != $this->useragent ) { //Use default WP user agent unless custom has been specified
$args['user-agent'] = $this->useragent;
}
$res = wp_safe_remote_request($url, $args);
$res = wp_safe_remote_request( $url, $args );
if ( is_wp_error($res) ) {
$this->error = 'WP HTTP Error: ' . $res->get_error_message();
if ( is_wp_error( $res ) ) {
$this->error = 'WP HTTP Error: ' . $res->get_error_message();
$this->success = false;
} else {
$this->headers = wp_remote_retrieve_headers( $res );
$this->body = wp_remote_retrieve_body( $res );
$this->headers = wp_remote_retrieve_headers( $res );
$this->body = wp_remote_retrieve_body( $res );
$this->status_code = wp_remote_retrieve_response_code( $res );
}
} else {
$this->error = '';
$this->error = '';
$this->success = false;
}
}

View file

@ -35,10 +35,9 @@ class WP_SimplePie_Sanitize_KSES extends SimplePie_Sanitize {
public function sanitize( $data, $type, $base = '' ) {
$data = trim( $data );
if ( $type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML ) {
if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data)) {
if ( preg_match( '/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data ) ) {
$type |= SIMPLEPIE_CONSTRUCT_HTML;
}
else {
} else {
$type |= SIMPLEPIE_CONSTRUCT_TEXT;
}
}

View file

@ -39,6 +39,22 @@ class WP_Site_Query {
'limits' => '',
);
/**
* Metadata query container.
*
* @since 5.1.0
* @var WP_Meta_Query
*/
public $meta_query = false;
/**
* Metadata query clauses.
*
* @since 5.1.0
* @var array
*/
protected $meta_query_clauses;
/**
* Date query container.
*
@ -92,86 +108,104 @@ class WP_Site_Query {
*
* @since 4.6.0
* @since 4.8.0 Introduced the 'lang_id', 'lang__in', and 'lang__not_in' parameters.
* @since 5.1.0 Introduced the 'update_site_meta_cache', 'meta_query', 'meta_key',
* 'meta_value', 'meta_type' and 'meta_compare' parameters.
*
* @param string|array $query {
* Optional. Array or query string of site query parameters. Default empty.
*
* @type array $site__in Array of site IDs to include. Default empty.
* @type array $site__not_in Array of site IDs to exclude. Default empty.
* @type bool $count Whether to return a site count (true) or array of site objects.
* Default false.
* @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
* Default null.
* @type string $fields Site fields to return. Accepts 'ids' (returns an array of site IDs)
* or empty (returns an array of complete site objects). Default empty.
* @type int $ID A site ID to only return that site. Default empty.
* @type int $number Maximum number of sites to retrieve. Default 100.
* @type int $offset Number of sites to offset the query. Used to build LIMIT clause.
* Default 0.
* @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* @type string|array $orderby Site status or array of statuses. Accepts 'id', 'domain', 'path',
* 'network_id', 'last_updated', 'registered', 'domain_length',
* 'path_length', 'site__in' and 'network__in'. Also accepts false,
* an empty array, or 'none' to disable `ORDER BY` clause.
* Default 'id'.
* @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
* @type int $network_id Limit results to those affiliated with a given network ID. If 0,
* include all networks. Default 0.
* @type array $network__in Array of network IDs to include affiliated sites for. Default empty.
* @type array $network__not_in Array of network IDs to exclude affiliated sites for. Default empty.
* @type string $domain Limit results to those affiliated with a given domain. Default empty.
* @type array $domain__in Array of domains to include affiliated sites for. Default empty.
* @type array $domain__not_in Array of domains to exclude affiliated sites for. Default empty.
* @type string $path Limit results to those affiliated with a given path. Default empty.
* @type array $path__in Array of paths to include affiliated sites for. Default empty.
* @type array $path__not_in Array of paths to exclude affiliated sites for. Default empty.
* @type int $public Limit results to public sites. Accepts '1' or '0'. Default empty.
* @type int $archived Limit results to archived sites. Accepts '1' or '0'. Default empty.
* @type int $mature Limit results to mature sites. Accepts '1' or '0'. Default empty.
* @type int $spam Limit results to spam sites. Accepts '1' or '0'. Default empty.
* @type int $deleted Limit results to deleted sites. Accepts '1' or '0'. Default empty.
* @type int $lang_id Limit results to a language ID. Default empty.
* @type array $lang__in Array of language IDs to include affiliated sites for. Default empty.
* @type array $lang__not_in Array of language IDs to exclude affiliated sites for. Default empty.
* @type string $search Search term(s) to retrieve matching sites for. Default empty.
* @type array $search_columns Array of column names to be searched. Accepts 'domain' and 'path'.
* Default empty array.
* @type bool $update_site_cache Whether to prime the cache for found sites. Default true.
* @type array $site__in Array of site IDs to include. Default empty.
* @type array $site__not_in Array of site IDs to exclude. Default empty.
* @type bool $count Whether to return a site count (true) or array of site objects.
* Default false.
* @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
* Default null.
* @type string $fields Site fields to return. Accepts 'ids' (returns an array of site IDs)
* or empty (returns an array of complete site objects). Default empty.
* @type int $ID A site ID to only return that site. Default empty.
* @type int $number Maximum number of sites to retrieve. Default 100.
* @type int $offset Number of sites to offset the query. Used to build LIMIT clause.
* Default 0.
* @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* @type string|array $orderby Site status or array of statuses. Accepts 'id', 'domain', 'path',
* 'network_id', 'last_updated', 'registered', 'domain_length',
* 'path_length', 'site__in' and 'network__in'. Also accepts false,
* an empty array, or 'none' to disable `ORDER BY` clause.
* Default 'id'.
* @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
* @type int $network_id Limit results to those affiliated with a given network ID. If 0,
* include all networks. Default 0.
* @type array $network__in Array of network IDs to include affiliated sites for. Default empty.
* @type array $network__not_in Array of network IDs to exclude affiliated sites for. Default empty.
* @type string $domain Limit results to those affiliated with a given domain. Default empty.
* @type array $domain__in Array of domains to include affiliated sites for. Default empty.
* @type array $domain__not_in Array of domains to exclude affiliated sites for. Default empty.
* @type string $path Limit results to those affiliated with a given path. Default empty.
* @type array $path__in Array of paths to include affiliated sites for. Default empty.
* @type array $path__not_in Array of paths to exclude affiliated sites for. Default empty.
* @type int $public Limit results to public sites. Accepts '1' or '0'. Default empty.
* @type int $archived Limit results to archived sites. Accepts '1' or '0'. Default empty.
* @type int $mature Limit results to mature sites. Accepts '1' or '0'. Default empty.
* @type int $spam Limit results to spam sites. Accepts '1' or '0'. Default empty.
* @type int $deleted Limit results to deleted sites. Accepts '1' or '0'. Default empty.
* @type int $lang_id Limit results to a language ID. Default empty.
* @type array $lang__in Array of language IDs to include affiliated sites for. Default empty.
* @type array $lang__not_in Array of language IDs to exclude affiliated sites for. Default empty.
* @type string $search Search term(s) to retrieve matching sites for. Default empty.
* @type array $search_columns Array of column names to be searched. Accepts 'domain' and 'path'.
* Default empty array.
* @type bool $update_site_cache Whether to prime the cache for found sites. Default true.
* @type bool $update_site_meta_cache Whether to prime the metadata cache for found sites. Default true.
* @type array $meta_query Meta query clauses to limit retrieved sites by. See `WP_Meta_Query`.
* Default empty.
* @type string $meta_key Limit sites to those matching a specific metadata key.
* Can be used in conjunction with `$meta_value`. Default empty.
* @type string $meta_value Limit sites to those matching a specific metadata value.
* Usually used in conjunction with `$meta_key`. Default empty.
* @type string $meta_type Data type that the `$meta_value` column will be CAST to for
* comparisons. Default empty.
* @type string $meta_compare Comparison operator to test the `$meta_value`. Default empty.
* }
*/
public function __construct( $query = '' ) {
$this->query_var_defaults = array(
'fields' => '',
'ID' => '',
'site__in' => '',
'site__not_in' => '',
'number' => 100,
'offset' => '',
'no_found_rows' => true,
'orderby' => 'id',
'order' => 'ASC',
'network_id' => 0,
'network__in' => '',
'network__not_in' => '',
'domain' => '',
'domain__in' => '',
'domain__not_in' => '',
'path' => '',
'path__in' => '',
'path__not_in' => '',
'public' => null,
'archived' => null,
'mature' => null,
'spam' => null,
'deleted' => null,
'lang_id' => null,
'lang__in' => '',
'lang__not_in' => '',
'search' => '',
'search_columns' => array(),
'count' => false,
'date_query' => null, // See WP_Date_Query
'update_site_cache' => true,
'fields' => '',
'ID' => '',
'site__in' => '',
'site__not_in' => '',
'number' => 100,
'offset' => '',
'no_found_rows' => true,
'orderby' => 'id',
'order' => 'ASC',
'network_id' => 0,
'network__in' => '',
'network__not_in' => '',
'domain' => '',
'domain__in' => '',
'domain__not_in' => '',
'path' => '',
'path__in' => '',
'path__not_in' => '',
'public' => null,
'archived' => null,
'mature' => null,
'spam' => null,
'deleted' => null,
'lang_id' => null,
'lang__in' => '',
'lang__not_in' => '',
'search' => '',
'search_columns' => array(),
'count' => false,
'date_query' => null, // See WP_Date_Query
'update_site_cache' => true,
'update_site_meta_cache' => true,
'meta_query' => '',
'meta_key' => '',
'meta_value' => '',
'meta_type' => '',
'meta_compare' => '',
);
if ( ! empty( $query ) ) {
@ -225,12 +259,20 @@ class WP_Site_Query {
*
* @since 4.6.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return array|int List of WP_Site objects, a list of site ids when 'fields' is set to 'ids',
* or the number of sites when 'count' is passed as a query var.
*/
public function get_sites() {
global $wpdb;
$this->parse_query();
// Parse meta query.
$this->meta_query = new WP_Meta_Query();
$this->meta_query->parse_query_vars( $this->query_vars );
/**
* Fires before sites are retrieved.
*
@ -240,16 +282,22 @@ class WP_Site_Query {
*/
do_action_ref_array( 'pre_get_sites', array( &$this ) );
// Reparse query vars, in case they were modified in a 'pre_get_sites' callback.
$this->meta_query->parse_query_vars( $this->query_vars );
if ( ! empty( $this->meta_query->queries ) ) {
$this->meta_query_clauses = $this->meta_query->get_sql( 'blog', $wpdb->blogs, 'blog_id', $this );
}
// $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
$_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
// Ignore the $fields argument as the queried result will be the same regardless.
unset( $_args['fields'] );
$key = md5( serialize( $_args ) );
$key = md5( serialize( $_args ) );
$last_changed = wp_cache_get_last_changed( 'sites' );
$cache_key = "get_sites:$key:$last_changed";
$cache_key = "get_sites:$key:$last_changed";
$cache_value = wp_cache_get( $cache_key, 'sites' );
if ( false === $cache_value ) {
@ -259,12 +307,12 @@ class WP_Site_Query {
}
$cache_value = array(
'site_ids' => $site_ids,
'site_ids' => $site_ids,
'found_sites' => $this->found_sites,
);
wp_cache_add( $cache_key, $cache_value, 'sites' );
} else {
$site_ids = $cache_value['site_ids'];
$site_ids = $cache_value['site_ids'];
$this->found_sites = $cache_value['found_sites'];
}
@ -288,7 +336,7 @@ class WP_Site_Query {
// Prime site network caches.
if ( $this->query_vars['update_site_cache'] ) {
_prime_site_caches( $site_ids );
_prime_site_caches( $site_ids, $this->query_vars['update_site_meta_cache'] );
}
// Fetch full site objects from the primed cache.
@ -304,7 +352,7 @@ class WP_Site_Query {
*
* @since 4.6.0
*
* @param array $_sites An array of WP_Site objects.
* @param WP_Site[] $_sites An array of WP_Site objects.
* @param WP_Site_Query $this Current instance of WP_Site_Query (passed by reference).
*/
$_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
@ -345,10 +393,10 @@ class WP_Site_Query {
if ( is_int( $_key ) ) {
$_orderby = $_value;
$_order = $order;
$_order = $order;
} else {
$_orderby = $_key;
$_order = $_value;
$_order = $_value;
}
$parsed = $this->parse_orderby( $_orderby );
@ -367,7 +415,7 @@ class WP_Site_Query {
$orderby = implode( ', ', $orderby_array );
} else {
$orderby = "blog_id $order";
$orderby = "{$wpdb->blogs}.blog_id $order";
}
$number = absint( $this->query_vars['number'] );
@ -385,23 +433,23 @@ class WP_Site_Query {
if ( $this->query_vars['count'] ) {
$fields = 'COUNT(*)';
} else {
$fields = 'blog_id';
$fields = "{$wpdb->blogs}.blog_id";
}
// Parse site IDs for an IN clause.
$site_id = absint( $this->query_vars['ID'] );
if ( ! empty( $site_id ) ) {
$this->sql_clauses['where']['ID'] = $wpdb->prepare( 'blog_id = %d', $site_id );
$this->sql_clauses['where']['ID'] = $wpdb->prepare( "{$wpdb->blogs}.blog_id = %d", $site_id );
}
// Parse site IDs for an IN clause.
if ( ! empty( $this->query_vars['site__in'] ) ) {
$this->sql_clauses['where']['site__in'] = "blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
$this->sql_clauses['where']['site__in'] = "{$wpdb->blogs}.blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
}
// Parse site IDs for a NOT IN clause.
if ( ! empty( $this->query_vars['site__not_in'] ) ) {
$this->sql_clauses['where']['site__not_in'] = "blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
$this->sql_clauses['where']['site__not_in'] = "{$wpdb->blogs}.blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
}
$network_id = absint( $this->query_vars['network_id'] );
@ -449,33 +497,33 @@ class WP_Site_Query {
}
if ( is_numeric( $this->query_vars['archived'] ) ) {
$archived = absint( $this->query_vars['archived'] );
$this->sql_clauses['where']['archived'] = $wpdb->prepare( "archived = %s ", absint( $archived ) );
$archived = absint( $this->query_vars['archived'] );
$this->sql_clauses['where']['archived'] = $wpdb->prepare( 'archived = %s ', absint( $archived ) );
}
if ( is_numeric( $this->query_vars['mature'] ) ) {
$mature = absint( $this->query_vars['mature'] );
$this->sql_clauses['where']['mature'] = $wpdb->prepare( "mature = %d ", $mature );
$mature = absint( $this->query_vars['mature'] );
$this->sql_clauses['where']['mature'] = $wpdb->prepare( 'mature = %d ', $mature );
}
if ( is_numeric( $this->query_vars['spam'] ) ) {
$spam = absint( $this->query_vars['spam'] );
$this->sql_clauses['where']['spam'] = $wpdb->prepare( "spam = %d ", $spam );
$spam = absint( $this->query_vars['spam'] );
$this->sql_clauses['where']['spam'] = $wpdb->prepare( 'spam = %d ', $spam );
}
if ( is_numeric( $this->query_vars['deleted'] ) ) {
$deleted = absint( $this->query_vars['deleted'] );
$this->sql_clauses['where']['deleted'] = $wpdb->prepare( "deleted = %d ", $deleted );
$deleted = absint( $this->query_vars['deleted'] );
$this->sql_clauses['where']['deleted'] = $wpdb->prepare( 'deleted = %d ', $deleted );
}
if ( is_numeric( $this->query_vars['public'] ) ) {
$public = absint( $this->query_vars['public'] );
$this->sql_clauses['where']['public'] = $wpdb->prepare( "public = %d ", $public );
$public = absint( $this->query_vars['public'] );
$this->sql_clauses['where']['public'] = $wpdb->prepare( 'public = %d ', $public );
}
if ( is_numeric( $this->query_vars['lang_id'] ) ) {
$lang_id = absint( $this->query_vars['lang_id'] );
$this->sql_clauses['where']['lang_id'] = $wpdb->prepare( "lang_id = %d ", $lang_id );
$lang_id = absint( $this->query_vars['lang_id'] );
$this->sql_clauses['where']['lang_id'] = $wpdb->prepare( 'lang_id = %d ', $lang_id );
}
// Parse site language IDs for an IN clause.
@ -507,7 +555,7 @@ class WP_Site_Query {
*
* @since 4.6.0
*
* @param array $search_columns Array of column names to be searched.
* @param string[] $search_columns Array of column names to be searched.
* @param string $search Text being searched.
* @param WP_Site_Query $this The current WP_Site_Query instance.
*/
@ -518,16 +566,26 @@ class WP_Site_Query {
$date_query = $this->query_vars['date_query'];
if ( ! empty( $date_query ) && is_array( $date_query ) ) {
$this->date_query = new WP_Date_Query( $date_query, 'registered' );
$this->date_query = new WP_Date_Query( $date_query, 'registered' );
$this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
}
$join = '';
$join = '';
$groupby = '';
if ( ! empty( $this->meta_query_clauses ) ) {
$join .= $this->meta_query_clauses['join'];
// Strip leading 'AND'.
$this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
if ( ! $this->query_vars['count'] ) {
$groupby = "{$wpdb->blogs}.blog_id";
}
}
$where = implode( ' AND ', $this->sql_clauses['where'] );
$groupby = '';
$pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
/**
@ -535,16 +593,16 @@ class WP_Site_Query {
*
* @since 4.6.0
*
* @param array $pieces A compacted array of site query clauses.
* @param string[] $pieces An associative array of site query clauses.
* @param WP_Site_Query $this Current instance of WP_Site_Query (passed by reference).
*/
$clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
if ( $where ) {
@ -614,8 +672,8 @@ class WP_Site_Query {
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $string Search string.
* @param array $columns Columns to search.
* @param string $string Search string.
* @param string[] $columns Array of columns to search.
* @return string Search SQL.
*/
protected function get_search_sql( $string, $columns ) {
@ -653,11 +711,11 @@ class WP_Site_Query {
switch ( $orderby ) {
case 'site__in':
$site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) );
$parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
$parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
break;
case 'network__in':
$network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
$parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
$parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
break;
case 'domain':
case 'last_updated':
@ -675,10 +733,42 @@ class WP_Site_Query {
$parsed = 'CHAR_LENGTH(path)';
break;
case 'id':
$parsed = 'blog_id';
$parsed = "{$wpdb->blogs}.blog_id";
break;
}
if ( ! empty( $parsed ) || empty( $this->meta_query_clauses ) ) {
return $parsed;
}
$meta_clauses = $this->meta_query->get_clauses();
if ( empty( $meta_clauses ) ) {
return $parsed;
}
$primary_meta_query = reset( $meta_clauses );
if ( ! empty( $primary_meta_query['key'] ) && $primary_meta_query['key'] === $orderby ) {
$orderby = 'meta_value';
}
switch ( $orderby ) {
case 'meta_value':
if ( ! empty( $primary_meta_query['type'] ) ) {
$parsed = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
} else {
$parsed = "{$primary_meta_query['alias']}.meta_value";
}
break;
case 'meta_value_num':
$parsed = "{$primary_meta_query['alias']}.meta_value+0";
break;
default:
if ( isset( $meta_clauses[ $orderby ] ) ) {
$meta_clause = $meta_clauses[ $orderby ];
$parsed = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
}
}
return $parsed;
}

View file

@ -145,7 +145,6 @@ final class WP_Site {
/**
* Retrieves a site from the database by its ID.
*
* @static
* @since 4.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
@ -187,7 +186,7 @@ final class WP_Site {
* @param WP_Site|object $site A site object.
*/
public function __construct( $site ) {
foreach( get_object_vars( $site ) as $key => $value ) {
foreach ( get_object_vars( $site ) as $key => $value ) {
$this->$key = $value;
}
}

View file

@ -43,11 +43,12 @@ class WP_Tax_Query {
* Standard response when the query should not return any rows.
*
* @since 3.2.0
*
* @static
* @var string
*/
private static $no_results = array( 'join' => array( '' ), 'where' => array( '0 = 1' ) );
private static $no_results = array(
'join' => array( '' ),
'where' => array( '0 = 1' ),
);
/**
* A flat list of table aliases used in the JOIN clauses.
@ -135,10 +136,10 @@ class WP_Tax_Query {
$cleaned_query = array();
$defaults = array(
'taxonomy' => '',
'terms' => array(),
'field' => 'term_id',
'operator' => 'IN',
'taxonomy' => '',
'terms' => array(),
'field' => 'term_id',
'operator' => 'IN',
'include_children' => true,
);
@ -146,12 +147,12 @@ class WP_Tax_Query {
if ( 'relation' === $key ) {
$cleaned_query['relation'] = $this->sanitize_relation( $query );
// First-order clause.
// First-order clause.
} elseif ( self::is_first_order_clause( $query ) ) {
$cleaned_clause = array_merge( $defaults, $query );
$cleaned_clause = array_merge( $defaults, $query );
$cleaned_clause['terms'] = (array) $cleaned_clause['terms'];
$cleaned_query[] = $cleaned_clause;
$cleaned_query[] = $cleaned_clause;
/*
* Keep a copy of the clause in the flate
@ -176,7 +177,7 @@ class WP_Tax_Query {
}
}
// Otherwise, it's a nested query, so we recurse.
// Otherwise, it's a nested query, so we recurse.
} elseif ( is_array( $query ) ) {
$cleaned_subquery = $this->sanitize_query( $query );
@ -221,8 +222,6 @@ class WP_Tax_Query {
*
* @since 4.1.0
*
* @static
*
* @param array $query Tax query arguments.
* @return bool Whether the query clause is a first-order clause.
*/
@ -235,8 +234,6 @@ class WP_Tax_Query {
*
* @since 3.1.0
*
* @static
*
* @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
* @param string $primary_id_column ID column for the filtered object in $primary_table.
* @return array {
@ -247,7 +244,7 @@ class WP_Tax_Query {
* }
*/
public function get_sql( $primary_table, $primary_id_column ) {
$this->primary_table = $primary_table;
$this->primary_table = $primary_table;
$this->primary_id_column = $primary_id_column;
return $this->get_sql_clauses();
@ -274,7 +271,7 @@ class WP_Tax_Query {
* To keep $this->queries unaltered, pass a copy.
*/
$queries = $this->queries;
$sql = $this->get_sql_for_query( $queries );
$sql = $this->get_sql_for_query( $queries );
if ( ! empty( $sql['where'] ) ) {
$sql['where'] = ' AND ' . $sql['where'];
@ -314,7 +311,7 @@ class WP_Tax_Query {
$indent = '';
for ( $i = 0; $i < $depth; $i++ ) {
$indent .= " ";
$indent .= ' ';
}
foreach ( $query as $key => &$clause ) {
@ -336,7 +333,7 @@ class WP_Tax_Query {
}
$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
// This is a subquery, so we recurse.
// This is a subquery, so we recurse.
} else {
$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
@ -399,7 +396,7 @@ class WP_Tax_Query {
return self::$no_results;
}
$terms = $clause['terms'];
$terms = $clause['terms'];
$operator = strtoupper( $clause['operator'] );
if ( 'IN' == $operator ) {
@ -416,7 +413,7 @@ class WP_Tax_Query {
*/
$alias = $this->find_compatible_table_alias( $clause, $parent_query );
if ( false === $alias ) {
$i = count( $this->table_aliases );
$i = count( $this->table_aliases );
$alias = $i ? 'tt' . $i : $wpdb->term_relationships;
// Store the alias as part of a flat array to build future iterators.
@ -430,7 +427,6 @@ class WP_Tax_Query {
$join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
}
$where = "$alias.term_taxonomy_id $operator ($terms)";
} elseif ( 'NOT IN' == $operator ) {
@ -466,14 +462,17 @@ class WP_Tax_Query {
} elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
$where = $wpdb->prepare( "$operator (
$where = $wpdb->prepare(
"$operator (
SELECT 1
FROM $wpdb->term_relationships
INNER JOIN $wpdb->term_taxonomy
ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE $wpdb->term_taxonomy.taxonomy = %s
AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
)", $clause['taxonomy'] );
)",
$clause['taxonomy']
);
}
@ -561,12 +560,13 @@ class WP_Tax_Query {
if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
$this->transform_query( $query, 'term_id' );
if ( is_wp_error( $query ) )
if ( is_wp_error( $query ) ) {
return;
}
$children = array();
foreach ( $query['terms'] as $term ) {
$children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
$children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
$children[] = $term;
}
$query['terms'] = $children;
@ -590,11 +590,13 @@ class WP_Tax_Query {
* or 'term_id'. Default 'term_id'.
*/
public function transform_query( &$query, $resulting_field ) {
if ( empty( $query['terms'] ) )
if ( empty( $query['terms'] ) ) {
return;
}
if ( $query['field'] == $resulting_field )
if ( $query['field'] == $resulting_field ) {
return;
}
$resulting_field = sanitize_key( $resulting_field );

View file

@ -127,6 +127,14 @@ final class WP_Taxonomy {
*/
public $meta_box_cb = null;
/**
* The callback function for sanitizing taxonomy data saved from a meta box.
*
* @since 5.1.0
* @var callable
*/
public $meta_box_sanitize_cb = null;
/**
* An array of object types this taxonomy is registered for.
*
@ -139,7 +147,7 @@ final class WP_Taxonomy {
* Capabilities for this taxonomy.
*
* @since 4.7.0
* @var array
* @var object
*/
public $cap;
@ -238,9 +246,9 @@ final class WP_Taxonomy {
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param array $object_type Array of names of object types for the taxonomy.
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param string[] $object_type Array of names of object types for the taxonomy.
*/
$args = apply_filters( 'register_taxonomy_args', $args, $this->name, (array) $object_type );
@ -257,6 +265,7 @@ final class WP_Taxonomy {
'show_in_quick_edit' => null,
'show_admin_column' => false,
'meta_box_cb' => null,
'meta_box_sanitize_cb' => null,
'capabilities' => array(),
'rewrite' => true,
'query_var' => $this->name,
@ -286,11 +295,14 @@ final class WP_Taxonomy {
}
if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
$args['rewrite'] = wp_parse_args( $args['rewrite'], array(
'with_front' => true,
'hierarchical' => false,
'ep_mask' => EP_NONE,
) );
$args['rewrite'] = wp_parse_args(
$args['rewrite'],
array(
'with_front' => true,
'hierarchical' => false,
'ep_mask' => EP_NONE,
)
);
if ( empty( $args['rewrite']['slug'] ) ) {
$args['rewrite']['slug'] = sanitize_title_with_dashes( $this->name );
@ -345,12 +357,26 @@ final class WP_Taxonomy {
$args['name'] = $this->name;
// Default meta box sanitization callback depends on the value of 'meta_box_cb'.
if ( null === $args['meta_box_sanitize_cb'] ) {
switch ( $args['meta_box_cb'] ) {
case 'post_categories_meta_box':
$args['meta_box_sanitize_cb'] = 'taxonomy_meta_box_sanitize_cb_checkboxes';
break;
case 'post_tags_meta_box':
default:
$args['meta_box_sanitize_cb'] = 'taxonomy_meta_box_sanitize_cb_input';
break;
}
}
foreach ( $args as $property_name => $property_value ) {
$this->$property_name = $property_value;
}
$this->labels = get_taxonomy_labels( $this );
$this->label = $this->labels->name;
$this->label = $this->labels->name;
}
/**

View file

@ -123,8 +123,8 @@ class WP_Term_Query {
* @type int $offset The number by which to offset the terms query. Default empty.
* @type string $fields Term fields to query for. Accepts 'all' (returns an array of
* complete term objects), 'all_with_object_id' (returns an
* array of term objects with the 'object_id' param; only works
* when the `$fields` parameter is 'object_ids' ), 'ids'
* array of term objects with the 'object_id' param; works only
* when the `$object_ids` parameter is populated), 'ids'
* (returns an array of ids), 'tt_ids' (returns an array of
* term taxonomy ids), 'id=>parent' (returns an associative
* array with ids as keys, parent term IDs as values), 'names'
@ -238,8 +238,8 @@ class WP_Term_Query {
*
* @since 4.4.0
*
* @param array $defaults An array of default get_terms() arguments.
* @param array $taxonomies An array of taxonomies.
* @param array $defaults An array of default get_terms() arguments.
* @param string[] $taxonomies An array of taxonomy names.
*/
$this->query_var_defaults = apply_filters( 'get_terms_defaults', $this->query_var_defaults, $taxonomies );
@ -254,11 +254,11 @@ class WP_Term_Query {
}
if ( 'all' == $query['get'] ) {
$query['childless'] = false;
$query['child_of'] = 0;
$query['hide_empty'] = 0;
$query['childless'] = false;
$query['child_of'] = 0;
$query['hide_empty'] = 0;
$query['hierarchical'] = false;
$query['pad_counts'] = false;
$query['pad_counts'] = false;
}
$query['taxonomy'] = $taxonomies;
@ -330,7 +330,7 @@ class WP_Term_Query {
if ( ! $has_hierarchical_tax ) {
$args['hierarchical'] = false;
$args['pad_counts'] = false;
$args['pad_counts'] = false;
}
// 'parent' overrides 'child_of'.
@ -339,11 +339,11 @@ class WP_Term_Query {
}
if ( 'all' == $args['get'] ) {
$args['childless'] = false;
$args['child_of'] = 0;
$args['hide_empty'] = 0;
$args['childless'] = false;
$args['child_of'] = 0;
$args['hide_empty'] = 0;
$args['hierarchical'] = false;
$args['pad_counts'] = false;
$args['pad_counts'] = false;
}
/**
@ -351,8 +351,8 @@ class WP_Term_Query {
*
* @since 3.1.0
*
* @param array $args An array of get_terms() arguments.
* @param array $taxonomies An array of taxonomies.
* @param array $args An array of get_terms() arguments.
* @param string[] $taxonomies An array of taxonomy names.
*/
$args = apply_filters( 'get_terms_args', $args, $taxonomies );
@ -379,7 +379,12 @@ class WP_Term_Query {
}
if ( ! $in_hierarchy ) {
return array();
if ( 'count' == $args['fields'] ) {
return 0;
} else {
$this->terms = array();
return $this->terms;
}
}
}
@ -406,9 +411,9 @@ class WP_Term_Query {
$inclusions = '';
if ( ! empty( $include ) ) {
$exclude = '';
$exclude = '';
$exclude_tree = '';
$inclusions = implode( ',', wp_parse_id_list( $include ) );
$inclusions = implode( ',', wp_parse_id_list( $include ) );
}
if ( ! empty( $inclusions ) ) {
@ -417,16 +422,19 @@ class WP_Term_Query {
$exclusions = array();
if ( ! empty( $exclude_tree ) ) {
$exclude_tree = wp_parse_id_list( $exclude_tree );
$exclude_tree = wp_parse_id_list( $exclude_tree );
$excluded_children = $exclude_tree;
foreach ( $exclude_tree as $extrunk ) {
$excluded_children = array_merge(
$excluded_children,
(array) get_terms( reset( $taxonomies ), array(
'child_of' => intval( $extrunk ),
'fields' => 'ids',
'hide_empty' => 0
) )
(array) get_terms(
reset( $taxonomies ),
array(
'child_of' => intval( $extrunk ),
'fields' => 'ids',
'hide_empty' => 0,
)
)
);
}
$exclusions = array_merge( $excluded_children, $exclusions );
@ -441,7 +449,7 @@ class WP_Term_Query {
if ( $childless ) {
foreach ( $taxonomies as $_tax ) {
$term_hierarchy = _get_term_hierarchy( $_tax );
$exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions );
$exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions );
}
}
@ -456,9 +464,9 @@ class WP_Term_Query {
*
* @since 2.3.0
*
* @param string $exclusions `NOT IN` clause of the terms query.
* @param array $args An array of terms query arguments.
* @param array $taxonomies An array of taxonomies.
* @param string $exclusions `NOT IN` clause of the terms query.
* @param array $args An array of terms query arguments.
* @param string[] $taxonomies An array of taxonomy names.
*/
$exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
@ -485,10 +493,10 @@ class WP_Term_Query {
( is_string( $args['slug'] ) && 0 !== strlen( $args['slug'] ) )
) {
if ( is_array( $args['slug'] ) ) {
$slug = array_map( 'sanitize_title', $args['slug'] );
$slug = array_map( 'sanitize_title', $args['slug'] );
$this->sql_clauses['where']['slug'] = "t.slug IN ('" . implode( "', '", $slug ) . "')";
} else {
$slug = sanitize_title( $args['slug'] );
$slug = sanitize_title( $args['slug'] );
$this->sql_clauses['where']['slug'] = "t.slug = '$slug'";
}
}
@ -498,16 +506,16 @@ class WP_Term_Query {
$tt_ids = implode( ',', array_map( 'intval', $args['term_taxonomy_id'] ) );
$this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})";
} else {
$this->sql_clauses['where']['term_taxonomy_id'] = $wpdb->prepare( "tt.term_taxonomy_id = %d", $args['term_taxonomy_id'] );
$this->sql_clauses['where']['term_taxonomy_id'] = $wpdb->prepare( 'tt.term_taxonomy_id = %d', $args['term_taxonomy_id'] );
}
}
if ( ! empty( $args['name__like'] ) ) {
$this->sql_clauses['where']['name__like'] = $wpdb->prepare( "t.name LIKE %s", '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
$this->sql_clauses['where']['name__like'] = $wpdb->prepare( 't.name LIKE %s', '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
}
if ( ! empty( $args['description__like'] ) ) {
$this->sql_clauses['where']['description__like'] = $wpdb->prepare( "tt.description LIKE %s", '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
$this->sql_clauses['where']['description__like'] = $wpdb->prepare( 'tt.description LIKE %s', '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
}
if ( ! empty( $args['object_ids'] ) ) {
@ -516,7 +524,7 @@ class WP_Term_Query {
$object_ids = array( $object_ids );
}
$object_ids = implode( ', ', array_map( 'intval', $object_ids ) );
$object_ids = implode( ', ', array_map( 'intval', $object_ids ) );
$this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)";
}
@ -529,7 +537,7 @@ class WP_Term_Query {
}
if ( '' !== $parent ) {
$parent = (int) $parent;
$parent = (int) $parent;
$this->sql_clauses['where']['parent'] = "tt.parent = '$parent'";
}
@ -537,7 +545,7 @@ class WP_Term_Query {
if ( 'count' == $args['fields'] ) {
$hierarchical = false;
}
if ( $args['hide_empty'] && !$hierarchical ) {
if ( $args['hide_empty'] && ! $hierarchical ) {
$this->sql_clauses['where']['count'] = 'tt.count > 0';
}
@ -555,33 +563,32 @@ class WP_Term_Query {
$limits = '';
}
if ( ! empty( $args['search'] ) ) {
$this->sql_clauses['where']['search'] = $this->get_search_sql( $args['search'] );
}
// Meta query support.
$join = '';
$join = '';
$distinct = '';
// Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback.
$this->meta_query->parse_query_vars( $this->query_vars );
$mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' );
$mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' );
$meta_clauses = $this->meta_query->get_clauses();
if ( ! empty( $meta_clauses ) ) {
$join .= $mq_sql['join'];
$join .= $mq_sql['join'];
$this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $mq_sql['where'] );
$distinct .= "DISTINCT";
$distinct .= 'DISTINCT';
}
$selects = array();
switch ( $args['fields'] ) {
case 'all':
case 'all_with_object_id' :
case 'tt_ids' :
case 'slugs' :
case 'all_with_object_id':
case 'tt_ids':
case 'slugs':
$selects = array( 't.*', 'tt.*' );
if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) {
$selects[] = 'tr.object_id';
@ -596,7 +603,7 @@ class WP_Term_Query {
break;
case 'count':
$orderby = '';
$order = '';
$order = '';
$selects = array( 'COUNT(*)' );
break;
case 'id=>name':
@ -621,9 +628,9 @@ class WP_Term_Query {
*
* @since 2.8.0
*
* @param array $selects An array of fields to select for the terms query.
* @param array $args An array of term query arguments.
* @param array $taxonomies An array of taxonomies.
* @param string[] $selects An array of fields to select for the terms query.
* @param array $args An array of term query arguments.
* @param string[] $taxonomies An array of taxonomy names.
*/
$fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
@ -640,19 +647,19 @@ class WP_Term_Query {
*
* @since 3.1.0
*
* @param array $pieces Terms query SQL clauses.
* @param array $taxonomies An array of taxonomies.
* @param array $args An array of terms query arguments.
* @param string[] $pieces Array of query SQL clauses.
* @param string[] $taxonomies An array of taxonomy names.
* @param array $args An array of term query arguments.
*/
$clauses = apply_filters( 'terms_clauses', compact( 'fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits' ), $taxonomies, $args );
$fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
$join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
$where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
$distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
$orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
$order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
$limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$order = isset( $clauses['order'] ) ? $clauses['order'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
if ( $where ) {
$where = "WHERE $where";
@ -666,10 +673,10 @@ class WP_Term_Query {
$this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
// $args can be anything. Only use the args defined in defaults to compute the key.
$key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) ) ) . serialize( $taxonomies ) . $this->request );
$key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) ) ) . serialize( $taxonomies ) . $this->request );
$last_changed = wp_cache_get_last_changed( 'terms' );
$cache_key = "get_terms:$key:$last_changed";
$cache = wp_cache_get( $cache_key, 'terms' );
$cache_key = "get_terms:$key:$last_changed";
$cache = wp_cache_get( $cache_key, 'terms' );
if ( false !== $cache ) {
if ( 'all' === $_fields || 'all_with_object_id' === $_fields ) {
$cache = $this->populate_terms( $cache );
@ -751,7 +758,7 @@ class WP_Term_Query {
}
$_tt_ids[ $term->term_id ] = 1;
$_terms[] = $term;
$_terms[] = $term;
}
$terms = $_terms;
@ -822,7 +829,7 @@ class WP_Term_Query {
* @return string|false Value to used in the ORDER clause. False otherwise.
*/
protected function parse_orderby( $orderby_raw ) {
$_orderby = strtolower( $orderby_raw );
$_orderby = strtolower( $orderby_raw );
$maybe_orderby_meta = false;
if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) {
@ -835,7 +842,7 @@ class WP_Term_Query {
$include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) );
$orderby = "FIELD( t.term_id, $include )";
} elseif ( 'slug__in' == $_orderby && ! empty( $this->query_vars['slug'] ) && is_array( $this->query_vars['slug'] ) ) {
$slugs = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) );
$slugs = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) );
$orderby = "FIELD( t.slug, '" . $slugs . "')";
} elseif ( 'none' == $_orderby ) {
$orderby = '';
@ -853,9 +860,9 @@ class WP_Term_Query {
*
* @since 2.8.0
*
* @param string $orderby `ORDERBY` clause of the terms query.
* @param array $args An array of terms query arguments.
* @param array $taxonomies An array of taxonomies.
* @param string $orderby `ORDERBY` clause of the terms query.
* @param array $args An array of term query arguments.
* @param string[] $taxonomies An array of taxonomy names.
*/
$orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] );
@ -888,12 +895,12 @@ class WP_Term_Query {
return $orderby;
}
$allowed_keys = array();
$primary_meta_key = null;
$allowed_keys = array();
$primary_meta_key = null;
$primary_meta_query = reset( $meta_clauses );
if ( ! empty( $primary_meta_query['key'] ) ) {
$primary_meta_key = $primary_meta_query['key'];
$allowed_keys[] = $primary_meta_key;
$allowed_keys[] = $primary_meta_key;
}
$allowed_keys[] = 'meta_value';
$allowed_keys[] = 'meta_value_num';
@ -903,7 +910,7 @@ class WP_Term_Query {
return $orderby;
}
switch( $orderby_raw ) {
switch ( $orderby_raw ) {
case $primary_meta_key:
case 'meta_value':
if ( ! empty( $primary_meta_query['type'] ) ) {
@ -921,7 +928,7 @@ class WP_Term_Query {
if ( array_key_exists( $orderby_raw, $meta_clauses ) ) {
// $orderby corresponds to a meta_query clause.
$meta_clause = $meta_clauses[ $orderby_raw ];
$orderby = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
$orderby = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
}
break;
}

View file

@ -102,7 +102,6 @@ final class WP_Term {
* Retrieve WP_Term instance.
*
* @since 4.4.0
* @static
*
* @global wpdb $wpdb WordPress database abstraction object.
*
@ -143,11 +142,11 @@ final class WP_Term {
}
}
// If only one match was found, it's the one we want.
// If only one match was found, it's the one we want.
} elseif ( 1 === count( $terms ) ) {
$_term = reset( $terms );
// Otherwise, the term must be shared between taxonomies.
// Otherwise, the term must be shared between taxonomies.
} else {
// If the term is shared only with invalid taxonomies, return the one valid term.
foreach ( $terms as $t ) {
@ -232,8 +231,8 @@ final class WP_Term {
*/
public function __get( $key ) {
switch ( $key ) {
case 'data' :
$data = new stdClass();
case 'data':
$data = new stdClass();
$columns = array( 'term_id', 'name', 'slug', 'term_group', 'term_taxonomy_id', 'taxonomy', 'description', 'parent', 'count' );
foreach ( $columns as $column ) {
$data->{$column} = isset( $this->{$column} ) ? $this->{$column} : null;

View file

@ -23,8 +23,8 @@ class WP_Text_Diff_Renderer_inline extends Text_Diff_Renderer_inline {
* @param string $newlineEscape
* @return string
*/
public function _splitOnWords($string, $newlineEscape = "\n") {
$string = str_replace("\0", '', $string);
public function _splitOnWords( $string, $newlineEscape = "\n" ) {
$string = str_replace( "\0", '', $string );
$words = preg_split( '/([^\w])/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
$words = str_replace( "\n", $newlineEscape, $words );
return $words;

View file

@ -20,7 +20,7 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
* @var int
* @since 2.6.0
*/
public $_leading_context_lines = 10000;
public $_leading_context_lines = 10000;
/**
* @see Text_Diff_Renderer::_trailing_context_lines
@ -82,8 +82,9 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
*/
public function __construct( $params = array() ) {
parent::__construct( $params );
if ( isset( $params[ 'show_split_view' ] ) )
$this->_show_split_view = $params[ 'show_split_view' ];
if ( isset( $params['show_split_view'] ) ) {
$this->_show_split_view = $params['show_split_view'];
}
}
/**
@ -102,7 +103,7 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
* @param array $lines
* @param string $prefix
*/
public function _lines( $lines, $prefix=' ' ) {
public function _lines( $lines, $prefix = ' ' ) {
}
/**
@ -154,7 +155,7 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
*/
public function _added( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
@ -169,7 +170,7 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
*
* @param String $processed_line The processed diffed line.
* @param String $line The unprocessed diffed line.
* @param string null The line context. Values are 'added', 'deleted' or 'unchanged'.
* @param string null The line context. Values are 'added', 'deleted' or 'unchanged'.
*/
$line = apply_filters( 'process_text_diff_html', $processed_line, $line, 'added' );
}
@ -192,7 +193,7 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
*/
public function _deleted( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
@ -204,7 +205,6 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
} else {
$r .= '<tr>' . $this->deletedLine( $line ) . "</tr>\n";
}
}
return $r;
}
@ -218,15 +218,15 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
*/
public function _context( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
/** This filter is documented in wp-includes/wp-diff.php */
$line = apply_filters( 'process_text_diff_html', $processed_line, $line, 'unchanged' );
}
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->contextLine( $line ) . $this->emptyLine() . $this->contextLine( $line ) . "</tr>\n";
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->contextLine( $line ) . $this->emptyLine() . $this->contextLine( $line ) . "</tr>\n";
} else {
$r .= '<tr>' . $this->contextLine( $line ) . "</tr>\n";
}
@ -264,58 +264,62 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
// Compute word diffs for each matched pair using the inline diff
foreach ( $orig_matches as $o => $f ) {
if ( is_numeric($o) && is_numeric($f) ) {
$text_diff = new Text_Diff( 'auto', array( array($orig[$o]), array($final[$f]) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
if ( is_numeric( $o ) && is_numeric( $f ) ) {
$text_diff = new Text_Diff( 'auto', array( array( $orig[ $o ] ), array( $final[ $f ] ) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
// If they're too different, don't include any <ins> or <dels>
if ( preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) {
// length of all text between <ins> or <del>
$stripped_matches = strlen(strip_tags( join(' ', $diff_matches[0]) ));
$stripped_matches = strlen( strip_tags( join( ' ', $diff_matches[0] ) ) );
// since we count lengith of text between <ins> or <del> (instead of picking just one),
// we double the length of chars not in those tags.
$stripped_diff = strlen(strip_tags( $diff )) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold )
$stripped_diff = strlen( strip_tags( $diff ) ) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold ) {
continue; // Too different. Don't save diffs.
}
}
// Un-inline the diffs by removing del or ins
$orig_diffs[$o] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[$f] = preg_replace( '|<del>.*?</del>|', '', $diff );
$orig_diffs[ $o ] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[ $f ] = preg_replace( '|<del>.*?</del>|', '', $diff );
}
}
foreach ( array_keys($orig_rows) as $row ) {
foreach ( array_keys( $orig_rows ) as $row ) {
// Both columns have blanks. Ignore them.
if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 )
if ( $orig_rows[ $row ] < 0 && $final_rows[ $row ] < 0 ) {
continue;
}
// If we have a word based diff, use it. Otherwise, use the normal line.
if ( isset( $orig_diffs[$orig_rows[$row]] ) )
$orig_line = $orig_diffs[$orig_rows[$row]];
elseif ( isset( $orig[$orig_rows[$row]] ) )
$orig_line = htmlspecialchars($orig[$orig_rows[$row]]);
else
if ( isset( $orig_diffs[ $orig_rows[ $row ] ] ) ) {
$orig_line = $orig_diffs[ $orig_rows[ $row ] ];
} elseif ( isset( $orig[ $orig_rows[ $row ] ] ) ) {
$orig_line = htmlspecialchars( $orig[ $orig_rows[ $row ] ] );
} else {
$orig_line = '';
}
if ( isset( $final_diffs[$final_rows[$row]] ) )
$final_line = $final_diffs[$final_rows[$row]];
elseif ( isset( $final[$final_rows[$row]] ) )
$final_line = htmlspecialchars($final[$final_rows[$row]]);
else
if ( isset( $final_diffs[ $final_rows[ $row ] ] ) ) {
$final_line = $final_diffs[ $final_rows[ $row ] ];
} elseif ( isset( $final[ $final_rows[ $row ] ] ) ) {
$final_line = htmlspecialchars( $final[ $final_rows[ $row ] ] );
} else {
$final_line = '';
}
if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array($final_line), false );
} elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array($orig_line), false );
if ( $orig_rows[ $row ] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array( $final_line ), false );
} elseif ( $final_rows[ $row ] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array( $orig_line ), false );
} else { // A true changed row.
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->deletedLine( $orig_line ) . $this->emptyLine() . $this->addedLine( $final_line ) . "</tr>\n";
} else {
$r .= '<tr>' . $this->deletedLine( $orig_line ) . "</tr><tr>" . $this->addedLine( $final_line ) . "</tr>\n";
$r .= '<tr>' . $this->deletedLine( $orig_line ) . '</tr><tr>' . $this->addedLine( $final_line ) . "</tr>\n";
}
}
}
@ -355,54 +359,55 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
// Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array.
$matches = array();
foreach ( array_keys($orig) as $o ) {
foreach ( array_keys($final) as $f ) {
$matches["$o,$f"] = $this->compute_string_distance( $orig[$o], $final[$f] );
foreach ( array_keys( $orig ) as $o ) {
foreach ( array_keys( $final ) as $f ) {
$matches[ "$o,$f" ] = $this->compute_string_distance( $orig[ $o ], $final[ $f ] );
}
}
asort($matches); // Order by string distance.
asort( $matches ); // Order by string distance.
$orig_matches = array();
$final_matches = array();
foreach ( $matches as $keys => $difference ) {
list($o, $f) = explode(',', $keys);
$o = (int) $o;
$f = (int) $f;
list($o, $f) = explode( ',', $keys );
$o = (int) $o;
$f = (int) $f;
// Already have better matches for these guys
if ( isset($orig_matches[$o]) && isset($final_matches[$f]) )
if ( isset( $orig_matches[ $o ] ) && isset( $final_matches[ $f ] ) ) {
continue;
}
// First match for these guys. Must be best match
if ( !isset($orig_matches[$o]) && !isset($final_matches[$f]) ) {
$orig_matches[$o] = $f;
$final_matches[$f] = $o;
if ( ! isset( $orig_matches[ $o ] ) && ! isset( $final_matches[ $f ] ) ) {
$orig_matches[ $o ] = $f;
$final_matches[ $f ] = $o;
continue;
}
// Best match of this final is already taken? Must mean this final is a new row.
if ( isset($orig_matches[$o]) )
$final_matches[$f] = 'x';
// Best match of this orig is already taken? Must mean this orig is a deleted row.
elseif ( isset($final_matches[$f]) )
$orig_matches[$o] = 'x';
if ( isset( $orig_matches[ $o ] ) ) {
$final_matches[ $f ] = 'x';
} elseif ( isset( $final_matches[ $f ] ) ) {
// Best match of this orig is already taken? Must mean this orig is a deleted row.
$orig_matches[ $o ] = 'x';
}
}
// We read the text in this order
ksort($orig_matches);
ksort($final_matches);
ksort( $orig_matches );
ksort( $final_matches );
// Stores rows and blanks for each column.
$orig_rows = $orig_rows_copy = array_keys($orig_matches);
$final_rows = array_keys($final_matches);
$orig_rows = $orig_rows_copy = array_keys( $orig_matches );
$final_rows = array_keys( $final_matches );
// Interleaves rows with blanks to keep matches aligned.
// We may end up with some extraneous blank rows, but we'll just ignore them later.
foreach ( $orig_rows_copy as $orig_row ) {
$final_pos = array_search($orig_matches[$orig_row], $final_rows, true);
$orig_pos = (int) array_search($orig_row, $orig_rows, true);
$final_pos = array_search( $orig_matches[ $orig_row ], $final_rows, true );
$orig_pos = (int) array_search( $orig_row, $orig_rows, true );
if ( false === $final_pos ) { // This orig is paired with a blank final.
array_splice( $final_rows, $orig_pos, 0, -1 );
@ -416,17 +421,19 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
}
// Pad the ends with blank rows if the columns aren't the same length
$diff_count = count($orig_rows) - count($final_rows);
$diff_count = count( $orig_rows ) - count( $final_rows );
if ( $diff_count < 0 ) {
while ( $diff_count < 0 )
array_push($orig_rows, $diff_count++);
while ( $diff_count < 0 ) {
array_push( $orig_rows, $diff_count++ );
}
} elseif ( $diff_count > 0 ) {
$diff_count = -1 * $diff_count;
while ( $diff_count < 0 )
array_push($final_rows, $diff_count++);
while ( $diff_count < 0 ) {
array_push( $final_rows, $diff_count++ );
}
}
return array($orig_matches, $final_matches, $orig_rows, $final_rows);
return array( $orig_matches, $final_matches, $orig_rows, $final_rows );
}
/**
@ -463,11 +470,12 @@ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
$difference = $this->difference_cache[ $difference_key ];
// $string1 has zero length? Odd. Give huge penalty by not dividing.
if ( !$string1 )
if ( ! $string1 ) {
return $difference;
}
// Return distance per character (of string1).
return $difference / strlen($string1);
return $difference / strlen( $string1 );
}
/**

View file

@ -21,7 +21,6 @@ final class WP_Theme implements ArrayAccess {
/**
* Headers for style.css files.
*
* @static
* @var array
*/
private static $file_headers = array(
@ -41,7 +40,6 @@ final class WP_Theme implements ArrayAccess {
/**
* Default themes.
*
* @static
* @var array
*/
private static $default_themes = array(
@ -61,7 +59,6 @@ final class WP_Theme implements ArrayAccess {
/**
* Renamed theme tags.
*
* @static
* @var array
*/
private static $tag_map = array(
@ -159,7 +156,6 @@ final class WP_Theme implements ArrayAccess {
*
* Default is false. Can be set with the {@see 'wp_cache_themes_persistently'} filter.
*
* @static
* @var bool
*/
private static $persistently_cache;
@ -169,7 +165,6 @@ final class WP_Theme implements ArrayAccess {
*
* By default the bucket is not cached, so this value is useless.
*
* @static
* @var bool
*/
private static $cache_expiration = 1800;
@ -194,8 +189,9 @@ final class WP_Theme implements ArrayAccess {
self::$persistently_cache = apply_filters( 'wp_cache_themes_persistently', false, 'WP_Theme' );
if ( self::$persistently_cache ) {
wp_cache_add_global_groups( 'themes' );
if ( is_int( self::$persistently_cache ) )
if ( is_int( self::$persistently_cache ) ) {
self::$cache_expiration = self::$persistently_cache;
}
} else {
wp_cache_add_non_persistent_groups( 'themes' );
}
@ -211,50 +207,79 @@ final class WP_Theme implements ArrayAccess {
}
$this->cache_hash = md5( $this->theme_root . '/' . $this->stylesheet );
$theme_file = $this->stylesheet . '/style.css';
$theme_file = $this->stylesheet . '/style.css';
$cache = $this->cache_get( 'theme' );
if ( is_array( $cache ) ) {
foreach ( array( 'errors', 'headers', 'template' ) as $key ) {
if ( isset( $cache[ $key ] ) )
if ( isset( $cache[ $key ] ) ) {
$this->$key = $cache[ $key ];
}
}
if ( $this->errors )
if ( $this->errors ) {
return;
if ( isset( $cache['theme_root_template'] ) )
}
if ( isset( $cache['theme_root_template'] ) ) {
$theme_root_template = $cache['theme_root_template'];
}
} elseif ( ! file_exists( $this->theme_root . '/' . $theme_file ) ) {
$this->headers['Name'] = $this->stylesheet;
if ( ! file_exists( $this->theme_root . '/' . $this->stylesheet ) )
if ( ! file_exists( $this->theme_root . '/' . $this->stylesheet ) ) {
$this->errors = new WP_Error( 'theme_not_found', sprintf( __( 'The theme directory "%s" does not exist.' ), esc_html( $this->stylesheet ) ) );
else
} else {
$this->errors = new WP_Error( 'theme_no_stylesheet', __( 'Stylesheet is missing.' ) );
}
$this->template = $this->stylesheet;
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
if ( ! file_exists( $this->theme_root ) ) // Don't cache this one.
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
if ( ! file_exists( $this->theme_root ) ) { // Don't cache this one.
$this->errors->add( 'theme_root_missing', __( 'ERROR: The themes directory is either empty or doesn&#8217;t exist. Please check your installation.' ) );
}
return;
} elseif ( ! is_readable( $this->theme_root . '/' . $theme_file ) ) {
$this->headers['Name'] = $this->stylesheet;
$this->errors = new WP_Error( 'theme_stylesheet_not_readable', __( 'Stylesheet is not readable.' ) );
$this->template = $this->stylesheet;
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
$this->errors = new WP_Error( 'theme_stylesheet_not_readable', __( 'Stylesheet is not readable.' ) );
$this->template = $this->stylesheet;
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
return;
} else {
$this->headers = get_file_data( $this->theme_root . '/' . $theme_file, self::$file_headers, 'theme' );
// Default themes always trump their pretenders.
// Properly identify default themes that are inside a directory within wp-content/themes.
if ( $default_theme_slug = array_search( $this->headers['Name'], self::$default_themes ) ) {
if ( basename( $this->stylesheet ) != $default_theme_slug )
if ( basename( $this->stylesheet ) != $default_theme_slug ) {
$this->headers['Name'] .= '/' . $this->stylesheet;
}
}
}
if ( ! $this->template && $this->stylesheet === $this->headers['Template'] ) {
/* translators: %s: Template */
$this->errors = new WP_Error( 'theme_child_invalid', sprintf( __( 'The theme defines itself as its parent theme. Please check the %s header.' ), '<code>Template</code>' ) );
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet ) );
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
)
);
return;
}
@ -271,7 +296,15 @@ final class WP_Theme implements ArrayAccess {
'<code>style.css</code>'
);
$this->errors = new WP_Error( 'theme_no_index', $error_message );
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
return;
}
}
@ -290,7 +323,15 @@ final class WP_Theme implements ArrayAccess {
} else {
// Parent theme is missing.
$this->errors = new WP_Error( 'theme_no_parent', sprintf( __( 'The parent theme is missing. Please install the "%s" parent theme.' ), esc_html( $this->template ) ) );
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
$this->parent = new WP_Theme( $this->template, $this->theme_root, $this );
return;
}
@ -302,11 +343,27 @@ final class WP_Theme implements ArrayAccess {
if ( $_child instanceof WP_Theme && $_child->template == $this->stylesheet ) {
$_child->parent = null;
$_child->errors = new WP_Error( 'theme_parent_invalid', sprintf( __( 'The "%s" theme is not a valid parent theme.' ), esc_html( $_child->template ) ) );
$_child->cache_add( 'theme', array( 'headers' => $_child->headers, 'errors' => $_child->errors, 'stylesheet' => $_child->stylesheet, 'template' => $_child->template ) );
$_child->cache_add(
'theme',
array(
'headers' => $_child->headers,
'errors' => $_child->errors,
'stylesheet' => $_child->stylesheet,
'template' => $_child->template,
)
);
// The two themes actually reference each other with the Template header.
if ( $_child->stylesheet == $this->template ) {
$this->errors = new WP_Error( 'theme_parent_invalid', sprintf( __( 'The "%s" theme is not a valid parent theme.' ), esc_html( $this->template ) ) );
$this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
}
return;
}
@ -316,10 +373,16 @@ final class WP_Theme implements ArrayAccess {
// We're good. If we didn't retrieve from cache, set it.
if ( ! is_array( $cache ) ) {
$cache = array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template );
$cache = array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
);
// If the parent theme is in another root, we'll want to cache this. Avoids an entire branch of filesystem calls above.
if ( isset( $theme_root_template ) )
if ( isset( $theme_root_template ) ) {
$cache['theme_root_template'] = $theme_root_template;
}
$this->cache_add( 'theme', $cache );
}
}
@ -332,7 +395,7 @@ final class WP_Theme implements ArrayAccess {
* @return string Theme name, ready for display (translated)
*/
public function __toString() {
return (string) $this->display('Name');
return (string) $this->display( 'Name' );
}
/**
@ -347,8 +410,20 @@ final class WP_Theme implements ArrayAccess {
*/
public function __isset( $offset ) {
static $properties = array(
'name', 'title', 'version', 'parent_theme', 'template_dir', 'stylesheet_dir', 'template', 'stylesheet',
'screenshot', 'description', 'author', 'tags', 'theme_root', 'theme_root_uri',
'name',
'title',
'version',
'parent_theme',
'template_dir',
'stylesheet_dir',
'template',
'stylesheet',
'screenshot',
'description',
'author',
'tags',
'theme_root',
'theme_root_uri',
);
return in_array( $offset, $properties );
@ -364,36 +439,36 @@ final class WP_Theme implements ArrayAccess {
*/
public function __get( $offset ) {
switch ( $offset ) {
case 'name' :
case 'title' :
return $this->get('Name');
case 'version' :
return $this->get('Version');
case 'parent_theme' :
return $this->parent() ? $this->parent()->get('Name') : '';
case 'template_dir' :
case 'name':
case 'title':
return $this->get( 'Name' );
case 'version':
return $this->get( 'Version' );
case 'parent_theme':
return $this->parent() ? $this->parent()->get( 'Name' ) : '';
case 'template_dir':
return $this->get_template_directory();
case 'stylesheet_dir' :
case 'stylesheet_dir':
return $this->get_stylesheet_directory();
case 'template' :
case 'template':
return $this->get_template();
case 'stylesheet' :
case 'stylesheet':
return $this->get_stylesheet();
case 'screenshot' :
case 'screenshot':
return $this->get_screenshot( 'relative' );
// 'author' and 'description' did not previously return translated data.
case 'description' :
return $this->display('Description');
case 'author' :
return $this->display('Author');
case 'tags' :
case 'description':
return $this->display( 'Description' );
case 'author':
return $this->display( 'Author' );
case 'tags':
return $this->get( 'Tags' );
case 'theme_root' :
case 'theme_root':
return $this->get_theme_root();
case 'theme_root_uri' :
case 'theme_root_uri':
return $this->get_theme_root_uri();
// For cases where the array was converted to an object.
default :
default:
return $this->offsetGet( $offset );
}
}
@ -429,9 +504,25 @@ final class WP_Theme implements ArrayAccess {
*/
public function offsetExists( $offset ) {
static $keys = array(
'Name', 'Version', 'Status', 'Title', 'Author', 'Author Name', 'Author URI', 'Description',
'Template', 'Stylesheet', 'Template Files', 'Stylesheet Files', 'Template Dir', 'Stylesheet Dir',
'Screenshot', 'Tags', 'Theme Root', 'Theme Root URI', 'Parent Theme',
'Name',
'Version',
'Status',
'Title',
'Author',
'Author Name',
'Author URI',
'Description',
'Template',
'Stylesheet',
'Template Files',
'Stylesheet Files',
'Template Dir',
'Stylesheet Dir',
'Screenshot',
'Tags',
'Theme Root',
'Theme Root URI',
'Parent Theme',
);
return in_array( $offset, $keys );
@ -454,47 +545,47 @@ final class WP_Theme implements ArrayAccess {
*/
public function offsetGet( $offset ) {
switch ( $offset ) {
case 'Name' :
case 'Title' :
case 'Name':
case 'Title':
/*
* See note above about using translated data. get() is not ideal.
* It is only for backward compatibility. Use display().
*/
return $this->get('Name');
case 'Author' :
return $this->display( 'Author');
case 'Author Name' :
return $this->display( 'Author', false);
case 'Author URI' :
return $this->display('AuthorURI');
case 'Description' :
return $this->display( 'Description');
case 'Version' :
case 'Status' :
return $this->get( 'Name' );
case 'Author':
return $this->display( 'Author' );
case 'Author Name':
return $this->display( 'Author', false );
case 'Author URI':
return $this->display( 'AuthorURI' );
case 'Description':
return $this->display( 'Description' );
case 'Version':
case 'Status':
return $this->get( $offset );
case 'Template' :
case 'Template':
return $this->get_template();
case 'Stylesheet' :
case 'Stylesheet':
return $this->get_stylesheet();
case 'Template Files' :
case 'Template Files':
return $this->get_files( 'php', 1, true );
case 'Stylesheet Files' :
case 'Stylesheet Files':
return $this->get_files( 'css', 0, false );
case 'Template Dir' :
case 'Template Dir':
return $this->get_template_directory();
case 'Stylesheet Dir' :
case 'Stylesheet Dir':
return $this->get_stylesheet_directory();
case 'Screenshot' :
case 'Screenshot':
return $this->get_screenshot( 'relative' );
case 'Tags' :
return $this->get('Tags');
case 'Theme Root' :
case 'Tags':
return $this->get( 'Tags' );
case 'Theme Root':
return $this->get_theme_root();
case 'Theme Root URI' :
case 'Theme Root URI':
return $this->get_theme_root_uri();
case 'Parent Theme' :
return $this->parent() ? $this->parent()->get('Name') : '';
default :
case 'Parent Theme':
return $this->parent() ? $this->parent()->get( 'Name' ) : '';
default:
return null;
}
}
@ -570,10 +661,11 @@ final class WP_Theme implements ArrayAccess {
* @since 3.4.0
*/
public function cache_delete() {
foreach ( array( 'theme', 'screenshot', 'headers', 'post_templates' ) as $key )
foreach ( array( 'theme', 'screenshot', 'headers', 'post_templates' ) as $key ) {
wp_cache_delete( $key . '-' . $this->cache_hash, 'themes' );
}
$this->template = $this->textdomain_loaded = $this->theme_root_uri = $this->parent = $this->errors = $this->headers_sanitized = $this->name_translated = null;
$this->headers = array();
$this->headers = array();
$this->__construct( $this->stylesheet, $this->theme_root );
}
@ -594,22 +686,26 @@ final class WP_Theme implements ArrayAccess {
* @return string|false String on success, false on failure.
*/
public function get( $header ) {
if ( ! isset( $this->headers[ $header ] ) )
if ( ! isset( $this->headers[ $header ] ) ) {
return false;
}
if ( ! isset( $this->headers_sanitized ) ) {
$this->headers_sanitized = $this->cache_get( 'headers' );
if ( ! is_array( $this->headers_sanitized ) )
if ( ! is_array( $this->headers_sanitized ) ) {
$this->headers_sanitized = array();
}
}
if ( isset( $this->headers_sanitized[ $header ] ) )
if ( isset( $this->headers_sanitized[ $header ] ) ) {
return $this->headers_sanitized[ $header ];
}
// If themes are a persistent group, sanitize everything and cache it. One cache add is better than many cache sets.
if ( self::$persistently_cache ) {
foreach ( array_keys( $this->headers ) as $_header )
foreach ( array_keys( $this->headers ) as $_header ) {
$this->headers_sanitized[ $_header ] = $this->sanitize_header( $_header, $this->headers[ $_header ] );
}
$this->cache_add( 'headers', $this->headers_sanitized );
} else {
$this->headers_sanitized[ $header ] = $this->sanitize_header( $header, $this->headers[ $header ] );
@ -634,14 +730,17 @@ final class WP_Theme implements ArrayAccess {
return false;
}
if ( $translate && ( empty( $value ) || ! $this->load_textdomain() ) )
if ( $translate && ( empty( $value ) || ! $this->load_textdomain() ) ) {
$translate = false;
}
if ( $translate )
if ( $translate ) {
$value = $this->translate_header( $header, $value );
}
if ( $markup )
if ( $markup ) {
$value = $this->markup_header( $header, $value, $translate );
}
return $value;
}
@ -660,13 +759,13 @@ final class WP_Theme implements ArrayAccess {
*/
private function sanitize_header( $header, $value ) {
switch ( $header ) {
case 'Status' :
case 'Status':
if ( ! $value ) {
$value = 'publish';
break;
}
// Fall through otherwise.
case 'Name' :
case 'Name':
static $header_tags = array(
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
@ -674,29 +773,32 @@ final class WP_Theme implements ArrayAccess {
'em' => true,
'strong' => true,
);
$value = wp_kses( $value, $header_tags );
$value = wp_kses( $value, $header_tags );
break;
case 'Author' :
case 'Author':
// There shouldn't be anchor tags in Author, but some themes like to be challenging.
case 'Description' :
case 'Description':
static $header_tags_with_a = array(
'a' => array( 'href' => true, 'title' => true ),
'a' => array(
'href' => true,
'title' => true,
),
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
'code' => true,
'em' => true,
'strong' => true,
);
$value = wp_kses( $value, $header_tags_with_a );
$value = wp_kses( $value, $header_tags_with_a );
break;
case 'ThemeURI' :
case 'AuthorURI' :
case 'ThemeURI':
case 'AuthorURI':
$value = esc_url_raw( $value );
break;
case 'Tags' :
case 'Tags':
$value = array_filter( array_map( 'trim', explode( ',', strip_tags( $value ) ) ) );
break;
case 'Version' :
case 'Version':
$value = strip_tags( $value );
break;
}
@ -707,7 +809,7 @@ final class WP_Theme implements ArrayAccess {
/**
* Mark up a theme header.
*
* @since 3.4.0
* @since 3.4.0
*
* @staticvar string $comma
*
@ -718,22 +820,22 @@ final class WP_Theme implements ArrayAccess {
*/
private function markup_header( $header, $value, $translate ) {
switch ( $header ) {
case 'Name' :
case 'Name':
if ( empty( $value ) ) {
$value = esc_html( $this->get_stylesheet() );
}
break;
case 'Description' :
case 'Description':
$value = wptexturize( $value );
break;
case 'Author' :
if ( $this->get('AuthorURI') ) {
case 'Author':
if ( $this->get( 'AuthorURI' ) ) {
$value = sprintf( '<a href="%1$s">%2$s</a>', $this->display( 'AuthorURI', true, $translate ), $value );
} elseif ( ! $value ) {
$value = __( 'Anonymous' );
}
break;
case 'Tags' :
case 'Tags':
static $comma = null;
if ( ! isset( $comma ) ) {
/* translators: used between list items, there is a space after the comma */
@ -741,8 +843,8 @@ final class WP_Theme implements ArrayAccess {
}
$value = implode( $comma, $value );
break;
case 'ThemeURI' :
case 'AuthorURI' :
case 'ThemeURI':
case 'AuthorURI':
$value = esc_url( $value );
break;
}
@ -763,13 +865,15 @@ final class WP_Theme implements ArrayAccess {
*/
private function translate_header( $header, $value ) {
switch ( $header ) {
case 'Name' :
case 'Name':
// Cached for sorting reasons.
if ( isset( $this->name_translated ) )
if ( isset( $this->name_translated ) ) {
return $this->name_translated;
$this->name_translated = translate( $value, $this->get('TextDomain' ) );
}
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
$this->name_translated = translate( $value, $this->get( 'TextDomain' ) );
return $this->name_translated;
case 'Tags' :
case 'Tags':
if ( empty( $value ) || ! function_exists( 'get_theme_feature_list' ) ) {
return $value;
}
@ -778,14 +882,27 @@ final class WP_Theme implements ArrayAccess {
if ( ! isset( $tags_list ) ) {
$tags_list = array(
// As of 4.6, deprecated tags which are only used to provide translation for older themes.
'black' => __( 'Black' ), 'blue' => __( 'Blue' ), 'brown' => __( 'Brown' ),
'gray' => __( 'Gray' ), 'green' => __( 'Green' ), 'orange' => __( 'Orange' ),
'pink' => __( 'Pink' ), 'purple' => __( 'Purple' ), 'red' => __( 'Red' ),
'silver' => __( 'Silver' ), 'tan' => __( 'Tan' ), 'white' => __( 'White' ),
'yellow' => __( 'Yellow' ), 'dark' => __( 'Dark' ), 'light' => __( 'Light' ),
'fixed-layout' => __( 'Fixed Layout' ), 'fluid-layout' => __( 'Fluid Layout' ),
'responsive-layout' => __( 'Responsive Layout' ), 'blavatar' => __( 'Blavatar' ),
'photoblogging' => __( 'Photoblogging' ), 'seasonal' => __( 'Seasonal' ),
'black' => __( 'Black' ),
'blue' => __( 'Blue' ),
'brown' => __( 'Brown' ),
'gray' => __( 'Gray' ),
'green' => __( 'Green' ),
'orange' => __( 'Orange' ),
'pink' => __( 'Pink' ),
'purple' => __( 'Purple' ),
'red' => __( 'Red' ),
'silver' => __( 'Silver' ),
'tan' => __( 'Tan' ),
'white' => __( 'White' ),
'yellow' => __( 'Yellow' ),
'dark' => __( 'Dark' ),
'light' => __( 'Light' ),
'fixed-layout' => __( 'Fixed Layout' ),
'fluid-layout' => __( 'Fluid Layout' ),
'responsive-layout' => __( 'Responsive Layout' ),
'blavatar' => __( 'Blavatar' ),
'photoblogging' => __( 'Photoblogging' ),
'seasonal' => __( 'Seasonal' ),
);
$feature_list = get_theme_feature_list( false ); // No API
@ -804,8 +921,9 @@ final class WP_Theme implements ArrayAccess {
return $value;
default :
$value = translate( $value, $this->get('TextDomain') );
default:
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
$value = translate( $value, $this->get( 'TextDomain' ) );
}
return $value;
}
@ -849,8 +967,9 @@ final class WP_Theme implements ArrayAccess {
* @return string Absolute path of the stylesheet directory.
*/
public function get_stylesheet_directory() {
if ( $this->errors() && in_array( 'theme_root_missing', $this->errors()->get_error_codes() ) )
if ( $this->errors() && in_array( 'theme_root_missing', $this->errors()->get_error_codes() ) ) {
return '';
}
return $this->theme_root . '/' . $this->stylesheet;
}
@ -866,10 +985,11 @@ final class WP_Theme implements ArrayAccess {
* @return string Absolute path of the template directory.
*/
public function get_template_directory() {
if ( $this->parent() )
if ( $this->parent() ) {
$theme_root = $this->parent()->theme_root;
else
} else {
$theme_root = $this->theme_root;
}
return $theme_root . '/' . $this->template;
}
@ -899,10 +1019,11 @@ final class WP_Theme implements ArrayAccess {
* @return string URL to the template directory.
*/
public function get_template_directory_uri() {
if ( $this->parent() )
if ( $this->parent() ) {
$theme_root_uri = $this->parent()->get_theme_root_uri();
else
} else {
$theme_root_uri = $this->get_theme_root_uri();
}
return $theme_root_uri . '/' . str_replace( '%2F', '/', rawurlencode( $this->template ) );
}
@ -932,8 +1053,9 @@ final class WP_Theme implements ArrayAccess {
* @return string Theme root URI.
*/
public function get_theme_root_uri() {
if ( ! isset( $this->theme_root_uri ) )
if ( ! isset( $this->theme_root_uri ) ) {
$this->theme_root_uri = get_theme_root_uri( $this->stylesheet, $this->theme_root );
}
return $this->theme_root_uri;
}
@ -953,8 +1075,9 @@ final class WP_Theme implements ArrayAccess {
public function get_screenshot( $uri = 'uri' ) {
$screenshot = $this->cache_get( 'screenshot' );
if ( $screenshot ) {
if ( 'relative' == $uri )
if ( 'relative' == $uri ) {
return $screenshot;
}
return $this->get_stylesheet_directory_uri() . '/' . $screenshot;
} elseif ( 0 === $screenshot ) {
return false;
@ -963,8 +1086,9 @@ final class WP_Theme implements ArrayAccess {
foreach ( array( 'png', 'gif', 'jpg', 'jpeg' ) as $ext ) {
if ( file_exists( $this->get_stylesheet_directory() . "/screenshot.$ext" ) ) {
$this->cache_add( 'screenshot', 'screenshot.' . $ext );
if ( 'relative' == $uri )
if ( 'relative' == $uri ) {
return 'screenshot.' . $ext;
}
return $this->get_stylesheet_directory_uri() . '/' . 'screenshot.' . $ext;
}
}
@ -1013,7 +1137,7 @@ final class WP_Theme implements ArrayAccess {
if ( ! is_array( $post_templates ) ) {
$post_templates = array();
$files = (array) $this->get_files( 'php', 1, true);
$files = (array) $this->get_files( 'php', 1, true );
foreach ( $files as $file => $full_path ) {
if ( ! preg_match( '|Template Name:(.*)$|mi', file_get_contents( $full_path ), $header ) ) {
@ -1090,7 +1214,7 @@ final class WP_Theme implements ArrayAccess {
* @since 4.4.0 Converted to allow complete control over the `$page_templates` array.
* @since 4.7.0 Added the `$post_type` parameter.
*
* @param array $post_templates Array of page templates. Keys are filenames,
* @param string[] $post_templates Array of page templates. Keys are filenames,
* values are translated names.
* @param WP_Theme $this The theme object.
* @param WP_Post|null $post The post being edited, provided for context, or null.
@ -1106,8 +1230,6 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @param string $path Absolute path to search.
* @param array|string|null $extensions Optional. Array of extensions to find, string of a single extension,
* or null for all extensions. Default null.
@ -1125,7 +1247,7 @@ final class WP_Theme implements ArrayAccess {
}
if ( $extensions ) {
$extensions = (array) $extensions;
$extensions = (array) $extensions;
$_extensions = implode( '|', $extensions );
}
@ -1135,14 +1257,14 @@ final class WP_Theme implements ArrayAccess {
}
$results = scandir( $path );
$files = array();
$files = array();
/**
* Filters the array of excluded directories and files while scanning theme folder.
*
* @since 4.7.4
*
* @param array $exclusions Array of excluded directories and files.
* @param string[] $exclusions Array of excluded directories and files.
*/
$exclusions = (array) apply_filters( 'theme_scandir_exclusions', array( 'CVS', 'node_modules', 'vendor', 'bower_components' ) );
@ -1154,7 +1276,7 @@ final class WP_Theme implements ArrayAccess {
if ( ! $depth ) {
continue;
}
$found = self::scandir( $path . '/' . $result, $extensions, $depth - 1 , $relative_path . $result );
$found = self::scandir( $path . '/' . $result, $extensions, $depth - 1, $relative_path . $result );
$files = array_merge_recursive( $files, $found );
} elseif ( ! $extensions || preg_match( '~\.(' . $_extensions . ')$~', $result ) ) {
$files[ $relative_path . $result ] = $path . '/' . $result;
@ -1173,13 +1295,14 @@ final class WP_Theme implements ArrayAccess {
* @since 3.4.0
*
* @return bool True if the textdomain was successfully loaded or has already been loaded.
* False if no textdomain was specified in the file headers, or if the domain could not be loaded.
* False if no textdomain was specified in the file headers, or if the domain could not be loaded.
*/
public function load_textdomain() {
if ( isset( $this->textdomain_loaded ) )
if ( isset( $this->textdomain_loaded ) ) {
return $this->textdomain_loaded;
}
$textdomain = $this->get('TextDomain');
$textdomain = $this->get( 'TextDomain' );
if ( ! $textdomain ) {
$this->textdomain_loaded = false;
return false;
@ -1191,10 +1314,11 @@ final class WP_Theme implements ArrayAccess {
}
$path = $this->get_stylesheet_directory();
if ( $domainpath = $this->get('DomainPath') )
if ( $domainpath = $this->get( 'DomainPath' ) ) {
$path .= $domainpath;
else
} else {
$path .= '/languages';
}
$this->textdomain_loaded = load_theme_textdomain( $textdomain, $path );
return $this->textdomain_loaded;
@ -1206,24 +1330,27 @@ final class WP_Theme implements ArrayAccess {
* @since 3.4.0
*
* @param string $check Optional. Whether to check only the 'network'-wide settings, the 'site'
* settings, or 'both'. Defaults to 'both'.
* settings, or 'both'. Defaults to 'both'.
* @param int $blog_id Optional. Ignored if only network-wide settings are checked. Defaults to current site.
* @return bool Whether the theme is allowed for the network. Returns true in single-site.
*/
public function is_allowed( $check = 'both', $blog_id = null ) {
if ( ! is_multisite() )
if ( ! is_multisite() ) {
return true;
}
if ( 'both' == $check || 'network' == $check ) {
$allowed = self::get_allowed_on_network();
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) )
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) ) {
return true;
}
}
if ( 'both' == $check || 'site' == $check ) {
$allowed = self::get_allowed_on_site( $blog_id );
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) )
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) ) {
return true;
}
}
return false;
@ -1253,10 +1380,8 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @param int $blog_id Optional. ID of the site. Defaults to the current site.
* @return array Array of stylesheet names.
* @return string[] Array of stylesheet names.
*/
public static function get_allowed( $blog_id = null ) {
/**
@ -1267,8 +1392,8 @@ final class WP_Theme implements ArrayAccess {
*
* @since 4.5.0
*
* @param array $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site.
* @param string[] $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site.
*/
$network = (array) apply_filters( 'network_allowed_themes', self::get_allowed_on_network(), $blog_id );
return $network + self::get_allowed_on_site( $blog_id );
@ -1279,11 +1404,9 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @staticvar array $allowed_themes
*
* @return array Array of stylesheet names.
* @return string[] Array of stylesheet names.
*/
public static function get_allowed_on_network() {
static $allowed_themes;
@ -1296,7 +1419,7 @@ final class WP_Theme implements ArrayAccess {
*
* @since MU (3.0.0)
*
* @param array $allowed_themes An array of theme stylesheet names.
* @param string[] $allowed_themes An array of theme stylesheet names.
*/
$allowed_themes = apply_filters( 'allowed_themes', $allowed_themes );
@ -1308,18 +1431,17 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @staticvar array $allowed_themes
*
* @param int $blog_id Optional. ID of the site. Defaults to the current site.
* @return array Array of stylesheet names.
* @return string[] Array of stylesheet names.
*/
public static function get_allowed_on_site( $blog_id = null ) {
static $allowed_themes = array();
if ( ! $blog_id || ! is_multisite() )
if ( ! $blog_id || ! is_multisite() ) {
$blog_id = get_current_blog_id();
}
if ( isset( $allowed_themes[ $blog_id ] ) ) {
/**
@ -1327,8 +1449,8 @@ final class WP_Theme implements ArrayAccess {
*
* @since 4.5.0
*
* @param array $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site. Defaults to current site.
* @param string[] $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site. Defaults to current site.
*/
return (array) apply_filters( 'site_allowed_themes', $allowed_themes[ $blog_id ], $blog_id );
}
@ -1358,10 +1480,11 @@ final class WP_Theme implements ArrayAccess {
$allowed_themes[ $blog_id ] = array();
} else {
$converted = array();
$themes = wp_get_themes();
$themes = wp_get_themes();
foreach ( $themes as $stylesheet => $theme_data ) {
if ( isset( $allowed_themes[ $blog_id ][ $theme_data->get('Name') ] ) )
if ( isset( $allowed_themes[ $blog_id ][ $theme_data->get( 'Name' ) ] ) ) {
$converted[ $stylesheet ] = true;
}
}
$allowed_themes[ $blog_id ] = $converted;
}
@ -1387,9 +1510,8 @@ final class WP_Theme implements ArrayAccess {
* Enables a theme for all sites on the current network.
*
* @since 4.6.0
* @static
*
* @param string|array $stylesheets Stylesheet name or array of stylesheet names.
* @param string|string[] $stylesheets Stylesheet name or array of stylesheet names.
*/
public static function network_enable_theme( $stylesheets ) {
if ( ! is_multisite() ) {
@ -1412,9 +1534,8 @@ final class WP_Theme implements ArrayAccess {
* Disables a theme for all sites on the current network.
*
* @since 4.6.0
* @static
*
* @param string|array $stylesheets Stylesheet name or array of stylesheet names.
* @param string|string[] $stylesheets Stylesheet name or array of stylesheet names.
*/
public static function network_disable_theme( $stylesheets ) {
if ( ! is_multisite() ) {
@ -1440,14 +1561,15 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @param array $themes Array of themes to sort (passed by reference).
* @param WP_Theme[] $themes Array of theme objects to sort (passed by reference).
*/
public static function sort_by_name( &$themes ) {
if ( 0 === strpos( get_user_locale(), 'en_' ) ) {
uasort( $themes, array( 'WP_Theme', '_name_sort' ) );
} else {
foreach ( $themes as $key => $theme ) {
$theme->translate_header( 'Name', $theme->headers['Name'] );
}
uasort( $themes, array( 'WP_Theme', '_name_sort_i18n' ) );
}
}
@ -1460,8 +1582,6 @@ final class WP_Theme implements ArrayAccess {
*
* @since 3.4.0
*
* @static
*
* @param string $a First name.
* @param string $b Second name.
* @return int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
@ -1472,19 +1592,16 @@ final class WP_Theme implements ArrayAccess {
}
/**
* Name sort (with translation).
* Callback function for usort() to naturally sort themes by translated name.
*
* @since 3.4.0
*
* @static
*
* @param string $a First name.
* @param string $b Second name.
* @return int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
* Greater than 0 if `$a` falls higher in the natural order than `$b`. Used with usort().
*/
private static function _name_sort_i18n( $a, $b ) {
// Don't mark up; Do translate.
return strnatcasecmp( $a->display( 'Name', false, true ), $b->display( 'Name', false, true ) );
return strnatcasecmp( $a->name_translated, $b->name_translated );
}
}

View file

@ -11,15 +11,17 @@
* Meta-based user sessions token manager.
*
* @since 4.0.0
*
* @see WP_Session_Tokens
*/
class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
/**
* Get all sessions of a user.
* Retrieves all sessions of the user.
*
* @since 4.0.0
*
* @return array Sessions of a user.
* @return array Sessions of the user.
*/
protected function get_sessions() {
$sessions = get_user_meta( $this->user_id, 'session_tokens', true );
@ -47,11 +49,11 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Retrieve a session by its verifier (token hash).
* Retrieves a session based on its verifier (token hash).
*
* @since 4.0.0
*
* @param string $verifier Verifier of the session to retrieve.
* @param string $verifier Verifier for the session to retrieve.
* @return array|null The session, or null if it does not exist
*/
protected function get_session( $verifier ) {
@ -65,11 +67,11 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Update a session by its verifier.
* Updates a session based on its verifier (token hash).
*
* @since 4.0.0
*
* @param string $verifier Verifier of the session to update.
* @param string $verifier Verifier for the session to update.
* @param array $session Optional. Session. Omitting this argument destroys the session.
*/
protected function update_session( $verifier, $session = null ) {
@ -85,7 +87,7 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Update a user's sessions in the usermeta table.
* Updates the user's sessions in the usermeta table.
*
* @since 4.0.0
*
@ -100,7 +102,7 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Destroy all session tokens for a user, except a single session passed.
* Destroys all sessions for this user, except the single session with the given verifier.
*
* @since 4.0.0
*
@ -112,7 +114,7 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Destroy all session tokens for a user.
* Destroys all session tokens for the user.
*
* @since 4.0.0
*/
@ -121,10 +123,9 @@ class WP_User_Meta_Session_Tokens extends WP_Session_Tokens {
}
/**
* Destroy all session tokens for all users.
* Destroys all sessions for all users.
*
* @since 4.0.0
* @static
*/
public static function drop_sessions() {
delete_metadata( 'user', 0, 'session_tokens', false, true );

View file

@ -89,32 +89,32 @@ class WP_User_Query {
*/
public static function fill_query_vars( $args ) {
$defaults = array(
'blog_id' => get_current_blog_id(),
'role' => '',
'role__in' => array(),
'role__not_in' => array(),
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'include' => array(),
'exclude' => array(),
'search' => '',
'search_columns' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'number' => '',
'paged' => 1,
'count_total' => true,
'fields' => 'all',
'who' => '',
'blog_id' => get_current_blog_id(),
'role' => '',
'role__in' => array(),
'role__not_in' => array(),
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'include' => array(),
'exclude' => array(),
'search' => '',
'search_columns' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'number' => '',
'paged' => 1,
'count_total' => true,
'fields' => 'all',
'who' => '',
'has_published_posts' => null,
'nicename' => '',
'nicename__in' => array(),
'nicename__not_in' => array(),
'login' => '',
'login__in' => array(),
'login__not_in' => array()
'nicename' => '',
'nicename__in' => array(),
'nicename__not_in' => array(),
'login' => '',
'login__in' => array(),
'login__not_in' => array(),
);
return wp_parse_args( $args, $defaults );
@ -134,7 +134,6 @@ class WP_User_Query {
* @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in',
* and 'login__not_in' parameters.
*
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $blog_id
*
@ -213,7 +212,7 @@ class WP_User_Query {
if ( empty( $this->query_vars ) || ! empty( $query ) ) {
$this->query_limit = null;
$this->query_vars = $this->fill_query_vars( $query );
$this->query_vars = $this->fill_query_vars( $query );
}
/**
@ -231,14 +230,14 @@ class WP_User_Query {
// Ensure that query vars are filled after 'pre_get_users'.
$qv =& $this->query_vars;
$qv = $this->fill_query_vars( $qv );
$qv = $this->fill_query_vars( $qv );
if ( is_array( $qv['fields'] ) ) {
$qv['fields'] = array_unique( $qv['fields'] );
$this->query_fields = array();
foreach ( $qv['fields'] as $field ) {
$field = 'ID' === $field ? 'ID' : sanitize_key( $field );
$field = 'ID' === $field ? 'ID' : sanitize_key( $field );
$this->query_fields[] = "$wpdb->users.$field";
}
$this->query_fields = implode( ',', $this->query_fields );
@ -248,11 +247,12 @@ class WP_User_Query {
$this->query_fields = "$wpdb->users.ID";
}
if ( isset( $qv['count_total'] ) && $qv['count_total'] )
if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
$this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
}
$this->query_from = "FROM $wpdb->users";
$this->query_where = "WHERE 1=1";
$this->query_from = "FROM $wpdb->users";
$this->query_where = 'WHERE 1=1';
// Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
if ( ! empty( $qv['include'] ) ) {
@ -277,42 +277,42 @@ class WP_User_Query {
$post_type = $wpdb->prepare( '%s', $post_type );
}
$posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
$this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . join( ", ", $post_types ) . " ) )";
$posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
$this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . join( ', ', $post_types ) . ' ) )';
}
// nicename
if ( '' !== $qv['nicename']) {
if ( '' !== $qv['nicename'] ) {
$this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] );
}
if ( ! empty( $qv['nicename__in'] ) ) {
$sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] );
$nicename__in = implode( "','", $sanitized_nicename__in );
$this->query_where .= " AND user_nicename IN ( '$nicename__in' )";
$nicename__in = implode( "','", $sanitized_nicename__in );
$this->query_where .= " AND user_nicename IN ( '$nicename__in' )";
}
if ( ! empty( $qv['nicename__not_in'] ) ) {
$sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] );
$nicename__not_in = implode( "','", $sanitized_nicename__not_in );
$this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )";
$nicename__not_in = implode( "','", $sanitized_nicename__not_in );
$this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )";
}
// login
if ( '' !== $qv['login']) {
if ( '' !== $qv['login'] ) {
$this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] );
}
if ( ! empty( $qv['login__in'] ) ) {
$sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] );
$login__in = implode( "','", $sanitized_login__in );
$this->query_where .= " AND user_login IN ( '$login__in' )";
$login__in = implode( "','", $sanitized_login__in );
$this->query_where .= " AND user_login IN ( '$login__in' )";
}
if ( ! empty( $qv['login__not_in'] ) ) {
$sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] );
$login__not_in = implode( "','", $sanitized_login__not_in );
$this->query_where .= " AND user_login NOT IN ( '$login__not_in' )";
$login__not_in = implode( "','", $sanitized_login__not_in );
$this->query_where .= " AND user_login NOT IN ( '$login__not_in' )";
}
// Meta query.
@ -321,8 +321,8 @@ class WP_User_Query {
if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
$who_query = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
'value' => 0,
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
'value' => 0,
'compare' => '!=',
);
@ -362,7 +362,7 @@ class WP_User_Query {
}
if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
$role_queries = array();
$role_queries = array();
$roles_clauses = array( 'relation' => 'AND' );
if ( ! empty( $roles ) ) {
@ -406,7 +406,7 @@ class WP_User_Query {
// If there are no specific roles named, make sure the user is a member of the site.
if ( empty( $role_queries ) ) {
$role_queries[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'compare' => 'EXISTS',
);
}
@ -428,8 +428,8 @@ class WP_User_Query {
}
if ( ! empty( $this->meta_query->queries ) ) {
$clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
$this->query_from .= $clauses['join'];
$clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
$this->query_from .= $clauses['join'];
$this->query_where .= $clauses['where'];
if ( $this->meta_query->has_or_relation() ) {
@ -439,7 +439,7 @@ class WP_User_Query {
// sorting
$qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
$order = $this->parse_order( $qv['order'] );
$order = $this->parse_order( $qv['order'] );
if ( empty( $qv['orderby'] ) ) {
// Default order is by 'user_login'.
@ -460,11 +460,11 @@ class WP_User_Query {
if ( is_int( $_key ) ) {
// Integer key means this is a flat array of 'orderby' fields.
$_orderby = $_value;
$_order = $order;
$_order = $order;
} else {
// Non-integer key means this the key is the field and the value is ASC/DESC.
$_orderby = $_key;
$_order = $_value;
$_order = $_value;
}
$parsed = $this->parse_orderby( $_orderby );
@ -490,43 +490,47 @@ class WP_User_Query {
// limit
if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
if ( $qv['offset'] ) {
$this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
$this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] );
} else {
$this->query_limit = $wpdb->prepare( "LIMIT %d, %d", $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
$this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
}
}
$search = '';
if ( isset( $qv['search'] ) )
if ( isset( $qv['search'] ) ) {
$search = trim( $qv['search'] );
}
if ( $search ) {
$leading_wild = ( ltrim($search, '*') != $search );
$trailing_wild = ( rtrim($search, '*') != $search );
if ( $leading_wild && $trailing_wild )
$leading_wild = ( ltrim( $search, '*' ) != $search );
$trailing_wild = ( rtrim( $search, '*' ) != $search );
if ( $leading_wild && $trailing_wild ) {
$wild = 'both';
elseif ( $leading_wild )
} elseif ( $leading_wild ) {
$wild = 'leading';
elseif ( $trailing_wild )
} elseif ( $trailing_wild ) {
$wild = 'trailing';
else
} else {
$wild = false;
if ( $wild )
$search = trim($search, '*');
}
if ( $wild ) {
$search = trim( $search, '*' );
}
$search_columns = array();
if ( $qv['search_columns'] ) {
$search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) );
}
if ( ! $search_columns ) {
if ( false !== strpos( $search, '@') )
$search_columns = array('user_email');
elseif ( is_numeric($search) )
$search_columns = array('user_login', 'ID');
elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
$search_columns = array('user_url');
else
$search_columns = array('user_login', 'user_url', 'user_email', 'user_nicename', 'display_name');
if ( false !== strpos( $search, '@' ) ) {
$search_columns = array( 'user_email' );
} elseif ( is_numeric( $search ) ) {
$search_columns = array( 'user_login', 'ID' );
} elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) {
$search_columns = array( 'user_url' );
} else {
$search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' );
}
}
/**
@ -537,7 +541,7 @@ class WP_User_Query {
*
* @since 3.6.0
*
* @param array $search_columns Array of column names to be searched.
* @param string[] $search_columns Array of column names to be searched.
* @param string $search Text being searched.
* @param WP_User_Query $this The current WP_User_Query instance.
*/
@ -548,16 +552,16 @@ class WP_User_Query {
if ( ! empty( $include ) ) {
// Sanitized earlier.
$ids = implode( ',', $include );
$ids = implode( ',', $include );
$this->query_where .= " AND $wpdb->users.ID IN ($ids)";
} elseif ( ! empty( $qv['exclude'] ) ) {
$ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
$ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
$this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
}
// Date queries are allowed for the user_registered field.
if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
$date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
$date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
$this->query_where .= $date_query->get_sql();
}
@ -588,35 +592,61 @@ class WP_User_Query {
$qv =& $this->query_vars;
$this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
/**
* Filters the users array before the query takes place.
*
* Return a non-null value to bypass WordPress's default user queries.
* Filtering functions that require pagination information are encouraged to set
* the `total_users` property of the WP_User_Query object, passed to the filter
* by reference. If WP_User_Query does not perform a database query, it will not
* have enough information to generate these values itself.
*
* @since 5.1.0
*
* @param array|null $results Return an array of user data to short-circuit WP's user query
* or null to allow WP to run its normal queries.
* @param WP_User_Query $this The WP_User_Query instance (passed by reference).
*/
$this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) );
if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
$this->results = $wpdb->get_results( $this->request );
} else {
$this->results = $wpdb->get_col( $this->request );
if ( null === $this->results ) {
$this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
$this->results = $wpdb->get_results( $this->request );
} else {
$this->results = $wpdb->get_col( $this->request );
}
if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
/**
* Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
*
* @since 3.2.0
* @since 5.1.0 Added the `$this` parameter.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
* @param WP_User_Query $this The current WP_User_Query instance.
*/
$found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this );
$this->total_users = (int) $wpdb->get_var( $found_users_query );
}
}
/**
* Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
*
* @since 3.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
*/
if ( isset( $qv['count_total'] ) && $qv['count_total'] )
$this->total_users = (int) $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
if ( !$this->results )
if ( ! $this->results ) {
return;
}
if ( 'all_with_meta' == $qv['fields'] ) {
cache_users( $this->results );
$r = array();
foreach ( $this->results as $userid )
foreach ( $this->results as $userid ) {
$r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
}
$this->results = $r;
} elseif ( 'all' == $qv['fields'] ) {
@ -635,8 +665,9 @@ class WP_User_Query {
* @return mixed
*/
public function get( $query_var ) {
if ( isset( $this->query_vars[$query_var] ) )
return $this->query_vars[$query_var];
if ( isset( $this->query_vars[ $query_var ] ) ) {
return $this->query_vars[ $query_var ];
}
return null;
}
@ -650,7 +681,7 @@ class WP_User_Query {
* @param mixed $value Query variable value.
*/
public function set( $query_var, $value ) {
$this->query_vars[$query_var] = $value;
$this->query_vars[ $query_var ] = $value;
}
/**
@ -669,10 +700,10 @@ class WP_User_Query {
protected function get_search_sql( $string, $cols, $wild = false ) {
global $wpdb;
$searches = array();
$leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
$searches = array();
$leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
$trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
$like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
$like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
foreach ( $cols as $col ) {
if ( 'ID' == $col ) {
@ -682,7 +713,7 @@ class WP_User_Query {
}
}
return ' AND (' . implode(' OR ', $searches) . ')';
return ' AND (' . implode( ' OR ', $searches ) . ')';
}
/**
@ -731,7 +762,7 @@ class WP_User_Query {
$_orderby = 'display_name';
} elseif ( 'post_count' == $orderby ) {
// todo: avoid the JOIN
$where = get_posts_by_author_sql( 'post' );
$where = get_posts_by_author_sql( 'post' );
$this->query_from .= " LEFT OUTER JOIN (
SELECT post_author, COUNT(*) as post_count
FROM $wpdb->posts
@ -739,7 +770,7 @@ class WP_User_Query {
GROUP BY post_author
) p ON ({$wpdb->users}.ID = p.post_author)
";
$_orderby = 'post_count';
$_orderby = 'post_count';
} elseif ( 'ID' == $orderby || 'id' == $orderby ) {
$_orderby = 'ID';
} elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
@ -747,20 +778,20 @@ class WP_User_Query {
} elseif ( 'meta_value_num' == $orderby ) {
$_orderby = "$wpdb->usermeta.meta_value+0";
} elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
$include = wp_parse_id_list( $this->query_vars['include'] );
$include = wp_parse_id_list( $this->query_vars['include'] );
$include_sql = implode( ',', $include );
$_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
$_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
} elseif ( 'nicename__in' === $orderby ) {
$sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] );
$nicename__in = implode( "','", $sanitized_nicename__in );
$_orderby = "FIELD( user_nicename, '$nicename__in' )";
$nicename__in = implode( "','", $sanitized_nicename__in );
$_orderby = "FIELD( user_nicename, '$nicename__in' )";
} elseif ( 'login__in' === $orderby ) {
$sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] );
$login__in = implode( "','", $sanitized_login__in );
$_orderby = "FIELD( user_login, '$login__in' )";
$login__in = implode( "','", $sanitized_login__in );
$_orderby = "FIELD( user_login, '$login__in' )";
} elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
$meta_clause = $meta_query_clauses[ $orderby ];
$_orderby = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
$_orderby = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
}
return $_orderby;
@ -847,7 +878,7 @@ class WP_User_Query {
*
* @since 4.0.0
*
* @param callable $name Method to call.
* @param string $name Method to call.
* @param array $arguments Arguments to pass when calling.
* @return mixed Return value of the callback, false otherwise.
*/

View file

@ -80,7 +80,8 @@ class WP_User {
* All capabilities the user has, including individual and role based.
*
* @since 2.0.0
* @var array
* @var bool[] Array of key/value pairs where keys represent a capability name and boolean values
* represent whether the user has that capability.
*/
public $allcaps = array();
@ -101,7 +102,6 @@ class WP_User {
private $site_id = 0;
/**
* @static
* @since 3.3.0
* @var array
*/
@ -114,21 +114,19 @@ class WP_User {
*
* @since 2.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int|string|stdClass|WP_User $id User's ID, a WP_User object, or a user object from the DB.
* @param string $name Optional. User's username
* @param int $site_id Optional Site ID, defaults to current site.
*/
public function __construct( $id = 0, $name = '', $site_id = '' ) {
if ( ! isset( self::$back_compat_keys ) ) {
$prefix = $GLOBALS['wpdb']->prefix;
$prefix = $GLOBALS['wpdb']->prefix;
self::$back_compat_keys = array(
'user_firstname' => 'first_name',
'user_lastname' => 'last_name',
'user_description' => 'description',
'user_level' => $prefix . 'user_level',
$prefix . 'usersettings' => $prefix . 'user-settings',
'user_firstname' => 'first_name',
'user_lastname' => 'last_name',
'user_description' => 'description',
'user_level' => $prefix . 'user_level',
$prefix . 'usersettings' => $prefix . 'user-settings',
$prefix . 'usersettingstime' => $prefix . 'user-settings-time',
);
}
@ -143,7 +141,7 @@ class WP_User {
if ( ! empty( $id ) && ! is_numeric( $id ) ) {
$name = $id;
$id = 0;
$id = 0;
}
if ( $id ) {
@ -169,7 +167,7 @@ class WP_User {
*/
public function init( $data, $site_id = '' ) {
$this->data = $data;
$this->ID = (int) $data->ID;
$this->ID = (int) $data->ID;
$this->for_site( $site_id );
}
@ -180,8 +178,6 @@ class WP_User {
* @since 3.3.0
* @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
*
* @static
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $field The field to query against: 'id', 'ID', 'slug', 'email' or 'login'.
@ -199,34 +195,37 @@ class WP_User {
if ( 'id' == $field ) {
// Make sure the value is numeric to avoid casting objects, for example,
// to int 1.
if ( ! is_numeric( $value ) )
if ( ! is_numeric( $value ) ) {
return false;
}
$value = intval( $value );
if ( $value < 1 )
if ( $value < 1 ) {
return false;
}
} else {
$value = trim( $value );
}
if ( !$value )
if ( ! $value ) {
return false;
}
switch ( $field ) {
case 'id':
$user_id = $value;
$user_id = $value;
$db_field = 'ID';
break;
case 'slug':
$user_id = wp_cache_get($value, 'userslugs');
$user_id = wp_cache_get( $value, 'userslugs' );
$db_field = 'user_nicename';
break;
case 'email':
$user_id = wp_cache_get($value, 'useremail');
$user_id = wp_cache_get( $value, 'useremail' );
$db_field = 'user_email';
break;
case 'login':
$value = sanitize_user( $value );
$user_id = wp_cache_get($value, 'userlogins');
$value = sanitize_user( $value );
$user_id = wp_cache_get( $value, 'userlogins' );
$db_field = 'user_login';
break;
default:
@ -234,14 +233,19 @@ class WP_User {
}
if ( false !== $user_id ) {
if ( $user = wp_cache_get( $user_id, 'users' ) )
if ( $user = wp_cache_get( $user_id, 'users' ) ) {
return $user;
}
}
if ( !$user = $wpdb->get_row( $wpdb->prepare(
"SELECT * FROM $wpdb->users WHERE $db_field = %s", $value
) ) )
if ( ! $user = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM $wpdb->users WHERE $db_field = %s LIMIT 1",
$value
)
) ) {
return false;
}
update_user_caches( $user );
@ -258,7 +262,9 @@ class WP_User {
*/
public function __isset( $key ) {
if ( 'id' == $key ) {
_deprecated_argument( 'WP_User->id', '2.1.0',
_deprecated_argument(
'WP_User->id',
'2.1.0',
sprintf(
/* translators: %s: WP_User->ID */
__( 'Use %s instead.' ),
@ -268,11 +274,13 @@ class WP_User {
$key = 'ID';
}
if ( isset( $this->data->$key ) )
if ( isset( $this->data->$key ) ) {
return true;
}
if ( isset( self::$back_compat_keys[ $key ] ) )
if ( isset( self::$back_compat_keys[ $key ] ) ) {
$key = self::$back_compat_keys[ $key ];
}
return metadata_exists( 'user', $this->ID, $key );
}
@ -287,7 +295,9 @@ class WP_User {
*/
public function __get( $key ) {
if ( 'id' == $key ) {
_deprecated_argument( 'WP_User->id', '2.1.0',
_deprecated_argument(
'WP_User->id',
'2.1.0',
sprintf(
/* translators: %s: WP_User->ID */
__( 'Use %s instead.' ),
@ -300,8 +310,9 @@ class WP_User {
if ( isset( $this->data->$key ) ) {
$value = $this->data->$key;
} else {
if ( isset( self::$back_compat_keys[ $key ] ) )
if ( isset( self::$back_compat_keys[ $key ] ) ) {
$key = self::$back_compat_keys[ $key ];
}
$value = get_user_meta( $this->ID, $key, true );
}
@ -325,7 +336,9 @@ class WP_User {
*/
public function __set( $key, $value ) {
if ( 'id' == $key ) {
_deprecated_argument( 'WP_User->id', '2.1.0',
_deprecated_argument(
'WP_User->id',
'2.1.0',
sprintf(
/* translators: %s: WP_User->ID */
__( 'Use %s instead.' ),
@ -348,7 +361,9 @@ class WP_User {
*/
public function __unset( $key ) {
if ( 'id' == $key ) {
_deprecated_argument( 'WP_User->id', '2.1.0',
_deprecated_argument(
'WP_User->id',
'2.1.0',
sprintf(
/* translators: %s: WP_User->ID */
__( 'Use %s instead.' ),
@ -421,7 +436,7 @@ class WP_User {
*
* @since 4.3.0
*
* @param callable $name Method to call.
* @param string $name Method to call.
* @param array $arguments Arguments to pass when calling.
* @return mixed|false Return value of the callback, false otherwise.
*/
@ -464,16 +479,15 @@ class WP_User {
}
/**
* Retrieve all of the role capabilities and merge with individual capabilities.
* Retrieves all of the capabilities of the roles of the user, and merges them with individual user capabilities.
*
* All of the capabilities of the roles the user belongs to are merged with
* the users individual roles. This also means that the user can be denied
* specific roles that their role might have, but the specific user isn't
* granted permission to.
* All of the capabilities of the roles of the user are merged with the user's individual capabilities. This means
* that the user can be denied specific capabilities that their role might have, but the user is specifically denied.
*
* @since 2.0.0
*
* @return array List of all capabilities for the user.
* @return bool[] Array of key/value pairs where keys represent a capability name and boolean values
* represent whether the user has that capability.
*/
public function get_role_caps() {
$switch_site = false;
@ -485,14 +499,15 @@ class WP_User {
$wp_roles = wp_roles();
//Filter out caps that are not role names and assign to $this->roles
if ( is_array( $this->caps ) )
// Filter out caps that are not role names and assign to $this->roles.
if ( is_array( $this->caps ) ) {
$this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) );
}
//Build $allcaps from role caps, overlay user's $caps
// Build $allcaps from role caps, overlay user's $caps.
$this->allcaps = array();
foreach ( (array) $this->roles as $role ) {
$the_role = $wp_roles->get_role( $role );
$the_role = $wp_roles->get_role( $role );
$this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities );
}
$this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps );
@ -518,7 +533,7 @@ class WP_User {
return;
}
$this->caps[$role] = true;
$this->caps[ $role ] = true;
update_user_meta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
$this->update_user_level_from_caps();
@ -542,9 +557,10 @@ class WP_User {
* @param string $role Role name.
*/
public function remove_role( $role ) {
if ( !in_array($role, $this->roles) )
if ( ! in_array( $role, $this->roles ) ) {
return;
unset( $this->caps[$role] );
}
unset( $this->caps[ $role ] );
update_user_meta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
$this->update_user_level_from_caps();
@ -572,16 +588,18 @@ class WP_User {
* @param string $role Role name.
*/
public function set_role( $role ) {
if ( 1 == count( $this->roles ) && $role == current( $this->roles ) )
if ( 1 == count( $this->roles ) && $role == current( $this->roles ) ) {
return;
}
foreach ( (array) $this->roles as $oldrole )
unset( $this->caps[$oldrole] );
foreach ( (array) $this->roles as $oldrole ) {
unset( $this->caps[ $oldrole ] );
}
$old_roles = $this->roles;
if ( !empty( $role ) ) {
$this->caps[$role] = true;
$this->roles = array( $role => true );
if ( ! empty( $role ) ) {
$this->caps[ $role ] = true;
$this->roles = array( $role => true );
} else {
$this->roles = false;
}
@ -595,9 +613,9 @@ class WP_User {
* @since 2.9.0
* @since 3.6.0 Added $old_roles to include an array of the user's previous roles.
*
* @param int $user_id The user ID.
* @param string $role The new role.
* @param array $old_roles An array of the user's previous roles.
* @param int $user_id The user ID.
* @param string $role The new role.
* @param string[] $old_roles An array of the user's previous roles.
*/
do_action( 'set_user_role', $this->ID, $role, $old_roles );
}
@ -655,7 +673,7 @@ class WP_User {
* @param bool $grant Whether to grant capability to user.
*/
public function add_cap( $cap, $grant = true ) {
$this->caps[$cap] = $grant;
$this->caps[ $cap ] = $grant;
update_user_meta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
$this->update_user_level_from_caps();
@ -723,8 +741,9 @@ class WP_User {
// Multisite super admin has all caps by definition, Unless specifically denied.
if ( is_multisite() && is_super_admin( $this->ID ) ) {
if ( in_array('do_not_allow', $caps) )
if ( in_array( 'do_not_allow', $caps ) ) {
return false;
}
return true;
}
@ -732,12 +751,19 @@ class WP_User {
* Dynamically filter a user's capabilities.
*
* @since 2.0.0
* @since 3.7.0 Added the user object.
* @since 3.7.0 Added the `$user` parameter.
*
* @param array $allcaps An array of all the user's capabilities.
* @param array $caps Actual capabilities for meta capability.
* @param array $args Optional parameters passed to has_cap(), typically object ID.
* @param WP_User $user The user object.
* @param bool[] $allcaps Array of key/value pairs where keys represent a capability name and boolean values
* represent whether the user has that capability.
* @param string[] $caps Required primitive capabilities for the requested capability.
* @param array $args {
* Arguments that accompany the requested capability check.
*
* @type string $0 Requested capability.
* @type int $1 Concerned user ID.
* @type mixed ...$2 Optional second and further parameters, typically object ID.
* }
* @param WP_User $user The user object.
*/
$capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this );
@ -749,8 +775,9 @@ class WP_User {
// Must have ALL requested caps.
foreach ( (array) $caps as $cap ) {
if ( empty( $capabilities[ $cap ] ) )
if ( empty( $capabilities[ $cap ] ) ) {
return false;
}
}
return true;
@ -776,8 +803,6 @@ class WP_User {
* @since 3.0.0
* @deprecated 4.9.0 Use WP_User::for_site()
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $blog_id Optional. Site ID, defaults to current site.
*/
public function for_blog( $blog_id = '' ) {

View file

@ -141,34 +141,34 @@ class Walker {
$args[0]['has_children'] = $this->has_children; // Back-compat.
}
$cb_args = array_merge( array(&$output, $element, $depth), $args);
call_user_func_array(array($this, 'start_el'), $cb_args);
$cb_args = array_merge( array( &$output, $element, $depth ), $args );
call_user_func_array( array( $this, 'start_el' ), $cb_args );
// descend only when the depth is right and there are childrens for this element
if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) {
if ( ( $max_depth == 0 || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {
foreach ( $children_elements[ $id ] as $child ){
foreach ( $children_elements[ $id ] as $child ) {
if ( !isset($newlevel) ) {
if ( ! isset( $newlevel ) ) {
$newlevel = true;
//start the child delimiter
$cb_args = array_merge( array(&$output, $depth), $args);
call_user_func_array(array($this, 'start_lvl'), $cb_args);
$cb_args = array_merge( array( &$output, $depth ), $args );
call_user_func_array( array( $this, 'start_lvl' ), $cb_args );
}
$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
}
unset( $children_elements[ $id ] );
}
if ( isset($newlevel) && $newlevel ){
if ( isset( $newlevel ) && $newlevel ) {
//end the child delimiter
$cb_args = array_merge( array(&$output, $depth), $args);
call_user_func_array(array($this, 'end_lvl'), $cb_args);
$cb_args = array_merge( array( &$output, $depth ), $args );
call_user_func_array( array( $this, 'end_lvl' ), $cb_args );
}
//end this element
$cb_args = array_merge( array(&$output, $element, $depth), $args);
call_user_func_array(array($this, 'end_el'), $cb_args);
$cb_args = array_merge( array( &$output, $element, $depth ), $args );
call_user_func_array( array( $this, 'end_el' ), $cb_args );
}
/**
@ -187,7 +187,7 @@ class Walker {
* @return string The hierarchical item output.
*/
public function walk( $elements, $max_depth ) {
$args = array_slice(func_get_args(), 2);
$args = array_slice( func_get_args(), 2 );
$output = '';
//invalid parameter or nothing to walk
@ -200,8 +200,9 @@ class Walker {
// flat display
if ( -1 == $max_depth ) {
$empty_array = array();
foreach ( $elements as $e )
foreach ( $elements as $e ) {
$this->display_element( $e, $empty_array, 1, 0, $args, $output );
}
return $output;
}
@ -213,34 +214,37 @@ class Walker {
*/
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e) {
if ( empty( $e->$parent_field ) )
foreach ( $elements as $e ) {
if ( empty( $e->$parent_field ) ) {
$top_level_elements[] = $e;
else
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
/*
* When none of the elements is top level.
* Assume the first one must be root of the sub elements.
*/
if ( empty($top_level_elements) ) {
if ( empty( $top_level_elements ) ) {
$first = array_slice( $elements, 0, 1 );
$root = $first[0];
$root = $first[0];
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e) {
if ( $root->$parent_field == $e->$parent_field )
foreach ( $elements as $e ) {
if ( $root->$parent_field == $e->$parent_field ) {
$top_level_elements[] = $e;
else
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
}
foreach ( $top_level_elements as $e )
foreach ( $top_level_elements as $e ) {
$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
}
/*
* If we are displaying all levels, and remaining children_elements is not empty,
@ -248,25 +252,27 @@ class Walker {
*/
if ( ( $max_depth == 0 ) && count( $children_elements ) > 0 ) {
$empty_array = array();
foreach ( $children_elements as $orphans )
foreach ( $orphans as $op )
foreach ( $children_elements as $orphans ) {
foreach ( $orphans as $op ) {
$this->display_element( $op, $empty_array, 1, 0, $args, $output );
}
}
}
}
return $output;
return $output;
}
/**
* paged_walk() - produce a page of nested elements
*
* Given an array of hierarchical elements, the maximum depth, a specific page number,
* and number of elements per page, this function first determines all top level root elements
* belonging to that page, then lists them and all of their children in hierarchical order.
*
* paged_walk() - produce a page of nested elements
*
* Given an array of hierarchical elements, the maximum depth, a specific page number,
* and number of elements per page, this function first determines all top level root elements
* belonging to that page, then lists them and all of their children in hierarchical order.
*
* $max_depth = 0 means display all levels.
* $max_depth > 0 specifies the number of display levels.
*
* @since 2.7.0
* @since 2.7.0
*
* @param array $elements
* @param int $max_depth The maximum hierarchical depth.
@ -279,45 +285,50 @@ class Walker {
return '';
}
$args = array_slice( func_get_args(), 4 );
$args = array_slice( func_get_args(), 4 );
$output = '';
$parent_field = $this->db_fields['parent'];
$count = -1;
if ( -1 == $max_depth )
if ( -1 == $max_depth ) {
$total_top = count( $elements );
if ( $page_num < 1 || $per_page < 0 ) {
}
if ( $page_num < 1 || $per_page < 0 ) {
// No paging
$paging = false;
$start = 0;
if ( -1 == $max_depth )
$start = 0;
if ( -1 == $max_depth ) {
$end = $total_top;
}
$this->max_pages = 1;
} else {
$paging = true;
$start = ( (int)$page_num - 1 ) * (int)$per_page;
$end = $start + $per_page;
if ( -1 == $max_depth )
$this->max_pages = ceil($total_top / $per_page);
$start = ( (int) $page_num - 1 ) * (int) $per_page;
$end = $start + $per_page;
if ( -1 == $max_depth ) {
$this->max_pages = ceil( $total_top / $per_page );
}
}
// flat display
if ( -1 == $max_depth ) {
if ( !empty($args[0]['reverse_top_level']) ) {
if ( ! empty( $args[0]['reverse_top_level'] ) ) {
$elements = array_reverse( $elements );
$oldstart = $start;
$start = $total_top - $end;
$end = $total_top - $oldstart;
$start = $total_top - $end;
$end = $total_top - $oldstart;
}
$empty_array = array();
foreach ( $elements as $e ) {
$count++;
if ( $count < $start )
if ( $count < $start ) {
continue;
if ( $count >= $end )
}
if ( $count >= $end ) {
break;
}
$this->display_element( $e, $empty_array, 1, 0, $args, $output );
}
return $output;
@ -330,51 +341,59 @@ class Walker {
*/
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e) {
if ( 0 == $e->$parent_field )
foreach ( $elements as $e ) {
if ( 0 == $e->$parent_field ) {
$top_level_elements[] = $e;
else
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
$total_top = count( $top_level_elements );
if ( $paging )
$this->max_pages = ceil($total_top / $per_page);
else
if ( $paging ) {
$this->max_pages = ceil( $total_top / $per_page );
} else {
$end = $total_top;
if ( !empty($args[0]['reverse_top_level']) ) {
$top_level_elements = array_reverse( $top_level_elements );
$oldstart = $start;
$start = $total_top - $end;
$end = $total_top - $oldstart;
}
if ( !empty($args[0]['reverse_children']) ) {
foreach ( $children_elements as $parent => $children )
$children_elements[$parent] = array_reverse( $children );
if ( ! empty( $args[0]['reverse_top_level'] ) ) {
$top_level_elements = array_reverse( $top_level_elements );
$oldstart = $start;
$start = $total_top - $end;
$end = $total_top - $oldstart;
}
if ( ! empty( $args[0]['reverse_children'] ) ) {
foreach ( $children_elements as $parent => $children ) {
$children_elements[ $parent ] = array_reverse( $children );
}
}
foreach ( $top_level_elements as $e ) {
$count++;
// For the last page, need to unset earlier children in order to keep track of orphans.
if ( $end >= $total_top && $count < $start )
if ( $end >= $total_top && $count < $start ) {
$this->unset_children( $e, $children_elements );
}
if ( $count < $start )
if ( $count < $start ) {
continue;
}
if ( $count >= $end )
if ( $count >= $end ) {
break;
}
$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
}
if ( $end >= $total_top && count( $children_elements ) > 0 ) {
$empty_array = array();
foreach ( $children_elements as $orphans )
foreach ( $orphans as $op )
foreach ( $children_elements as $orphans ) {
foreach ( $orphans as $op ) {
$this->display_element( $op, $empty_array, 1, 0, $args, $output );
}
}
}
return $output;
@ -388,13 +407,14 @@ class Walker {
* @param array $elements Elements to list.
* @return int Number of root elements.
*/
public function get_number_of_root_elements( $elements ){
$num = 0;
public function get_number_of_root_elements( $elements ) {
$num = 0;
$parent_field = $this->db_fields['parent'];
foreach ( $elements as $e) {
if ( 0 == $e->$parent_field )
foreach ( $elements as $e ) {
if ( 0 == $e->$parent_field ) {
$num++;
}
}
return $num;
}
@ -407,17 +427,19 @@ class Walker {
* @param object $e
* @param array $children_elements
*/
public function unset_children( $e, &$children_elements ){
public function unset_children( $e, &$children_elements ) {
if ( ! $e || ! $children_elements ) {
return;
}
$id_field = $this->db_fields['id'];
$id = $e->$id_field;
$id = $e->$id_field;
if ( !empty($children_elements[$id]) && is_array($children_elements[$id]) )
foreach ( (array) $children_elements[$id] as $child )
if ( ! empty( $children_elements[ $id ] ) && is_array( $children_elements[ $id ] ) ) {
foreach ( (array) $children_elements[ $id ] as $child ) {
$this->unset_children( $child, $children_elements );
}
}
unset( $children_elements[ $id ] );
}

View file

@ -71,13 +71,13 @@ class WP_Widget_Factory {
return spl_object_hash( $widget );
} else {
$class_name = get_class( $widget );
$hash = $class_name;
$hash = $class_name;
if ( ! isset( $widget->_wp_widget_factory_hash_id ) ) {
if ( ! isset( $this->hashed_class_counts[ $class_name ] ) ) {
$this->hashed_class_counts[ $class_name ] = 0;
}
$this->hashed_class_counts[ $class_name ] += 1;
$widget->_wp_widget_factory_hash_id = $this->hashed_class_counts[ $class_name ];
$widget->_wp_widget_factory_hash_id = $this->hashed_class_counts[ $class_name ];
}
$hash .= ':' . $widget->_wp_widget_factory_hash_id;
return $hash;
@ -127,18 +127,18 @@ class WP_Widget_Factory {
*/
public function _register_widgets() {
global $wp_registered_widgets;
$keys = array_keys($this->widgets);
$registered = array_keys($wp_registered_widgets);
$registered = array_map('_get_widget_id_base', $registered);
$keys = array_keys( $this->widgets );
$registered = array_keys( $wp_registered_widgets );
$registered = array_map( '_get_widget_id_base', $registered );
foreach ( $keys as $key ) {
// don't register new widget if old widget with the same id is already registered
if ( in_array($this->widgets[$key]->id_base, $registered, true) ) {
unset($this->widgets[$key]);
if ( in_array( $this->widgets[ $key ]->id_base, $registered, true ) ) {
unset( $this->widgets[ $key ] );
continue;
}
$this->widgets[$key]->_register();
$this->widgets[ $key ]->_register();
}
}
}

View file

@ -110,7 +110,7 @@ class WP_Widget {
* @param array $instance The settings for the particular instance of the widget.
*/
public function widget( $args, $instance ) {
die('function WP_Widget::widget() must be over-ridden in a sub-class.');
die( 'function WP_Widget::widget() must be over-ridden in a sub-class.' );
}
/**
@ -140,7 +140,7 @@ class WP_Widget {
* @return string Default return is 'noform'.
*/
public function form( $instance ) {
echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
echo '<p class="no-options-widget">' . __( 'There are no options for this widget.' ) . '</p>';
return 'noform';
}
@ -160,10 +160,16 @@ class WP_Widget {
* information on accepted arguments. Default empty array.
*/
public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
$this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
$this->name = $name;
$this->option_name = 'widget_' . $this->id_base;
$this->widget_options = wp_parse_args( $widget_options, array( 'classname' => $this->option_name, 'customize_selective_refresh' => false ) );
$this->id_base = empty( $id_base ) ? preg_replace( '/(wp_)?widget_/', '', strtolower( get_class( $this ) ) ) : strtolower( $id_base );
$this->name = $name;
$this->option_name = 'widget_' . $this->id_base;
$this->widget_options = wp_parse_args(
$widget_options,
array(
'classname' => $this->option_name,
'customize_selective_refresh' => false,
)
);
$this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
}
@ -199,7 +205,7 @@ class WP_Widget {
* @param string $field_name Field name
* @return string Name attribute for $field_name
*/
public function get_field_name($field_name) {
public function get_field_name( $field_name ) {
if ( false === $pos = strpos( $field_name, '[' ) ) {
return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
} else {
@ -230,7 +236,7 @@ class WP_Widget {
*/
public function _register() {
$settings = $this->get_settings();
$empty = true;
$empty = true;
// When $settings is an array-like object, get an intrinsic array for use with array_keys().
if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
@ -262,9 +268,9 @@ class WP_Widget {
* @param int $number The unique order number of this widget instance compared to other
* instances of the same class.
*/
public function _set($number) {
public function _set( $number ) {
$this->number = $number;
$this->id = $this->id_base . '-' . $number;
$this->id = $this->id_base . '-' . $number;
}
/**
@ -275,7 +281,7 @@ class WP_Widget {
* @return callable Display callback.
*/
public function _get_display_callback() {
return array($this, 'display_callback');
return array( $this, 'display_callback' );
}
/**
@ -286,7 +292,7 @@ class WP_Widget {
* @return callable Update callback.
*/
public function _get_update_callback() {
return array($this, 'update_callback');
return array( $this, 'update_callback' );
}
/**
@ -297,7 +303,7 @@ class WP_Widget {
* @return callable Form callback.
*/
public function _get_form_callback() {
return array($this, 'form_callback');
return array( $this, 'form_callback' );
}
/**
@ -316,7 +322,7 @@ class WP_Widget {
*/
public function is_preview() {
global $wp_customize;
return ( isset( $wp_customize ) && $wp_customize->is_preview() ) ;
return ( isset( $wp_customize ) && $wp_customize->is_preview() );
}
/**
@ -392,37 +398,40 @@ class WP_Widget {
$all_instances = $this->get_settings();
// We need to update the data
if ( $this->updated )
if ( $this->updated ) {
return;
}
if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) {
// Delete the settings for this instance of the widget
if ( isset($_POST['the-widget-id']) )
if ( isset( $_POST['the-widget-id'] ) ) {
$del_id = $_POST['the-widget-id'];
else
} else {
return;
}
if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
$number = $wp_registered_widgets[$del_id]['params'][0]['number'];
if ( isset( $wp_registered_widgets[ $del_id ]['params'][0]['number'] ) ) {
$number = $wp_registered_widgets[ $del_id ]['params'][0]['number'];
if ( $this->id_base . '-' . $number == $del_id )
unset($all_instances[$number]);
if ( $this->id_base . '-' . $number == $del_id ) {
unset( $all_instances[ $number ] );
}
}
} else {
if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
$settings = $_POST['widget-' . $this->id_base];
} elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
$num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
if ( isset( $_POST[ 'widget-' . $this->id_base ] ) && is_array( $_POST[ 'widget-' . $this->id_base ] ) ) {
$settings = $_POST[ 'widget-' . $this->id_base ];
} elseif ( isset( $_POST['id_base'] ) && $_POST['id_base'] == $this->id_base ) {
$num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
$settings = array( $num => array() );
} else {
return;
}
foreach ( $settings as $number => $new_instance ) {
$new_instance = stripslashes_deep($new_instance);
$this->_set($number);
$new_instance = stripslashes_deep( $new_instance );
$this->_set( $number );
$old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
$old_instance = isset( $all_instances[ $number ] ) ? $all_instances[ $number ] : array();
$was_cache_addition_suspended = wp_suspend_cache_addition();
if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
@ -450,14 +459,14 @@ class WP_Widget {
*/
$instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
if ( false !== $instance ) {
$all_instances[$number] = $instance;
$all_instances[ $number ] = $instance;
}
break; // run only once
}
}
$this->save_settings($all_instances);
$this->save_settings( $all_instances );
$this->updated = true;
}
@ -475,18 +484,19 @@ class WP_Widget {
* @return string|null
*/
public function form_callback( $widget_args = 1 ) {
if ( is_numeric($widget_args) )
if ( is_numeric( $widget_args ) ) {
$widget_args = array( 'number' => $widget_args );
}
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
$all_instances = $this->get_settings();
if ( -1 == $widget_args['number'] ) {
// We echo out a form where 'number' can be set later
$this->_set('__i__');
$this->_set( '__i__' );
$instance = array();
} else {
$this->_set($widget_args['number']);
$this->_set( $widget_args['number'] );
$instance = $all_instances[ $widget_args['number'] ];
}
@ -504,7 +514,7 @@ class WP_Widget {
$return = null;
if ( false !== $instance ) {
$return = $this->form($instance);
$return = $this->form( $instance );
/**
* Fires at the end of the widget control form.
@ -536,9 +546,9 @@ class WP_Widget {
* compared to other instances of the same class. Default -1.
*/
public function _register_one( $number = -1 ) {
wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
_register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
_register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
_register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
}
/**

File diff suppressed because it is too large Load diff

View file

@ -12,9 +12,9 @@ class WP {
* Long list of public query variables.
*
* @since 2.0.0
* @var array
* @var string[]
*/
public $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type', 'embed' );
public $public_query_vars = array( 'm', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type', 'embed' );
/**
* Private query variables.
@ -22,7 +22,7 @@ class WP {
* Long list of private query variables.
*
* @since 2.0.0
* @var array
* @var string[]
*/
public $private_query_vars = array( 'offset', 'posts_per_page', 'posts_per_archive_page', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page', 'post__in', 'post__not_in', 'post_parent', 'post_parent__in', 'post_parent__not_in', 'title', 'fields' );
@ -89,9 +89,10 @@ class WP {
*
* @param string $qv Query variable name.
*/
public function add_query_var($qv) {
if ( !in_array($qv, $this->public_query_vars) )
public function add_query_var( $qv ) {
if ( ! in_array( $qv, $this->public_query_vars ) ) {
$this->public_query_vars[] = $qv;
}
}
/**
@ -113,8 +114,8 @@ class WP {
* @param string $key Query variable name.
* @param mixed $value Query variable value.
*/
public function set_query_var($key, $value) {
$this->query_vars[$key] = $value;
public function set_query_var( $key, $value ) {
$this->query_vars[ $key ] = $value;
}
/**
@ -129,7 +130,7 @@ class WP {
*
* @param array|string $extra_query_vars Set the extra query variables.
*/
public function parse_request($extra_query_vars = '') {
public function parse_request( $extra_query_vars = '' ) {
global $wp_rewrite;
/**
@ -141,10 +142,11 @@ class WP {
* @param WP $this Current WordPress environment instance.
* @param array|string $extra_query_vars Extra passed query variables.
*/
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) ) {
return;
}
$this->query_vars = array();
$this->query_vars = array();
$post_type_query_vars = array();
if ( is_array( $extra_query_vars ) ) {
@ -157,43 +159,44 @@ class WP {
// Fetch the rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
if ( ! empty($rewrite) ) {
if ( ! empty( $rewrite ) ) {
// If we match a rewrite rule, this will be cleared.
$error = '404';
$error = '404';
$this->did_permalink = true;
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
list( $pathinfo ) = explode( '?', $pathinfo );
$pathinfo = str_replace( "%", "%25", $pathinfo );
$pathinfo = str_replace( '%', '%25', $pathinfo );
list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$self = $_SERVER['PHP_SELF'];
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
$self = $_SERVER['PHP_SELF'];
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
$home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
// Trim path info from the end and the leading home path from the
// front. For path info requests, this leaves us with the requesting
// filename, if any. For 404 requests, this leaves us with the
// requested permalink.
$req_uri = str_replace($pathinfo, '', $req_uri);
$req_uri = trim($req_uri, '/');
$req_uri = preg_replace( $home_path_regex, '', $req_uri );
$req_uri = trim($req_uri, '/');
$pathinfo = trim($pathinfo, '/');
$req_uri = str_replace( $pathinfo, '', $req_uri );
$req_uri = trim( $req_uri, '/' );
$req_uri = preg_replace( $home_path_regex, '', $req_uri );
$req_uri = trim( $req_uri, '/' );
$pathinfo = trim( $pathinfo, '/' );
$pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
$pathinfo = trim($pathinfo, '/');
$self = trim($self, '/');
$self = preg_replace( $home_path_regex, '', $self );
$self = trim($self, '/');
$pathinfo = trim( $pathinfo, '/' );
$self = trim( $self, '/' );
$self = preg_replace( $home_path_regex, '', $self );
$self = trim( $self, '/' );
// The requested permalink is in $pathinfo for path info requests and
// $req_uri for other requests.
if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
if ( ! empty( $pathinfo ) && ! preg_match( '|^.*' . $wp_rewrite->index . '$|', $pathinfo ) ) {
$requested_path = $pathinfo;
} else {
// If the request uri is the index, blank it out so that we don't try to match it against a rule.
if ( $req_uri == $wp_rewrite->index )
if ( $req_uri == $wp_rewrite->index ) {
$req_uri = '';
}
$requested_path = $req_uri;
}
$requested_file = $req_uri;
@ -206,23 +209,24 @@ class WP {
// An empty request could only match against ^$ regex
if ( isset( $rewrite['$'] ) ) {
$this->matched_rule = '$';
$query = $rewrite['$'];
$matches = array('');
$query = $rewrite['$'];
$matches = array( '' );
}
} else {
foreach ( (array) $rewrite as $match => $query ) {
// If the requested file is the anchor of the match, prepend it to the path info.
if ( ! empty($requested_file) && strpos($match, $requested_file) === 0 && $requested_file != $requested_path )
if ( ! empty( $requested_file ) && strpos( $match, $requested_file ) === 0 && $requested_file != $requested_path ) {
$request_match = $requested_file . '/' . $requested_path;
}
if ( preg_match("#^$match#", $request_match, $matches) ||
preg_match("#^$match#", urldecode($request_match), $matches) ) {
if ( preg_match( "#^$match#", $request_match, $matches ) ||
preg_match( "#^$match#", urldecode( $request_match ), $matches ) ) {
if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
// This is a verbose page match, let's check to be sure about it.
$page = get_page_by_path( $matches[ $varmatch[1] ] );
if ( ! $page ) {
continue;
continue;
}
$post_status_obj = get_post_status_object( $page->post_status );
@ -241,27 +245,29 @@ class WP {
if ( isset( $this->matched_rule ) ) {
// Trim the query of everything up to the '?'.
$query = preg_replace("!^.+\?!", '', $query);
$query = preg_replace( '!^.+\?!', '', $query );
// Substitute the substring matches into the query.
$query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
$query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) );
$this->matched_query = $query;
// Parse the query.
parse_str($query, $perma_query_vars);
parse_str( $query, $perma_query_vars );
// If we're processing a 404 request, clear the error var since we found something.
if ( '404' == $error )
if ( '404' == $error ) {
unset( $error, $_GET['error'] );
}
}
// If req_uri is empty or if it is a request for ourself, unset error.
if ( empty($requested_path) || $requested_file == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
if ( empty( $requested_path ) || $requested_file == $self || strpos( $_SERVER['PHP_SELF'], 'wp-admin/' ) !== false ) {
unset( $error, $_GET['error'] );
if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
if ( isset( $perma_query_vars ) && strpos( $_SERVER['PHP_SELF'], 'wp-admin/' ) !== false ) {
unset( $perma_query_vars );
}
$this->did_permalink = false;
}
@ -276,50 +282,53 @@ class WP {
*
* @since 1.5.0
*
* @param array $public_query_vars The array of whitelisted query variables.
* @param string[] $public_query_vars The array of whitelisted query variable names.
*/
$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
if ( is_post_type_viewable( $t ) && $t->query_var ) {
$post_type_query_vars[$t->query_var] = $post_type;
$post_type_query_vars[ $t->query_var ] = $post_type;
}
}
foreach ( $this->public_query_vars as $wpvar ) {
if ( isset( $this->extra_query_vars[$wpvar] ) )
$this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] ) && $_GET[ $wpvar ] !== $_POST[ $wpvar ] )
if ( isset( $this->extra_query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $this->extra_query_vars[ $wpvar ];
} elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] ) && $_GET[ $wpvar ] !== $_POST[ $wpvar ] ) {
wp_die( __( 'A variable mismatch has been detected.' ), __( 'Sorry, you are not allowed to view this item.' ), 400 );
elseif ( isset( $_POST[$wpvar] ) )
$this->query_vars[$wpvar] = $_POST[$wpvar];
elseif ( isset( $_GET[$wpvar] ) )
$this->query_vars[$wpvar] = $_GET[$wpvar];
elseif ( isset( $perma_query_vars[$wpvar] ) )
$this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
} elseif ( isset( $_POST[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $_POST[ $wpvar ];
} elseif ( isset( $_GET[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $_GET[ $wpvar ];
} elseif ( isset( $perma_query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $perma_query_vars[ $wpvar ];
}
if ( !empty( $this->query_vars[$wpvar] ) ) {
if ( ! is_array( $this->query_vars[$wpvar] ) ) {
$this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
if ( ! empty( $this->query_vars[ $wpvar ] ) ) {
if ( ! is_array( $this->query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = (string) $this->query_vars[ $wpvar ];
} else {
foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
if ( !is_object( $v ) ) {
$this->query_vars[$wpvar][$vkey] = (string) $v;
foreach ( $this->query_vars[ $wpvar ] as $vkey => $v ) {
if ( is_scalar( $v ) ) {
$this->query_vars[ $wpvar ][ $vkey ] = (string) $v;
}
}
}
if ( isset($post_type_query_vars[$wpvar] ) ) {
$this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
$this->query_vars['name'] = $this->query_vars[$wpvar];
if ( isset( $post_type_query_vars[ $wpvar ] ) ) {
$this->query_vars['post_type'] = $post_type_query_vars[ $wpvar ];
$this->query_vars['name'] = $this->query_vars[ $wpvar ];
}
}
}
// Convert urldecoded spaces back into +
foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
$this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) {
if ( $t->query_var && isset( $this->query_vars[ $t->query_var ] ) ) {
$this->query_vars[ $t->query_var ] = str_replace( ' ', '+', $this->query_vars[ $t->query_var ] );
}
}
// Don't allow non-publicly queryable taxonomies to be queried from the front end.
if ( ! is_admin() ) {
@ -335,11 +344,12 @@ class WP {
}
// Limit publicly queried post_types to those that are publicly_queryable
if ( isset( $this->query_vars['post_type']) ) {
$queryable_post_types = get_post_types( array('publicly_queryable' => true) );
if ( isset( $this->query_vars['post_type'] ) ) {
$queryable_post_types = get_post_types( array( 'publicly_queryable' => true ) );
if ( ! is_array( $this->query_vars['post_type'] ) ) {
if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) ) {
unset( $this->query_vars['post_type'] );
}
} else {
$this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
}
@ -348,13 +358,15 @@ class WP {
// Resolve conflicts between posts with numeric slugs and date archive queries.
$this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
foreach ( (array) $this->private_query_vars as $var) {
if ( isset($this->extra_query_vars[$var]) )
$this->query_vars[$var] = $this->extra_query_vars[$var];
foreach ( (array) $this->private_query_vars as $var ) {
if ( isset( $this->extra_query_vars[ $var ] ) ) {
$this->query_vars[ $var ] = $this->extra_query_vars[ $var ];
}
}
if ( isset($error) )
if ( isset( $error ) ) {
$this->query_vars['error'] = $error;
}
/**
* Filters the array of parsed query variables.
@ -385,23 +397,25 @@ class WP {
* @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
*/
public function send_headers() {
$headers = array();
$status = null;
$headers = array();
$status = null;
$exit_required = false;
if ( is_user_logged_in() )
$headers = array_merge($headers, wp_get_nocache_headers());
if ( is_user_logged_in() ) {
$headers = array_merge( $headers, wp_get_nocache_headers() );
}
if ( ! empty( $this->query_vars['error'] ) ) {
$status = (int) $this->query_vars['error'];
if ( 404 === $status ) {
if ( ! is_user_logged_in() )
$headers = array_merge($headers, wp_get_nocache_headers());
$headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
if ( ! is_user_logged_in() ) {
$headers = array_merge( $headers, wp_get_nocache_headers() );
}
$headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
} elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
$exit_required = true;
}
} elseif ( empty( $this->query_vars['feed'] ) ) {
$headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
$headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
} else {
// Set the correct content type for feeds
$type = $this->query_vars['feed'];
@ -412,16 +426,16 @@ class WP {
// We're showing a feed, so WP is indeed the only thing that last changed.
if ( ! empty( $this->query_vars['withcomments'] )
|| false !== strpos( $this->query_vars['feed'], 'comments-' )
|| ( empty( $this->query_vars['withoutcomments'] )
&& ( ! empty( $this->query_vars['p'] )
|| ! empty( $this->query_vars['name'] )
|| ! empty( $this->query_vars['page_id'] )
|| ! empty( $this->query_vars['pagename'] )
|| ! empty( $this->query_vars['attachment'] )
|| ! empty( $this->query_vars['attachment_id'] )
)
)
|| false !== strpos( $this->query_vars['feed'], 'comments-' )
|| ( empty( $this->query_vars['withoutcomments'] )
&& ( ! empty( $this->query_vars['p'] )
|| ! empty( $this->query_vars['name'] )
|| ! empty( $this->query_vars['page_id'] )
|| ! empty( $this->query_vars['pagename'] )
|| ! empty( $this->query_vars['attachment'] )
|| ! empty( $this->query_vars['attachment_id'] )
)
)
) {
$wp_last_modified = mysql2date( 'D, d M Y H:i:s', get_lastcommentmodified( 'GMT' ), false );
} else {
@ -434,26 +448,28 @@ class WP {
$wp_last_modified .= ' GMT';
$wp_etag = '"' . md5($wp_last_modified) . '"';
$wp_etag = '"' . md5( $wp_last_modified ) . '"';
$headers['Last-Modified'] = $wp_last_modified;
$headers['ETag'] = $wp_etag;
$headers['ETag'] = $wp_etag;
// Support for Conditional GET
if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
if ( isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) {
$client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
else $client_etag = false;
} else {
$client_etag = false;
}
$client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
$client_last_modified = empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ? '' : trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;
// Make a timestamp for our most recent modification...
$wp_modified_timestamp = strtotime($wp_last_modified);
$wp_modified_timestamp = strtotime( $wp_last_modified );
if ( ($client_last_modified && $client_etag) ?
(($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
(($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
$status = 304;
if ( ( $client_last_modified && $client_etag ) ?
( ( $client_modified_timestamp >= $wp_modified_timestamp ) && ( $client_etag == $wp_etag ) ) :
( ( $client_modified_timestamp >= $wp_modified_timestamp ) || ( $client_etag == $wp_etag ) ) ) {
$status = 304;
$exit_required = true;
}
}
@ -463,13 +479,14 @@ class WP {
*
* @since 2.8.0
*
* @param array $headers The list of headers to be sent.
* @param WP $this Current WordPress environment instance.
* @param string[] $headers Associative array of headers to be sent.
* @param WP $this Current WordPress environment instance.
*/
$headers = apply_filters( 'wp_headers', $headers, $this );
if ( ! empty( $status ) )
if ( ! empty( $status ) ) {
status_header( $status );
}
// If Last-Modified is set to false, it should not be sent (no-cache situation).
if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
@ -490,11 +507,13 @@ class WP {
}
}
foreach ( (array) $headers as $name => $field_value )
@header("{$name}: {$field_value}");
foreach ( (array) $headers as $name => $field_value ) {
@header( "{$name}: {$field_value}" );
}
if ( $exit_required )
if ( $exit_required ) {
exit();
}
/**
* Fires once the requested HTTP headers for caching, content type, etc. have been sent.
@ -516,12 +535,13 @@ class WP {
*/
public function build_query_string() {
$this->query_string = '';
foreach ( (array) array_keys($this->query_vars) as $wpvar) {
if ( '' != $this->query_vars[$wpvar] ) {
$this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
foreach ( (array) array_keys( $this->query_vars ) as $wpvar ) {
if ( '' != $this->query_vars[ $wpvar ] ) {
$this->query_string .= ( strlen( $this->query_string ) < 1 ) ? '' : '&';
if ( ! is_scalar( $this->query_vars[ $wpvar ] ) ) { // Discard non-scalars.
continue;
$this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
}
$this->query_string .= $wpvar . '=' . rawurlencode( $this->query_vars[ $wpvar ] );
}
}
@ -535,7 +555,7 @@ class WP {
* @param string $query_string The query string to modify.
*/
$this->query_string = apply_filters( 'query_string', $this->query_string );
parse_str($this->query_string, $this->query_vars);
parse_str( $this->query_string, $this->query_vars );
}
}
@ -566,17 +586,18 @@ class WP {
}
$GLOBALS['query_string'] = $this->query_string;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;
if ( $wp_query->is_single() || $wp_query->is_page() ) {
$GLOBALS['more'] = 1;
$GLOBALS['single'] = 1;
}
if ( $wp_query->is_author() && isset( $wp_query->post ) )
if ( $wp_query->is_author() && isset( $wp_query->post ) ) {
$GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
}
}
/**
@ -598,10 +619,10 @@ class WP {
public function query_posts() {
global $wp_the_query;
$this->build_query_string();
$wp_the_query->query($this->query_vars);
}
$wp_the_query->query( $this->query_vars );
}
/**
/**
* Set the Headers for 404, if nothing is found for requested URL.
*
* Issue a 404 if a request doesn't match any posts and doesn't match
@ -615,9 +636,9 @@ class WP {
* a 404 so that canonical redirection logic can kick in.
*
* @since 2.0.0
*
*
* @global WP_Query $wp_query
*/
*/
public function handle_404() {
global $wp_query;
@ -637,8 +658,9 @@ class WP {
}
// If we've already issued a 404, bail.
if ( is_404() )
if ( is_404() ) {
return;
}
// Never 404 for the admin, robots, or if we found posts.
if ( is_admin() || is_robots() || $wp_query->posts ) {
@ -659,7 +681,7 @@ class WP {
// check for paged content that exceeds the max number of pages
$next = '<!--nextpage-->';
if ( $p && false !== strpos( $p->post_content, $next ) && ! empty( $this->query_vars['page'] ) ) {
$page = trim( $this->query_vars['page'], '/' );
$page = trim( $this->query_vars['page'], '/' );
$success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
}
}
@ -710,9 +732,9 @@ class WP {
*
* @param string|array $query_args Passed to parse_request().
*/
public function main($query_args = '') {
public function main( $query_args = '' ) {
$this->init();
$this->parse_request($query_args);
$this->parse_request( $query_args );
$this->send_headers();
$this->query_posts();
$this->handle_404();

View file

@ -96,17 +96,18 @@ class WP_Dependencies {
$this->all_deps( $handles );
foreach ( $this->to_do as $key => $handle ) {
if ( !in_array($handle, $this->done, true) && isset($this->registered[$handle]) ) {
if ( ! in_array( $handle, $this->done, true ) && isset( $this->registered[ $handle ] ) ) {
/*
* Attempt to process the item. If successful,
* add the handle to the done array.
*
* Unset the item from the to_do array.
*/
if ( $this->do_item( $handle, $group ) )
if ( $this->do_item( $handle, $group ) ) {
$this->done[] = $handle;
}
unset( $this->to_do[$key] );
unset( $this->to_do[ $key ] );
}
}
@ -122,7 +123,7 @@ class WP_Dependencies {
* @return bool True on success, false if not set.
*/
public function do_item( $handle ) {
return isset($this->registered[$handle]);
return isset( $this->registered[ $handle ] );
}
/**
@ -141,43 +142,50 @@ class WP_Dependencies {
* @return bool True on success, false on failure.
*/
public function all_deps( $handles, $recursion = false, $group = false ) {
if ( !$handles = (array) $handles )
if ( ! $handles = (array) $handles ) {
return false;
}
foreach ( $handles as $handle ) {
$handle_parts = explode('?', $handle);
$handle = $handle_parts[0];
$queued = in_array($handle, $this->to_do, true);
$handle_parts = explode( '?', $handle );
$handle = $handle_parts[0];
$queued = in_array( $handle, $this->to_do, true );
if ( in_array($handle, $this->done, true) ) // Already done
if ( in_array( $handle, $this->done, true ) ) { // Already done
continue;
}
$moved = $this->set_group( $handle, $recursion, $group );
$new_group = $this->groups[ $handle ];
if ( $queued && !$moved ) // already queued and in the right group
if ( $queued && ! $moved ) { // already queued and in the right group
continue;
$keep_going = true;
if ( !isset($this->registered[$handle]) )
$keep_going = false; // Item doesn't exist.
elseif ( $this->registered[$handle]->deps && array_diff($this->registered[$handle]->deps, array_keys($this->registered)) )
$keep_going = false; // Item requires dependencies that don't exist.
elseif ( $this->registered[$handle]->deps && !$this->all_deps( $this->registered[$handle]->deps, true, $new_group ) )
$keep_going = false; // Item requires dependencies that don't exist.
if ( ! $keep_going ) { // Either item or its dependencies don't exist.
if ( $recursion )
return false; // Abort this branch.
else
continue; // We're at the top level. Move on to the next one.
}
if ( $queued ) // Already grabbed it and its dependencies.
continue;
$keep_going = true;
if ( ! isset( $this->registered[ $handle ] ) ) {
$keep_going = false; // Item doesn't exist.
} elseif ( $this->registered[ $handle ]->deps && array_diff( $this->registered[ $handle ]->deps, array_keys( $this->registered ) ) ) {
$keep_going = false; // Item requires dependencies that don't exist.
} elseif ( $this->registered[ $handle ]->deps && ! $this->all_deps( $this->registered[ $handle ]->deps, true, $new_group ) ) {
$keep_going = false; // Item requires dependencies that don't exist.
}
if ( isset($handle_parts[1]) )
$this->args[$handle] = $handle_parts[1];
if ( ! $keep_going ) { // Either item or its dependencies don't exist.
if ( $recursion ) {
return false; // Abort this branch.
} else {
continue; // We're at the top level. Move on to the next one.
}
}
if ( $queued ) { // Already grabbed it and its dependencies.
continue;
}
if ( isset( $handle_parts[1] ) ) {
$this->args[ $handle ] = $handle_parts[1];
}
$this->to_do[] = $handle;
}
@ -194,8 +202,9 @@ class WP_Dependencies {
* @since 2.6.0 Moved from `WP_Scripts`.
*
* @param string $handle Name of the item. Should be unique.
* @param string $src Full URL of the item, or path of the item relative to the WordPress root directory.
* @param array $deps Optional. An array of registered item handles this item depends on. Default empty array.
* @param string|bool $src Full URL of the item, or path of the item relative to the WordPress root directory.
* If source is set to false, item is an alias of other items it depends on.
* @param string[] $deps Optional. An array of registered item handles this item depends on. Default empty array.
* @param string|bool|null $ver Optional. String specifying item version number, if it has one, which is added to the URL
* as a query string for cache busting purposes. If version is set to false, a version
* number is automatically added equal to current installed WordPress version.
@ -204,9 +213,10 @@ class WP_Dependencies {
* @return bool Whether the item has been registered. True on success, false on failure.
*/
public function add( $handle, $src, $deps = array(), $ver = false, $args = null ) {
if ( isset($this->registered[$handle]) )
if ( isset( $this->registered[ $handle ] ) ) {
return false;
$this->registered[$handle] = new _WP_Dependency( $handle, $src, $deps, $ver, $args );
}
$this->registered[ $handle ] = new _WP_Dependency( $handle, $src, $deps, $ver, $args );
return true;
}
@ -223,10 +233,11 @@ class WP_Dependencies {
* @return bool True on success, false on failure.
*/
public function add_data( $handle, $key, $value ) {
if ( !isset( $this->registered[$handle] ) )
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
return $this->registered[$handle]->add_data( $key, $value );
return $this->registered[ $handle ]->add_data( $key, $value );
}
/**
@ -241,13 +252,15 @@ class WP_Dependencies {
* @return mixed Extra item data (string), false otherwise.
*/
public function get_data( $handle, $key ) {
if ( !isset( $this->registered[$handle] ) )
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
if ( !isset( $this->registered[$handle]->extra[$key] ) )
if ( ! isset( $this->registered[ $handle ]->extra[ $key ] ) ) {
return false;
}
return $this->registered[$handle]->extra[$key];
return $this->registered[ $handle ]->extra[ $key ];
}
/**
@ -260,8 +273,9 @@ class WP_Dependencies {
* @return void
*/
public function remove( $handles ) {
foreach ( (array) $handles as $handle )
unset($this->registered[$handle]);
foreach ( (array) $handles as $handle ) {
unset( $this->registered[ $handle ] );
}
}
/**
@ -279,11 +293,12 @@ class WP_Dependencies {
*/
public function enqueue( $handles ) {
foreach ( (array) $handles as $handle ) {
$handle = explode('?', $handle);
if ( !in_array($handle[0], $this->queue) && isset($this->registered[$handle[0]]) ) {
$handle = explode( '?', $handle );
if ( ! in_array( $handle[0], $this->queue ) && isset( $this->registered[ $handle[0] ] ) ) {
$this->queue[] = $handle[0];
if ( isset($handle[1]) )
$this->args[$handle[0]] = $handle[1];
if ( isset( $handle[1] ) ) {
$this->args[ $handle[0] ] = $handle[1];
}
}
}
}
@ -301,11 +316,11 @@ class WP_Dependencies {
*/
public function dequeue( $handles ) {
foreach ( (array) $handles as $handle ) {
$handle = explode('?', $handle);
$key = array_search($handle[0], $this->queue);
$handle = explode( '?', $handle );
$key = array_search( $handle[0], $this->queue );
if ( false !== $key ) {
unset($this->queue[$key]);
unset($this->args[$handle[0]]);
unset( $this->queue[ $key ] );
unset( $this->args[ $handle[0] ] );
}
}
}
@ -315,8 +330,8 @@ class WP_Dependencies {
*
* @since 4.0.0
*
* @param array $queue An array of queued _WP_Dependency handle objects.
* @param string $handle Name of the item. Should be unique.
* @param string[] $queue An array of queued _WP_Dependency handles.
* @param string $handle Name of the item. Should be unique.
* @return bool Whether the handle is found after recursively searching the dependency tree.
*/
protected function recurse_deps( $queue, $handle ) {
@ -347,24 +362,25 @@ class WP_Dependencies {
*/
public function query( $handle, $list = 'registered' ) {
switch ( $list ) {
case 'registered' :
case 'registered':
case 'scripts': // back compat
if ( isset( $this->registered[ $handle ] ) )
if ( isset( $this->registered[ $handle ] ) ) {
return $this->registered[ $handle ];
}
return false;
case 'enqueued' :
case 'queue' :
case 'enqueued':
case 'queue':
if ( in_array( $handle, $this->queue ) ) {
return true;
}
return $this->recurse_deps( $this->queue, $handle );
case 'to_do' :
case 'to_do':
case 'to_print': // back compat
return in_array( $handle, $this->to_do );
case 'done' :
case 'done':
case 'printed': // back compat
return in_array( $handle, $this->done );
}

View file

@ -35,7 +35,7 @@ class WP_Scripts extends WP_Dependencies {
public $content_url;
/**
* Default version string for stylesheets.
* Default version string for scripts.
*
* @since 2.6.0
* @var string
@ -145,7 +145,7 @@ class WP_Scripts extends WP_Dependencies {
*
* @param WP_Scripts $this WP_Scripts instance (passed by reference).
*/
do_action_ref_array( 'wp_default_scripts', array(&$this) );
do_action_ref_array( 'wp_default_scripts', array( &$this ) );
}
/**
@ -196,13 +196,15 @@ class WP_Scripts extends WP_Dependencies {
* @return bool|string|void Void if no data exists, extra scripts if `$echo` is true, true otherwise.
*/
public function print_extra_script( $handle, $echo = true ) {
if ( !$output = $this->get_data( $handle, 'data' ) )
if ( ! $output = $this->get_data( $handle, 'data' ) ) {
return;
}
if ( !$echo )
if ( ! $echo ) {
return $output;
}
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5.
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
@ -219,23 +221,25 @@ class WP_Scripts extends WP_Dependencies {
*
* @see WP_Dependencies::do_item()
*
* @param string $handle The script's registered handle.
* @param string $handle The script's registered handle.
* @param int|false $group Optional. Group level: (int) level, (false) no groups. Default false.
* @return bool True on success, false on failure.
*/
public function do_item( $handle, $group = false ) {
if ( !parent::do_item($handle) )
if ( ! parent::do_item( $handle ) ) {
return false;
}
if ( 0 === $group && $this->groups[$handle] > 0 ) {
if ( 0 === $group && $this->groups[ $handle ] > 0 ) {
$this->in_footer[] = $handle;
return false;
}
if ( false === $group && in_array($handle, $this->in_footer, true) )
if ( false === $group && in_array( $handle, $this->in_footer, true ) ) {
$this->in_footer = array_diff( $this->in_footer, (array) $handle );
}
$obj = $this->registered[$handle];
$obj = $this->registered[ $handle ];
if ( null === $obj->ver ) {
$ver = '';
@ -243,20 +247,21 @@ class WP_Scripts extends WP_Dependencies {
$ver = $obj->ver ? $obj->ver : $this->default_version;
}
if ( isset($this->args[$handle]) )
$ver = $ver ? $ver . '&amp;' . $this->args[$handle] : $this->args[$handle];
if ( isset( $this->args[ $handle ] ) ) {
$ver = $ver ? $ver . '&amp;' . $this->args[ $handle ] : $this->args[ $handle ];
}
$src = $obj->src;
$src = $obj->src;
$cond_before = $cond_after = '';
$conditional = isset( $obj->extra['conditional'] ) ? $obj->extra['conditional'] : '';
if ( $conditional ) {
$cond_before = "<!--[if {$conditional}]>\n";
$cond_after = "<![endif]-->\n";
$cond_after = "<![endif]-->\n";
}
$before_handle = $this->print_inline_script( $handle, 'before', false );
$after_handle = $this->print_inline_script( $handle, 'after', false );
$after_handle = $this->print_inline_script( $handle, 'after', false );
if ( $before_handle ) {
$before_handle = sprintf( "<script type='text/javascript'>\n%s\n</script>\n", $before_handle );
@ -290,8 +295,8 @@ class WP_Scripts extends WP_Dependencies {
_print_scripts();
$this->reset();
} elseif ( $this->in_default_dir( $srce ) && ! $conditional ) {
$this->print_code .= $this->print_extra_script( $handle, false );
$this->concat .= "$handle,";
$this->print_code .= $this->print_extra_script( $handle, false );
$this->concat .= "$handle,";
$this->concat_version .= "$handle$ver";
return true;
} else {
@ -334,14 +339,16 @@ class WP_Scripts extends WP_Dependencies {
$src = $this->base_url . $src;
}
if ( ! empty( $ver ) )
if ( ! empty( $ver ) ) {
$src = add_query_arg( 'ver', $ver, $src );
}
/** This filter is documented in wp-includes/class.wp-scripts.php */
$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
if ( ! $src )
if ( ! $src ) {
return true;
}
$tag = "{$translations}{$cond_before}{$before_handle}<script type='text/javascript' src='$src'></script>\n{$after_handle}{$cond_after}";
@ -399,7 +406,7 @@ class WP_Scripts extends WP_Dependencies {
* @param string $handle Name of the script to add the inline script to. Must be lowercase.
* @param string $position Optional. Whether to add the inline script before the handle
* or after. Default 'after'.
* @param bool $echo Optional. Whether to echo the script instead of just returning it.
* @param bool $echo Optional. Whether to echo the script instead of just returning it.
* Default true.
* @return string|false Script on success, false otherwise.
*/
@ -424,36 +431,40 @@ class WP_Scripts extends WP_Dependencies {
*
* @since 2.1.0
*
* @param string $handle
* @param string $object_name
* @param array $l10n
* @return bool
* @param string $handle Name of the script to attach data to.
* @param string $object_name Name of the variable that will contain the data.
* @param array $l10n Array of data to localize.
* @return bool True on success, false on failure.
*/
public function localize( $handle, $object_name, $l10n ) {
if ( $handle === 'jquery' )
if ( $handle === 'jquery' ) {
$handle = 'jquery-core';
}
if ( is_array($l10n) && isset($l10n['l10n_print_after']) ) { // back compat, preserve the code in 'l10n_print_after' if present
if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
$after = $l10n['l10n_print_after'];
unset($l10n['l10n_print_after']);
unset( $l10n['l10n_print_after'] );
}
foreach ( (array) $l10n as $key => $value ) {
if ( !is_scalar($value) )
if ( ! is_scalar( $value ) ) {
continue;
}
$l10n[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8');
$l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
}
$script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
if ( !empty($after) )
if ( ! empty( $after ) ) {
$script .= "\n$after;";
}
$data = $this->get_data( $handle, 'data' );
if ( !empty( $data ) )
if ( ! empty( $data ) ) {
$script = "$data\n$script";
}
return $this->add_data( $handle, 'data', $script );
}
@ -471,13 +482,15 @@ class WP_Scripts extends WP_Dependencies {
* @return bool Not already in the group or a lower group
*/
public function set_group( $handle, $recursion, $group = false ) {
if ( isset( $this->registered[$handle]->args ) && $this->registered[$handle]->args === 1 )
if ( isset( $this->registered[ $handle ]->args ) && $this->registered[ $handle ]->args === 1 ) {
$grp = 1;
else
} else {
$grp = (int) $this->get_data( $handle, 'group' );
}
if ( false !== $group && $grp > $group )
if ( false !== $group && $grp > $group ) {
$grp = $group;
}
return parent::set_group( $handle, $recursion, $grp );
}
@ -486,14 +499,14 @@ class WP_Scripts extends WP_Dependencies {
* Sets a translation textdomain.
*
* @since 5.0.0
* @since 5.1.0 The `$domain` parameter was made optional.
*
* @param string $handle Name of the script to register a translation domain to.
* @param string $domain The textdomain.
* @param string $domain Optional. Text domain. Default 'default'.
* @param string $path Optional. The full file path to the directory containing translation files.
*
* @return bool True if the textdomain was registered, false if not.
* @return bool True if the text domain was registered, false if not.
*/
public function set_translations( $handle, $domain, $path = null ) {
public function set_translations( $handle, $domain = 'default', $path = null ) {
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
@ -504,6 +517,7 @@ class WP_Scripts extends WP_Dependencies {
if ( ! in_array( 'wp-i18n', $obj->deps, true ) ) {
$obj->deps[] = 'wp-i18n';
}
return $obj->set_translations( $domain, $path );
}
@ -567,7 +581,7 @@ JS;
*
* @since 2.3.0
*
* @param array $to_do An array of script dependencies.
* @param string[] $to_do An array of script dependency handles.
*/
$this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
}
@ -584,7 +598,7 @@ JS;
* @return array Handles of items that have been processed.
*/
public function do_head_items() {
$this->do_items(false, 0);
$this->do_items( false, 0 );
return $this->done;
}
@ -598,7 +612,7 @@ JS;
* @return array Handles of items that have been processed.
*/
public function do_footer_items() {
$this->do_items(false, 1);
$this->do_items( false, 1 );
return $this->done;
}
@ -633,12 +647,12 @@ JS;
* @since 2.8.0
*/
public function reset() {
$this->do_concat = false;
$this->print_code = '';
$this->concat = '';
$this->do_concat = false;
$this->print_code = '';
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
$this->ext_version = '';
$this->ext_handles = '';
$this->print_html = '';
$this->ext_version = '';
$this->ext_handles = '';
}
}

View file

@ -113,7 +113,7 @@ class WP_Styles extends WP_Dependencies {
*
* @param WP_Styles $this WP_Styles instance (passed by reference).
*/
do_action_ref_array( 'wp_default_styles', array(&$this) );
do_action_ref_array( 'wp_default_styles', array( &$this ) );
}
/**
@ -127,54 +127,76 @@ class WP_Styles extends WP_Dependencies {
* @return bool True on success, false on failure.
*/
public function do_item( $handle ) {
if ( !parent::do_item($handle) )
if ( ! parent::do_item( $handle ) ) {
return false;
}
$obj = $this->registered[$handle];
if ( null === $obj->ver )
$obj = $this->registered[ $handle ];
if ( null === $obj->ver ) {
$ver = '';
else
} else {
$ver = $obj->ver ? $obj->ver : $this->default_version;
}
if ( isset($this->args[$handle]) )
$ver = $ver ? $ver . '&amp;' . $this->args[$handle] : $this->args[$handle];
if ( isset( $this->args[ $handle ] ) ) {
$ver = $ver ? $ver . '&amp;' . $this->args[ $handle ] : $this->args[ $handle ];
}
$src = $obj->src;
$cond_before = $cond_after = '';
$conditional = isset( $obj->extra['conditional'] ) ? $obj->extra['conditional'] : '';
if ( $conditional ) {
$cond_before = "<!--[if {$conditional}]>\n";
$cond_after = "<![endif]-->\n";
}
$inline_style = $this->print_inline_style( $handle, false );
if ( $inline_style ) {
$inline_style_tag = sprintf( "<style id='%s-inline-css' type='text/css'>\n%s\n</style>\n", esc_attr( $handle ), $inline_style );
} else {
$inline_style_tag = '';
}
if ( $this->do_concat ) {
if ( $this->in_default_dir($obj->src) && !isset($obj->extra['conditional']) && !isset($obj->extra['alt']) ) {
$this->concat .= "$handle,";
if ( $this->in_default_dir( $src ) && ! $conditional && ! isset( $obj->extra['alt'] ) ) {
$this->concat .= "$handle,";
$this->concat_version .= "$handle$ver";
$this->print_code .= $this->print_inline_style( $handle, false );
$this->print_code .= $inline_style;
return true;
}
}
if ( isset($obj->args) )
if ( isset( $obj->args ) ) {
$media = esc_attr( $obj->args );
else
} else {
$media = 'all';
}
// A single item may alias a set of items, by having dependencies, but no source.
if ( ! $obj->src ) {
if ( $inline_style = $this->print_inline_style( $handle, false ) ) {
$inline_style = sprintf( "<style id='%s-inline-css' type='text/css'>\n%s\n</style>\n", esc_attr( $handle ), $inline_style );
if ( ! $src ) {
if ( $inline_style_tag ) {
if ( $this->do_concat ) {
$this->print_html .= $inline_style;
$this->print_html .= $inline_style_tag;
} else {
echo $inline_style;
echo $inline_style_tag;
}
}
return true;
}
$href = $this->_css_href( $obj->src, $ver, $handle );
$href = $this->_css_href( $src, $ver, $handle );
if ( ! $href ) {
return true;
}
$rel = isset($obj->extra['alt']) && $obj->extra['alt'] ? 'alternate stylesheet' : 'stylesheet';
$title = isset($obj->extra['title']) ? "title='" . esc_attr( $obj->extra['title'] ) . "'" : '';
$rel = isset( $obj->extra['alt'] ) && $obj->extra['alt'] ? 'alternate stylesheet' : 'stylesheet';
$title = isset( $obj->extra['title'] ) ? "title='" . esc_attr( $obj->extra['title'] ) . "'" : '';
/**
* Filters the HTML link tag of an enqueued style.
@ -188,11 +210,12 @@ class WP_Styles extends WP_Dependencies {
* @param string $href The stylesheet's source URL.
* @param string $media The stylesheet's media attribute.
*/
$tag = apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle, $href, $media);
if ( 'rtl' === $this->text_direction && isset($obj->extra['rtl']) && $obj->extra['rtl'] ) {
$tag = apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle, $href, $media );
if ( 'rtl' === $this->text_direction && isset( $obj->extra['rtl'] ) && $obj->extra['rtl'] ) {
if ( is_bool( $obj->extra['rtl'] ) || 'replace' === $obj->extra['rtl'] ) {
$suffix = isset( $obj->extra['suffix'] ) ? $obj->extra['suffix'] : '';
$rtl_href = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $this->_css_href( $obj->src , $ver, "$handle-rtl" ));
$suffix = isset( $obj->extra['suffix'] ) ? $obj->extra['suffix'] : '';
$rtl_href = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $this->_css_href( $src, $ver, "$handle-rtl" ) );
} else {
$rtl_href = $this->_css_href( $obj->extra['rtl'], $ver, "$handle-rtl" );
}
@ -207,24 +230,18 @@ class WP_Styles extends WP_Dependencies {
}
}
$conditional_pre = $conditional_post = '';
if ( isset( $obj->extra['conditional'] ) && $obj->extra['conditional'] ) {
$conditional_pre = "<!--[if {$obj->extra['conditional']}]>\n";
$conditional_post = "<![endif]-->\n";
}
if ( $this->do_concat ) {
$this->print_html .= $conditional_pre;
$this->print_html .= $cond_before;
$this->print_html .= $tag;
if ( $inline_style = $this->print_inline_style( $handle, false ) ) {
$this->print_html .= sprintf( "<style id='%s-inline-css' type='text/css'>\n%s\n</style>\n", esc_attr( $handle ), $inline_style );
if ( $inline_style_tag ) {
$this->print_html .= $inline_style_tag;
}
$this->print_html .= $conditional_post;
$this->print_html .= $cond_after;
} else {
echo $conditional_pre;
echo $cond_before;
echo $tag;
$this->print_inline_style( $handle );
echo $conditional_post;
echo $cond_after;
}
return true;
@ -302,7 +319,7 @@ class WP_Styles extends WP_Dependencies {
*
* @since 2.6.0
*
* @param array $to_do The list of enqueued styles about to be processed.
* @param string[] $to_do The list of enqueued style handles about to be processed.
*/
$this->to_do = apply_filters( 'print_styles_array', $this->to_do );
}
@ -320,12 +337,13 @@ class WP_Styles extends WP_Dependencies {
* @return string Style's fully-qualified URL.
*/
public function _css_href( $src, $ver, $handle ) {
if ( !is_bool($src) && !preg_match('|^(https?:)?//|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) {
if ( ! is_bool( $src ) && ! preg_match( '|^(https?:)?//|', $src ) && ! ( $this->content_url && 0 === strpos( $src, $this->content_url ) ) ) {
$src = $this->base_url . $src;
}
if ( !empty($ver) )
$src = add_query_arg('ver', $ver, $src);
if ( ! empty( $ver ) ) {
$src = add_query_arg( 'ver', $ver, $src );
}
/**
* Filters an enqueued style's fully-qualified URL.
@ -348,12 +366,14 @@ class WP_Styles extends WP_Dependencies {
* @return bool True if found, false if not.
*/
public function in_default_dir( $src ) {
if ( ! $this->default_dirs )
if ( ! $this->default_dirs ) {
return true;
}
foreach ( (array) $this->default_dirs as $test ) {
if ( 0 === strpos($src, $test) )
if ( 0 === strpos( $src, $test ) ) {
return true;
}
}
return false;
}
@ -370,7 +390,7 @@ class WP_Styles extends WP_Dependencies {
* @return array Handles of items that have been processed.
*/
public function do_footer_items() {
$this->do_items(false, 1);
$this->do_items( false, 1 );
return $this->done;
}
@ -380,9 +400,9 @@ class WP_Styles extends WP_Dependencies {
* @since 3.3.0
*/
public function reset() {
$this->do_concat = false;
$this->concat = '';
$this->do_concat = false;
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
$this->print_html = '';
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -7,8 +7,8 @@
*/
// If gettext isn't available
if ( !function_exists('_') ) {
function _($string) {
if ( ! function_exists( '_' ) ) {
function _( $string ) {
return $string;
}
}
@ -125,7 +125,7 @@ function _mb_substr( $str, $start, $length = null, $encoding = null ) {
$chars = array_merge( $chars, $pieces );
// If there's anything left over, repeat the loop.
// If there's anything left over, repeat the loop.
} while ( count( $pieces ) > 1 && $str = array_pop( $pieces ) );
return join( '', array_slice( $chars, $start, $length ) );
@ -209,33 +209,33 @@ function _mb_strlen( $str, $encoding = null ) {
// Increment.
$count += count( $pieces );
// If there's anything left over, repeat the loop.
// If there's anything left over, repeat the loop.
} while ( $str = array_pop( $pieces ) );
// Fencepost: preg_split() always returns one extra item in the array.
return --$count;
}
if ( !function_exists('hash_hmac') ):
/**
* Compat function to mimic hash_hmac().
*
* @ignore
* @since 3.2.0
*
* @see _hash_hmac()
*
* @param string $algo Hash algorithm. Accepts 'md5' or 'sha1'.
* @param string $data Data to be hashed.
* @param string $key Secret key to use for generating the hash.
* @param bool $raw_output Optional. Whether to output raw binary data (true),
* or lowercase hexits (false). Default false.
* @return string|false The hash in output determined by `$raw_output`. False if `$algo`
* is unknown or invalid.
*/
function hash_hmac($algo, $data, $key, $raw_output = false) {
return _hash_hmac($algo, $data, $key, $raw_output);
}
if ( ! function_exists( 'hash_hmac' ) ) :
/**
* Compat function to mimic hash_hmac().
*
* @ignore
* @since 3.2.0
*
* @see _hash_hmac()
*
* @param string $algo Hash algorithm. Accepts 'md5' or 'sha1'.
* @param string $data Data to be hashed.
* @param string $key Secret key to use for generating the hash.
* @param bool $raw_output Optional. Whether to output raw binary data (true),
* or lowercase hexits (false). Default false.
* @return string|false The hash in output determined by `$raw_output`. False if `$algo`
* is unknown or invalid.
*/
function hash_hmac( $algo, $data, $key, $raw_output = false ) {
return _hash_hmac( $algo, $data, $key, $raw_output );
}
endif;
/**
@ -252,30 +252,36 @@ endif;
* @return string|false The hash in output determined by `$raw_output`. False if `$algo`
* is unknown or invalid.
*/
function _hash_hmac($algo, $data, $key, $raw_output = false) {
$packs = array('md5' => 'H32', 'sha1' => 'H40');
function _hash_hmac( $algo, $data, $key, $raw_output = false ) {
$packs = array(
'md5' => 'H32',
'sha1' => 'H40',
);
if ( !isset($packs[$algo]) )
if ( ! isset( $packs[ $algo ] ) ) {
return false;
}
$pack = $packs[$algo];
$pack = $packs[ $algo ];
if (strlen($key) > 64)
$key = pack($pack, $algo($key));
if ( strlen( $key ) > 64 ) {
$key = pack( $pack, $algo( $key ) );
}
$key = str_pad($key, 64, chr(0));
$key = str_pad( $key, 64, chr( 0 ) );
$ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
$opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));
$ipad = ( substr( $key, 0, 64 ) ^ str_repeat( chr( 0x36 ), 64 ) );
$opad = ( substr( $key, 0, 64 ) ^ str_repeat( chr( 0x5C ), 64 ) );
$hmac = $algo($opad . pack($pack, $algo($ipad . $data)));
$hmac = $algo( $opad . pack( $pack, $algo( $ipad . $data ) ) );
if ( $raw_output )
if ( $raw_output ) {
return pack( $pack, $hmac );
}
return $hmac;
}
if ( !function_exists('json_encode') ) {
if ( ! function_exists( 'json_encode' ) ) {
function json_encode( $string ) {
global $wp_json;
@ -288,7 +294,7 @@ if ( !function_exists('json_encode') ) {
}
}
if ( !function_exists('json_decode') ) {
if ( ! function_exists( 'json_decode' ) ) {
/**
* @global Services_JSON $wp_json
* @param string $string
@ -298,14 +304,15 @@ if ( !function_exists('json_decode') ) {
function json_decode( $string, $assoc_array = false ) {
global $wp_json;
if ( ! ($wp_json instanceof Services_JSON ) ) {
if ( ! ( $wp_json instanceof Services_JSON ) ) {
require_once( ABSPATH . WPINC . '/class-json.php' );
$wp_json = new Services_JSON();
}
$res = $wp_json->decode( $string );
if ( $assoc_array )
if ( $assoc_array ) {
$res = _json_decode_object_helper( $res );
}
return $res;
}
@ -313,43 +320,44 @@ if ( !function_exists('json_decode') ) {
* @param object $data
* @return array
*/
function _json_decode_object_helper($data) {
if ( is_object($data) )
$data = get_object_vars($data);
return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
function _json_decode_object_helper( $data ) {
if ( is_object( $data ) ) {
$data = get_object_vars( $data );
}
return is_array( $data ) ? array_map( __FUNCTION__, $data ) : $data;
}
}
if ( ! function_exists( 'hash_equals' ) ) :
/**
* Timing attack safe string comparison
*
* Compares two strings using the same time whether they're equal or not.
*
* This function was added in PHP 5.6.
*
* Note: It can leak the length of a string when arguments of differing length are supplied.
*
* @since 3.9.2
*
* @param string $a Expected string.
* @param string $b Actual, user supplied, string.
* @return bool Whether strings are equal.
*/
function hash_equals( $a, $b ) {
$a_length = strlen( $a );
if ( $a_length !== strlen( $b ) ) {
return false;
}
$result = 0;
/**
* Timing attack safe string comparison
*
* Compares two strings using the same time whether they're equal or not.
*
* This function was added in PHP 5.6.
*
* Note: It can leak the length of a string when arguments of differing length are supplied.
*
* @since 3.9.2
*
* @param string $a Expected string.
* @param string $b Actual, user supplied, string.
* @return bool Whether strings are equal.
*/
function hash_equals( $a, $b ) {
$a_length = strlen( $a );
if ( $a_length !== strlen( $b ) ) {
return false;
}
$result = 0;
// Do not attempt to "optimize" this.
for ( $i = 0; $i < $a_length; $i++ ) {
$result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
}
// Do not attempt to "optimize" this.
for ( $i = 0; $i < $a_length; $i++ ) {
$result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
}
return $result === 0;
}
return $result === 0;
}
endif;
// JSON_PRETTY_PRINT was introduced in PHP 5.4
@ -472,9 +480,9 @@ if ( ! function_exists( 'array_replace_recursive' ) ) :
foreach ( array_keys( $head ) as $key ) {
if ( isset( $key, $bref ) &&
isset( $bref[ $key ] ) && is_array( $bref[ $key ] ) &&
isset( $head[ $key ] ) && is_array( $head[ $key ] )
) {
isset( $bref[ $key ] ) && is_array( $bref[ $key ] ) &&
isset( $head[ $key ] ) && is_array( $head[ $key ] ) ) {
$bref_stack[] = &$bref[ $key ];
$head_stack[] = $head[ $key ];
} else {

File diff suppressed because it is too large Load diff

View file

@ -22,8 +22,8 @@
font-family: Tahoma, sans-serif;
}
html:lang(he-il) .rtl #wpadminbar * {
font-family: Arial, sans-serif;
html:lang(he-il) .rtl #wpadminbar * {
font-family: Arial, sans-serif;
}
#wpadminbar .ab-empty-item {
@ -53,7 +53,6 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar a:hover,
#wpadminbar a img,
#wpadminbar a img:hover {
outline: none;
border: none;
text-decoration: none;
background: none;
@ -71,7 +70,11 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar textarea,
#wpadminbar div {
box-shadow: none;
outline: none;
}
#wpadminbar a:focus {
/* Inherits transparent outline only visible in Windows High Contrast mode */
outline-offset: -1px;
}
#wpadminbar {
@ -365,7 +368,7 @@ html:lang(he-il) .rtl #wpadminbar * {
border-radius: 10px;
}
#wpadminbar .quicklinks a:hover span#ab-updates {
#wpadminbar .quicklinks a:hover span#ab-updates {
background: #fff;
color: #000;
}
@ -657,7 +660,7 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar.ie8 > #wp-toolbar > #wp-admin-bar-top-secondary > #wp-admin-bar-search #adminbarsearch input.adminbar-input {
/* IE8 z-index bug with transparent / empty elements - fill in with an encoded transparent GIF */
background: transparent 100% 0 repeat scroll url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
background: transparent 100% 0 repeat scroll url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
}
/* IE8 doesn't redraw the pseudo elements unless you make a change to the content */
@ -784,7 +787,7 @@ html:lang(he-il) .rtl #wpadminbar * {
}
/* End no @font-face */
@media screen and ( max-width: 782px ) {
@media screen and (max-width: 782px) {
/* Toolbar Touchification*/
html #wpadminbar {
height: 46px;

File diff suppressed because one or more lines are too long

View file

@ -22,8 +22,8 @@
font-family: Tahoma, sans-serif;
}
html:lang(he-il) .rtl #wpadminbar * {
font-family: Arial, sans-serif;
html:lang(he-il) .rtl #wpadminbar * {
font-family: Arial, sans-serif;
}
#wpadminbar .ab-empty-item {
@ -53,7 +53,6 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar a:hover,
#wpadminbar a img,
#wpadminbar a img:hover {
outline: none;
border: none;
text-decoration: none;
background: none;
@ -71,7 +70,11 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar textarea,
#wpadminbar div {
box-shadow: none;
outline: none;
}
#wpadminbar a:focus {
/* Inherits transparent outline only visible in Windows High Contrast mode */
outline-offset: -1px;
}
#wpadminbar {
@ -365,7 +368,7 @@ html:lang(he-il) .rtl #wpadminbar * {
border-radius: 10px;
}
#wpadminbar .quicklinks a:hover span#ab-updates {
#wpadminbar .quicklinks a:hover span#ab-updates {
background: #fff;
color: #000;
}
@ -657,7 +660,7 @@ html:lang(he-il) .rtl #wpadminbar * {
#wpadminbar.ie8 > #wp-toolbar > #wp-admin-bar-top-secondary > #wp-admin-bar-search #adminbarsearch input.adminbar-input {
/* IE8 z-index bug with transparent / empty elements - fill in with an encoded transparent GIF */
background: transparent 0 0 repeat scroll url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
background: transparent 0 0 repeat scroll url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
}
/* IE8 doesn't redraw the pseudo elements unless you make a change to the content */
@ -784,7 +787,7 @@ html:lang(he-il) .rtl #wpadminbar * {
}
/* End no @font-face */
@media screen and ( max-width: 782px ) {
@media screen and (max-width: 782px) {
/* Toolbar Touchification*/
html #wpadminbar {
height: 46px;

File diff suppressed because one or more lines are too long

View file

@ -72,8 +72,8 @@ TABLE OF CONTENTS:
.wp-core-ui .button.button-large,
.wp-core-ui .button-group.button-large .button {
height: 30px;
line-height: 28px;
padding: 0 12px 2px;
line-height: 28px;
padding: 0 12px 2px;
}
.wp-core-ui .button.button-small,
@ -92,9 +92,12 @@ TABLE OF CONTENTS:
padding: 0 36px;
}
/* Only visible in Windows High Contrast mode */
.wp-core-ui .button:active,
.wp-core-ui .button:focus {
outline: none;
outline: 2px solid transparent;
/* Reset inherited offset from Gutenberg */
outline-offset: 0;
}
.wp-core-ui .button.hidden {
@ -124,7 +127,7 @@ TABLE OF CONTENTS:
border-color: #cccccc;
background: #f7f7f7;
box-shadow: 0 1px 0 #cccccc;
vertical-align: top;
vertical-align: top;
}
.wp-core-ui p .button {
@ -190,7 +193,6 @@ TABLE OF CONTENTS:
border: 0;
border-radius: 0;
background: none;
outline: none;
cursor: pointer;
text-align: right;
/* Mimics the default link style in common.css */
@ -211,6 +213,8 @@ TABLE OF CONTENTS:
box-shadow:
0 0 0 1px #5b9dd9,
0 0 2px 1px rgba(30, 140, 190, .8);
/* Only visible in Windows High Contrast mode */
outline: 1px solid transparent;
}
.wp-core-ui .button-link-delete {
@ -280,14 +284,14 @@ TABLE OF CONTENTS:
}
.wp-core-ui .button.button-primary.button-hero {
box-shadow: 0 2px 0 #006799;
box-shadow: 0 2px 0 #006799;
}
.wp-core-ui .button.button-primary.button-hero.active,
.wp-core-ui .button.button-primary.button-hero.active:hover,
.wp-core-ui .button.button-primary.button-hero.active:focus,
.wp-core-ui .button.button-primary.button-hero:active {
box-shadow: inset 0 3px 0 #006799;
box-shadow: inset 0 3px 0 #006799;
}
/* ----------------------------------------------------------------------------
@ -334,7 +338,7 @@ TABLE OF CONTENTS:
5.0 - Responsive Button Styles
---------------------------------------------------------------------------- */
@media screen and ( max-width: 782px ) {
@media screen and (max-width: 782px) {
.wp-core-ui .button,
.wp-core-ui .button.button-large,

File diff suppressed because one or more lines are too long

View file

@ -72,8 +72,8 @@ TABLE OF CONTENTS:
.wp-core-ui .button.button-large,
.wp-core-ui .button-group.button-large .button {
height: 30px;
line-height: 28px;
padding: 0 12px 2px;
line-height: 28px;
padding: 0 12px 2px;
}
.wp-core-ui .button.button-small,
@ -92,9 +92,12 @@ TABLE OF CONTENTS:
padding: 0 36px;
}
/* Only visible in Windows High Contrast mode */
.wp-core-ui .button:active,
.wp-core-ui .button:focus {
outline: none;
outline: 2px solid transparent;
/* Reset inherited offset from Gutenberg */
outline-offset: 0;
}
.wp-core-ui .button.hidden {
@ -124,7 +127,7 @@ TABLE OF CONTENTS:
border-color: #cccccc;
background: #f7f7f7;
box-shadow: 0 1px 0 #cccccc;
vertical-align: top;
vertical-align: top;
}
.wp-core-ui p .button {
@ -190,7 +193,6 @@ TABLE OF CONTENTS:
border: 0;
border-radius: 0;
background: none;
outline: none;
cursor: pointer;
text-align: left;
/* Mimics the default link style in common.css */
@ -211,6 +213,8 @@ TABLE OF CONTENTS:
box-shadow:
0 0 0 1px #5b9dd9,
0 0 2px 1px rgba(30, 140, 190, .8);
/* Only visible in Windows High Contrast mode */
outline: 1px solid transparent;
}
.wp-core-ui .button-link-delete {
@ -280,14 +284,14 @@ TABLE OF CONTENTS:
}
.wp-core-ui .button.button-primary.button-hero {
box-shadow: 0 2px 0 #006799;
box-shadow: 0 2px 0 #006799;
}
.wp-core-ui .button.button-primary.button-hero.active,
.wp-core-ui .button.button-primary.button-hero.active:hover,
.wp-core-ui .button.button-primary.button-hero.active:focus,
.wp-core-ui .button.button-primary.button-hero:active {
box-shadow: inset 0 3px 0 #006799;
box-shadow: inset 0 3px 0 #006799;
}
/* ----------------------------------------------------------------------------
@ -334,7 +338,7 @@ TABLE OF CONTENTS:
5.0 - Responsive Button Styles
---------------------------------------------------------------------------- */
@media screen and ( max-width: 782px ) {
@media screen and (max-width: 782px) {
.wp-core-ui .button,
.wp-core-ui .button.button-large,

File diff suppressed because one or more lines are too long

View file

@ -56,10 +56,11 @@
animation-duration: .4s;
opacity: 0;
pointer-events: none;
text-shadow: 0 -1px 1px #006799,
-1px 0 1px #006799,
0 1px 1px #006799,
1px 0 1px #006799;
text-shadow:
0 -1px 1px #006799,
-1px 0 1px #006799,
0 1px 1px #006799,
1px 0 1px #006799;
}
.wp-custom-header .customize-partial-edit-shortcut button {
right: 2px
@ -150,14 +151,14 @@ body.customize-partial-edit-shortcuts-hidden .customize-partial-edit-shortcut bu
}
}
@media screen and (max-width:800px) {
@media screen and (max-width: 800px) {
.widget .customize-partial-edit-shortcut button,
.customize-partial-edit-shortcut button {
right: -32px;
}
}
@media screen and (max-width:320px) {
@media screen and (max-width: 320px) {
.widget .customize-partial-edit-shortcut button,
.customize-partial-edit-shortcut button {
right: -30px;

Some files were not shown because too many files have changed in this diff Show more