MediaWiki  1.27.3
MWTimestamp.php
Go to the documentation of this file.
1 <?php
31 class MWTimestamp {
35  private static $formats = [
36  TS_UNIX => 'U',
37  TS_MW => 'YmdHis',
38  TS_DB => 'Y-m-d H:i:s',
39  TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
40  TS_ISO_8601_BASIC => 'Ymd\THis\Z',
41  TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
42  TS_RFC2822 => 'D, d M Y H:i:s',
43  TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
44  TS_POSTGRES => 'Y-m-d H:i:s',
45  ];
46 
51  public $timestamp;
52 
61  public function __construct( $timestamp = false ) {
62  $this->setTimestamp( $timestamp );
63  }
64 
76  public function setTimestamp( $ts = false ) {
77  $m = [];
78  $da = [];
79  $strtime = '';
80 
81  // We want to catch 0, '', null... but not date strings starting with a letter.
82  if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
83  $uts = time();
84  $strtime = "@$uts";
85  } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
86  # TS_DB
87  } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
88  # TS_EXIF
89  } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
90  # TS_MW
91  } elseif ( preg_match( '/^(-?\d{1,13})(\.\d+)?$/D', $ts, $m ) ) {
92  # TS_UNIX
93  $strtime = "@{$m[1]}"; // http://php.net/manual/en/datetime.formats.compound.php
94  } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
95  # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
96  $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
97  str_replace( '+00:00', 'UTC', $ts ) );
98  } elseif ( preg_match(
99  '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
100  $ts,
101  $da
102  ) ) {
103  # TS_ISO_8601
104  } elseif ( preg_match(
105  '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
106  $ts,
107  $da
108  ) ) {
109  # TS_ISO_8601_BASIC
110  } elseif ( preg_match(
111  '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
112  $ts,
113  $da
114  ) ) {
115  # TS_POSTGRES
116  } elseif ( preg_match(
117  '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
118  $ts,
119  $da
120  ) ) {
121  # TS_POSTGRES
122  } elseif ( preg_match(
123  # Day of week
124  '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
125  # dd Mon yyyy
126  '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
127  # hh:mm:ss
128  '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
129  $ts
130  ) ) {
131  # TS_RFC2822, accepting a trailing comment.
132  # See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
133  # The regex is a superset of rfc2822 for readability
134  $strtime = strtok( $ts, ';' );
135  } 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 ) ) {
136  # TS_RFC850
137  $strtime = $ts;
138  } 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 ) ) {
139  # asctime
140  $strtime = $ts;
141  } else {
142  throw new TimestampException( __METHOD__ . ": Invalid timestamp - $ts" );
143  }
144 
145  if ( !$strtime ) {
146  $da = array_map( 'intval', $da );
147  $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
148  $strtime = call_user_func_array( "sprintf", $da );
149  }
150 
151  try {
152  $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
153  } catch ( Exception $e ) {
154  throw new TimestampException( __METHOD__ . ': Invalid timestamp format.', $e->getCode(), $e );
155  }
156 
157  if ( $final === false ) {
158  throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
159  }
160  $this->timestamp = $final;
161  }
162 
175  public function getTimestamp( $style = TS_UNIX ) {
176  if ( !isset( self::$formats[$style] ) ) {
177  throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
178  }
179 
180  $output = $this->timestamp->format( self::$formats[$style] );
181 
182  if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
183  $output .= ' GMT';
184  }
185 
186  if ( $style == TS_MW && strlen( $output ) !== 14 ) {
187  throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
188  'the specified format' );
189  }
190 
191  return $output;
192  }
193 
212  public function getHumanTimestamp(
213  MWTimestamp $relativeTo = null, User $user = null, Language $lang = null
214  ) {
215  if ( $lang === null ) {
216  $lang = RequestContext::getMain()->getLanguage();
217  }
218 
219  return $lang->getHumanTimestamp( $this, $relativeTo, $user );
220  }
221 
230  public function offsetForUser( User $user ) {
232 
233  $option = $user->getOption( 'timecorrection' );
234  $data = explode( '|', $option, 3 );
235 
236  // First handle the case of an actual timezone being specified.
237  if ( $data[0] == 'ZoneInfo' ) {
238  try {
239  $tz = new DateTimeZone( $data[2] );
240  } catch ( Exception $e ) {
241  $tz = false;
242  }
243 
244  if ( $tz ) {
245  $this->timestamp->setTimezone( $tz );
246  return new DateInterval( 'P0Y' );
247  } else {
248  $data[0] = 'Offset';
249  }
250  }
251 
252  $diff = 0;
253  // If $option is in fact a pipe-separated value, check the
254  // first value.
255  if ( $data[0] == 'System' ) {
256  // First value is System, so use the system offset.
257  if ( $wgLocalTZoffset !== null ) {
258  $diff = $wgLocalTZoffset;
259  }
260  } elseif ( $data[0] == 'Offset' ) {
261  // First value is Offset, so use the specified offset
262  $diff = (int)$data[1];
263  } else {
264  // $option actually isn't a pipe separated value, but instead
265  // a comma separated value. Isn't MediaWiki fun?
266  $data = explode( ':', $option );
267  if ( count( $data ) >= 2 ) {
268  // Combination hours and minutes.
269  $diff = abs( (int)$data[0] ) * 60 + (int)$data[1];
270  if ( (int)$data[0] < 0 ) {
271  $diff *= -1;
272  }
273  } else {
274  // Just hours.
275  $diff = (int)$data[0] * 60;
276  }
277  }
278 
279  $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
280  if ( $diff < 1 ) {
281  $interval->invert = 1;
282  }
283 
284  $this->timestamp->add( $interval );
285  return $interval;
286  }
287 
298  public function getRelativeTimestamp(
299  MWTimestamp $relativeTo = null,
300  User $user = null,
301  Language $lang = null,
302  array $chosenIntervals = []
303  ) {
304  if ( $relativeTo === null ) {
305  $relativeTo = new self;
306  }
307  if ( $user === null ) {
308  $user = RequestContext::getMain()->getUser();
309  }
310  if ( $lang === null ) {
311  $lang = RequestContext::getMain()->getLanguage();
312  }
313 
314  $ts = '';
315  $diff = $this->diff( $relativeTo );
316  if ( Hooks::run(
317  'GetRelativeTimestamp',
318  [ &$ts, &$diff, $this, $relativeTo, $user, $lang ]
319  ) ) {
320  $seconds = ( ( ( $diff->days * 24 + $diff->h ) * 60 + $diff->i ) * 60 + $diff->s );
321  $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
322  ->inLanguage( $lang )->text();
323  }
324 
325  return $ts;
326  }
327 
333  public function __toString() {
334  return $this->getTimestamp();
335  }
336 
345  public function diff( MWTimestamp $relativeTo ) {
346  return $this->timestamp->diff( $relativeTo->timestamp );
347  }
348 
356  public function setTimezone( $timezone ) {
357  try {
358  $this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
359  } catch ( Exception $e ) {
360  throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
361  }
362  }
363 
370  public function getTimezone() {
371  return $this->timestamp->getTimezone();
372  }
373 
383  public function getTimezoneMessage() {
384  $tzMsg = $this->format( 'T' ); // might vary on DST changeover!
385  $key = 'timezone-' . strtolower( trim( $tzMsg ) );
386  $msg = wfMessage( $key );
387  if ( $msg->exists() ) {
388  return $msg;
389  } else {
390  return new RawMessage( $tzMsg );
391  }
392  }
393 
401  public function format( $format ) {
402  return $this->timestamp->format( $format );
403  }
404 
412  public static function getLocalInstance( $ts = false ) {
414  $timestamp = new self( $ts );
415  $timestamp->setTimezone( $wgLocaltimezone );
416  return $timestamp;
417  }
418 
426  public static function getInstance( $ts = false ) {
427  return new self( $ts );
428  }
429 }
__construct($timestamp=false)
Make a new timestamp and set it to the specified time, or the current time if unspecified.
Definition: MWTimestamp.php:61
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
diff(MWTimestamp $relativeTo)
Calculate the difference between two MWTimestamp objects.
the array() calling protocol came about after MediaWiki 1.4rc1.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2325
getHumanTimestamp(MWTimestamp $relativeTo=null, User $user=null, Language $lang=null)
Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
format($format)
Format the timestamp in a given format.
static TS_MW
Definition: MWTimestamp.php:37
getTimezone()
Get the timezone of this timestamp.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1936
offsetForUser(User $user)
Adjust the timestamp depending on the given user's preferences.
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Definition: globals.txt:10
if(!isset($args[0])) $lang
getTimezoneMessage()
Get the localized timezone message, if available.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static getLocalInstance($ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
const TS_EXIF
An Exif timestamp (YYYY:MM:DD HH:MM:SS)
static getMain()
Static methods.
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
static getInstance($ts=false)
Get a timestamp instance in GMT.
static $formats
Standard gmdate() formats for the different timestamp types.
Definition: MWTimestamp.php:35
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
const TS_ORACLE
Oracle format time.
getTimestamp($style=TS_UNIX)
Get the timestamp represented by this object in a certain form.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
$wgLocaltimezone
Fake out the timezone that the server thinks it's in.
const TS_DB
MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:246
getOption($oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2746
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1008
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
DateTime $timestamp
The actual timestamp being wrapped (DateTime object).
Definition: MWTimestamp.php:51
Variant of the Message class.
Definition: Message.php:1232
setTimezone($timezone)
Set the timezone of this timestamp to the specified timezone.
$wgLocalTZoffset
Set an offset from UTC in minutes to use for the default timezone setting for anonymous users and new...
getRelativeTimestamp(MWTimestamp $relativeTo=null, User $user=null, Language $lang=null, array $chosenIntervals=[])
Generate a purely relative timestamp, i.e., represent the time elapsed between the given base timesta...
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
const TS_POSTGRES
Postgres format time.
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:31
setTimestamp($ts=false)
Set the timestamp to the specified time, or the current time if unspecified.
Definition: MWTimestamp.php:76
const TS_ISO_8601_BASIC
ISO 8601 basic format with no timezone: 19860209T200000Z.