<?php
/**
 * Functions related to registering and parsing blocks.
 *
 * @package WordPress
 * @subpackage Blocks
 * @since 5.0.0
 */

/**
 * Registers a block type.
 *
 * @since 5.0.0
 *
 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
 *                                   a complete WP_Block_Type instance. In case a WP_Block_Type
 *                                   is provided, the $args parameter will be ignored.
 * @param array                $args {
 *     Optional. Array of block type arguments. Accepts any public property of `WP_Block_Type`.
 *     Any arguments may be defined, however the ones described below are supported by default.
 *     Default empty array.
 *
 *     @type callable $render_callback Callback used to render blocks of this block type.
 * }
 * @return WP_Block_Type|false The registered block type on success, or false on failure.
 */
function register_block_type( $name, $args = array() ) {
	return WP_Block_Type_Registry::get_instance()->register( $name, $args );
}

/**
 * Unregisters a block type.
 *
 * @since 5.0.0
 *
 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
 *                                   a complete WP_Block_Type instance.
 * @return WP_Block_Type|false The unregistered block type on success, or false on failure.
 */
function unregister_block_type( $name ) {
	return WP_Block_Type_Registry::get_instance()->unregister( $name );
}

/**
 * Removes the block asset's path prefix if provided.
 *
 * @since 5.5.0
 *
 * @param string $asset_handle_or_path Asset handle or prefixed path.
 * @return string Path without the prefix or the original value.
 */
function remove_block_asset_path_prefix( $asset_handle_or_path ) {
	$path_prefix = 'file:';
	if ( 0 !== strpos( $asset_handle_or_path, $path_prefix ) ) {
		return $asset_handle_or_path;
	}
	return substr(
		$asset_handle_or_path,
		strlen( $path_prefix )
	);
}

/**
 * Generates the name for an asset based on the name of the block
 * and the field name provided.
 *
 * @since 5.5.0
 *
 * @param string $block_name Name of the block.
 * @param string $field_name Name of the metadata field.
 * @return string Generated asset name for the block's field.
 */
function generate_block_asset_handle( $block_name, $field_name ) {
	$field_mappings = array(
		'editorScript' => 'editor-script',
		'script'       => 'script',
		'editorStyle'  => 'editor-style',
		'style'        => 'style',
	);
	return str_replace( '/', '-', $block_name ) .
		'-' . $field_mappings[ $field_name ];
}

/**
 * Finds a script handle for the selected block metadata field. It detects
 * when a path to file was provided and finds a corresponding asset file
 * with details necessary to register the script under automatically
 * generated handle name. It returns unprocessed script handle otherwise.
 *
 * @since 5.5.0
 *
 * @param array  $metadata   Block metadata.
 * @param string $field_name Field name to pick from metadata.
 * @return string|bool Script handle provided directly or created through
 *                     script's registration, or false on failure.
 */
function register_block_script_handle( $metadata, $field_name ) {
	if ( empty( $metadata[ $field_name ] ) ) {
		return false;
	}
	$script_handle = $metadata[ $field_name ];
	$script_path   = remove_block_asset_path_prefix( $metadata[ $field_name ] );
	if ( $script_handle === $script_path ) {
		return $script_handle;
	}

	$script_handle     = generate_block_asset_handle( $metadata['name'], $field_name );
	$script_asset_path = realpath(
		dirname( $metadata['file'] ) . '/' .
		substr_replace( $script_path, '.asset.php', - strlen( '.js' ) )
	);
	if ( ! file_exists( $script_asset_path ) ) {
		$message = sprintf(
			/* translators: %1: field name. %2: block name */
			__( 'The asset file for the "%1$s" defined in "%2$s" block definition is missing.', 'default' ),
			$field_name,
			$metadata['name']
		);
		_doing_it_wrong( __FUNCTION__, $message, '5.5.0' );
		return false;
	}
	$script_asset = require $script_asset_path;
	$result       = wp_register_script(
		$script_handle,
		plugins_url( $script_path, $metadata['file'] ),
		$script_asset['dependencies'],
		$script_asset['version']
	);
	return $result ? $script_handle : false;
}

/**
 * Finds a style handle for the block metadata field. It detects when a path
 * to file was provided and registers the style under automatically
 * generated handle name. It returns unprocessed style handle otherwise.
 *
 * @since 5.5.0
 *
 * @param array  $metadata Block metadata.
 * @param string $field_name Field name to pick from metadata.
 * @return string|boolean Style handle provided directly or created through
 *                        style's registration, or false on failure.
 */
function register_block_style_handle( $metadata, $field_name ) {
	if ( empty( $metadata[ $field_name ] ) ) {
		return false;
	}
	$style_handle = $metadata[ $field_name ];
	$style_path   = remove_block_asset_path_prefix( $metadata[ $field_name ] );
	if ( $style_handle === $style_path ) {
		return $style_handle;
	}

	$style_handle = generate_block_asset_handle( $metadata['name'], $field_name );
	$block_dir    = dirname( $metadata['file'] );
	$result       = wp_register_style(
		$style_handle,
		plugins_url( $style_path, $metadata['file'] ),
		array(),
		filemtime( realpath( "$block_dir/$style_path" ) )
	);
	return $result ? $style_handle : false;
}

/**
 * Registers a block type from metadata stored in the `block.json` file.
 *
 * @since 5.5.0
 *
 * @param string $file_or_folder Path to the JSON file with metadata definition for
 *                               the block or path to the folder where the `block.json` file is located.
 * @param array  $args {
 *     Optional. Array of block type arguments. Accepts any public property of `WP_Block_Type`.
 *     Any arguments may be defined, however the ones described below are supported by default.
 *     Default empty array.
 *
 *     @type callable $render_callback Callback used to render blocks of this block type.
 * }
 * @return WP_Block_Type|false The registered block type on success, or false on failure.
 */
function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
	$filename      = 'block.json';
	$metadata_file = ( substr( $file_or_folder, -strlen( $filename ) ) !== $filename ) ?
		trailingslashit( $file_or_folder ) . $filename :
		$file_or_folder;
	if ( ! file_exists( $metadata_file ) ) {
		return false;
	}

	$metadata = json_decode( file_get_contents( $metadata_file ), true );
	if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) {
		return false;
	}
	$metadata['file'] = $metadata_file;

	$settings          = array();
	$property_mappings = array(
		'title'           => 'title',
		'category'        => 'category',
		'parent'          => 'parent',
		'icon'            => 'icon',
		'description'     => 'description',
		'keywords'        => 'keywords',
		'attributes'      => 'attributes',
		'providesContext' => 'provides_context',
		'usesContext'     => 'uses_context',
		'supports'        => 'supports',
		'styles'          => 'styles',
		'example'         => 'example',
	);

	foreach ( $property_mappings as $key => $mapped_key ) {
		if ( isset( $metadata[ $key ] ) ) {
			$settings[ $mapped_key ] = $metadata[ $key ];
		}
	}

	if ( ! empty( $metadata['editorScript'] ) ) {
		$settings['editor_script'] = register_block_script_handle(
			$metadata,
			'editorScript'
		);
	}

	if ( ! empty( $metadata['script'] ) ) {
		$settings['script'] = register_block_script_handle(
			$metadata,
			'script'
		);
	}

	if ( ! empty( $metadata['editorStyle'] ) ) {
		$settings['editor_style'] = register_block_style_handle(
			$metadata,
			'editorStyle'
		);
	}

	if ( ! empty( $metadata['style'] ) ) {
		$settings['style'] = register_block_style_handle(
			$metadata,
			'style'
		);
	}

	return register_block_type(
		$metadata['name'],
		array_merge(
			$settings,
			$args
		)
	);
}

/**
 * Determine whether a post or content string has blocks.
 *
 * This test optimizes for performance rather than strict accuracy, detecting
 * the pattern of a block but not validating its structure. For strict accuracy,
 * you should use the block parser on post content.
 *
 * @since 5.0.0
 *
 * @see parse_blocks()
 *
 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. Defaults to global $post.
 * @return bool Whether the post has blocks.
 */
function has_blocks( $post = null ) {
	if ( ! is_string( $post ) ) {
		$wp_post = get_post( $post );
		if ( $wp_post instanceof WP_Post ) {
			$post = $wp_post->post_content;
		}
	}

	return false !== strpos( (string) $post, '<!-- wp:' );
}

/**
 * Determine whether a $post or a string contains a specific block type.
 *
 * This test optimizes for performance rather than strict accuracy, detecting
 * the block type exists but not validating its structure. For strict accuracy,
 * you should use the block parser on post content.
 *
 * @since 5.0.0
 *
 * @see parse_blocks()
 *
 * @param string                  $block_name Full Block type to look for.
 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. Defaults to global $post.
 * @return bool Whether the post content contains the specified block.
 */
function has_block( $block_name, $post = null ) {
	if ( ! has_blocks( $post ) ) {
		return false;
	}

	if ( ! is_string( $post ) ) {
		$wp_post = get_post( $post );
		if ( $wp_post instanceof WP_Post ) {
			$post = $wp_post->post_content;
		}
	}

	/*
	 * Normalize block name to include namespace, if provided as non-namespaced.
	 * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
	 * their serialized names.
	 */
	if ( false === strpos( $block_name, '/' ) ) {
		$block_name = 'core/' . $block_name;
	}

	// Test for existence of block by its fully qualified name.
	$has_block = false !== strpos( $post, '<!-- wp:' . $block_name . ' ' );

	if ( ! $has_block ) {
		/*
		 * If the given block name would serialize to a different name, test for
		 * existence by the serialized form.
		 */
		$serialized_block_name = strip_core_block_namespace( $block_name );
		if ( $serialized_block_name !== $block_name ) {
			$has_block = false !== strpos( $post, '<!-- wp:' . $serialized_block_name . ' ' );
		}
	}

	return $has_block;
}

