From e738203a8e1cff8d5841c561ae8b8c17f92c5bbf Mon Sep 17 00:00:00 2001 From: Tyler Anthony Romeo Date: Tue, 31 Jul 2012 15:37:01 -0400 Subject: [PATCH] Added PHP complement for mw.Time. Figured since a JS Timestamp class was being implemented it might be appropriate to create a complementary PHP Timestamp class. Much of code is taken from wfTimestamp(). Note: Another change (I53dcf547) is attempting a related issue. Not sure how much of scope overlap there is. Change-Id: I68eb9f27eebe80df757187f634392e1bcba5551f Signed-off-by: Tyler Romeo --- includes/AutoLoader.php | 1 + includes/GlobalFunctions.php | 115 +--------- includes/Timestamp.php | 204 ++++++++++++++++++ tests/phpunit/includes/TimestampTest.php | 72 +++++++ .../media/BitmapMetadataHandlerTest.php | 4 +- 5 files changed, 283 insertions(+), 113 deletions(-) create mode 100644 includes/Timestamp.php create mode 100644 tests/phpunit/includes/TimestampTest.php diff --git a/includes/AutoLoader.php b/includes/AutoLoader.php index 9d78dbdc38..706e1c83e2 100644 --- a/includes/AutoLoader.php +++ b/includes/AutoLoader.php @@ -245,6 +245,7 @@ $wgAutoloadLocalClasses = array( 'StubObject' => 'includes/StubObject.php', 'StubUserLang' => 'includes/StubObject.php', 'TablePager' => 'includes/Pager.php', + 'MWTimestamp' => 'includes/Timestamp.php', 'Title' => 'includes/Title.php', 'TitleArray' => 'includes/TitleArray.php', 'TitleArrayFromResult' => 'includes/TitleArray.php', diff --git a/includes/GlobalFunctions.php b/includes/GlobalFunctions.php index 84cdeea4b5..0a6051801a 100644 --- a/includes/GlobalFunctions.php +++ b/includes/GlobalFunctions.php @@ -2401,6 +2401,7 @@ define( 'TS_ISO_8601_BASIC', 9 ); /** * Get a timestamp string in one of various formats * + * @deprecated * @param $outputtype Mixed: A timestamp in one of the supported formats, the * function will autodetect which format is supplied and act * accordingly. @@ -2408,118 +2409,8 @@ define( 'TS_ISO_8601_BASIC', 9 ); * @return Mixed: String / false The same date in the format specified in $outputtype or false */ function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) { - $uts = 0; - $da = array(); - $strtime = ''; - - if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter. - $uts = time(); - $strtime = "@$uts"; - } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) { - # TS_DB - } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) { - # TS_EXIF - } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) { - # TS_MW - } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) { - # TS_UNIX - $uts = $ts; - $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php - } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) { - # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6 - $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3", - str_replace( '+00:00', 'UTC', $ts ) ); - } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) { - # TS_ISO_8601 - } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) { - #TS_ISO_8601_BASIC - } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) { - # TS_POSTGRES - } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) { - # TS_POSTGRES - } elseif (preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/', $ts, $da ) ) { - # TS_DB2 - } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week - '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy - '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss - # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171 - # The regex is a superset of rfc2822 for readability - $strtime = strtok( $ts, ';' ); - } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) { - # TS_RFC850 - $strtime = $ts; - } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) { - # asctime - $strtime = $ts; - } else { - # Bogus value... - wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n"); - - return false; - } - - static $formats = array( - TS_UNIX => 'U', - TS_MW => 'YmdHis', - TS_DB => 'Y-m-d H:i:s', - TS_ISO_8601 => 'Y-m-d\TH:i:s\Z', - TS_ISO_8601_BASIC => 'Ymd\THis\Z', - TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness - TS_RFC2822 => 'D, d M Y H:i:s', - TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500 - TS_POSTGRES => 'Y-m-d H:i:s', - TS_DB2 => 'Y-m-d H:i:s', - ); - - if ( !isset( $formats[$outputtype] ) ) { - throw new MWException( 'wfTimestamp() called with illegal output type.' ); - } - - if ( function_exists( "date_create" ) ) { - if ( count( $da ) ) { - $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00", - (int)$da[1], (int)$da[2], (int)$da[3], - (int)$da[4], (int)$da[5], (int)$da[6]); - - $d = date_create( $ds, new DateTimeZone( 'GMT' ) ); - } elseif ( $strtime ) { - $d = date_create( $strtime, new DateTimeZone( 'GMT' ) ); - } else { - return false; - } - - if ( !$d ) { - wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n"); - return false; - } - - $output = $d->format( $formats[$outputtype] ); - } else { - if ( count( $da ) ) { - // Warning! gmmktime() acts oddly if the month or day is set to 0 - // We may want to handle that explicitly at some point - $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6], - (int)$da[2], (int)$da[3], (int)$da[1] ); - } elseif ( $strtime ) { - $uts = strtotime( $strtime ); - } - - if ( $uts === false ) { - wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n"); - return false; - } - - if ( TS_UNIX == $outputtype ) { - return $uts; - } - $output = gmdate( $formats[$outputtype], $uts ); - } - - if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) { - $output .= ' GMT'; - } - - return $output; + $timestamp = new MWTimestamp( $ts ); + return $timestamp->getTimestamp( $outputtype ); } /** diff --git a/includes/Timestamp.php b/includes/Timestamp.php new file mode 100644 index 0000000000..b5ea775b47 --- /dev/null +++ b/includes/Timestamp.php @@ -0,0 +1,204 @@ + 'U', + TS_MW => 'YmdHis', + TS_DB => 'Y-m-d H:i:s', + TS_ISO_8601 => 'Y-m-d\TH:i:s\Z', + TS_ISO_8601_BASIC => 'Ymd\THis\Z', + TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness + TS_RFC2822 => 'D, d M Y H:i:s', + TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500 + TS_POSTGRES => 'Y-m-d H:i:s', + TS_DB2 => 'Y-m-d H:i:s', + ); + + /** + * Different units for human readable timestamps. + * @see MWTimestamp::getHumanTimestamp + */ + private static $units = array( + "milliseconds" => 1, + "seconds" => 1000, // 1000 milliseconds per second + "minutes" => 60, // 60 seconds per minute + "hours" => 60, // 60 minutes per hour + "days" => 24 // 24 hours per day + ); + + /** + * The actual timestamp being wrapped. Either a DateTime + * object or a string with a Unix timestamp depending on + * PHP. + */ + private $timestamp; + + /** + * Make a new timestamp and set it to the specified time, + * or the current time if unspecified. + * + * @param $timestamp Timestamp to set, or false for current time + */ + public function __construct( $timestamp = false ) { + $this->setTimestamp( $timestamp ); + } + + /** + * Set the timestamp to the specified time, or the current time if unspecified. + * + * Parse the given timestamp into either a DateTime object or a Unix teimstamp, + * and then store it. + * + * @param $ts Timestamp to store, or false for now + */ + public function setTimestamp( $ts = false ) { + $uts = 0; + $da = array(); + $strtime = ''; + + if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter. + $uts = time(); + $strtime = "@$uts"; + } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) { + # TS_DB + } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) { + # TS_EXIF + } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) { + # TS_MW + } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) { + # TS_UNIX + $uts = $ts; + $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php + } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) { + # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6 + $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3", + str_replace( '+00:00', 'UTC', $ts ) ); + } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) { + # TS_ISO_8601 + } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) { + #TS_ISO_8601_BASIC + } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) { + # TS_POSTGRES + } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) { + # TS_POSTGRES + } elseif (preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/', $ts, $da ) ) { + # TS_DB2 + } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week + '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy + '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss + # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171 + # The regex is a superset of rfc2822 for readability + $strtime = strtok( $ts, ';' ); + } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) { + # TS_RFC850 + $strtime = $ts; + } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) { + # asctime + $strtime = $ts; + } else { + throw new TimestampException( __METHOD__ . " : Invalid timestamp - $ts" ); + } + + if( !$strtime ) { + $da = array_map( 'intval', $da ); + $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00"; + $strtime = call_user_func_array( "sprintf", $da ); + } + + if( function_exists( "date_create" ) ) { + try { + $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) ); + } catch(Exception $e) { + throw new TimestampException( __METHOD__ . 'Invalid timestamp format.' ); + } + } else { + $final = strtotime( $strtime ); + } + + if( $final === false ) { + throw new TimestampException( __METHOD__ . 'Invalid timestamp format.' ); + } + $this->timestamp = $final; + } + + /** + * Get the timestamp represented by this object in a certain form. + * + * Convert the internal timestamp to the specified format and then + * return it. + * + * @param $style Output format for timestamp + * @return string The formatted timestamp + */ + public function getTimestamp( $style = TS_UNIX ) { + if( !isset( self::$formats[$style] ) ) { + throw new TimestampException( __METHOD__ . ' : Illegal timestamp output type.' ); + } + + if( is_object( $this->timestamp ) ) { + // DateTime object was used, call DateTime::format. + $output = $this->timestamp->format( self::$formats[$style] ); + } elseif( TS_UNIX == $style ) { + // Unix timestamp was used and is wanted, just return it. + $output = $this->timestamp; + } else { + // Unix timestamp was used, use gmdate(). + $output = gmdate( self::$formats[$style], $this->timestamp ); + } + + if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) { + $output .= ' GMT'; + } + + return $output; + } + + /** + * Get the timestamp in a human-friendly relative format, e.g., "3 days ago". + * + * Determine the difference between the timestamp and the current time, and + * generate a readable timestamp by returning " ago", where the + * largest possible unit is used. + * + * @return string Formatted timestamp + */ + public function getHumanTimestamp() { + $then = $this->getTimestamp( TS_UNIX ); + $now = time(); + $timeago = ($now - $then) * 1000; + $message = false; + + foreach( self::$units as $unit => $factor ) { + $next = $timeago / $factor; + if( $next < 1 ) { + break; + } else { + $timeago = $next; + $message = array( $unit, floor( $timeago ) ); + } + } + + if( $message ) { + $initial = call_user_func_array( 'wfMessage', $message ); + return wfMessage( 'ago', $initial ); + } else { + return wfMessage( 'just-now' ); + } + } + + public function __toString() { + return $this->getTimestamp(); + } +} + +class TimestampException extends MWException {} diff --git a/tests/phpunit/includes/TimestampTest.php b/tests/phpunit/includes/TimestampTest.php new file mode 100644 index 0000000000..231228f55f --- /dev/null +++ b/tests/phpunit/includes/TimestampTest.php @@ -0,0 +1,72 @@ +assertEquals( $expected, $timestamp->getTimestamp( TS_MW ) ); + } + + /** + * Test outputting valid timestamps to different formats. + * @dataProvider provideValidTimestamps + */ + function testValidOutput( $format, $expected, $original ) { + $timestamp = new MWTimestamp( $original ); + $this->assertEquals( $expected, (string) $timestamp->getTimestamp( $format ) ); + } + + /** + * Test an invalid timestamp. + * @expectedException TimestampException + */ + function testInvalidParse() { + $timestamp = new MWTimestamp( "This is not a timestamp." ); + } + + /** + * Test requesting an invalid output format. + * @expectedException TimestampException + */ + function testInvalidOutput() { + $timestamp = new MWTimestamp( '1343761268' ); + $timestamp->getTimestamp( 98 ); + } + + /** + * Test human readable timestamp format. + */ + function testHumanOutput() { + $timestamp = new MWTimestamp( time() - 3600 ); + $this->assertEquals( "1 hour ago", $timestamp->getHumanTimestamp()->toString() ); + } + + /** + * Returns a list of valid timestamps in the format: + * array( type, timestamp_of_type, timestamp_in_MW ) + */ + function provideValidTimestamps() { + return array( + // Various formats + array( TS_UNIX, '1343761268', '20120731190108' ), + array( TS_MW, '20120731190108', '20120731190108' ), + array( TS_DB, '2012-07-31 19:01:08', '20120731190108' ), + array( TS_ISO_8601, '2012-07-31T19:01:08Z', '20120731190108' ), + array( TS_ISO_8601_BASIC, '20120731T190108Z', '20120731190108' ), + array( TS_EXIF, '2012:07:31 19:01:08', '20120731190108' ), + array( TS_RFC2822, 'Tue, 31 Jul 2012 19:01:08 GMT', '20120731190108' ), + array( TS_ORACLE, '31-07-2012 19:01:08.000000', '20120731190108' ), + array( TS_POSTGRES, '2012-07-31 19:01:08 GMT', '20120731190108' ), + array( TS_DB2, '2012-07-31 19:01:08', '20120731190108' ), + // Some extremes and weird values + array( TS_ISO_8601, '9999-12-31T23:59:59Z', '99991231235959' ), + array( TS_UNIX, '-62135596801', '00001231235959' ) + ); + } +} diff --git a/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php b/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php index d6e25477bd..b604d59041 100644 --- a/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php +++ b/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php @@ -73,8 +73,10 @@ class BitmapMetadataHandlerTest extends MediaWikiTestCase { $this->assertEquals( '2020:07:14 01:36:05', $meta['DateTimeDigitized'] ); $this->assertEquals( '1997:03:02 00:01:02', $meta['DateTimeOriginal'] ); } - /* File has an invalid time (+ one valid but really weird time) + /** + * File has an invalid time (+ one valid but really weird time) * that shouldn't be included + * @expectedException TimestampException */ public function testIPTCDatesInvalid() { $meta = BitmapMetadataHandler::Jpeg( $this->filePath . -- 2.20.1