<?php
/**
 * Genesis Framework.
 *
 * WARNING: This file is part of the core Genesis Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package Genesis\Images
 * @author  StudioPress
 * @license GPL-2.0-or-later
 * @link    https://my.studiopress.com/themes/genesis/
 */

/**
 * Pull an attachment ID from a post, if one exists.
 *
 * @since 1.0.0
 *
 * @param int $index   Optional. Index of which image to return from a post. Default is 0.
 * @param int $post_id Optional. Post ID. Default is `get_the_ID()`.
 * @return int|bool Image ID, or `false` if image with given index does not exist.
 */
function genesis_get_image_id( $index = 0, $post_id = null ) {

	$image_ids = array_keys(
		get_children(
			[
				'post_parent'    => $post_id ?: get_the_ID(),
				'post_type'      => 'attachment',
				'post_mime_type' => 'image',
				'orderby'        => 'menu_order',
				'order'          => 'ASC',
			]
		)
	);

	if ( isset( $image_ids[ $index ] ) ) {
		return $image_ids[ $index ];
	}

	return false;

}

/**
 * Return an image pulled from the media gallery.
 *
 * Supported $args keys are:
 *
 *  - format   - string, default is 'html'
 *  - size     - string, default is 'full'
 *  - num      - integer, default is 0
 *  - attr     - string, default is ''
 *  - fallback - mixed, default is 'first-attached'
 *
 * Applies `genesis_get_image_default_args`, `genesis_pre_get_image` and `genesis_get_image` filters.
 *
 * @since 1.0.0
 *
 * @param array|string $args Optional. Image query arguments. Default is empty array.
 * @return string|bool Return image element HTML, URL of image, or `false`.
 */
function genesis_get_image( $args = [] ) {

	$defaults = [
		'post_id'  => null,
		'format'   => 'html',
		'size'     => 'full',
		'num'      => 0,
		'attr'     => '',
		'fallback' => 'first-attached',
		'context'  => '',
	];

	/**
	 * A filter on the default parameters used by `genesis_get_image()`.
	 *
	 * @since unknown
	 */
	$defaults = apply_filters( 'genesis_get_image_default_args', $defaults, $args );

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

	// Allow child theme to short-circuit this function.
	$pre = apply_filters( 'genesis_pre_get_image', false, $args, get_post() );
	if ( false !== $pre ) {
		return $pre;
	}

	// If post thumbnail (native WP) exists, use its id.
	if ( 0 === $args['num'] && has_post_thumbnail( $args['post_id'] ) ) {
		$id = get_post_thumbnail_id( $args['post_id'] );
	} elseif ( 'first-attached' === $args['fallback'] ) {
		// Else if the first (default) image attachment is the fallback, use its id.
		$id = genesis_get_image_id( $args['num'], $args['post_id'] );
	} elseif ( is_int( $args['fallback'] ) ) {
		// Else if fallback id is supplied, use it.
		$id = $args['fallback'];
	}

	// If we have an id, get the HTML and URL.
	if ( isset( $id ) ) {
		$html        = wp_get_attachment_image( $id, $args['size'], false, $args['attr'] );
		list( $url ) = wp_get_attachment_image_src( $id, $args['size'], false );
	} elseif ( is_array( $args['fallback'] ) ) {
		// Else if fallback HTML and URL exist, use them.
		$id   = 0;
		$html = $args['fallback']['html'];
		$url  = $args['fallback']['url'];
	} else {
		// No image.
		return false;
	}

	// Source path, relative to the root.
	$src = str_replace( home_url(), '', $url );

	// Determine output.
	if ( 'html' === mb_strtolower( $args['format'] ) ) {
		$output = $html;
	} elseif ( 'url' === mb_strtolower( $args['format'] ) ) {
		$output = $url;
	} else {
		$output = $src;
	}

	// Return false if $url is blank.
	if ( empty( $url ) ) {
		$output = false;
	}

	// Return data, filtered.
	return apply_filters( 'genesis_get_image', $output, $args, $id, $html, $url, $src );
}

/**
 * Echo an image pulled from the media gallery.
 *
 * Supported $args keys are:
 *
 *  - format - string, default is 'html', may be 'url'
 *  - size   - string, default is 'full'
 *  - num    - integer, default is 0
 *  - attr   - string, default is ''
 *
 * @since 1.0.0
 *
 * @param array|string $args Optional. Image query arguments. Default is empty array.
 * @return null|false Returns `false` if URL is empty.
 */
function genesis_image( $args = [] ) {

	$image = genesis_get_image( $args );

	if ( $image ) {
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $image;

		return null;
	}

	return false;

}