/**
 * Returns an array of the names of all registered dynamic block types.
 *
 * @since 5.0.0
 *
 * @return string[] Array of dynamic block names.
 */
function get_dynamic_block_names() {
	$dynamic_block_names = array();

	$block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
	foreach ( $block_types as $block_type ) {
		if ( $block_type->is_dynamic() ) {
			$dynamic_block_names[] = $block_type->name;
		}
	}

	return $dynamic_block_names;
}

/**
 * Given an array of attributes, returns a string in the serialized attributes
 * format prepared for post content.
 *
 * The serialized result is a JSON-encoded string, with unicode escape sequence
 * substitution for characters which might otherwise interfere with embedding
 * the result in an HTML comment.
 *
 * @since 5.3.1
 *
 * @param array $block_attributes Attributes object.
 * @return string Serialized attributes.
 */
function serialize_block_attributes( $block_attributes ) {
	$encoded_attributes = json_encode( $block_attributes );
	$encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
	$encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
	$encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
	$encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
	// Regex: /\\"/
	$encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );

	return $encoded_attributes;
}

/**
 * Returns the block name to use for serialization. This will remove the default
 * "core/" namespace from a block name.
 *
 * @since 5.3.1
 *
 * @param string $block_name Original block name.
 * @return string Block name to use for serialization.
 */
function strip_core_block_namespace( $block_name = null ) {
	if ( is_string( $block_name ) && 0 === strpos( $block_name, 'core/' ) ) {
		return substr( $block_name, 5 );
	}

	return $block_name;
}

/**
 * Returns the content of a block, including comment delimiters.
 *
 * @since 5.3.1
 *
 * @param string $block_name       Block name.
 * @param array  $block_attributes Block attributes.
 * @param string $block_content    Block save content.
 * @return string Comment-delimited block content.
 */
function get_comment_delimited_block_content( $block_name = null, $block_attributes, $block_content ) {
	if ( is_null( $block_name ) ) {
		return $block_content;
	}

	$serialized_block_name = strip_core_block_namespace( $block_name );
	$serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';

	if ( empty( $block_content ) ) {
		return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
	}

	return sprintf(
		'<!-- wp:%s %s-->%s<!-- /wp:%s -->',
		$serialized_block_name,
		$serialized_attributes,
		$block_content,
		$serialized_block_name
	);
}

/**
 * Returns the content of a block, including comment delimiters, serializing all
 * attributes from the given parsed block.
 *
 * This should be used when preparing a block to be saved to post content.
 * Prefer `render_block` when preparing a block for display. Unlike
 * `render_block`, this does not evaluate a block's `render_callback`, and will
 * instead preserve the markup as parsed.
 *
 * @since 5.3.1
 *
 * @param WP_Block_Parser_Block $block A single parsed block object.
 * @return string String of rendered HTML.
 */
function serialize_block( $block ) {
	$block_content = '';

	$index = 0;
	foreach ( $block['innerContent'] as $chunk ) {
		$block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
	}

	if ( ! is_array( $block['attrs'] ) ) {
		$block['attrs'] = array();
	}

	return get_comment_delimited_block_content(
		$block['blockName'],
		$block['attrs'],
		$block_content
	);
}

/**
 * Returns a joined string of the aggregate serialization of the given parsed
 * blocks.
 *
 * @since 5.3.1
 *
 * @param WP_Block_Parser_Block[] $blocks Parsed block objects.
 * @return string String of rendered HTML.
 */
function serialize_blocks( $blocks ) {
	return implode( '', array_map( 'serialize_block', $blocks ) );
}

/**
 * Filters and sanitizes block content to remove non-allowable HTML from
 * parsed block attribute values.
 *
 * @since 5.3.1
 *
 * @param string         $text              Text that may contain block content.
 * @param array[]|string $allowed_html      An array of allowed HTML elements
 *                                          and attributes, or a context name
 *                                          such as 'post'.
 * @param string[]       $allowed_protocols Array of allowed URL protocols.
 * @return string The filtered and sanitized content result.
 */
function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
	$result = '';

	$blocks = parse_blocks( $text );
	foreach ( $blocks as $block ) {
		$block   = filter_block_kses( $block, $allowed_html, $allowed_protocols );
		$result .= serialize_block( $block );
	}

	return $result;
}

/**
 * Filters and sanitizes a parsed block to remove non-allowable HTML from block
 * attribute values.
 *
 * @since 5.3.1
 *
 * @param WP_Block_Parser_Block $block             The parsed block object.
 * @param array[]|string        $allowed_html      An array of allowed HTML
 *                                                 elements and attributes, or a
 *                                                 context name such as 'post'.
 * @param string[]              $allowed_protocols Allowed URL protocols.
 * @return array The filtered and sanitized block object result.
 */
function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
	$block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols );

	if ( is_array( $block['innerBlocks'] ) ) {
		foreach ( $block['innerBlocks'] as $i => $inner_block ) {
			$block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
		}
	}

	return $block;
}

/**
 * Filters and sanitizes a parsed block attribute value to remove non-allowable
 * HTML.
 *
 * @since 5.3.1
 *
 * @param string[]|string $value             The attribute value to filter.
 * @param array[]|string  $allowed_html      An array of allowed HTML elements
 *                                           and attributes, or a context name
 *                                           such as 'post'.
 * @param string[]        $allowed_protocols Array of allowed URL protocols.
 * @return string[]|string The filtered and sanitized result.
 */
function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) {
	if ( is_array( $value ) ) {
		foreach ( $value as $key => $inner_value ) {
			$filtered_key   = filter_block_kses_value( $key, $allowed_html, $allowed_protocols );
			$filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols );

			if ( $filtered_key !== $key ) {
				unset( $value[ $key ] );
			}

			$value[ $filtered_key ] = $filtered_value;
		}
	} elseif ( is_string( $value ) ) {
		return wp_kses( $value, $allowed_html, $allowed_protocols );
	}

	return $value;
}

/**
 * Parses blocks out of a content string, and renders those appropriate for the excerpt.
 *
 * As the excerpt should be a small string of text relevant to the full post content,
 * this function renders the blocks that are most likely to contain such text.
 *
 * @since 5.0.0
 *
 * @param string $content The content to parse.
 * @return string The parsed and filtered content.
 */
function excerpt_remove_blocks( $content ) {
	$allowed_inner_blocks = array(
		// Classic blocks have their blockName set to null.
		null,
		'core/freeform',
		'core/heading',
		'core/html',
		'core/list',
		'core/media-text',
		'core/paragraph',
		'core/preformatted',
		'core/pullquote',
		'core/quote',
		'core/table',
		'core/verse',
	);

	$allowed_blocks = array_merge( $allowed_inner_blocks, array( 'core/columns' ) );

	/**
	 * Filters the list of blocks that can contribute to the excerpt.
	 *
	 * If a dynamic block is added to this list, it must not generate another
	 * excerpt, as this will cause an infinite loop to occur.
	 *
	 * @since 5.0.0
	 *
	 * @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 ) {
		if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
			if ( ! empty( $block['innerBlocks'] ) ) {
				if ( 'core/columns' === $block['blockName'] ) {
					$output .= _excerpt_render_inner_columns_blocks( $block, $allowed_inner_blocks );
					continue;
				}

				// Skip the block if it has disallowed or nested inner blocks.
				foreach ( $block['innerBlocks'] as $inner_block ) {
					if (
						! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
						! empty( $inner_block['innerBlocks'] )
					) {
						continue 2;
					}
				}
			}

			$output .= render_block( $block );
		}
	}

	return $output;
}

/**
 * Render inner blocks from the `core/columns` block for generating an excerpt.
 *
 * @since 5.2.0
 * @access private
 *
 * @param array $columns        The parsed columns block.
 * @param array $allowed_blocks The list of allowed inner blocks.
 * @return string The rendered inner blocks.
 */
function _excerpt_render_inner_columns_blocks( $columns, $allowed_blocks ) {
	$output = '';

	foreach ( $columns['innerBlocks'] as $column ) {
		foreach ( $column['innerBlocks'] as $inner_block ) {
			if ( in_array( $inner_block['blockName'], $allowed_blocks, true ) && empty( $inner_block['innerBlocks'] ) ) {
				$output .= render_block( $inner_block );
			}
		}
	}

	return $output;
}

/**
 * Renders a single block into a HTML string.
 *
 * @since 5.0.0
 *
 * @global WP_Post  $post     The post to edit.
 * @global WP_Query $wp_query WordPress Query object.
 *
 * @param array $parsed_block A single parsed block object.
 * @return string String of rendered HTML.
 */
function render_block( $parsed_block ) {
	global $post, $wp_query;

	/**
	 * Allows render_block() to be short-circuited, by returning a non-null value.
	 *
	 * @since 5.1.0
	 *
	 * @param string|null $pre_render   The pre-rendered content. Default null.
	 * @param array       $parsed_block The block being rendered.
	 */
	$pre_render = apply_filters( 'pre_render_block', null, $parsed_block );
	if ( ! is_null( $pre_render ) ) {
		return $pre_render;
	}

	$source_block = $parsed_block;

	/**
	 * Filters the block being rendered in render_block(), before it's processed.
	 *
	 * @since 5.1.0
	 *
	 * @param array $parsed_block The block being rendered.
	 * @param array $source_block An un-modified copy of $parsed_block, as it appeared in the source content.
	 */
	$parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block );

	$context = array();

	if ( $post instanceof WP_Post ) {
		$context['postId'] = $post->ID;

		/*
		 * The `postType` context is largely unnecessary server-side, since the ID
		 * is usually sufficient on its own. That being said, since a block's
		 * manifest is expected to be shared between the server and the client,
		 * it should be included to consistently fulfill the expectation.
		 */
		$context['postType'] = $post->post_type;
	}

	if ( $wp_query instanceof WP_Query && isset( $wp_query->tax_query->queried_terms['category'] ) ) {
		$context['query'] = array( 'categoryIds' => array() );
		foreach ( $wp_query->tax_query->queried_terms['category']['terms'] as $category_slug_or_id ) {
			$context['query']['categoryIds'][] = 'slug' === $wp_query->tax_query->queried_terms['category']['field'] ? get_cat_ID( $category_slug_or_id ) : $category_slug_or_id;
		}
	}

	/**
	 * Filters the default context provided to a rendered block.
	 *
	 * @since 5.5.0
	 *
	 * @param array $context      Default context.
	 * @param array $parsed_block Block being rendered, filtered by `render_block_data`.
	 */
	$context = apply_filters( 'render_block_context', $context, $parsed_block );

	$block = new WP_Block( $parsed_block, $context );

	return $block->render();
}

