Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace strftime with IntlDateFormatter for PHP8.1 #1228

Merged
merged 1 commit into from
Sep 25, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 197 additions & 4 deletions qtranslate_date_time.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,193 @@
<?php

/**
* Locale-formatted strftime using \IntlDateFormatter (PHP 8.1 compatible)
* This provides a cross-platform alternative to strftime() for when it will be removed from PHP.
* Note that output can be slightly different between libc sprintf and this function as it is using ICU.
* Non-standard strftime: '%q' is a qTranslate format to mimic date 'S'.
*
* Usage:
* echo strftime('%A %e %B %Y %X', new \DateTime('2021-09-28 00:00:00'), 'fr_FR');
*
* Original use:
* \setlocale('fr_FR.UTF-8', LC_TIME);
* echo \strftime('%A %e %B %Y %X', strtotime('2021-09-28 00:00:00'));
*
* @param string $format Date format
* @param integer|string|DateTime $timestamp Timestamp
*
* @return string
* @deprecated Don't use this function, only meant for transition from legacy strftime formats.
* @see https://gist.github.com/bohwaz/42fc223031e2b2dd2585aab159a20f30 (for the original code).
*/
function qxtranxf_intl_strftime( $format, $timestamp = null, $locale = null ) {
if ( null === $timestamp ) {
$timestamp = new \DateTime;
} elseif ( is_numeric( $timestamp ) ) {
$timestamp = date_create( '@' . $timestamp );

if ( $timestamp ) {
$timestamp->setTimezone( new \DateTimezone( date_default_timezone_get() ) );
}
} elseif ( is_string( $timestamp ) ) {
$timestamp = date_create( $timestamp );
}

if ( ! ( $timestamp instanceof \DateTimeInterface ) ) {
throw new \InvalidArgumentException( '$timestamp argument is neither a valid UNIX timestamp, a valid date-time string or a DateTime object.' );
}

$locale = substr( (string) $locale, 0, 5 );

$intl_formats = [
'%a' => 'EEE', // An abbreviated textual representation of the day Sun through Sat
'%A' => 'EEEE', // A full textual representation of the day Sunday through Saturday
'%b' => 'MMM', // Abbreviated month name, based on the locale Jan through Dec
'%B' => 'MMMM', // Full month name, based on the locale January through December
'%h' => 'MMM', // Abbreviated month name, based on the locale (an alias of %b) Jan through Dec
];

// \DateTimeInterface, string
$intl_formatter = function ( $timestamp, $format ) use ( $intl_formats, $locale ) {
$tz = $timestamp->getTimezone();
$date_type = \IntlDateFormatter::FULL;
$time_type = \IntlDateFormatter::FULL;
$pattern = '';

// %c = Preferred date and time stamp based on locale
// Example: Tue Feb 5 00:45:10 2009 for February 5, 2009 at 12:45:10 AM
if ( $format == '%c' ) {
$date_type = \IntlDateFormatter::LONG;
$time_type = \IntlDateFormatter::SHORT;
}
// %x = Preferred date representation based on locale, without the time
// Example: 02/05/09 for February 5, 2009
elseif ( $format == '%x' ) {
$date_type = \IntlDateFormatter::SHORT;
$time_type = \IntlDateFormatter::NONE;
} // Localized time format
elseif ( $format == '%X' ) {
$date_type = \IntlDateFormatter::NONE;
$time_type = \IntlDateFormatter::MEDIUM;
} else {
$pattern = $intl_formats[ $format ];
}

return ( new \IntlDateFormatter( $locale, $date_type, $time_type, $tz, null, $pattern ) )->format( $timestamp );
};

// Same order as https://www.php.net/manual/en/function.strftime.php
$translation_table = [
// Day
'%a' => $intl_formatter,
'%A' => $intl_formatter,
'%d' => 'd',
'%e' => function ( $timestamp ) {
return sprintf( '% 2u', $timestamp->format( 'j' ) );
},
'%j' => function ( $timestamp ) {
// Day number in year, 001 to 366
return sprintf( '%03d', $timestamp->format( 'z' ) + 1 );
},
'%q' => 'S', // Non-standard strftime: '%q' is a qTranslate format to mimic date 'S'.
'%u' => 'N',
'%w' => 'w',

// Week
'%U' => function ( $timestamp ) {
// Number of weeks between date and first Sunday of year
$day = new \DateTime( sprintf( '%d-01 Sunday', $timestamp->format( 'Y' ) ) );

return sprintf( '%02u', 1 + ( $timestamp->format( 'z' ) - $day->format( 'z' ) ) / 7 );
},
'%V' => 'W',
'%W' => function ( $timestamp ) {
// Number of weeks between date and first Monday of year
$day = new \DateTime( sprintf( '%d-01 Monday', $timestamp->format( 'Y' ) ) );

return sprintf( '%02u', 1 + ( $timestamp->format( 'z' ) - $day->format( 'z' ) ) / 7 );
},

// Month
'%b' => $intl_formatter,
'%B' => $intl_formatter,
'%h' => $intl_formatter,
'%m' => 'm',

// Year
'%C' => function ( $timestamp ) {
// Century (-1): 19 for 20th century
return floor( $timestamp->format( 'Y' ) / 100 );
},
'%g' => function ( $timestamp ) {
return substr( $timestamp->format( 'o' ), -2 );
},
'%G' => 'o',
'%y' => 'y',
'%Y' => 'Y',

// Time
'%H' => 'H',
'%k' => function ( $timestamp ) {
return sprintf( '% 2u', $timestamp->format( 'G' ) );
},
'%I' => 'h',
'%l' => function ( $timestamp ) {
return sprintf( '% 2u', $timestamp->format( 'g' ) );
},
'%M' => 'i',
'%p' => 'A', // AM PM (this is reversed on purpose!)
'%P' => 'a', // am pm
'%r' => 'h:i:s A', // %I:%M:%S %p
'%R' => 'H:i', // %H:%M
'%S' => 's',
'%T' => 'H:i:s', // %H:%M:%S
'%X' => $intl_formatter, // Preferred time representation based on locale, without the date

// Timezone
'%z' => 'O',
'%Z' => 'T',

// Time and Date Stamps
'%c' => $intl_formatter,
'%D' => 'm/d/Y',
'%F' => 'Y-m-d',
'%s' => 'U',
'%x' => $intl_formatter,
];

$out = preg_replace_callback( '/(?<!%)(%[a-zA-Z])/', function ( $match ) use ( $translation_table, $timestamp ) {
if ( $match[1] == '%n' ) {
return "\n";
} elseif ( $match[1] == '%t' ) {
return "\t";
}

if ( ! isset( $translation_table[ $match[1] ] ) ) {
throw new \InvalidArgumentException( sprintf( 'Format "%s" is unknown in time format', $match[1] ) );
}

$replace = $translation_table[ $match[1] ];

if ( is_string( $replace ) ) {
return $timestamp->format( $replace );
} else {
return $replace( $timestamp, $match[1] );
}
}, $format );

$out = str_replace( '%%', '%', $out );

return $out;
}

