6 ) {
$level = $fallback;
}
return 0 === $level ? 'p' : 'h' . $level;
}
/**
* Prepares text from Hardcover for display.
*
* Applies WordPress's typography, which turns straight quotes and apostrophes
* into curly ones, and escapes the result. Hardcover's text mixes both styles.
*
* @param string $text Plain text.
* @return string Text that is safe to output as HTML.
*/
function format_text( $text ) {
return esc_html( wptexturize( (string) $text ) );
}
/**
* Returns a value from the global styles, which are worked out once per request for each value.
*
* Reading a value with wp_get_global_styles() merges the theme's styles with the site's again each
* time, about a millisecond a call. A page with several blocks asks for the same few values for
* each of them, so the answers are kept for the rest of the request. They are dropped when the site
* or the theme changes within the request.
*
* @param array $path Path to the value, such as array( 'color', 'background' ).
* @param array $options Options for wp_get_global_styles(), such as the transforms.
* @return mixed The value, or null if there is none.
*/
function get_global_style( $path, $options = array() ) {
static $values = array();
if ( null === $path ) {
$values = array();
return null;
}
$key = wp_json_encode( array( $path, $options ) );
if ( ! array_key_exists( $key, $values ) ) {
$values[ $key ] = wp_get_global_styles( $path, $options );
}
return $values[ $key ];
}
/**
* Drops the global styles kept by get_global_style(), so that the next read looks them up again.
*
* @return void
*/
function clear_global_style_cache() {
get_global_style( null );
}
add_action( 'switch_blog', __NAMESPACE__ . '\clear_global_style_cache' );
add_action( 'switch_theme', __NAMESPACE__ . '\clear_global_style_cache' );
/**
* Turns a length from the block editor into a CSS value.
*
* Accepts a plain length such as "8px" or "50%", or a reference to one of the
* theme's presets, which the editor stores as "var:preset|{type}|{slug}".
* Anything else is rejected, so the result is safe to use in an inline style.
*
* @param mixed $value The stored value.
* @param string $preset_type The kind of preset the value may refer to: "border-radius" or "spacing".
* @return string A CSS value, or an empty string if the value is not valid.
*/
function sanitize_css_length( $value, $preset_type ) {
if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
return '';
}
$value = trim( (string) $value );
if ( preg_match( '/^var:preset\|' . preg_quote( $preset_type, '/' ) . '\|([a-zA-Z0-9_-]+)$/', $value, $matches ) ) {
return 'var(--wp--preset--' . $preset_type . '--' . _wp_to_kebab_case( $matches[1] ) . ')';
}
if ( preg_match( '/^(\d*\.?\d+)(px|%|em|rem|vw|vh)?$/', $value, $matches ) ) {
// A number without a unit gets one, zero included: a bare 0 is not valid inside calc().
return $matches[1] . ( isset( $matches[2] ) ? $matches[2] : 'px' );
}
return '';
}
/**
* Returns the inline style that sets the corner radius of book covers.
*
* The radius is passed to the stylesheet as a custom property on the block
* wrapper. Without a value in the block attributes, nothing is returned and
* the stylesheet falls back to the theme's default.
*
* @param array $attributes Block attributes.
* @return string An inline style declaration, or an empty string.
*/
function get_cover_radius_style( $attributes ) {
$radius = isset( $attributes['coverRadius'] ) ? $attributes['coverRadius'] : null;
if ( is_array( $radius ) ) {
// One value per corner, in the order CSS expects them.
$corners = array();
foreach ( array( 'topLeft', 'topRight', 'bottomRight', 'bottomLeft' ) as $corner ) {
$corners[] = isset( $radius[ $corner ] ) ? sanitize_css_length( $radius[ $corner ], 'border-radius' ) : '';
}
if ( ! array_filter( $corners, 'strlen' ) ) {
return '';
}
$value = implode( ' ', array_map( static fn( $corner ) => '' === $corner ? '0' : $corner, $corners ) );
} else {
$value = sanitize_css_length( $radius, 'border-radius' );
}
return '' === $value ? '' : '--endpaper-cover-radius: ' . $value . ';';
}
/**
* Returns the inline style that sets the gap between the items of a block.
*
* Reads the Block spacing setting of the block, or else the theme's block gap
* for the block. WordPress only applies that setting itself for
* blocks that use its layout system, so it is passed to the stylesheet as a
* custom property on the block wrapper instead.
*
* @param array $attributes Block attributes.
* @param string $block The block's name, to find the theme's gap for it.
* @return string An inline style declaration, or an empty string.
*/
function get_block_gap_style( $attributes, $block = 'endpaper/reading-list' ) {
$gap = isset( $attributes['style']['spacing']['blockGap'] ) ? $attributes['style']['spacing']['blockGap'] : null;
// Without a gap on the block, the theme's gap for the block is used, from theme.json or the Styles screen.
if ( null === $gap || '' === $gap ) {
$gap = get_global_style( array( 'blocks', $block, 'spacing', 'blockGap' ) );
}
$value = sanitize_css_length( $gap, 'spacing' );
return '' === $value ? '' : '--endpaper-gap: ' . $value . ';';
}
/**
* Outputs a reading progress bar with its label.
*
* @param float $progress Progress as a percentage, from 0 to 100.
* @param string $class_name Class for the wrapping paragraph.
* @return void
*/
function the_progress_bar( $progress, $class_name ) {
$percent = (int) round( $progress );
/* translators: %s: A percentage, such as 63. */
$label = sprintf( __( '%s%% read', 'endpaper' ), number_format_i18n( $percent ) );
printf(
'
%4$s
',
esc_attr( $class_name ),
esc_attr( $percent ),
esc_attr( $label ),
esc_html( $label )
);
}
/**
* Turns a color from the block editor into a CSS value.
*
* Accepts a hex color, an rgb() or hsl() color, or a reference to a color in
* the theme's palette, which is stored as "var:preset|color|{slug}". Anything
* else is rejected, so the result is safe to use in an inline style.
*
* @param mixed $value The stored value.
* @return string A CSS color, or an empty string if the value is not valid.
*/
function sanitize_css_color( $value ) {
if ( ! is_string( $value ) ) {
return '';
}
$value = trim( $value );
if ( preg_match( '/^var:preset\|color\|([a-zA-Z0-9_-]+)$/', $value, $matches ) ) {
return 'var(--wp--preset--color--' . _wp_to_kebab_case( $matches[1] ) . ')';
}
if ( preg_match( '/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $value ) ) {
return $value;
}
if ( preg_match( '/^(?:rgb|hsl)a?\([0-9.,%\/\s]+(?:deg)?[0-9.,%\/\s]*\)$/', $value ) ) {
return $value;
}
return '';
}
/**
* Shortens text to a maximum length, ending on a whole sentence where possible.
*
* Line breaks are turned into spaces, so the result is a single paragraph.
*
* @param string $text Plain text.
* @param int $max_length Maximum number of characters. 0 returns the full text.
* @return string The shortened text.
*/
function trim_to_sentence( $text, $max_length ) {
$text = trim( (string) preg_replace( '/\s+/u', ' ', (string) $text ) );
$max_length = absint( $max_length );
if ( ! $max_length || mb_strlen( $text ) <= $max_length ) {
return $text;
}
$cut = mb_substr( $text, 0, $max_length );
// Look for the last place a sentence ends: closing punctuation, followed by a space or the end of the cut.
if ( preg_match_all( '/[.!?…]["\'”’)]?(?=\s|$)/u', $cut, $matches, PREG_OFFSET_CAPTURE ) ) {
$last = end( $matches[0] );
$sentence = substr( $cut, 0, $last[1] + strlen( $last[0] ) );
// Only use it if it keeps a reasonable share of the text.
if ( mb_strlen( $sentence ) >= $max_length * 0.4 ) {
return $sentence;
}
}
// Otherwise end on a whole word.
$words = (string) preg_replace( '/\s+\S*$/u', '', $cut );
return rtrim( $words, ' ,;:–—-' ) . '…';
}
/**
* Turns the text of one line of Markdown into HTML that is safe to show.
*
* Handles links, bold, italic and code. Everything else in the text is
* escaped, so nothing a reviewer typed can become markup of its own.
*
* @param string $text Markdown on one or more lines of a block.
* @return string HTML.
*/
function markdown_inline_to_html( $text ) {
$text = (string) $text;
$links = array();
// Links are set aside first, so that nothing in an address is taken for bold or italic, or given curly quotes.
$text = preg_replace_callback(
'/\[([^\]]+)\]\(([^)\s]+)\)/',
static function ( $matches ) use ( &$links ) {
$url = esc_url( $matches[2], array( 'http', 'https' ) );
if ( '' === $url ) {
return $matches[1];
}
$links[] = '' . format_text( $matches[1] ) . '';
return "\x01" . ( count( $links ) - 1 ) . "\x02";
},
$text
);
$text = format_text( $text );
$text = preg_replace( '/\*\*(.+?)\*\*|__(.+?)__/s', '$1$2', $text );
$text = preg_replace( '/(?$1$2', $text );
$text = preg_replace( '/`([^`]+)`/', '$1', $text );
return (string) preg_replace_callback(
'/\x01(\d+)\x02/',
static function ( $matches ) use ( $links ) {
return isset( $links[ (int) $matches[1] ] ) ? $links[ (int) $matches[1] ] : '';
},
$text
);
}
/**
* Tells whether a line of Markdown is an item in a list.
*
* @param string $line A line of Markdown.
* @return string The marker that starts it, or an empty string if it is not a list item.
*/
function markdown_list_marker( $line ) {
return preg_match( '/^\s*([-*+]|\d+[.)])\s+/', $line, $matches ) ? $matches[1] : '';
}
/**
* Turns the lines of one block of Markdown into HTML.
*
* A block is what lies between two blank lines. Headings, quotes, lists and
* paragraphs are known, which is what Hardcover's editor makes.
*
* @param string[] $lines The lines of the block.
* @return string HTML.
*/
function markdown_block_to_html( $lines ) {
if ( ! $lines ) {
return '';
}
// A heading is shown as bold text, so the headings of a review do not become part of the outline of the page.
if ( preg_match( '/^#{1,6}\s+(.+)$/', $lines[0], $matches ) ) {
return '
';
}
/**
* Turns a review written in Markdown into HTML that is safe to show.
*
* Only paragraphs, line breaks, bold, italic, code, links, quotes and lists
* are let through, whatever the text contains.
*
* @param string $markdown The review, as Hardcover keeps it.
* @return string HTML, or an empty string if there is no text.
*/
function markdown_to_html( $markdown ) {
$markdown = trim( str_replace( array( "\r\n", "\r" ), "\n", (string) $markdown ) );
$html = '';
if ( '' === $markdown ) {
return '';
}
foreach ( (array) preg_split( '/\n{2,}/', $markdown ) as $block ) {
$html .= markdown_block_to_html( explode( "\n", trim( (string) $block, "\n" ) ) );
}
return wp_kses(
$html,
array(
'p' => array(),
'br' => array(),
'strong' => array(),
'em' => array(),
'code' => array(),
'blockquote' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'a' => array(
'href' => array(),
'rel' => array(),
),
)
);
}
/**
* Returns how many characters of text a piece of Markdown shows.
*
* @param string $markdown Markdown.
* @return int The number of characters, without markup.
*/
function markdown_text_length( $markdown ) {
return mb_strlen( trim( html_entity_decode( wp_strip_all_tags( markdown_to_html( $markdown ) ), ENT_QUOTES, 'UTF-8' ) ) );
}
/**
* Cuts a block of Markdown that is too long, without leaving a marker open.
*
* @param string $block One block of Markdown.
* @param int $length The most characters of text to keep.
* @return string The block, cut.
*/
function cut_markdown_block( $block, $length ) {
$lines = explode( "\n", $block );
// A heading is kept as it is.
if ( preg_match( '/^#{1,6}\s/', $lines[0] ) ) {
return $block;
}
// A list keeps the items that fit, and cuts the first one if not even that fits.
if ( '' !== markdown_list_marker( $lines[0] ) ) {
$kept = array();
$used = 0;
foreach ( $lines as $line ) {
$size = markdown_text_length( $line );
if ( $used + $size > $length ) {
break;
}
$kept[] = $line;
$used += $size;
}
if ( $kept ) {
return implode( "\n", $kept );
}
$first = preg_replace( '/^(\s*(?:[-*+]|\d+[.)])\s+)(.*)$/', '$2', $lines[0] );
$mark = (string) preg_replace( '/^(\s*(?:[-*+]|\d+[.)])\s+).*$/', '$1', $lines[0] );
return $mark . close_markdown_marks( trim_to_sentence( $first, $length ) );
}
// A quote is cut as text and put in a quote again.
if ( preg_match( '/^\s*>/', $lines[0] ) ) {
$text = '';
foreach ( $lines as $line ) {
$text .= ' ' . preg_replace( '/^\s*>\s?/', '', $line );
}
return '> ' . close_markdown_marks( trim_to_sentence( trim( $text ), $length ) );
}
return close_markdown_marks( trim_to_sentence( $block, $length ) );
}
/**
* Removes a bold, italic, code or link marker that a cut left open at the end.
*
* @param string $markdown Markdown that may have been cut.
* @return string Markdown without an open marker.
*/
function close_markdown_marks( $markdown ) {
// A link cut in the middle is dropped.
$markdown = (string) preg_replace( '/\[[^\]]*$|\[[^\]]*\]\([^)]*$/', '', $markdown );
foreach ( array( '**', '__', '*', '`' ) as $mark ) {
$text = '**' === $mark || '__' === $mark ? $markdown : str_replace( array( '**', '__' ), '', $markdown );
if ( 1 === substr_count( $text, $mark ) % 2 ) {
$position = strrpos( $markdown, $mark );
if ( false !== $position ) {
$markdown = substr( $markdown, 0, $position ) . substr( $markdown, $position + strlen( $mark ) );
}
}
}
return trim( $markdown );
}
/**
* Cuts a review written in Markdown to a length, on a whole block where it can.
*
* Blocks are kept whole as long as they fit. The block where the limit falls
* is cut on a sentence, and is left out if hardly any room is left.
*
* @param string $markdown The review.
* @param int $length The most characters of text to show. 0 shows everything.
* @return string Markdown.
*/
function trim_markdown( $markdown, $length ) {
$markdown = trim( str_replace( array( "\r\n", "\r" ), "\n", (string) $markdown ) );
$length = absint( $length );
if ( ! $length || markdown_text_length( $markdown ) <= $length ) {
return $markdown;
}
$kept = array();
$used = 0;
foreach ( (array) preg_split( '/\n{2,}/', $markdown ) as $block ) {
$size = markdown_text_length( $block );
if ( $used + $size <= $length ) {
$kept[] = $block;
$used += $size;
continue;
}
$room = $length - $used;
if ( ! $kept || $room >= 40 ) {
$kept[] = cut_markdown_block( $block, max( 1, $room ) );
}
break;
}
return implode( "\n\n", $kept );
}
/**
* Tells whether a block has been given a frame: a border, a background or a shadow.
*
* A framed block needs room between its edge and its contents.
*
* @param array $attributes Block attributes.
* @return bool Whether the block has a frame.
*/
function has_card_frame( $attributes ) {
$style = isset( $attributes['style'] ) && is_array( $attributes['style'] ) ? $attributes['style'] : array();
return ! empty( $attributes['borderColor'] )
|| ! empty( $attributes['backgroundColor'] )
|| ! empty( $attributes['gradient'] )
|| ! empty( $style['border'] )
|| ! empty( $style['color']['background'] )
|| ! empty( $style['color']['gradient'] )
|| ! empty( $style['shadow'] );
}
/**
* Returns a star icon, as inline SVG.
*
* The shape is the filled star from the WordPress icon library. It takes the
* color of the text around it, unless the stylesheet sets another.
*
* @param string $type Which star: "filled", "half" or "empty". The half star is a whole star with its first half drawn on top, so the two parts can have different colors. The empty star is the same shape as the filled one, to be given a fainter color.
* @return string SVG markup.
*/
function get_star_icon( $type = 'filled' ) {
$star = 'M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z';
$half = 'M12.0002 16.0322C11.9598 16.0322 11.9197 16.0419 11.884 16.0605L7.74627 18.2363C7.70501 18.2581 7.65801 18.267 7.6115 18.2637C7.56507 18.2603 7.52029 18.2441 7.48259 18.2168C7.44498 18.1895 7.41522 18.1524 7.39763 18.1094C7.38003 18.0662 7.37519 18.0186 7.38298 17.9727L8.17302 13.3662C8.18011 13.3262 8.17758 13.2848 8.16521 13.2461C8.15284 13.2074 8.13071 13.172 8.10173 13.1436L4.75408 9.88086C4.72079 9.84825 4.6968 9.80698 4.68572 9.76172C4.67469 9.71654 4.67716 9.66922 4.69158 9.625C4.70603 9.5807 4.7321 9.54075 4.76775 9.51074C4.80332 9.48083 4.84677 9.4618 4.89275 9.45508L9.51873 8.7832C9.55882 8.77731 9.5973 8.76117 9.63005 8.7373C9.66267 8.71346 9.68937 8.68176 9.7072 8.64551L11.7756 4.4541C11.7962 4.41237 11.8288 4.3771 11.8683 4.35254C11.9079 4.32804 11.9536 4.31543 12.0002 4.31543V16.0322Z';
if ( ! in_array( $type, array( 'filled', 'half', 'empty' ), true ) ) {
$type = 'filled';
}
$paths = 'half' === $type
? ''
: '';
return '';
}
/**
* Outputs a rating as five stars.
*
* The stars are decoration. Screen readers get the rating as text instead.
*
* @param float $rating A rating from 0 to 5. It is rounded to the nearest half star.
* @param string $class_name Class for the wrapping element.
* @return void
*/
function the_star_rating( $rating, $class_name ) {
$rating = max( 0.0, min( 5.0, round( (float) $rating * 2 ) / 2 ) );
$stars = '';
for ( $star = 1; $star <= 5; $star++ ) {
if ( $rating >= $star ) {
$stars .= get_star_icon( 'filled' );
} elseif ( $rating >= $star - 0.5 ) {
$stars .= get_star_icon( 'half' );
} else {
$stars .= get_star_icon( 'empty' );
}
}
// Whole ratings are read as "4", half ones as "4.5".
$number = number_format_i18n( $rating, floor( $rating ) === $rating ? 0 : 1 );
printf(
'%2$s%3$s',
esc_attr( $class_name ),
$stars, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG markup.
/* translators: %s: A rating, such as 4.5. */
esc_html( sprintf( __( 'Rated %s out of 5', 'endpaper' ), $number ) )
);
}
/**
* Formats a date from Hardcover the way the site shows dates.
*
* The format comes from the Date Format setting, and month names are translated.
*
* @param string $date A date as YYYY-MM-DD.
* @return string The formatted date, or an empty string if the date is not valid.
*/
function format_date( $date ) {
if ( ! is_string( $date ) || ! preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', $date, $matches ) ) {
return '';
}
if ( ! checkdate( (int) $matches[2], (int) $matches[3], (int) $matches[1] ) ) {
return '';
}
// The date has no time of day, so it is formatted in UTC to keep it on the same day everywhere.
$timezone = new \DateTimeZone( 'UTC' );
$datetime = date_create( $date . ' 12:00:00', $timezone );
$format = get_option( 'date_format' );
if ( ! $datetime ) {
return '';
}
$formatted = wp_date( $format ? $format : 'F j, Y', $datetime->getTimestamp(), $timezone );
return $formatted ? $formatted : '';
}
/**
* Formats a number from a reading goal: whole, or with one decimal for part of an hour.
*
* @param float $value The number.
* @return string The number, with separators for the site's language.
*/
function format_goal_number( $value ) {
$decimals = abs( $value - round( $value ) ) < 0.05 ? 0 : 1;
return number_format_i18n( $value, $decimals );
}
/**
* Returns the count and the rest of the text for how far along a goal is.
*
* "34" and "of 50 books read", so the count can be shown on its own, big.
*
* @param array $goal A normalized goal.
* @return array The count and the label.
*/
function get_goal_amount_parts( $goal ) {
$target = format_goal_number( $goal['target'] );
$number = (int) round( $goal['target'] );
if ( 'page' === $goal['metric'] ) {
/* translators: %s: The goal, in pages. This follows the number of pages read, as in "34 of 50 pages read". */
$text = _n( 'of %s page read', 'of %s pages read', $number, 'endpaper' );
} elseif ( 'hour' === $goal['metric'] ) {
/* translators: %s: The goal, in hours. This follows the number of hours listened, as in "34 of 50 hours listened". */
$text = _n( 'of %s hour listened', 'of %s hours listened', $number, 'endpaper' );
} else {
/* translators: %s: The goal, in books. This follows the number of books read, as in "34 of 50 books read". */
$text = _n( 'of %s book read', 'of %s books read', $number, 'endpaper' );
}
return array(
'count' => format_goal_number( $goal['progress'] ),
'label' => sprintf( $text, $target ),
);
}
/**
* Returns the text for how far along a goal is, such as "34 of 50 books read".
*
* @param array $goal A normalized goal.
* @return string The text.
*/
function get_goal_amount_text( $goal ) {
$parts = get_goal_amount_parts( $goal );
return $parts['count'] . ' ' . $parts['label'];
}
/**
* Returns the text for a goal whose time has run out, such as "Ended November 30, 2026".
*
* @param array $goal A normalized goal.
* @return string The text.
*/
function get_goal_ended_text( $goal ) {
$date = format_date( $goal['end'] );
/* translators: %s: A date, such as November 30, 2015. */
return '' === $date ? __( 'Ended', 'endpaper' ) : sprintf( __( 'Ended %s', 'endpaper' ), $date );
}
/**
* Returns how much of the time a goal runs for is left, as a text such as "48 days left".
*
* Days are counted in the site's time zone, from today to the last day of the goal.
*
* @param array $goal A normalized goal.
* @return string The text, or an empty string if the goal has no valid end date.
*/
function get_goal_days_text( $goal ) {
if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $goal['end'] ) ) {
return '';
}
$timezone = wp_timezone();
$end = date_create_immutable( $goal['end'] . ' 00:00:00', $timezone );
if ( ! $end ) {
return '';
}
$today = current_datetime()->setTime( 0, 0 );
$days = (int) $today->diff( $end )->format( '%r%a' );
if ( $days > 0 ) {
/* translators: %s: Number of days. */
return sprintf( _n( '%s day left', '%s days left', $days, 'endpaper' ), number_format_i18n( $days ) );
}
if ( 0 === $days ) {
return __( 'Ends today', 'endpaper' );
}
return get_goal_ended_text( $goal );
}
/**
* Returns the Hardcover logo, as inline SVG: the mark, followed by the name.
*
* It takes the color of the text around it. The logo is Hardcover's
* trademark, used to credit them as the source, with their permission.
*
* The paths are those of Hardcover's own one-color logo file, unchanged.
* Only the fill is different: the color of the text, in place of white.
*
* @return string SVG markup.
*/
function get_hardcover_logo() {
return '';
}
/**
* Outputs the credit to Hardcover: their logo, linked to Hardcover.
*
* The logo has no words that a screen reader can read, so the link carries
* the credit as hidden text.
*
* @param string $url Where the credit links to: a book on Hardcover, or Hardcover itself.
* @param string $class_name Class for the link.
* @return void
*/
function the_hardcover_credit( $url, $class_name ) {
printf(
'%3$s%4$s',
esc_attr( $class_name ),
esc_url( $url ? $url : 'https://hardcover.app/' ),
get_hardcover_logo(), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG markup.
esc_html__( 'Powered by Hardcover', 'endpaper' )
);
}
/**
* Outputs a message for the people who look after the site, in place of a block or next to it.
*
* Visitors never see it. It says so itself, since it shows up on the public
* page, where it could be taken for something everyone sees.
*
* @param string $message The message.
* @param bool $link_to_settings Optional. Whether to add a link to the plugin's settings, for those who may change them.
* @return void
*/
function the_editor_notice( $message, $link_to_settings = false ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return;
}
$link = $link_to_settings && current_user_can( 'manage_options' )
? ' ' . esc_html__( 'Go to the Endpaper settings.', 'endpaper' ) . ''
: '';
printf(
'
%1$s
%2$s%3$s
%4$s
',
esc_html__( 'Endpaper', 'endpaper' ),
esc_html( $message ),
$link, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above.
esc_html__( 'Only people who can edit this site see this message.', 'endpaper' )
);
}
/**
* Returns the path of one of the plugin's own icons.
*
* The paths are kept in assets/icons.json, which the editor reads as well, so
* a block has the same icon in both places. They are drawn on a 20 by 20 grid.
*
* @param string $name The icon's name.
* @return string The SVG path data, or an empty string if there is no such icon.
*/
function get_icon_path( $name ) {
static $icons = null;
if ( null === $icons ) {
$file = ENDPAPER_DIR . 'assets/icons.json';
$icons = is_readable( $file ) ? json_decode( (string) file_get_contents( $file ), true ) : array(); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- A file in the plugin, not a remote address.
$icons = is_array( $icons ) ? $icons : array();
}
return isset( $icons[ $name ] ) && is_string( $icons[ $name ] ) ? $icons[ $name ] : '';
}
/**
* Returns the styles the Book block has, with their labels.
*
* That is Plain and Card, and any style a theme or another plugin has registered for the block in PHP,
* including the style variations in a theme's styles folder. A style that is only registered in
* JavaScript cannot be seen from here.
*
* @return array Labels, keyed by the name of the style. "default" is Plain.
*/
function get_book_styles() {
$styles = array();
$type = \WP_Block_Type_Registry::get_instance()->get_registered( 'endpaper/book' );
if ( $type && is_array( $type->styles ) ) {
foreach ( $type->styles as $style ) {
if ( ! empty( $style['name'] ) ) {
$styles[ $style['name'] ] = isset( $style['label'] ) ? $style['label'] : $style['name'];
}
}
}
foreach ( \WP_Block_Styles_Registry::get_instance()->get_registered_styles_for_block( 'endpaper/book' ) as $name => $style ) {
if ( is_string( $name ) && '' !== $name ) {
$styles[ $name ] = isset( $style['label'] ) ? $style['label'] : $name;
}
}
if ( ! isset( $styles['default'] ) ) {
$styles = array( 'default' => __( 'Plain', 'endpaper' ) ) + $styles;
}
return $styles;
}
/**
* Returns the style new Book blocks start with.
*
* A style that is not registered any more, such as one from a theme that has been switched, counts as Plain.
*
* @return string The name of the style, or "default" for the Plain style.
*/
function get_default_book_style() {
$style = get_option( ENDPAPER_DEFAULT_STYLE_OPTION, 'default' );
return is_string( $style ) && isset( get_book_styles()[ $style ] ) ? $style : 'default';
}
/**
* Returns the typography of the theme's headings, as CSS variables.
*
* Big text, such as the count in the middle of the gauge, is not a heading, but looks better in the
* font of the theme's headings. The values come from the global styles, so they follow
* styles.elements.heading in theme.json and in the Styles screen. A theme can change them for one block
* under styles.blocks, in elements.heading.typography, which takes precedence.
*
* @param string $block_name Block name, such as "endpaper/reading-goal".
* @return string Inline style declarations, or an empty string.
*/
function get_heading_typography_style( $block_name ) {
$options = array( 'transforms' => array( 'resolve-variables' ) );
$typography = get_global_style( array( 'elements', 'heading', 'typography' ), $options );
$for_block = get_global_style( array( 'blocks', $block_name, 'elements', 'heading', 'typography' ), $options );
$typography = is_array( $typography ) ? $typography : array();
if ( is_array( $for_block ) ) {
$typography = array_merge( $typography, $for_block );
}
$properties = array(
'fontFamily' => 'font-family',
'fontWeight' => 'font-weight',
'fontStyle' => 'font-style',
'letterSpacing' => 'letter-spacing',
);
$style = '';
foreach ( $properties as $key => $property ) {
if ( ! isset( $typography[ $key ] ) || ! is_scalar( $typography[ $key ] ) ) {
continue;
}
$value = trim( wp_strip_all_tags( (string) $typography[ $key ] ) );
// Only plain values: no declarations, functions that load things, or leftover variables.
if ( '' === $value || preg_match( '/[;{}<>\\\\]|url\\(|expression\\(|var\\(/i', $value ) ) {
continue;
}
$style .= '--endpaper-heading-' . $property . ': ' . $value . ';';
}
return $style;
}