/**
 * Parses blocks out of a content string.
 *
 * @since 5.0.0
 *
 * @param string $content Post content.
 * @return array[] Array of parsed block objects.
 */
function parse_blocks( $content ) {
	/**
	 * Filter to allow plugins to replace the server-side block parser
	 *
	 * @since 5.0.0
	 *
	 * @param string $parser_class Name of block parser class.
	 */
	$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );

	$parser = new $parser_class();
	return $parser->parse( $content );
}

/**
 * Parses dynamic blocks out of `post_content` and re-renders them.
 *
 * @since 5.0.0
 *
 * @param string $content Post content.
 * @return string Updated post content.
 */
function do_blocks( $content ) {
	$blocks = parse_blocks( $content );
	$output = '';

	foreach ( $blocks as $block ) {
		$output .= render_block( $block );
	}

	// If there are blocks in this content, we shouldn't run wpautop() on it later.
	$priority = has_filter( 'the_content', 'wpautop' );
	if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
		remove_filter( 'the_content', 'wpautop', $priority );
		add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
	}

	return $output;
}

/**
 * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
 * for subsequent `the_content` usage.
 *
 * @access private
 *
 * @since 5.0.0
 *
 * @param string $content The post content running through this filter.
 * @return string The unmodified content.
 */
function _restore_wpautop_hook( $content ) {
	$current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );

	add_filter( 'the_content', 'wpautop', $current_priority - 1 );
	remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );

	return $content;
}

/**
 * Returns the current version of the block format that the content string is using.
 *
 * If the string doesn't contain blocks, it returns 0.
 *
 * @since 5.0.0
 *
 * @param string $content Content to test.
 * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
 */
function block_version( $content ) {
	return has_blocks( $content ) ? 1 : 0;
}

/**
 * Registers a new block style.
 *
 * @since 5.3.0
 *
 * @param string $block_name       Block type name including namespace.
 * @param array  $style_properties Array containing the properties of the style name,
 *                                 label, style (name of the stylesheet to be enqueued),
 *                                 inline_style (string containing the CSS to be added).
 * @return boolean True if the block style was registered with success and false otherwise.
 */
function register_block_style( $block_name, $style_properties ) {
	return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
}

/**
 * Unregisters a block style.
 *
 * @since 5.3.0
 *
 * @param string $block_name       Block type name including namespace.
 * @param array  $block_style_name Block style name.
 * @return boolean True if the block style was unregistered with success and false otherwise.
 */
function unregister_block_style( $block_name, $block_style_name ) {
	return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
}


<?php
/**
 * Bookmark Template Functions for usage in Themes
 *
 * @package WordPress
 * @subpackage Template
 */

/**
 * The formatted output of a list of bookmarks.
 *
 * The $bookmarks array must contain bookmark objects and will be iterated over
 * to retrieve the bookmark to be used in the output.
 *
 * The output is formatted as HTML with no way to change that format. However,
 * what is between, before, and after can be changed. The link itself will be
 * HTML.
 *
 * This function is used internally by wp_list_bookmarks() and should not be
 * used by themes.
 *
 * @since 2.1.0
 * @access private
 *
 * @param array        $bookmarks List of bookmarks to traverse.
 * @param string|array $args {
 *     Optional. Bookmarks arguments.
 *
 *     @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 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.
 *     @type int|bool $show_name        Whether to show link name if available. Accepts 1|true or
 *                                      0|false. Default 0|false.
 *     @type string   $before           The HTML or text to prepend to each bookmark. Default `<li>`.
 *     @type string   $after            The HTML or text to append to each bookmark. Default `</li>`.
 *     @type string   $link_before      The HTML or text to prepend to each bookmark inside the anchor
 *                                      tags. Default empty.
 *     @type string   $link_after       The HTML or text to append to each bookmark inside the anchor
 *                                      tags. Default empty.
 *     @type string   $between          The string for use in between the link, description, and image.
 *                                      Default "\n".
 *     @type int|bool $show_rating      Whether to show the link rating. Accepts 1|true or 0|false.
 *                                      Default 0|false.
 *
 * }
 * @return string Formatted output in HTML
 */
function _walk_bookmarks( $bookmarks, $args = '' ) {
	$defaults = array(
		'show_updated'     => 0,
		'show_description' => 0,
		'show_images'      => 1,
		'show_name'        => 0,
		'before'           => '
',
		'after'            => '
',
		'between'          => "\n",
		'show_rating'      => 0,
		'link_before'      => '',
		'link_after'       => '',
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$output = ''; // Blank string to start with.

	foreach ( (array) $bookmarks as $bookmark ) {
		if ( ! isset( $bookmark->recently_updated ) ) {
			$bookmark->recently_updated = false;
		}
		$output .= $parsed_args['before'];
		if ( $parsed_args['show_updated'] && $bookmark->recently_updated ) {
			$output .= '';
		}
		$the_link = '#';
		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;

		if ( $parsed_args['show_updated'] ) {
			if ( '00' !== substr( $bookmark->link_updated_f, 0, 2 ) ) {
				$title .= ' (';
				$title .= sprintf(
					/* translators: %s: Date and time of last update. */
					__( 'Last updated: %s' ),
					gmdate(
						get_option( 'links_updated_date_format' ),
						$bookmark->link_updated_f + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS )
					)
				);
				$title .= ')';
			}
		}
		$alt = ' alt="' . $name . ( $parsed_args['show_description'] ? ' ' . $title : '' ) . '"';

		if ( '' !== $title ) {
			$title = ' title="' . $title . '"';
		}
		$rel = $bookmark->link_rel;
		if ( '' !== $rel ) {
			$rel = ' rel="' . esc_attr( $rel ) . '"';
		}
		$target = $bookmark->link_target;
		if ( '' !== $target ) {
			$target = ' target="' . $target . '"';
		}
		$output .= '';

		$output .= $parsed_args['link_before'];

		if ( null != $bookmark->link_image && $parsed_args['show_images'] ) {
			if ( strpos( $bookmark->link_image, 'http' ) === 0 ) {
				$output .= "link_image\" $alt $title />";
			} else { // If it's a relative path.
				$output .= 'link_image\" $alt $title />";
			}
			if ( $parsed_args['show_name'] ) {
				$output .= " $name";
			}
		} else {
			$output .= $name;
		}

		$output .= $parsed_args['link_after'];

		$output .= '';

		if ( $parsed_args['show_updated'] && $bookmark->recently_updated ) {
			$output .= '';
		}

		if ( $parsed_args['show_description'] && '' !== $desc ) {
			$output .= $parsed_args['between'] . $desc;
		}

		if ( $parsed_args['show_rating'] ) {
			$output .= $parsed_args['between'] . sanitize_bookmark_field(
				'link_rating',
				$bookmark->link_rating,
				$bookmark->link_id,
				'display'
			);
		}
		$output .= $parsed_args['after'] . "\n";
	} // End while.

	return $output;
}