/**
* [Legacy] Converter of a format given in DateTime format, transformed to the extended "QTX-strftime" format.
*
* @param string $format in DateTime format.
*
* @return string
* @deprecated Don't use strftime formats anymore, since strftime is deprecated from PHP8.1.
* @see https://www.php.net/manual/en/function.strftime.php
* @see https://www.php.net/manual/en/datetime.format.php
*/
Expand Down Expand Up @@ -75,6 +257,7 @@ function qtranxf_convertDateFormatToStrftimeFormat( $format ) {
* @param string $default_format
*
* @return string
* @deprecated Don't use strftime formats anymore, since strftime is deprecated from PHP8.1.
*/
function qtranxf_convertFormat( $format, $default_format ) {
global $q_config;
Expand Down Expand Up @@ -114,6 +297,7 @@ function qtranxf_convertFormat( $format, $default_format ) {
* @param string $format
*
* @return string
* @deprecated Don't use strftime formats anymore, since strftime is deprecated from PHP8.1.
*/
function qtranxf_convertDateFormat( $format ) {
global $q_config;
Expand All @@ -134,6 +318,7 @@ function qtranxf_convertDateFormat( $format ) {
* @param string $format
*
* @return string
* @deprecated Don't use strftime formats anymore, since strftime is deprecated from PHP8.1.
*/
function qtranxf_convertTimeFormat( $format ) {
global $q_config;
Expand All @@ -155,17 +340,22 @@ function qtranxf_convertTimeFormat( $format ) {
* @param int $date timestamp
* @param string $default Default result when $format is empty.
* @param string $before Text copied before result.
* @param $after Text copied after result.
* @param string $after Text copied after result.
*
* @return mixed|string
* @deprecated Don't use this since strftime is deprecated from PHP8.1.
* @deprecated Don't use strftime formats anymore, since strftime is deprecated from PHP8.1.
* @See https://www.php.net/manual/en/function.strftime.php
*/
function qtranxf_strftime( $format, $date, $default = '', $before = '', $after = '' ) {
// don't do anything if format is not given
if ( $format == '' ) {
if ( empty( $format ) ) {
return $default;
}

// Workaround for legacy strftime formats, using IntlDateFormatter instead.
if ( version_compare( PHP_VERSION, '8.1' ) >= 0 ) {
return qxtranxf_intl_strftime( $format, $date, get_locale() );
}

// add date suffix ability (%q) to strftime
$day = intval( ltrim( strftime( "%d", $date ), '0' ) );
$search = array();
Expand Down Expand Up @@ -244,6 +434,7 @@ function qtranxf_format_date( $format, $mysq_time, $default, $before = '', $afte
return $ts;
}

// TODO: abandon strftime format in qTranslate.
$format = qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage( $format );
if ( ! empty( $format ) && $q_config['use_strftime'] == QTX_STRFTIME ) {
$format = qtranxf_convertDateFormatToStrftimeFormat( $format );
Expand All @@ -269,6 +460,8 @@ function qtranxf_format_time( $format, $mysq_time, $default, $before = '', $afte
if ( $format == 'U' ) {
return $ts;
}

// TODO: abandon strftime format in qTranslate.
$format = qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage( $format );
if ( ! empty( $format ) && $q_config['use_strftime'] == QTX_STRFTIME ) {
$format = qtranxf_convertDateFormatToStrftimeFormat( $format );
Expand Down