/**
 * Return all registered image sizes arrays, including the standard sizes.
 *
 * Return a two-dimensional array of standard and additionally registered image sizes, with width, height and crop sub-keys.
 *
 * Here, the standard sizes have their sub-keys populated by pulling from the options saved in the database.
 *
 * @since 1.0.2
 *
 * @return array Two-dimensional, with `width`, `height` and `crop` sub-keys.
 */
function genesis_get_image_sizes() {
	global $_wp_additional_image_sizes;

	/**
	 * Allows controlling the image sizes before running the get_intermediate_image_sizes() logic.
	 *
	 * The return value must be false or a two-dimensional array with `width`, `height`, and `crop` subkeys.
	 *
	 * @param bool|array $pre False or genesis_get_image_sizes compatible array.
	 */
	$pre = apply_filters( 'genesis_pre_get_image_sizes', false );

	if ( $pre ) {
		return $pre;
	}

	$sizes = [];

	foreach ( get_intermediate_image_sizes() as $size ) {
		if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
			$sizes[ $size ] = [
				'width'  => absint( $_wp_additional_image_sizes[ $size ]['width'] ),
				'height' => absint( $_wp_additional_image_sizes[ $size ]['height'] ),
				'crop'   => $_wp_additional_image_sizes[ $size ]['crop'],
			];
		} else {
			$sizes[ $size ] = [
				'width'  => absint( get_option( "{$size}_size_w" ) ),
				'height' => absint( get_option( "{$size}_size_h" ) ),
				'crop'   => (bool) get_option( "{$size}_crop" ),
			];
		}
	}

	/**
	 * Allows filtering the genesis_get_image_sizes() output.
	 *
	 * @param array $sizes Two-dimensional, with `width`, `height` and `crop` sub-keys.
	 */
	return (array) apply_filters( 'genesis_get_image_sizes', $sizes );
}

/**
 * Callback for Customizer featured image archive size.
 *
 * @since 2.1.0
 *
 * @return array List of image sizes.
 */
function genesis_get_image_sizes_for_customizer() {

	$sizes = [];

	foreach ( (array) genesis_get_image_sizes() as $name => $size ) {
		$sizes[ $name ] = $name . ' (' . absint( $size['width'] ) . ' &#x000D7; ' . absint( $size['height'] ) . ')';
	}

	return $sizes;

}

/**
 * Is the singular featured image set to display on the current page?
 *
 * @since 3.1.0
 *
 * @return bool True if the singular featured image is hidden or will not display.
 */
function genesis_singular_image_hidden_on_current_page() {

	$post_type                = get_post_type();
	$supports_singular_images = post_type_supports( $post_type, 'genesis-singular-images' );
	$singular_images_enabled  = genesis_get_option( "show_featured_image_{$post_type}" );

	/**
	 * Prevents the “hide featured image” checkbox from appearing or functioning by returning false.
	 *
	 * @since 3.1.0
	 *
	 * @param bool $image_toggle_enabled True if featured image toggle is enabled, false otherwise.
	 */
	$image_toggle_enabled = apply_filters( 'genesis_singular_image_toggle_enabled', true );

	if ( ! $supports_singular_images || ! $singular_images_enabled || ! $image_toggle_enabled ) {
		return true;
	}

	return get_post_meta( get_queried_object_id(), '_genesis_hide_singular_image', true );

}

/**
 * Which post types have singular images enabled and active?
 *
 * @since 3.1.0
 *
 * @return array The singular images with active 'genesis-singular-images' support.
 */
function genesis_post_types_with_singular_images_enabled() {

	$result             = [];
	$types_with_support = get_post_types_by_support( 'genesis-singular-images' );

	foreach ( $types_with_support as $type ) {
		if ( genesis_get_option( "show_featured_image_{$type}", GENESIS_SETTINGS_FIELD, false ) ) {
			$result[] = $type;
		}
	}

	return $result;

}

add_filter( 'wp_get_attachment_image_attributes', 'genesis_image_loading', 10, 3 );
/**
 * Filter the attributes of all images retrieved with `wp_get_attachment_image`, add `loading="lazy"` to enable lazy loading in Chrome.
 *
 * @since 3.2.0
 *
 * @param array $attr Attributes for the image markup.
 *
 * @return array The filtered $attr array.
 */
function genesis_image_loading( $attr ) {
	if ( ! current_theme_supports( 'genesis-lazy-load-images' ) || function_exists( 'wp_lazy_loading_enabled' ) ) {
		return $attr;
	}

	$attr['loading'] = 'lazy';

	return $attr;
}