/**
 * Retrieve or echo all of the bookmarks.
 *
 * List of default arguments are as follows:
 *
 * These options define how the Category name will appear before the category
 * links are displayed, if 'categorize' is 1. If 'categorize' is 0, then it will
 * display for only the 'title_li' string and only if 'title_li' is not empty.
 *
 * @since 2.1.0
 *
 * @see _walk_bookmarks()
 *
 * @param string|array $args {
 *     Optional. String or array of arguments to list bookmarks.
 *
 *     @type string   $orderby          How to order the links by. Accepts post fields. Default 'name'.
 *     @type string   $order            Whether to order bookmarks in ascending or descending order.
 *                                      Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'.
 *     @type int      $limit            Amount of bookmarks to display. Accepts 1+ or -1 for all.
 *                                      Default -1.
 *     @type string   $category         Comma-separated list of category IDs to include links from.
 *                                      Default empty.
 *     @type string   $category_name    Category to retrieve links for by name. Default empty.
 *     @type int|bool $hide_invisible   Whether to show or hide links marked as 'invisible'. Accepts
 *                                      1|true or 0|false. Default 1|true.
 *     @type int|bool $show_updated     Whether to display the time the bookmark was last updated.
 *                                      Accepts 1|true or 0|false. Default 0|false.
 *     @type int|bool $echo             Whether to echo or return the formatted bookmarks. Accepts
 *                                      1|true (echo) or 0|false (return). Default 1|true.
 *     @type int|bool $categorize       Whether to show links listed by category or in a single column.
 *                                      Accepts 1|true (by category) or 0|false (one column). Default 1|true.
 *     @type int|bool $show_description Whether to show the bookmark descriptions. Accepts 1|true or 0|false.
 *                                      Default 0|false.
 *     @type string   $title_li         What to show before the links appear. Default 'Bookmarks'.
 *     @type string   $title_before     The HTML or text to prepend to the $title_li string. Default '
'.
 *     @type string   $title_after      The HTML or text to append to the $title_li string. Default '
'.
 *     @type string   $class            The CSS class to use for the $title_li. Default 'linkcat'.
 *     @type string   $category_before  The HTML or text to prepend to $title_before if $categorize is true.
 *                                      String must contain '%id' and '%class' to inherit the category ID and
 *                                      the $class argument used for formatting in themes.
 *                                      Default '
'.
 *     @type string   $category_after   The HTML or text to append to $title_after if $categorize is true.
 *                                      Default '
'.
 *     @type string   $category_orderby How to order the bookmark category based on term scheme if $categorize
 *                                      is true. Default 'name'.
 *     @type string   $category_order   Whether to order categories in ascending or descending order if
 *                                      $categorize is true. Accepts 'ASC' (ascending) or 'DESC' (descending).
 *                                      Default 'ASC'.
 * }
 * @return void|string Void if 'echo' argument is true, HTML list of bookmarks if 'echo' is false.
 */
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'     => '
',
		'title_after'      => '
',
		'category_orderby' => 'name',
		'category_order'   => 'ASC',
		'class'            => 'linkcat',
		'category_before'  => '
',
		'category_after'   => '
',
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$output = '';

	if ( ! is_array( $parsed_args['class'] ) ) {
		$parsed_args['class'] = explode( ' ', $parsed_args['class'] );
	}
	$parsed_args['class'] = array_map( 'sanitize_html_class', $parsed_args['class'] );
	$parsed_args['class'] = trim( join( ' ', $parsed_args['class'] ) );

	if ( $parsed_args['categorize'] ) {
		$cats = get_terms(
			array(
				'taxonomy'     => 'link_category',
				'name__like'   => $parsed_args['category_name'],
				'include'      => $parsed_args['category'],
				'exclude'      => $parsed_args['exclude_category'],
				'orderby'      => $parsed_args['category_orderby'],
				'order'        => $parsed_args['category_order'],
				'hierarchical' => 0,
			)
		);
		if ( empty( $cats ) ) {
			$parsed_args['categorize'] = false;
		}
	}

	if ( $parsed_args['categorize'] ) {
		// Split the bookmarks into ul's for each category.
		foreach ( (array) $cats as $cat ) {
			$params    = array_merge( $parsed_args, array( 'category' => $cat->term_id ) );
			$bookmarks = get_bookmarks( $params );
			if ( empty( $bookmarks ) ) {
				continue;
			}
			$output .= str_replace(
				array( '%id', '%class' ),
				array( "linkcat-$cat->term_id", $parsed_args['class'] ),
				$parsed_args['category_before']
			);
			/**
			 * Filters the category name.
			 *
			 * @since 2.2.0
			 *
			 * @param string $cat_name The category name.
			 */
			$catname = apply_filters( 'link_category', $cat->name );

			$output .= $parsed_args['title_before'];
			$output .= $catname;
			$output .= $parsed_args['title_after'];
			$output .= "\n\t
\n";
			$output .= _walk_bookmarks( $bookmarks, $parsed_args );
			$output .= "\n\t
\n";
			$output .= $parsed_args['category_after'] . "\n";
		}
	} else {
		// Output one single list using title_li for the title.
		$bookmarks = get_bookmarks( $parsed_args );

		if ( ! empty( $bookmarks ) ) {
			if ( ! empty( $parsed_args['title_li'] ) ) {
				$output .= str_replace(
					array( '%id', '%class' ),
					array( 'linkcat-' . $parsed_args['category'], $parsed_args['class'] ),
					$parsed_args['category_before']
				);
				$output .= $parsed_args['title_before'];
				$output .= $parsed_args['title_li'];
				$output .= $parsed_args['title_after'];
				$output .= "\n\t
\n";
				$output .= _walk_bookmarks( $bookmarks, $parsed_args );
				$output .= "\n\t
\n";
				$output .= $parsed_args['category_after'] . "\n";
			} else {
				$output .= _walk_bookmarks( $bookmarks, $parsed_args );
			}
		}
	}

	/**
	 * Filters the bookmarks list before it is echoed or returned.
	 *
	 * @since 2.5.0
	 *
	 * @param string $html The HTML list of bookmarks.
	 */
	$html = apply_filters( 'wp_list_bookmarks', $output );

	if ( $parsed_args['echo'] ) {
		echo $html;
	} else {
		return $html;
	}
}


<?php
/**
 * Link/Bookmark API
 *
 * @package WordPress
 * @subpackage Bookmark
 */

/**
 * Retrieve Bookmark data
 *
 * @since 2.1.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int|stdClass $bookmark
 * @param string       $output   Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 *                               correspond to an stdClass object, an associative array, or a numeric array,
 *                               respectively. Default OBJECT.
 * @param string       $filter   Optional. How to sanitize bookmark fields. Default 'raw'.
 * @return array|object|null Type returned depends on $output value.
 */
function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) {
	global $wpdb;

	if ( empty( $bookmark ) ) {
		if ( isset( $GLOBALS['link'] ) ) {
			$_bookmark = & $GLOBALS['link'];
		} else {
			$_bookmark = null;
		}
	} elseif ( is_object( $bookmark ) ) {
		wp_cache_add( $bookmark->link_id, $bookmark, 'bookmark' );
		$_bookmark = $bookmark;
	} else {
		if ( isset( $GLOBALS['link'] ) && ( $GLOBALS['link']->link_id == $bookmark ) ) {
			$_bookmark = & $GLOBALS['link'];
		} else {
			$_bookmark = wp_cache_get( $bookmark, 'bookmark' );
			if ( ! $_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' );
				}
			}
		}
	}

	if ( ! $_bookmark ) {
		return $_bookmark;
	}

	$_bookmark = sanitize_bookmark( $_bookmark, $filter );

	if ( OBJECT == $output ) {
		return $_bookmark;
	} elseif ( ARRAY_A == $output ) {
		return get_object_vars( $_bookmark );
	} elseif ( ARRAY_N == $output ) {
		return array_values( get_object_vars( $_bookmark ) );
	} else {
		return $_bookmark;
	}
}

/**
 * Retrieve single bookmark data item or field.
 *
 * @since 2.3.0
 *
 * @param string $field    The name of the data field to return.
 * @param int    $bookmark The bookmark ID to get field.
 * @param string $context  Optional. The context of how the field will be used.
 * @return string|WP_Error
 */
function get_bookmark_field( $field, $bookmark, $context = 'display' ) {
	$bookmark = (int) $bookmark;
	$bookmark = get_bookmark( $bookmark );

	if ( is_wp_error( $bookmark ) ) {
		return $bookmark;
	}

	if ( ! is_object( $bookmark ) ) {
		return '';
	}

	if ( ! isset( $bookmark->$field ) ) {
		return '';
	}

	return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context );
}

