MediaWiki  1.23.8
DateFormatter.php
Go to the documentation of this file.
1 <?php
32 
35 
36  protected $lang;
37 
38  const ALL = -1;
39  const NONE = 0;
40  const MDY = 1;
41  const DMY = 2;
42  const YMD = 3;
43  const ISO1 = 4;
44  const LASTPREF = 4;
45  const ISO2 = 5;
46  const YDM = 6;
47  const DM = 7;
48  const MD = 8;
49  const LAST = 8;
50 
54  function __construct( Language $lang ) {
55  $this->lang = $lang;
56 
57  $this->monthNames = $this->getMonthRegex();
58  for ( $i = 1; $i <= 12; $i++ ) {
59  $this->xMonths[$this->lang->lc( $this->lang->getMonthName( $i ) )] = $i;
60  $this->xMonths[$this->lang->lc( $this->lang->getMonthAbbreviation( $i ) )] = $i;
61  }
62 
63  $this->regexTrail = '(?![a-z])/iu';
64 
65  # Partial regular expressions
66  $this->prxDM = '\[\[(\d{1,2})[ _](' . $this->monthNames . ')\]\]';
67  $this->prxMD = '\[\[(' . $this->monthNames . ')[ _](\d{1,2})\]\]';
68  $this->prxY = '\[\[(\d{1,4}([ _]BC|))\]\]';
69  $this->prxISO1 = '\[\[(-?\d{4})]]-\[\[(\d{2})-(\d{2})\]\]';
70  $this->prxISO2 = '\[\[(-?\d{4})-(\d{2})-(\d{2})\]\]';
71 
72  # Real regular expressions
73  $this->regexes[self::DMY] = "/{$this->prxDM}(?: *, *| +){$this->prxY}{$this->regexTrail}";
74  $this->regexes[self::YDM] = "/{$this->prxY}(?: *, *| +){$this->prxDM}{$this->regexTrail}";
75  $this->regexes[self::MDY] = "/{$this->prxMD}(?: *, *| +){$this->prxY}{$this->regexTrail}";
76  $this->regexes[self::YMD] = "/{$this->prxY}(?: *, *| +){$this->prxMD}{$this->regexTrail}";
77  $this->regexes[self::DM] = "/{$this->prxDM}{$this->regexTrail}";
78  $this->regexes[self::MD] = "/{$this->prxMD}{$this->regexTrail}";
79  $this->regexes[self::ISO1] = "/{$this->prxISO1}{$this->regexTrail}";
80  $this->regexes[self::ISO2] = "/{$this->prxISO2}{$this->regexTrail}";
81 
82  # Extraction keys
83  # See the comments in replace() for the meaning of the letters
84  $this->keys[self::DMY] = 'jFY';
85  $this->keys[self::YDM] = 'Y jF';
86  $this->keys[self::MDY] = 'FjY';
87  $this->keys[self::YMD] = 'Y Fj';
88  $this->keys[self::DM] = 'jF';
89  $this->keys[self::MD] = 'Fj';
90  $this->keys[self::ISO1] = 'ymd'; # y means ISO year
91  $this->keys[self::ISO2] = 'ymd';
92 
93  # Target date formats
94  $this->targets[self::DMY] = '[[F j|j F]] [[Y]]';
95  $this->targets[self::YDM] = '[[Y]], [[F j|j F]]';
96  $this->targets[self::MDY] = '[[F j]], [[Y]]';
97  $this->targets[self::YMD] = '[[Y]] [[F j]]';
98  $this->targets[self::DM] = '[[F j|j F]]';
99  $this->targets[self::MD] = '[[F j]]';
100  $this->targets[self::ISO1] = '[[Y|y]]-[[F j|m-d]]';
101  $this->targets[self::ISO2] = '[[y-m-d]]';
102 
103  # Rules
104  # pref source target
105  $this->rules[self::DMY][self::MD] = self::DM;
106  $this->rules[self::ALL][self::MD] = self::MD;
107  $this->rules[self::MDY][self::DM] = self::MD;
108  $this->rules[self::ALL][self::DM] = self::DM;
109  $this->rules[self::NONE][self::ISO2] = self::ISO1;
110 
111  $this->preferences = array(
112  'default' => self::NONE,
113  'dmy' => self::DMY,
114  'mdy' => self::MDY,
115  'ymd' => self::YMD,
116  'ISO 8601' => self::ISO1,
117  );
118  }
119 
127  public static function &getInstance( $lang = null ) {
129  static $dateFormatter = false;
131  $key = wfMemcKey( 'dateformatter', $lang->getCode() );
132  if ( !$dateFormatter ) {
133  $dateFormatter = $wgMemc->get( $key );
134  if ( !$dateFormatter ) {
135  $dateFormatter = new DateFormatter( $lang );
136  $wgMemc->set( $key, $dateFormatter, 3600 );
137  }
138  }
139  return $dateFormatter;
140  }
141 
149  function reformat( $preference, $text, $options = array( 'linked' ) ) {
150  $linked = in_array( 'linked', $options );
151  $match_whole = in_array( 'match-whole', $options );
152 
153  if ( isset( $this->preferences[$preference] ) ) {
154  $preference = $this->preferences[$preference];
155  } else {
156  $preference = self::NONE;
157  }
158  for ( $i = 1; $i <= self::LAST; $i++ ) {
159  $this->mSource = $i;
160  if ( isset( $this->rules[$preference][$i] ) ) {
161  # Specific rules
162  $this->mTarget = $this->rules[$preference][$i];
163  } elseif ( isset( $this->rules[self::ALL][$i] ) ) {
164  # General rules
165  $this->mTarget = $this->rules[self::ALL][$i];
166  } elseif ( $preference ) {
167  # User preference
168  $this->mTarget = $preference;
169  } else {
170  # Default
171  $this->mTarget = $i;
172  }
173  $regex = $this->regexes[$i];
174 
175  // Horrible hack
176  if ( !$linked ) {
177  $regex = str_replace( array( '\[\[', '\]\]' ), '', $regex );
178  }
179 
180  if ( $match_whole ) {
181  // Let's hope this works
182  $regex = preg_replace( '!^/!', '/^', $regex );
183  $regex = str_replace( $this->regexTrail,
184  '$' . $this->regexTrail, $regex );
185  }
186 
187  // Another horrible hack
188  $this->mLinked = $linked;
189  $text = preg_replace_callback( $regex, array( &$this, 'replace' ), $text );
190  unset( $this->mLinked );
191  }
192  return $text;
193  }
194 
199  function replace( $matches ) {
200  # Extract information from $matches
201  $linked = true;
202  if ( isset( $this->mLinked ) ) {
203  $linked = $this->mLinked;
204  }
205 
206  $bits = array();
207  $key = $this->keys[$this->mSource];
208  for ( $p = 0; $p < strlen( $key ); $p++ ) {
209  if ( $key[$p] != ' ' ) {
210  $bits[$key[$p]] = $matches[$p + 1];
211  }
212  }
213 
214  return $this->formatDate( $bits, $linked );
215  }
216 
222  function formatDate( $bits, $link = true ) {
223  $format = $this->targets[$this->mTarget];
224 
225  if ( !$link ) {
226  // strip piped links
227  $format = preg_replace( '/\[\[[^|]+\|([^\]]+)\]\]/', '$1', $format );
228  // strip remaining links
229  $format = str_replace( array( '[[', ']]' ), '', $format );
230  }
231 
232  # Construct new date
233  $text = '';
234  $fail = false;
235 
236  // Pre-generate y/Y stuff because we need the year for the <span> title.
237  if ( !isset( $bits['y'] ) && isset( $bits['Y'] ) ) {
238  $bits['y'] = $this->makeIsoYear( $bits['Y'] );
239  }
240  if ( !isset( $bits['Y'] ) && isset( $bits['y'] ) ) {
241  $bits['Y'] = $this->makeNormalYear( $bits['y'] );
242  }
243 
244  if ( !isset( $bits['m'] ) ) {
245  $m = $this->makeIsoMonth( $bits['F'] );
246  if ( !$m || $m == '00' ) {
247  $fail = true;
248  } else {
249  $bits['m'] = $m;
250  }
251  }
252 
253  if ( !isset( $bits['d'] ) ) {
254  $bits['d'] = sprintf( '%02d', $bits['j'] );
255  }
256 
257  for ( $p = 0; $p < strlen( $format ); $p++ ) {
258  $char = $format[$p];
259  switch ( $char ) {
260  case 'd': # ISO day of month
261  $text .= $bits['d'];
262  break;
263  case 'm': # ISO month
264  $text .= $bits['m'];
265  break;
266  case 'y': # ISO year
267  $text .= $bits['y'];
268  break;
269  case 'j': # ordinary day of month
270  if ( !isset( $bits['j'] ) ) {
271  $text .= intval( $bits['d'] );
272  } else {
273  $text .= $bits['j'];
274  }
275  break;
276  case 'F': # long month
277  if ( !isset( $bits['F'] ) ) {
278  $m = intval( $bits['m'] );
279  if ( $m > 12 || $m < 1 ) {
280  $fail = true;
281  } else {
282  $text .= $this->lang->getMonthName( $m );
283  }
284  } else {
285  $text .= ucfirst( $bits['F'] );
286  }
287  break;
288  case 'Y': # ordinary (optional BC) year
289  $text .= $bits['Y'];
290  break;
291  default:
292  $text .= $char;
293  }
294  }
295  if ( $fail ) {
296  $text = $matches[0];
297  }
298 
299  $isoBits = array();
300  if ( isset( $bits['y'] ) ) {
301  $isoBits[] = $bits['y'];
302  }
303  $isoBits[] = $bits['m'];
304  $isoBits[] = $bits['d'];
305  $isoDate = implode( '-', $isoBits );
306 
307  // Output is not strictly HTML (it's wikitext), but <span> is whitelisted.
308  $text = Html::rawElement( 'span',
309  array( 'class' => 'mw-formatted-date', 'title' => $isoDate ), $text );
310 
311  return $text;
312  }
313 
318  function getMonthRegex() {
319  $names = array();
320  for ( $i = 1; $i <= 12; $i++ ) {
321  $names[] = $this->lang->getMonthName( $i );
322  $names[] = $this->lang->getMonthAbbreviation( $i );
323  }
324  return implode( '|', $names );
325  }
326 
332  function makeIsoMonth( $monthName ) {
333  $n = $this->xMonths[$this->lang->lc( $monthName )];
334  return sprintf( '%02d', $n );
335  }
336 
342  function makeIsoYear( $year ) {
343  # Assumes the year is in a nice format, as enforced by the regex
344  if ( substr( $year, -2 ) == 'BC' ) {
345  $num = intval( substr( $year, 0, -3 ) ) - 1;
346  # PHP bug note: sprintf( "%04d", -1 ) fails poorly
347  $text = sprintf( '-%04d', $num );
348 
349  } else {
350  $text = sprintf( '%04d', $year );
351  }
352  return $text;
353  }
354 
359  function makeNormalYear( $iso ) {
360  if ( $iso[0] == '-' ) {
361  $text = ( intval( substr( $iso, 1 ) ) + 1 ) . ' BC';
362  } else {
363  $text = intval( $iso );
364  }
365  return $text;
366  }
367 }
DateFormatter\$regexes
$regexes
Definition: DateFormatter.php:33
DateFormatter\getInstance
static & getInstance( $lang=null)
Get a DateFormatter object.
Definition: DateFormatter.php:127
of
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
Definition: globals.txt:10
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
DateFormatter\$pYears
$pYears
Definition: DateFormatter.php:33
DateFormatter\replace
replace( $matches)
Definition: DateFormatter.php:199
$wgMemc
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $wgMemc
Definition: globals.txt:25
$n
$n
Definition: RandomTest.php:76
DateFormatter\LASTPREF
const LASTPREF
Definition: DateFormatter.php:44
DateFormatter\$xMonths
$xMonths
Definition: DateFormatter.php:34
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
DateFormatter\$rxYMD
$rxYMD
Definition: DateFormatter.php:31
$link
set to $title object and return false for a match for latest after cache objects are set use the ContentHandler facility to handle CSS and JavaScript for highlighting & $link
Definition: hooks.txt:2149
DateFormatter\$rxDMY
$rxDMY
Definition: DateFormatter.php:31
DateFormatter\$rxYDM
$rxYDM
Definition: DateFormatter.php:31
DateFormatter\makeIsoMonth
makeIsoMonth( $monthName)
Makes an ISO month, e.g.
Definition: DateFormatter.php:332
wfMemcKey
wfMemcKey()
Get a cache key.
Definition: GlobalFunctions.php:3580
DateFormatter\YMD
const YMD
Definition: DateFormatter.php:42
DateFormatter\reformat
reformat( $preference, $text, $options=array( 'linked'))
Definition: DateFormatter.php:149
DateFormatter\$lang
$lang
Definition: DateFormatter.php:36
DateFormatter\$monthNames
$monthNames
Definition: DateFormatter.php:31
DateFormatter\NONE
const NONE
Definition: DateFormatter.php:39
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1352
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
DateFormatter\MD
const MD
Definition: DateFormatter.php:48
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DateFormatter\$preferences
$preferences
Definition: DateFormatter.php:34
$options
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 & $options
Definition: hooks.txt:1530
DateFormatter\$rules
$rules
Definition: DateFormatter.php:34
$matches
if(!defined( 'MEDIAWIKI')) if(!isset( $wgVersion)) $matches
Definition: NoLocalSettings.php:33
DateFormatter\DM
const DM
Definition: DateFormatter.php:47
DateFormatter\__construct
__construct(Language $lang)
Definition: DateFormatter.php:54
DateFormatter\DMY
const DMY
Definition: DateFormatter.php:41
DateFormatter\MDY
const MDY
Definition: DateFormatter.php:40
DateFormatter\YDM
const YDM
Definition: DateFormatter.php:46
DateFormatter\$rxDM
$rxDM
Definition: DateFormatter.php:31
DateFormatter\getMonthRegex
getMonthRegex()
Definition: DateFormatter.php:318
DateFormatter\makeIsoYear
makeIsoYear( $year)
Definition: DateFormatter.php:342
DateFormatter\$mSource
$mSource
Definition: DateFormatter.php:30
DateFormatter\$rxMDY
$rxMDY
Definition: DateFormatter.php:31
DateFormatter\ISO1
const ISO1
Definition: DateFormatter.php:43
DateFormatter\$pMonths
$pMonths
Definition: DateFormatter.php:33
DateFormatter\$pDays
$pDays
Definition: DateFormatter.php:33
DateFormatter\$rxMD
$rxMD
Definition: DateFormatter.php:31
DateFormatter\LAST
const LAST
Definition: DateFormatter.php:49
DateFormatter\formatDate
formatDate( $bits, $link=true)
Definition: DateFormatter.php:222
Html\rawElement
static rawElement( $element, $attribs=array(), $contents='')
Returns an HTML element in a string.
Definition: Html.php:124
DateFormatter\makeNormalYear
makeNormalYear( $iso)
Definition: DateFormatter.php:359
DateFormatter\ISO2
const ISO2
Definition: DateFormatter.php:45
Language
Internationalisation code.
Definition: Language.php:74
DateFormatter
Date formatter, recognises dates in plain text and formats them according to user preferences.
Definition: DateFormatter.php:29
DateFormatter\ALL
const ALL
Definition: DateFormatter.php:38
DateFormatter\$mTarget
$mTarget
Definition: DateFormatter.php:30