/**
 * Retrieves the list of bookmarks
 *
 * Attempts to retrieve from the cache first based on MD5 hash of arguments. If
 * that fails, then the query will be built from the arguments and executed. The
 * results will be stored to the cache.
 *
 * @since 2.1.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string|array $args {
 *     Optional. String or array of arguments to retrieve bookmarks.
 *
 *     @type string   $orderby        How to order the links by. Accepts 'id', 'link_id', 'name', 'link_name',
 *                                    'url', 'link_url', 'visible', 'link_visible', 'rating', 'link_rating',
 *                                    'owner', 'link_owner', 'updated', 'link_updated', 'notes', 'link_notes',
 *                                    'description', 'link_description', 'length' and 'rand'.
 *                                    When `$orderby` is 'length', orders by the character length of
 *                                    'link_name'. Default 'name'.
 *     @type string   $order          Whether to order bookmarks in ascending or descending order.
 *                                    Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'.
 *     @type int      $limit          Amount of bookmarks to display. Accepts any positive number or
 *                                    -1 for all.  Default -1.
 *     @type string   $category       Comma-separated list of category IDs to include links from.
 *                                    Default empty.
 *     @type string   $category_name  Category to retrieve links for by name. Default empty.
 *     @type int|bool $hide_invisible Whether to show or hide links marked as 'invisible'. Accepts
 *                                    1|true or 0|false. Default 1|true.
 *     @type int|bool $show_updated   Whether to display the time the bookmark was last updated.
 *                                    Accepts 1|true or 0|false. Default 0|false.
 *     @type string   $include        Comma-separated list of bookmark IDs to include. Default empty.
 *     @type string   $exclude        Comma-separated list of bookmark IDs to exclude. Default empty.
 *     @type string   $search         Search terms. Will be SQL-formatted with wildcards before and after
 *                                    and searched in 'link_url', 'link_name' and 'link_description'.
 *                                    Default empty.
 * }
 * @return object[] List of bookmark row objects.
 */
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'         => '',
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$key   = md5( serialize( $parsed_args ) );
	$cache = wp_cache_get( 'get_bookmarks', 'bookmark' );

	if ( 'rand' !== $parsed_args['orderby'] && $cache ) {
		if ( is_array( $cache ) && isset( $cache[ $key ] ) ) {
			$bookmarks = $cache[ $key ];
			/**
			 * Filters the returned list of bookmarks.
			 *
			 * The first time the hook is evaluated in this file, it returns the cached
			 * bookmarks list. The second evaluation returns a cached bookmarks list if the
			 * link category is passed but does not exist. The third evaluation returns
			 * the full cached results.
			 *
			 * @since 2.1.0
			 *
			 * @see get_bookmarks()
			 *
			 * @param array $bookmarks   List of the cached bookmarks.
			 * @param array $parsed_args An array of bookmark query arguments.
			 */
			return apply_filters( 'get_bookmarks', $bookmarks, $parsed_args );
		}
	}

	if ( ! is_array( $cache ) ) {
		$cache = array();
	}

	$inclusions = '';
	if ( ! empty( $parsed_args['include'] ) ) {
		$parsed_args['exclude']       = '';  // Ignore exclude, category, and category_name params if using include.
		$parsed_args['category']      = '';
		$parsed_args['category_name'] = '';

		$inclinks = wp_parse_id_list( $parsed_args['include'] );
		if ( count( $inclinks ) ) {
			foreach ( $inclinks as $inclink ) {
				if ( empty( $inclusions ) ) {
					$inclusions = ' AND ( link_id = ' . $inclink . ' ';
				} else {
					$inclusions .= ' OR link_id = ' . $inclink . ' ';
				}
			}
		}
	}
	if ( ! empty( $inclusions ) ) {
		$inclusions .= ')';
	}

	$exclusions = '';
	if ( ! empty( $parsed_args['exclude'] ) ) {
		$exlinks = wp_parse_id_list( $parsed_args['exclude'] );
		if ( count( $exlinks ) ) {
			foreach ( $exlinks as $exlink ) {
				if ( empty( $exclusions ) ) {
					$exclusions = ' AND ( link_id <> ' . $exlink . ' ';
				} else {
					$exclusions .= ' AND link_id <> ' . $exlink . ' ';
				}
			}
		}
	}
	if ( ! empty( $exclusions ) ) {
		$exclusions .= ')';
	}

	if ( ! empty( $parsed_args['category_name'] ) ) {
		$parsed_args['category'] = get_term_by( 'name', $parsed_args['category_name'], 'link_category' );
		if ( $parsed_args['category'] ) {
			$parsed_args['category'] = $parsed_args['category']->term_id;
		} else {
			$cache[ $key ] = array();
			wp_cache_set( 'get_bookmarks', $cache, 'bookmark' );
			/** This filter is documented in wp-includes/bookmark.php */
			return apply_filters( 'get_bookmarks', array(), $parsed_args );
		}
	}

	$search = '';
	if ( ! empty( $parsed_args['search'] ) ) {
		$like   = '%' . $wpdb->esc_like( $parsed_args['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           = '';
	if ( ! empty( $parsed_args['category'] ) ) {
		$incategories = wp_parse_id_list( $parsed_args['category'] );
		if ( count( $incategories ) ) {
			foreach ( $incategories as $incat ) {
				if ( empty( $category_query ) ) {
					$category_query = ' AND ( tt.term_id = ' . $incat . ' ';
				} else {
					$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";
	}

	if ( $parsed_args['show_updated'] ) {
		$recently_updated_test = ', IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated ';
	} else {
		$recently_updated_test = '';
	}

	$get_updated = ( $parsed_args['show_updated'] ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : '';

	$orderby = strtolower( $parsed_args['orderby'] );
	$length  = '';
	switch ( $orderby ) {
		case 'length':
			$length = ', CHAR_LENGTH(link_name) AS length';
			break;
		case 'rand':
			$orderby = 'rand()';
			break;
		case 'link_id':
			$orderby = "$wpdb->links.link_id";
			break;
		default:
			$orderparams = array();
			$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 );

				if ( in_array( 'link_' . $ordparam, $keys, true ) ) {
					$orderparams[] = 'link_' . $ordparam;
				} elseif ( in_array( $ordparam, $keys, true ) ) {
					$orderparams[] = $ordparam;
				}
			}
			$orderby = implode( ',', $orderparams );
	}

	if ( empty( $orderby ) ) {
		$orderby = 'link_name';
	}

	$order = strtoupper( $parsed_args['order'] );
	if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ), true ) ) {
		$order = 'ASC';
	}

	$visible = '';
	if ( $parsed_args['hide_invisible'] ) {
		$visible = "AND link_visible = 'Y'";
	}

	$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 ( -1 != $parsed_args['limit'] ) {
		$query .= ' LIMIT ' . $parsed_args['limit'];
	}

	$results = $wpdb->get_results( $query );

	if ( 'rand()' !== $orderby ) {
		$cache[ $key ] = $results;
		wp_cache_set( 'get_bookmarks', $cache, 'bookmark' );
	}

	/** This filter is documented in wp-includes/bookmark.php */
	return apply_filters( 'get_bookmarks', $results, $parsed_args );
}

/**
 * Sanitizes all bookmark fields.
 *
 * @since 2.3.0
 *
 * @param stdClass|array $bookmark Bookmark row.
 * @param string         $context  Optional. How to filter the fields. Default 'display'.
 * @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',
	);

	if ( is_object( $bookmark ) ) {
		$do_object = true;
		$link_id   = $bookmark->link_id;
	} else {
		$do_object = false;
		$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 );
			}
		} else {
			if ( isset( $bookmark[ $field ] ) ) {
				$bookmark[ $field ] = sanitize_bookmark_field( $field, $bookmark[ $field ], $link_id, $context );
			}
		}
	}

	return $bookmark;
}

/**
 * Sanitizes a bookmark field.
 *
 * Sanitizes the bookmark fields based on what the field name is. If the field
 * has a strict value set, then it will be tested for that, else a more generic
 * filtering is applied. After the more strict filter is applied, if the `$context`
 * is 'raw' then the value is immediately return.
 *
 * Hooks exist for the more generic cases. With the 'edit' context, the {@see 'edit_$field'}
 * filter will be called and passed the `$value` and `$bookmark_id` respectively.
 *
 * With the 'db' context, the {@see 'pre_$field'} filter is called and passed the value.
 * The 'display' context is the final context and has the `$field` has the filter name
 * and is passed the `$value`, `$bookmark_id`, and `$context`, respectively.
 *
 * @since 2.3.0
 *
 * @param string $field       The bookmark field.
 * @param mixed  $value       The bookmark field value.
 * @param int    $bookmark_id Bookmark ID.
 * @param string $context     How to filter the field value. Accepts 'raw', 'edit', 'attribute',
 *                            'js', 'db', or 'display'
 * @return mixed The filtered value.
 */
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_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, true ) ) {
				$value = '';
			}
			break;
	}

	if ( 'raw' === $context ) {
		return $value;
	}

	if ( 'edit' === $context ) {
		/** This filter is documented in wp-includes/post.php */
		$value = apply_filters( "edit_{$field}", $value, $bookmark_id );

		if ( 'link_notes' === $field ) {
			$value = esc_html( $value ); // textarea_escaped
		} else {
			$value = esc_attr( $value );
		}
	} elseif ( 'db' === $context ) {
		/** This filter is documented in wp-includes/post.php */
		$value = apply_filters( "pre_{$field}", $value );
	} else {
		/** This filter is documented in wp-includes/post.php */
		$value = apply_filters( "{$field}", $value, $bookmark_id, $context );

		if ( 'attribute' === $context ) {
			$value = esc_attr( $value );
		} elseif ( 'js' === $context ) {
			$value = esc_js( $value );
		}
	}

	return $value;
}

/**
 * Deletes the bookmark cache.
 *
 * @since 2.7.0
 *
 * @param int $bookmark_id Bookmark ID.
 */
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' );
}


<?php
/**
 * Object Cache API functions missing from 3rd party object caches.
 *
 * @link https://codex.wordpress.org/Class_Reference/WP_Object_Cache
 *
 * @package WordPress
 * @subpackage Cache
 */

if ( ! function_exists( 'wp_cache_get_multiple' ) ) :
	/**
	 * Retrieves multiple values from the cache in one call.
	 *
	 * Compat function to mimic wp_cache_get_multiple().
	 *
	 * @ignore
	 * @since 5.5.0
	 *
	 * @see wp_cache_get_multiple()
	 *
	 * @param array  $keys  Array of keys under which the cache contents are stored.
	 * @param string $group Optional. Where the cache contents are grouped. Default empty.
	 * @param bool   $force Optional. Whether to force an update of the local cache
	 *                      from the persistent cache. Default false.
	 * @return array Array of values organized into groups.
	 */
	function wp_cache_get_multiple( $keys, $group = '', $force = false ) {
		$values = array();

		foreach ( $keys as $key ) {
			$values[ $key ] = wp_cache_get( $key, $group, $force );
		}

		return $values;
	}
endif;


<?php
/**
 * Object Cache API
 *
 * @link https://codex.wordpress.org/Class_Reference/WP_Object_Cache
 *
 * @package WordPress
 * @subpackage Cache
 */

/** WP_Object_Cache class */
require_once ABSPATH . WPINC . '/class-wp-object-cache.php';

/**
 * Adds data to the cache, if the cache key doesn't already exist.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::add()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key    The cache key to use for retrieval later.
 * @param mixed      $data   The data to add to the cache.
 * @param string     $group  Optional. The group to add the cache to. Enables the same key
 *                           to be used across groups. Default empty.
 * @param int        $expire Optional. When the cache data should expire, in seconds.
 *                           Default 0 (no expiration).
 * @return bool True on success, false if cache key and group already exist.
 */
function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->add( $key, $data, $group, (int) $expire );
}

/**
 * Closes the cache.
 *
 * This function has ceased to do anything since WordPress 2.5. The
 * functionality was removed along with the rest of the persistent cache.
 *
 * This does not mean that plugins can't implement this function when they need
 * to make sure that the cache is cleaned up after WordPress no longer needs it.
 *
 * @since 2.0.0
 *
 * @return true Always returns true.
 */
function wp_cache_close() {
	return true;
}

/**
 * Decrements numeric cache item's value.
 *
 * @since 3.3.0
 *
 * @see WP_Object_Cache::decr()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key    The cache key to decrement.
 * @param int        $offset Optional. The amount by which to decrement the item's value. Default 1.
 * @param string     $group  Optional. The group the key is in. Default empty.
 * @return int|false The item's new value on success, false on failure.
 */
function wp_cache_decr( $key, $offset = 1, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->decr( $key, $offset, $group );
}

/**
 * Removes the cache contents matching key and group.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::delete()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key   What the contents in the cache are called.
 * @param string     $group Optional. Where the cache contents are grouped. Default empty.
 * @return bool True on successful removal, false on failure.
 */
function wp_cache_delete( $key, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->delete( $key, $group );
}

/**
 * Removes all cache items.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::flush()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @return bool True on success, false on failure.
 */
function wp_cache_flush() {
	global $wp_object_cache;

	return $wp_object_cache->flush();
}

/**
 * Retrieves the cache contents from the cache by key and group.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::get()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key   The key under which the cache contents are stored.
 * @param string     $group Optional. Where the cache contents are grouped. Default empty.
 * @param bool       $force Optional. Whether to force an update of the local cache
 *                          from the persistent 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.
 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
 */
function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
	global $wp_object_cache;

	return $wp_object_cache->get( $key, $group, $force, $found );
}

/**
 * Retrieves multiple values from the cache in one call.
 *
 * @since 5.5.0
 *
 * @see WP_Object_Cache::get_multiple()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param array  $keys  Array of keys under which the cache contents are stored.
 * @param string $group Optional. Where the cache contents are grouped. Default empty.
 * @param bool   $force Optional. Whether to force an update of the local cache
 *                      from the persistent cache. Default false.
 * @return array Array of values organized into groups.
 */
function wp_cache_get_multiple( $keys, $group = '', $force = false ) {
	global $wp_object_cache;

	return $wp_object_cache->get_multiple( $keys, $group, $force );
}

/**
 * Increment numeric cache item's value
 *
 * @since 3.3.0
 *
 * @see WP_Object_Cache::incr()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key    The key for the cache contents that should be incremented.
 * @param int        $offset Optional. The amount by which to increment the item's value. Default 1.
 * @param string     $group  Optional. The group the key is in. Default empty.
 * @return int|false The item's new value on success, false on failure.
 */
function wp_cache_incr( $key, $offset = 1, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->incr( $key, $offset, $group );
}

/**
 * Sets up Object Cache Global and assigns it.
 *
 * @since 2.0.0
 *
 * @global WP_Object_Cache $wp_object_cache
 */
function wp_cache_init() {
	$GLOBALS['wp_object_cache'] = new WP_Object_Cache();
}

/**
 * Replaces the contents of the cache with new data.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::replace()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key    The key for the cache data that should be replaced.
 * @param mixed      $data   The new data to store in the cache.
 * @param string     $group  Optional. The group for the cache data that should be replaced.
 *                           Default empty.
 * @param int        $expire Optional. When to expire the cache contents, in seconds.
 *                           Default 0 (no expiration).
 * @return bool False if original value does not exist, true if contents were replaced
 */
function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->replace( $key, $data, $group, (int) $expire );
}

/**
 * Saves the data to the cache.
 *
 * Differs from wp_cache_add() and wp_cache_replace() in that it will always write data.
 *
 * @since 2.0.0
 *
 * @see WP_Object_Cache::set()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int|string $key    The cache key to use for retrieval later.
 * @param mixed      $data   The contents to store in the cache.
 * @param string     $group  Optional. Where to group the cache contents. Enables the same key
 *                           to be used across groups. Default empty.
 * @param int        $expire Optional. When to expire the cache contents, in seconds.
 *                           Default 0 (no expiration).
 * @return bool True on success, false on failure.
 */
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}

/**
 * Switches the internal blog ID.
 *
 * This changes the blog id used to create keys in blog specific groups.
 *
 * @since 3.5.0
 *
 * @see WP_Object_Cache::switch_to_blog()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param int $blog_id Site ID.
 */
function wp_cache_switch_to_blog( $blog_id ) {
	global $wp_object_cache;

	$wp_object_cache->switch_to_blog( $blog_id );
}

/**
 * Adds a group or set of groups to the list of global groups.
 *
 * @since 2.6.0
 *
 * @see WP_Object_Cache::add_global_groups()
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 *
 * @param string|array $groups A group or an array of groups to add.
 */
function wp_cache_add_global_groups( $groups ) {
	global $wp_object_cache;

	$wp_object_cache->add_global_groups( $groups );
}

/**
 * Adds a group or set of groups to the list of non-persistent groups.
 *
 * @since 2.6.0
 *
 * @param string|array $groups A group or an array of groups to add.
 */
function wp_cache_add_non_persistent_groups( $groups ) {
	// Default cache doesn't persist so nothing to do here.
}

/**
 * Reset internal cache keys and structures.
 *
 * If the cache back end uses global blog or site IDs as part of its cache keys,
 * this function instructs the back end to reset those keys and perform any cleanup
 * since blog or site IDs have changed since cache init.
 *
 * This function is deprecated. Use wp_cache_switch_to_blog() instead of this
 * function when preparing the cache for a blog switch. For clearing the cache
 * during unit tests, consider using wp_cache_init(). wp_cache_init() is not
 * recommended outside of unit tests as the performance penalty for using it is
 * high.
 *
 * @since 2.6.0
 * @deprecated 3.5.0 WP_Object_Cache::reset()
 * @see WP_Object_Cache::reset()
 *
 * @global WP_Object_Cache $wp_object_cache Object cache global instance.
 */
function wp_cache_reset() {
	_deprecated_function( __FUNCTION__, '3.5.0', 'WP_Object_Cache::reset()' );

	global $wp_object_cache;

	$wp_object_cache->reset();
}


<?php
/**
 * Canonical API to handle WordPress Redirecting
 *
 * Based on "Permalink Redirect" from Scott Yang and "Enforce www. Preference"
 * by Mark Jaquith
 *
 * @package WordPress
 * @since 2.3.0
 */

/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, and
 * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
 * page/post previews, WP admin, Trackbacks, robots.txt, favicon.ico, searches,
 * or on POST requests.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 *
 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 * @global bool       $is_IIS
 * @global WP_Query   $wp_query   WordPress Query object.
 * @global wpdb       $wpdb       WordPress database abstraction object.
 * @global WP         $wp         Current WordPress environment instance.
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *                              figure if redirect is needed.
 * @param bool   $do_redirect   Optional. Redirect to the new URL.
 * @return string|void The string of the URL, if redirect needed.
 */
function redirect_canonical( $requested_url = null, $do_redirect = true ) {
	global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;

	if ( isset( $_SERVER['REQUEST_METHOD'] ) && ! in_array( strtoupper( $_SERVER['REQUEST_METHOD'] ), array( 'GET', 'HEAD' ), true ) ) {
		return;
	}

	// If we're not in wp-admin and the post has been published and preview nonce
	// is non-existent or invalid then no need for preview in query.
	if ( is_preview() && get_query_var( 'p' ) && 'publish' === get_post_status( get_query_var( 'p' ) ) ) {
		if ( ! isset( $_GET['preview_id'] )
			|| ! isset( $_GET['preview_nonce'] )
			|| ! wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'] )
		) {
			$wp_query->is_preview = false;
		}
	}

	if ( is_admin() || is_search() || is_preview() || is_trackback() || is_favicon()
		|| ( $is_IIS && ! iis7_supports_permalinks() )
	) {
		return;
	}

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

	$original = parse_url( $requested_url );
	if ( false === $original ) {
		return;
	}

	$redirect     = $original;
	$redirect_url = false;

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

	/*
	 * If the original URL ended with non-breaking spaces, they were almost
	 * certainly inserted by accident. Let's remove them, so the reader doesn't
	 * see a 404 error with no obvious cause.
	 */
	$redirect['path'] = preg_replace( '|(%C2%A0)+$|i', '', $redirect['path'] );

	// It's not a preview, so remove it from URL.
	if ( get_query_var( 'preview' ) ) {
		$redirect['query'] = remove_query_arg( 'preview', $redirect['query'] );
	}

	$post_id = get_query_var( 'p' );

	if ( is_feed() && $post_id ) {
		$redirect_url = get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );

		if ( $redirect_url ) {
			$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() && $wp_query->post_count < 1 && $post_id ) {

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

		if ( ! empty( $vars[0] ) ) {
			$vars = $vars[0];

			if ( 'revision' === $vars->post_type && $vars->post_parent > 0 ) {
				$post_id = $vars->post_parent;
			}

			$redirect_url = get_permalink( $post_id );

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

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

		// Redirect ?page_id, ?p=, ?attachment_id= to their respective URLs.
		$post_id = max( get_query_var( 'p' ), get_query_var( 'page_id' ), get_query_var( 'attachment_id' ) );

		$redirect_post = $post_id ? get_post( $post_id ) : false;

		if ( $redirect_post ) {
			$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['query'] = _remove_qs_args_if_not_in_url(
					$redirect['query'],
					array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
					$redirect_url
				);
			}
		}

		$year  = get_query_var( 'year' );
		$month = get_query_var( 'monthnum' );
		$day   = get_query_var( 'day' );

		if ( $year && $month && $day ) {
			$date = sprintf( '%04d-%02d-%02d', $year, $month, $day );

			if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
				$redirect_url = get_month_link( $year, $month );

				$redirect['query'] = _remove_qs_args_if_not_in_url(
					$redirect['query'],
					array( 'year', 'monthnum', 'day' ),
					$redirect_url
				);
			}
		} elseif ( $year && $month && $month > 12 ) {
			$redirect_url = get_year_link( $year );

			$redirect['query'] = _remove_qs_args_if_not_in_url(
				$redirect['query'],
				array( 'year', 'monthnum' ),
				$redirect_url
			);
		}

		// Strip off non-existing <!--nextpage--> links from single posts or pages.
		if ( get_query_var( 'page' ) ) {
			$post_id = 0;

			if ( $wp_query->queried_object instanceof WP_Post ) {
				$post_id = $wp_query->queried_object->ID;
			} elseif ( $wp_query->post ) {
				$post_id = $wp_query->post->ID;
			}

			if ( $post_id ) {
				$redirect_url = get_permalink( $post_id );

				$redirect['path']  = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
				$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
			}
		}

		if ( ! $redirect_url ) {
			$redirect_url = redirect_guess_404_permalink();

			if ( $redirect_url ) {
				$redirect['query'] = _remove_qs_args_if_not_in_url(
					$redirect['query'],
					array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
					$redirect_url
				);
			}
		}
	} elseif ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) {

		// Rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101.
		if ( is_attachment()
			&& ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) )
			&& ! $redirect_url
		) {
			if ( ! empty( $_GET['attachment_id'] ) ) {
				$redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );

				if ( $redirect_url ) {
					$redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
				}
			} else {
				$redirect_url = get_attachment_link();
			}
		} elseif ( is_single() && ! empty( $_GET['p'] ) && ! $redirect_url ) {
			$redirect_url = get_permalink( get_query_var( 'p' ) );

			if ( $redirect_url ) {
				$redirect['query'] = remove_query_arg( array( 'p', 'post_type' ), $redirect['query'] );
			}
		} elseif ( is_single() && ! empty( $_GET['name'] ) && ! $redirect_url ) {
			$redirect_url = get_permalink( $wp_query->get_queried_object_id() );

			if ( $redirect_url ) {
				$redirect['query'] = remove_query_arg( 'name', $redirect['query'] );
			}
		} elseif ( is_page() && ! empty( $_GET['page_id'] ) && ! $redirect_url ) {
			$redirect_url = get_permalink( get_query_var( 'page_id' ) );

			if ( $redirect_url ) {
				$redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
			}
		} elseif ( is_page() && ! is_feed() && ! $redirect_url
			&& 'page' === get_option( 'show_on_front' ) && get_queried_object_id() === (int) get_option( 'page_on_front' )
		) {
			$redirect_url = home_url( '/' );
		} elseif ( is_home() && ! empty( $_GET['page_id'] ) && ! $redirect_url
			&& 'page' === get_option( 'show_on_front' ) && get_query_var( 'page_id' ) === (int) get_option( 'page_for_posts' )
		) {
			$redirect_url = get_permalink( get_option( 'page_for_posts' ) );

			if ( $redirect_url ) {
				$redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
			}
		} elseif ( ! empty( $_GET['m'] ) && ( is_year() || is_month() || is_day() ) ) {
			$m = get_query_var( 'm' );

			switch ( strlen( $m ) ) {
				case 4: // Yearly.
					$redirect_url = get_year_link( $m );
					break;
				case 6: // Monthly.
					$redirect_url = get_month_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ) );
					break;
				case 8: // Daily.
					$redirect_url = get_day_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ), substr( $m, 6, 2 ) );
					break;
			}

			if ( $redirect_url ) {
				$redirect['query'] = remove_query_arg( 'm', $redirect['query'] );
			}
			// Now moving on to non ?m=X year/month/day links.
		} elseif ( is_date() ) {
			$year  = get_query_var( 'year' );
			$month = get_query_var( 'monthnum' );
			$day   = get_query_var( 'day' );

			if ( is_day() && $year && $month && ! empty( $_GET['day'] ) ) {
				$redirect_url = get_day_link( $year, $month, $day );

				if ( $redirect_url ) {
					$redirect['query'] = remove_query_arg( array( 'year', 'monthnum', 'day' ), $redirect['query'] );
				}
			} elseif ( is_month() && $year && ! empty( $_GET['monthnum'] ) ) {
				$redirect_url = get_month_link( $year, $month );

				if ( $redirect_url ) {
					$redirect['query'] = remove_query_arg( array( 'year', 'monthnum' ), $redirect['query'] );
				}
			} elseif ( is_year() && ! empty( $_GET['year'] ) ) {
				$redirect_url = get_year_link( $year );

				if ( $redirect_url ) {
					$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 ) )
			) {
				$redirect_url = get_author_posts_url( $author->ID, $author->user_nicename );

				if ( $redirect_url ) {
					$redirect['query'] = remove_query_arg( 'author', $redirect['query'] );
				}
			}
		} elseif ( is_category() || is_tag() || is_tax() ) { // Terms (tags/categories).
			$term_count = 0;

			foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
				$term_count += count( $tax_query['terms'] );
			}

			$obj = $wp_query->get_queried_object();

			if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
				$tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );

				if ( $tax_url && ! is_wp_error( $tax_url ) ) {
					if ( ! empty( $redirect['query'] ) ) {
						// Strip taxonomy query vars off the URL.
						$qv_remove = array( 'term', 'taxonomy' );

						if ( is_category() ) {
							$qv_remove[] = 'category_name';
							$qv_remove[] = 'cat';
						} elseif ( is_tag() ) {
							$qv_remove[] = 'tag';
							$qv_remove[] = 'tag_id';
						} else {
							// Custom taxonomies will have a custom query var, remove those too.
							$tax_obj = get_taxonomy( $obj->taxonomy );
							if ( false !== $tax_obj->query_var ) {
								$qv_remove[] = $tax_obj->query_var;
							}
						}

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

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

							// 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 query var.
								parse_str( $tax_url['query'], $query_vars );
								$redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
							} else {
								// Taxonomy is accessible via a "pretty URL".
								$redirect['path'] = $tax_url['path'];
							}
						} else {
							// Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
							foreach ( $qv_remove as $_qv ) {
								if ( isset( $rewrite_vars[ $_qv ] ) ) {
									$redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
								}
							}
						}
					}
				}
			}
		} elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false ) {
			$category_name = get_query_var( 'category_name' );

			if ( $category_name ) {
				$category = get_category_by_path( $category_name );

				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() );
				}
			}
		}

		// Post paging.
		if ( is_singular() && get_query_var( 'page' ) ) {
			$page = get_query_var( 'page' );

			if ( ! $redirect_url ) {
				$redirect_url = get_permalink( get_queried_object_id() );
			}

			if ( $page > 1 ) {
				$redirect_url = trailingslashit( $redirect_url );

				if ( is_front_page() ) {
					$redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
				} else {
					$redirect_url .= user_trailingslashit( $page, 'single_paged' );
				}
			}

			$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
		}

		if ( get_query_var( 'sitemap' ) ) {
			$redirect_url      = get_sitemap_url( get_query_var( 'sitemap' ), get_query_var( 'sitemap-subtype' ), get_query_var( 'paged' ) );
			$redirect['query'] = remove_query_arg( array( 'sitemap', 'sitemap-subtype', 'paged' ), $redirect['query'] );
		} elseif ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
			// Paging and feeds.
			$paged = get_query_var( 'paged' );
			$feed  = get_query_var( 'feed' );
			$cpage = get_query_var( 'cpage' );

			while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
				|| preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
				|| preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
			) {
				// Strip off any existing paging.
				$redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
				// Strip off feed endings.
				$redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
				// Strip off any existing comment paging.
				$redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
			}

			$addl_path    = '';
			$default_feed = get_default_feed();

			if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
				$addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';

				if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
					$addl_path .= 'comments/';
				}

				if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
					$format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
				} else {
					$format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
				}

				$addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );

				$redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
			} elseif ( is_feed() && 'old' === $feed ) {
				$old_feed_files = array(
					'wp-atom.php'         => 'atom',
					'wp-commentsrss2.php' => 'comments_rss2',
					'wp-feed.php'         => $default_feed,
					'wp-rdf.php'          => 'rdf',
					'wp-rss.php'          => 'rss2',
					'wp-rss2.php'         => 'rss2',
				);

				if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
					$redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );

					wp_redirect( $redirect_url, 301 );
					die();
				}
			}

			if ( $paged > 0 ) {
				$redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );

				if ( ! is_feed() ) {
					if ( ! is_single() ) {
						$addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';

						if ( $paged > 1 ) {
							$addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
						}
					}
				} elseif ( $paged > 1 ) {
					$redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
				}
			}

			$default_comments_page = get_option( 'default_comments_page' );

			if ( get_option( 'page_comments' )
				&& ( 'newest' === $default_comments_page && $cpage > 0
					|| 'newest' !== $default_comments_page && $cpage > 1 )
			) {
				$addl_path  = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
				$addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );

				$redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
			}

			// Strip off trailing /index.php/.
			$redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
			$redirect['path'] = user_trailingslashit( $redirect['path'] );

			if ( ! empty( $addl_path )
				&& $wp_rewrite->using_index_permalinks()
				&& strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
			) {
				$redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
			}

			if ( ! empty( $addl_path ) ) {
				$redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
			}

			$redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
		}

		if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
			if ( is_multisite() ) {
				/** This filter is documented in wp-login.php */
				$redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
			} else {
				$redirect_url = wp_registration_url();
			}

			wp_redirect( $redirect_url, 301 );
			die();
		}
	}

	$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );

	// Tack on any additional query vars.
	if ( $redirect_url && ! empty( $redirect['query'] ) ) {
		parse_str( $redirect['query'], $_parsed_query );
		$redirect = parse_url( $redirect_url );

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

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

		$_parsed_query = array_combine(
			rawurlencode_deep( array_keys( $_parsed_query ) ),
			rawurlencode_deep( array_values( $_parsed_query ) )
		);

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

	if ( $redirect_url ) {
		$redirect = parse_url( $redirect_url );
	}

	// www.example.com vs. example.com
	$user_home = parse_url( home_url() );

	if ( ! empty( $user_home['host'] ) ) {
		$redirect['host'] = $user_home['host'];
	}

	if ( empty( $user_home['path'] ) ) {
		$user_home['path'] = '/';
	}

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

	// Trailing /index.php.
	$redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );

	$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'] ) ) {
		// 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 obsolete feeds.
		$redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );

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

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

	// Trailing slashes.
	if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
		&& ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
	) {
		$user_ts_type = '';

		if ( get_query_var( 'paged' ) > 0 ) {
			$user_ts_type = 'paged';
		} else {
			foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
				$func = 'is_' . $type;
				if ( call_user_func( $func ) ) {
					$user_ts_type = $type;
					break;
				}
			}
		}

		$redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
	} elseif ( is_front_page() ) {
		$redirect['path'] = trailingslashit( $redirect['path'] );
	}

	// Remove trailing slash for robots.txt or sitemap requests.
	if ( is_robots()
		|| ! empty( get_query_var( 'sitemap' ) ) || ! empty( get_query_var( 'sitemap-stylesheet' ) )
	) {
		$redirect['path'] = untrailingslashit( $redirect['path'] );
	}

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

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

	$original_host_low = strtolower( $original['host'] );
	$redirect_host_low = strtolower( $redirect['host'] );

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

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

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

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

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

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

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

	if ( $compare_original !== $compare_redirect ) {
		$redirect_url = $redirect['scheme'] . '://' . $redirect['host'];

		if ( ! empty( $redirect['port'] ) ) {
			$redirect_url .= ':' . $redirect['port'];
		}

		$redirect_url .= $redirect['path'];

		if ( ! empty( $redirect['query'] ) ) {
			$redirect_url .= '?' . $redirect['query'];
		}
	}

	if ( ! $redirect_url || $redirect_url === $requested_url ) {
		return;
	}

	// Hex encoded octets are case-insensitive.
	if ( false !== strpos( $requested_url, '%' ) ) {
		if ( ! function_exists( 'lowercase_octets' ) ) {
			/**
			 * Converts the first hex-encoded octet match to lowercase.
			 *
			 * @since 3.1.0
			 * @ignore
			 *
			 * @param array $matches Hex-encoded octet matches for the requested URL.
			 * @return string Lowercased version of the first match.
			 */
			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 );
	}

	/**
	 * Filters the canonical redirect URL.
	 *
	 * Returning false to this filter will cancel the redirect.
	 *
	 * @since 2.3.0
	 *
	 * @param string $redirect_url  The redirect URL.
	 * @param string $requested_url The requested URL.
	 */
	$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );

	// Yes, again -- in case the filter aborted the request.
	if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
		return;
	}

	if ( $do_redirect ) {
		// Protect against chained redirects.
		if ( ! redirect_canonical( $redirect_url, false ) ) {
			wp_redirect( $redirect_url, 301 );
			exit;
		} else {
			// Debug.
			// die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
			return;
		}
	} else {
		return $redirect_url;
	}
}

/**
 * Removes arguments from a query string if they are not present in a URL
 * DO NOT use this in plugin code.
 *
 * @since 3.4.0
 * @access private
 *
 * @param string $query_string
 * @param array  $args_to_check
 * @param string $url
 * @return string The altered query string
 */
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 ] ) ) {
				$query_string = remove_query_arg( $qv, $query_string );
			}
		}
	} else {
		$query_string = remove_query_arg( $args_to_check, $query_string );
	}

	return $query_string;
}

/**
 * Strips the #fragment from a URL, if one is present.
 *
 * @since 4.4.0
 *
 * @param string $url The URL to strip.
 * @return string The altered URL.
 */
function strip_fragment_from_url( $url ) {
	$parsed_url = parse_url( $url );

	if ( ! empty( $parsed_url['host'] ) ) {
		// This mirrors code in redirect_canonical(). It does not handle every case.
		$url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
		if ( ! empty( $parsed_url['port'] ) ) {
			$url .= ':' . $parsed_url['port'];
		}

		if ( ! empty( $parsed_url['path'] ) ) {
			$url .= $parsed_url['path'];
		}

		if ( ! empty( $parsed_url['query'] ) ) {
			$url .= '?' . $parsed_url['query'];
		}
	}

	return $url;
}

/**
 * Attempts to guess the correct URL for a 404 request based on query vars.
 *
 * @since 2.3.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @return string|false The correct URL if one is found. False on failure.
 */
function redirect_guess_404_permalink() {
	global $wpdb;

	/**
	 * Filters whether to attempt to guess a redirect URL for a 404 request.
	 *
	 * Returning a false value from the filter will disable the URL guessing
	 * and return early without performing a redirect.
	 *
	 * @since 5.5.0
	 *
	 * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
	 *                                for a 404 request. Default true.
	 */
	if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
		return false;
	}

	/**
	 * Short-circuits the redirect URL guessing for 404 requests.
	 *
	 * Returning a non-null value from the filter will effectively short-circuit
	 * the URL guessing, returning the passed value instead.
	 *
	 * @since 5.5.0
	 *
	 * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
	 *                               Default null to continue with the URL guessing.
	 */
	$pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
	if ( null !== $pre ) {
		return $pre;
	}

	if ( get_query_var( 'name' ) ) {
		/**
		 * Filters whether to perform a strict guess for a 404 redirect.
		 *
		 * Returning a truthy value from the filter will redirect only exact post_name matches.
		 *
		 * @since 5.5.0
		 *
		 * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
		 */
		$strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );

		if ( $strict_guess ) {
			$where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
		} else {
			$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 {
			$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' ) );
		}

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$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' ) ) {
			return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
		} elseif ( get_query_var( 'page' ) > 1 ) {
			return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
		} else {
			return get_permalink( $post_id );
		}
	}

	return false;
}

/**
 * Redirects a variety of shorthand URLs to the admin.
 *
 * If a user visits example.com/admin, they'll be redirected to /wp-admin.
 * Visiting /login redirects to /wp-login.php, and so on.
 *
 * @since 3.4.0
 *
 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 */
function wp_redirect_admin_locations() {
	global $wp_rewrite;

	if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
		return;
	}

	$admins = array(
		home_url( 'wp-admin', 'relative' ),
		home_url( 'dashboard', 'relative' ),
		home_url( 'admin', 'relative' ),
		site_url( 'dashboard', 'relative' ),
		site_url( 'admin', 'relative' ),
	);

	if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
		wp_redirect( admin_url() );
		exit;
	}

	$logins = array(
		home_url( 'wp-login.php', 'relative' ),
		home_url( 'login', 'relative' ),
		site_url( 'login', 'relative' ),
	);

	if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
		wp_redirect( wp_login_url() );
		exit;
	}
}